Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_canvas_element_2.lucb

#==============================================================================================
#
#   html_canvas_element_2 - HTML::HTMLCanvasElement: getContext, the bitmap and serialization
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLCanvasElement.cpp (lines 265-508): creating the 2D and WebGL
#       contexts and getContext, the bitmap size, toDataURL and toBlob, reading the bitmap from
#       the context's surface, presenting, and the surface.
#
#       `create_webgl_context<ContextType>` is a template over the two WebGL context classes; a
#       generic Luce body cannot name a type's static create, so it is two functions, one per
#       instantiation the C++ makes (`_web_gl` and `_web_gl2`).
#
#==============================================================================================

# mark: Contexts =================================================================================

## `m_context.has<Empty>()`.
func html_canvas_element_context_is_empty(this: HtmlCanvasElement*) -> bool:
    return match this.m_context:
        .empty => true
        _ => false

## Ported from HTMLCanvasElement.cpp:265 Web::HTML::HTMLCanvasElement::create_2d_context.
pub func html_canvas_element_create_2d_context(this: HtmlCanvasElement*, options: JsValue) -> HtmlCanvasElementHasOrCreatedContext!:
    if not html_canvas_element_context_is_empty(this):
        let has_this_context = match this.m_context:
            .html_canvas_rendering_context2_d(_) => true
            _ => false
        return HtmlCanvasElementHasOrCreatedContext.yes if has_this_context else HtmlCanvasElementHasOrCreatedContext.no

    let context = try html_canvas_rendering_context2_d_create(dom_element_realm(this.dom_element()), this, options)
    this.m_context = .html_canvas_rendering_context2_d(context)
    return HtmlCanvasElementHasOrCreatedContext.yes

## Ported from HTMLCanvasElement.cpp:275 Web::HTML::HTMLCanvasElement::create_webgl_context
## (the instantiation for WebGL::WebGLRenderingContext).
pub func html_canvas_element_create_webgl_context_web_gl(this: HtmlCanvasElement*, options: JsValue) -> HtmlCanvasElementHasOrCreatedContext!:
    if not html_canvas_element_context_is_empty(this):
        let has_this_context = match this.m_context:
            .web_gl_web_gl_rendering_context(_) => true
            _ => false
        return HtmlCanvasElementHasOrCreatedContext.yes if has_this_context else HtmlCanvasElementHasOrCreatedContext.no

    let maybe_context = try web_gl_web_gl_rendering_context_create(dom_element_realm(this.dom_element()), this, options)
    let context = maybe_context else return HtmlCanvasElementHasOrCreatedContext.no

    this.m_context = .web_gl_web_gl_rendering_context(context)
    return HtmlCanvasElementHasOrCreatedContext.yes

## Ported from HTMLCanvasElement.cpp:275 Web::HTML::HTMLCanvasElement::create_webgl_context
## (the instantiation for WebGL::WebGL2RenderingContext).
pub func html_canvas_element_create_webgl_context_web_gl2(this: HtmlCanvasElement*, options: JsValue) -> HtmlCanvasElementHasOrCreatedContext!:
    if not html_canvas_element_context_is_empty(this):
        let has_this_context = match this.m_context:
            .web_gl_web_gl2_rendering_context(_) => true
            _ => false
        return HtmlCanvasElementHasOrCreatedContext.yes if has_this_context else HtmlCanvasElementHasOrCreatedContext.no

    let maybe_context = try web_gl_web_gl2_rendering_context_create(dom_element_realm(this.dom_element()), this, options)
    let context = maybe_context else return HtmlCanvasElementHasOrCreatedContext.no

    this.m_context = .web_gl_web_gl2_rendering_context(context)
    return HtmlCanvasElementHasOrCreatedContext.yes

