Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_canvas_element_1.lucb

#==============================================================================================
#
#   html_canvas_element_1 - HTML::HTMLCanvasElement: <canvas>, its size and its context slot
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLCanvasElement.cpp (lines 1-263): construction (which moves the
#       mixin tables to HTMLCanvasElement's, as C++'s vptrs move), initialize and finalize
#       (registering with the page), visit_edges, the aspect-ratio presentational hint, the
#       reflected width and height, the external content source, resetting and resizing the
#       context, the font computation context, attribute_changed, the CanvasBox layout node and
#       the display adjustment.
#
#       The rendering contexts (CanvasRenderingContext2D, WebGL) are phase 4: an element with no
#       context (the `Empty` alternative, all phase 1 ever has) runs every function here; the
#       context alternatives call the closure stubs of phase 4.
#
#==============================================================================================

# mark: Construction, initialization and visiting ================================================

## Ported from HTMLCanvasElement.cpp:41 Web::HTML::HTMLCanvasElement::HTMLCanvasElement.
pub func html_canvas_element_construct(this: HtmlCanvasElement*, document: DomDocument*, qualified_name: DomQualifiedName):
    html_element_construct(this.html_element(), document, qualified_name)
    # The vptrs of the mixin bases move to HTMLCanvasElement's tables.
    let element = this.html_element()
    element.element.slottable_mixin.vtable = &html_canvas_element_slottable_mixin_vtable
    element.element.aria_mixin.vtable = &html_canvas_element_aria_mixin_vtable
    element.element.animatable.vtable = &html_canvas_element_animatable_vtable
    element.global_event_handlers.vtable = &html_canvas_element_global_event_handlers_vtable
    element.form_associated_element.vtable = &html_canvas_element_form_associated_element_vtable

    # The default member initializers: m_context is a default-constructed Variant, whose
    # alternative is its first (C++ `Variant<GC::Ref<...>, ..., Empty>` has no default, so the
    # element's declaration starts it at Empty; the zeroed cell would be a null context).
    this.m_context = HtmlCanvasRenderingContext2DOrWebGlWebGlRenderingContextOrWebGlWebGl2RenderingContextOrEmpty.empty

## Ported from HTMLCanvasElement.cpp:48 Web::HTML::HTMLCanvasElement::initialize (override).
pub func html_canvas_element_initialize_impl(base: JsCell*, realm: Realm*):
    let this = (HtmlCanvasElement*)base
    web_set_prototype_for_interface(base, realm, BindInterfaceName.html_canvas_element)
    html_element_initialize_impl(base, realm)
    page_register_canvas_element(dom_document_page(dom_node_document(this.dom_node())), dom_node_unique_id(this.dom_node()))

## Ported from HTMLCanvasElement.cpp:55 Web::HTML::HTMLCanvasElement::finalize (override).
pub func html_canvas_element_finalize_impl(base: gc.Cell*):
    let this = (HtmlCanvasElement*)base
    dom_node_finalize_impl(base)
    page_unregister_canvas_element(dom_document_page(dom_node_document(this.dom_node())), dom_node_unique_id(this.dom_node()))

## The cell m_context holds, if any (the contexts are opaque in phase 1, so they are visited as
## cells).
func html_canvas_element_context_cell(context: HtmlCanvasRenderingContext2DOrWebGlWebGlRenderingContextOrWebGlWebGl2RenderingContextOrEmpty) -> gc.Cell*?:
    return match context:
        .html_canvas_rendering_context2_d(context_2d) => (gc.Cell*?)context_2d
        .web_gl_web_gl_rendering_context(webgl) => (gc.Cell*?)webgl
        .web_gl_web_gl2_rendering_context(webgl2) => (gc.Cell*?)webgl2
        .empty => none

## Ported from HTMLCanvasElement.cpp:61 Web::HTML::HTMLCanvasElement::visit_edges (override).
pub func html_canvas_element_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlCanvasElement*)base
    html_element_visit_edges_impl(base, visitor)
    # m_context.visit([&](GC::Ref<...>& context) { visitor.visit(context); }, ..., [](Empty) {})
    gc.cell_visitor_visit_cell(visitor, html_canvas_element_context_cell(this.m_context))

# mark: Presentational hints and the reflected size ==============================================

## Ported from HTMLCanvasElement.cpp:78 Web::HTML::HTMLCanvasElement::is_presentational_hint (override).
pub func html_canvas_element_is_presentational_hint_impl(base: DomElement*, name: ak.FlyString) -> bool:
    if dom_element_is_presentational_hint_impl(base, name):
        return true

    let names: ak.FlyString[2] = [html_attribute_names_width, html_attribute_names_height]
    return html_name_is_one_of(name, names)