## Ported from HTMLCanvasElement.cpp:289 Web::HTML::HTMLCanvasElement::get_context.
# https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext
pub func html_canvas_element_get_context(this: HtmlCanvasElement*, type_: ak.String, options: JsValue) -> HtmlCanvasElementRenderingContext!:
    var context_options = options

    # 1. If options is not an object, then set options to null.
    if not js_value_is_object(context_options):
        context_options = js_null()

    # 2. Set options to the result of converting options to a JavaScript value.
    # NOTE: No-op.

    # 3. Run the steps in the cell of the following table whose column header matches this canvas element's canvas context mode and whose row header matches contextId:
    # NOTE: See the spec for the full table.
    if ak.string_eq_string_view(&type_, ak.sv("2d")):
        if (try html_canvas_element_create_2d_context(this, context_options)) == HtmlCanvasElementHasOrCreatedContext.yes:
            match this.m_context:
                .html_canvas_rendering_context2_d(context):
                    return HtmlCanvasElementRenderingContext.html_canvas_rendering_context2_d(context)
                _:
                    trap("Variant::get<GC::Ref<CanvasRenderingContext2D>>: another alternative")

        return HtmlCanvasElementRenderingContext.empty

    # NOTE: The WebGL spec says "experimental-webgl" is also acceptable and must be equivalent to "webgl". Other engines accept this, so we do too.
    if ak.string_eq_string_view(&type_, ak.sv("webgl")) or ak.string_eq_string_view(&type_, ak.sv("experimental-webgl")):
        if (try html_canvas_element_create_webgl_context_web_gl(this, context_options)) == HtmlCanvasElementHasOrCreatedContext.yes:
            match this.m_context:
                .web_gl_web_gl_rendering_context(context):
                    return HtmlCanvasElementRenderingContext.web_gl_web_gl_rendering_context(context)
                _:
                    trap("Variant::get<GC::Ref<WebGL::WebGLRenderingContext>>: another alternative")

        return HtmlCanvasElementRenderingContext.empty

    if ak.string_eq_string_view(&type_, ak.sv("webgl2")):
        if (try html_canvas_element_create_webgl_context_web_gl2(this, context_options)) == HtmlCanvasElementHasOrCreatedContext.yes:
            match this.m_context:
                .web_gl_web_gl2_rendering_context(context):
                    return HtmlCanvasElementRenderingContext.web_gl_web_gl2_rendering_context(context)
                _:
                    trap("Variant::get<GC::Ref<WebGL::WebGL2RenderingContext>>: another alternative")

        return HtmlCanvasElementRenderingContext.empty

    return HtmlCanvasElementRenderingContext.empty

# mark: The bitmap and serialization =============================================================

## Ported from HTMLCanvasElement.cpp:325 Web::HTML::HTMLCanvasElement::bitmap_size_for_canvas.
pub func html_canvas_element_bitmap_size_for_canvas(this: HtmlCanvasElement*, minimum_width: usize = 0, minimum_height: usize = 0) -> gfx.IntSize:
    let width = ak.max((usize)html_canvas_element_width(this), minimum_width)
    let height = ak.max((usize)html_canvas_element_height(this), minimum_height)

    # Checked<size_t> area = width; area *= height;
    let area = width *? height
    if area == none:
        ak.dbgln(f"Refusing to create {width}x{height} canvas (overflow)")
        return gfx.IntSize()
    if (area else trap("unreachable")) > (usize)html_max_canvas_area:
        ak.dbgln(f"Refusing to create {width}x{height} canvas (exceeds maximum size)")
        return gfx.IntSize()
    var size: gfx.IntSize = ---
    gfx.int_size_construct(&size, (i32)width, (i32)height)
    return size

## The `Optional<double> quality = js_quality.is_number() ? js_quality.as_double() : Optional<double>()` of
## toDataURL and toBlob.
func html_canvas_element_quality(js_quality: JsValue) -> f64?:
    if js_value_is_number(js_quality):
        return js_value_as_double(js_quality)
    return none

## Ported from HTMLCanvasElement.cpp:345 Web::HTML::HTMLCanvasElement::to_data_url.
# https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-todataurl
pub func html_canvas_element_to_data_url(this: HtmlCanvasElement*, type_: ak.StringView, js_quality: JsValue) -> ak.String:
    # It is possible the canvas doesn't have an associated bitmap so create one
    html_canvas_element_allocate_painting_surface_if_needed(this)
    var surface = html_canvas_element_surface(this)
    let size = html_canvas_element_bitmap_size_for_canvas(this)
    if surface == none and not gfx.int_size_is_empty(&size):
        # If the context is not initialized yet, we need to allocate transparent surface for serialization
        surface = gfx.painting_surface_create_with_size(size, gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied)

    # FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.

    # 2. If this canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero),
    #    then return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)
    let present_surface = surface else return ak.string_from_str("data:,")

    # 3. Let file be a serialization of this canvas element's bitmap as a file, passing type and quality if given.
    let bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, gfx.painting_surface_size(present_surface)) else trap("MUST: Gfx::Bitmap::create")
    gfx.painting_surface_read_into_bitmap(present_surface, bitmap)
    let quality = html_canvas_element_quality(js_quality)

    # 4. If file is null, then return "data:,".
    var file = html_serialize_bitmap(bitmap, type_, quality) catch failure:
        ak.dbgln(f"HTMLCanvasElement: Failed to encode canvas bitmap to {ak.string_view_text(type_)}: {failure.message}")
        return ak.string_from_str("data:,")

    # 5. Return a data: URL representing file. [RFC2397]
    let base64_encoded = ak.encode_base64(ak.byte_buffer_bytes(&file.buffer)) catch:
        return ak.string_from_str("data:,")
    let url = web_url.create_with_data(file.mime_type, ak.string_bytes_as_string_view(&base64_encoded), true)
    return web_url.url_to_string(&url)

## The captures of toBlob's deferred serialization: `[this, callback, bitmap_result, type, quality]`.
struct HtmlCanvasElementToBlobSerialization:
    var this: HtmlCanvasElement*
    var callback: IdlCallbackType*
    var bitmap_result: gfx.Bitmap*?
    var type_: ak.StringView
    var quality: f64?

## The captures of toBlob's element task: `[this, callback, file_result = move(file_result)]`.
struct HtmlCanvasElementToBlobTask:
    var this: HtmlCanvasElement*
    var callback: IdlCallbackType*
    var file_result: HtmlSerializeBitmapResult?

## toBlob's steps that run in parallel: serialize the bitmap, then queue the element task.
func html_canvas_element_to_blob_serialize(context: void*?):
    let captures = (HtmlCanvasElementToBlobSerialization*)(context else trap("toBlob: no captures"))
    let this = captures.this

    # 1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.
    var file_result: HtmlSerializeBitmapResult? = none
    if let bitmap = captures.bitmap_result:
        file_result = html_serialize_bitmap(bitmap, captures.type_, captures.quality) catch:
            recover none

    # 2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:
    let task = new HtmlCanvasElementToBlobTask(this = this, callback = captures.callback, file_result = file_result) else trap("out of memory")
    _ = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.canvas_blob_serialization_task, ak.Function0[unit](call = html_canvas_element_to_blob_task, context = task))

## toBlob's element task: `throw_dom_exception_if_needed(vm(), [&] { ... })`, reporting a thrown
## exception.
func html_canvas_element_to_blob_task(context: void*?):
    let captures = (HtmlCanvasElementToBlobTask*)(context else trap("toBlob: no captures"))
    let realm = dom_element_realm(captures.this.dom_element())
    html_canvas_element_to_blob_invoke_callback(captures) catch:
        # if (maybe_error.is_throw_completion()) report_exception(maybe_error.throw_completion(), realm());
        let vm = js_cell_vm(captures.this.js_cell())
        html_report_exception_js_completion(bind_exception_to_throw_completion(vm, vm_take_pending_exception(vm)), realm)
        return

## The lambda toBlob's element task hands to throw_dom_exception_if_needed.
func html_canvas_element_to_blob_invoke_callback(captures: HtmlCanvasElementToBlobTask*) -> !:
    let realm = dom_element_realm(captures.this.dom_element())

    # 1. If result is non-null, then set result to a new Blob object, created in the relevant realm of this canvas element, representing result. [FILEAPI]
    var blob_result: FileApiBlob*? = none
    if let file = captures.file_result:
        blob_result = file_api_blob_create(realm, file.buffer, try ak.string_from_utf8(file.mime_type))

    # 2. Invoke callback with « result » and "report".
    let arguments: JsValue[1] = [js_value_from_object((JsObject*?)blob_result)]
    var completion = idl_invoke_callback_idl_exception_behavior(captures.callback, none, IdlExceptionBehavior.report, arguments)
    if js_completion_is_error(&completion):
        vm_set_pending_exception(js_cell_vm(captures.this.js_cell()), .js_completion(js_completion_release_error(&completion)))
        error(js_exception, "")