## Ported from HTMLCanvasElement.cpp:88 Web::HTML::HTMLCanvasElement::apply_presentational_hints (override).
pub func html_canvas_element_apply_presentational_hints_impl(base: DomElement*, properties: ak.Vector[CssStyleProperty]*):
    dom_element_apply_presentational_hints_impl(base, properties)
    # https://html.spec.whatwg.org/multipage/rendering.html#attributes-for-embedded-content-and-images
    # The width and height attributes map to the aspect-ratio property on canvas elements.

    # FIXME: Multiple elements have aspect-ratio presentational hints, make this into a helper function

    # https://html.spec.whatwg.org/multipage/rendering.html#map-to-the-aspect-ratio-property
    # if element has both attributes w and h, and parsing those attributes' values using the rules for parsing non-negative integers doesn't generate an error for either
    let width_value = dom_element_get_attribute_value(base, html_attribute_names_width)
    let height_value = dom_element_get_attribute_value(base, html_attribute_names_height)
    let w = html_parse_non_negative_integer(ak.string_bytes_as_string_view(&width_value))
    let h = html_parse_non_negative_integer(ak.string_bytes_as_string_view(&height_value))

    # then the user agent is expected to use the parsed integers as a presentational hint for the 'aspect-ratio' property of the form auto w / h.
    if let w_value = w:
        if let h_value = h:
            var values = ak.Vector[CssStyleValue*]()
            ak.vector_append_t(&values, css_keyword_style_value_create(css_data.Keyword.auto).css_style_value())
            ak.vector_append_t(&values, css_ratio_style_value_create(css_number_style_value_create(f64(w_value)).css_style_value(), css_number_style_value_create(f64(h_value)).css_style_value()).css_style_value())
            let aspect_ratio = css_style_value_list_create(values, CssStyleValueListSeparator.space)
            html_append_presentational_hint(properties, css_data.PropertyId.aspect_ratio, aspect_ratio.css_style_value())

## Ported from HTMLCanvasElement.cpp:114 Web::HTML::HTMLCanvasElement::width.
# https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-width
pub func html_canvas_element_width(this: HtmlCanvasElement*) -> u32:
    # The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.
    # https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
    # The rules for parsing non-negative integers must be used to obtain their numeric values.
    # If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
    # The width attribute defaults to 300
    if let width_string = dom_element_get_attribute(this.dom_element(), html_attribute_names_width):
        if let width = html_parse_non_negative_integer(ak.string_bytes_as_string_view(&width_string)):
            if width <= 2147483647:
                return width

    return 300

## Ported from HTMLCanvasElement.cpp:130 Web::HTML::HTMLCanvasElement::height.
# https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-height
pub func html_canvas_element_height(this: HtmlCanvasElement*) -> u32:
    # The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.
    # https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
    # The rules for parsing non-negative integers must be used to obtain their numeric values.
    # If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
    # the height attribute defaults to 150
    if let height_string = dom_element_get_attribute(this.dom_element(), html_attribute_names_height):
        if let height = html_parse_non_negative_integer(ak.string_bytes_as_string_view(&height_string)):
            if height <= 2147483647:
                return height

    return 150

# mark: The external content source and the context ==============================================

## Ported from HTMLCanvasElement.cpp:145 Web::HTML::HTMLCanvasElement::ensure_external_content_source.
pub func html_canvas_element_ensure_external_content_source(this: HtmlCanvasElement*) -> display_list.ExternalContentSource*:
    if this.m_external_content_source == none:
        this.m_external_content_source = display_list.external_content_source_create()
    return this.m_external_content_source else trap("unreachable")

## Ported from HTMLCanvasElement.cpp:152 Web::HTML::HTMLCanvasElement::reset_context_to_default_state.
pub func html_canvas_element_reset_context_to_default_state(this: HtmlCanvasElement*):
    if let external_content_source = this.m_external_content_source:
        display_list.external_content_source_clear(external_content_source)
    match this.m_context:
        .html_canvas_rendering_context2_d(context):
            html_canvas_rendering_context2_d_reset_to_default_state(context)
        .web_gl_web_gl_rendering_context(context):
            web_gl_web_gl_rendering_context_reset_to_default_state(context)
        .web_gl_web_gl2_rendering_context(context):
            web_gl_web_gl2_rendering_context_reset_to_default_state(context)
        .empty:
            # Do nothing.
            return

## Ported from HTMLCanvasElement.cpp:171 Web::HTML::HTMLCanvasElement::canvas_font_computation_context.
pub func html_canvas_element_canvas_font_computation_context(this: HtmlCanvasElement*) -> CssComputationContext:
    var abstract_element: DomAbstractElement = ---
    dom_abstract_element_construct(&abstract_element, this.dom_element())
    var length_resolution_context: CssLengthResolutionContext? = none

    if dom_node_is_connected(this.dom_node()) and dom_node_navigable(this.dom_node()) != none:
        length_resolution_context = css_length_resolution_context_for_element(abstract_element)
    else:
        # NB: This is similar to the document's LRC but using the default canvas context font size of 10px
        let default_font = platform_font_plugin_default_font(platform_font_plugin_the(), 8.0) else trap("FontPlugin::default_font")
        var font_metrics: CssLengthFontMetrics = ---
        css_length_font_metrics_construct(&font_metrics, gfx.css_pixels_from_int(10), web_fonts.font_pixel_metrics(default_font), css_initial_values_line_height())

        var viewport_rect = gfx.CssPixelRect()
        if let navigable = dom_node_navigable(this.dom_node()):
            viewport_rect = html_navigable_viewport_rect(navigable)

        length_resolution_context = CssLengthResolutionContext(viewport_rect = viewport_rect, font_metrics = font_metrics, root_font_metrics = font_metrics)

    # NB: We require a abstract element here since tree counting functions are allowed in font values unlike for
    #     OffscreenCanvas
    # FIXME: Do we require a color scheme to resolve light-dark()?
    return CssComputationContext(length_resolution_context = length_resolution_context else trap("Optional::value()"), abstract_element = abstract_element, color_scheme = none)

## Ported from HTMLCanvasElement.cpp:205 Web::HTML::HTMLCanvasElement::notify_context_about_canvas_size_change.
pub func html_canvas_element_notify_context_about_canvas_size_change(this: HtmlCanvasElement*):
    match this.m_context:
        .html_canvas_rendering_context2_d(context):
            html_canvas_rendering_context2_d_set_size(context, html_canvas_element_bitmap_size_for_canvas(this))
        .web_gl_web_gl_rendering_context(context):
            web_gl_web_gl_rendering_context_set_size(context, html_canvas_element_bitmap_size_for_canvas(this))
        .web_gl_web_gl2_rendering_context(context):
            web_gl_web_gl2_rendering_context_set_size(context, html_canvas_element_bitmap_size_for_canvas(this))
        .empty:
            # Do nothing.
            return

## Ported from HTMLCanvasElement.cpp:222 Web::HTML::HTMLCanvasElement::set_width.
pub func html_canvas_element_set_width(this: HtmlCanvasElement*, value: u32):
    var new_value = value
    if new_value > 2147483647:
        new_value = 300

    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_width, ak.string_number_u64((u64)new_value))
    html_canvas_element_notify_context_about_canvas_size_change(this)
    html_canvas_element_reset_context_to_default_state(this)

## Ported from HTMLCanvasElement.cpp:232 Web::HTML::HTMLCanvasElement::set_height.
pub func html_canvas_element_set_height(this: HtmlCanvasElement*, value: u32):
    var new_value = value
    if new_value > 2147483647:
        new_value = 150

    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_height, ak.string_number_u64((u64)new_value))
    html_canvas_element_notify_context_about_canvas_size_change(this)
    html_canvas_element_reset_context_to_default_state(this)

## Ported from HTMLCanvasElement.cpp:242 Web::HTML::HTMLCanvasElement::attribute_changed (override).
pub func html_canvas_element_attribute_changed_impl(base: DomElement*, local_name: ak.FlyString, old_value: ak.String?, value: ak.String?, namespace_: ak.FlyString?):
    let this = (HtmlCanvasElement*)base
    html_element_attribute_changed_impl(base, local_name, old_value, value, namespace_)

    let names: ak.FlyString[2] = [html_attribute_names_width, html_attribute_names_height]
    if html_name_is_one_of(local_name, names):
        html_canvas_element_notify_context_about_canvas_size_change(this)
        html_canvas_element_reset_context_to_default_state(this)
        dom_node_set_needs_layout_update(this.dom_node(), DomSetNeedsLayoutReason.html_canvas_element_width_or_height_change)

## Ported from HTMLCanvasElement.cpp:253 Web::HTML::HTMLCanvasElement::create_layout_node (override).
pub func html_canvas_element_create_layout_node_impl(base: DomElement*, style: CssComputedProperties*) -> LayoutNode*?:
    let this = (HtmlCanvasElement*)base
    # heap().allocate<Layout::CanvasBox>(...): a layout node's initialize is JS::Cell's, which does nothing.
    return realm_create_layout_canvas_box(dom_element_realm(base), dom_node_document(base.dom_node()), this, style).layout_node()

## Ported from HTMLCanvasElement.cpp:258 Web::HTML::HTMLCanvasElement::adjust_computed_style (override).
pub func html_canvas_element_adjust_computed_style_impl(base: DomElement*, style: CssComputedProperties*):
    # https://drafts.csswg.org/css-display-3/#unbox
    let display = css_computed_properties_display(style)
    if css_display_is_contents(&display):
        css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.none_)).css_style_value())