## Ported from HTMLCanvasElement.cpp:384 Web::HTML::HTMLCanvasElement::to_blob.
# https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-toblob
pub func html_canvas_element_to_blob(this: HtmlCanvasElement*, callback: IdlCallbackType*, type_: ak.StringView, js_quality: JsValue) -> !:
    # FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.

    # 2. Let result be null.
    # 3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension nor its vertical dimension is zero),
    #    then set result to a copy of this canvas element's bitmap.
    let bitmap_result = html_canvas_element_get_bitmap_from_surface(this)

    let quality = html_canvas_element_quality(js_quality)

    # 4. Run these steps in parallel:
    let captures = new HtmlCanvasElementToBlobSerialization(this = this, callback = callback, bitmap_result = bitmap_result, type_ = type_, quality = quality) else trap("out of memory")
    let heap = gc.cell_heap(this.cell())
    platform_event_loop_plugin_deferred_invoke(platform_event_loop_plugin_the(), gc.create_function0(heap, ak.Function0[unit](call = html_canvas_element_to_blob_serialize, context = captures)))

## Ported from HTMLCanvasElement.cpp:423 Web::HTML::HTMLCanvasElement::get_bitmap_from_surface.
pub func html_canvas_element_get_bitmap_from_surface(this: HtmlCanvasElement*) -> gfx.Bitmap*?:
    # It is possible the canvas doesn't have an associated bitmap so create one
    html_canvas_element_allocate_painting_surface_if_needed(this)
    var surface = html_canvas_element_surface(this)
    let size = html_canvas_element_bitmap_size_for_canvas(this)
    if surface == none and not gfx.int_size_is_empty(&size):
        # If the context is not initialized yet, we need to allocate transparent surface for serialization
        surface = gfx.painting_surface_create_with_size(size, gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied)

    var bitmap: gfx.Bitmap*? = none
    if let present_surface = surface:
        let new_bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, gfx.painting_surface_size(present_surface)) else trap("MUST: Gfx::Bitmap::create")
        gfx.painting_surface_read_into_bitmap(present_surface, new_bitmap)
        bitmap = new_bitmap

    return bitmap

# mark: Presenting and the surface ===============================================================

## Ported from HTMLCanvasElement.cpp:442 Web::HTML::HTMLCanvasElement::set_canvas_content_dirty.
pub func html_canvas_element_set_canvas_content_dirty(this: HtmlCanvasElement*):
    this.m_canvas_content_dirty = true

## Ported from HTMLCanvasElement.cpp:447 Web::HTML::HTMLCanvasElement::present.
pub func html_canvas_element_present(this: HtmlCanvasElement*):
    if not this.m_canvas_content_dirty:
        return
    this.m_canvas_content_dirty = false

    html_canvas_element_present_context(this)

    if let surface = html_canvas_element_surface(this):
        gfx.painting_surface_flush(surface)
        let snapshot = gfx.immutable_bitmap_create_snapshot_from_painting_surface(surface)
        display_list.external_content_source_update(html_canvas_element_ensure_external_content_source(this), snapshot)

## present()'s `m_context.visit(...)`: the WebGL contexts present.
func html_canvas_element_present_context(this: HtmlCanvasElement*):
    match this.m_context:
        .html_canvas_rendering_context2_d(_):
            # Do nothing, CRC2D writes directly to the canvas bitmap.
            return
        .web_gl_web_gl_rendering_context(context):
            web_gl_web_gl_rendering_context_present(context)
        .web_gl_web_gl2_rendering_context(context):
            web_gl_web_gl2_rendering_context_present(context)
        .empty:
            # Do nothing.
            return

## Ported from HTMLCanvasElement.cpp:474 Web::HTML::HTMLCanvasElement::surface.
pub func html_canvas_element_surface(this: HtmlCanvasElement*) -> gfx.PaintingSurface*?:
    return match this.m_context:
        .html_canvas_rendering_context2_d(context) => html_canvas_rendering_context2_d_surface(context)
        .web_gl_web_gl_rendering_context(context) => web_gl_web_gl_rendering_context_surface(context)
        .web_gl_web_gl2_rendering_context(context) => web_gl_web_gl2_rendering_context_surface(context)
        .empty => none

## Ported from HTMLCanvasElement.cpp:491 Web::HTML::HTMLCanvasElement::allocate_painting_surface_if_needed.
pub func html_canvas_element_allocate_painting_surface_if_needed(this: HtmlCanvasElement*):
    match this.m_context:
        .html_canvas_rendering_context2_d(context):
            html_canvas_rendering_context2_d_allocate_painting_surface_if_needed(context)
        .web_gl_web_gl_rendering_context(context):
            web_gl_web_gl_rendering_context_allocate_painting_surface_if_needed(context)
        .web_gl_web_gl2_rendering_context(context):
            web_gl_web_gl2_rendering_context_allocate_painting_surface_if_needed(context)
        .empty:
            # Do nothing.
            return