Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / window_3.lucb

#==============================================================================================
#
#   window_3 - HTML::Window: parent and frame element, window.open(), the objects a window
#   creates on demand, simple dialogs, postMessage, computed style, media queries, and the
#   CSSOM View geometry (inner size, scrolling, screen position, device pixel ratio)
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/Window.cpp lines 1108-1735 (parent through
#       device_pixel_ratio).
#
#       Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
#       Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Parent and frame element ================================================================

## Ported from Window.cpp:1109 Web::HTML::Window::parent.
# https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-parent
pub func html_window_parent(this: HtmlWindow*) -> HtmlWindowProxy*?:
    # 1. Let navigable be this's navigable.
    var navigable = html_window_navigable(this)

    # 2. If navigable is null, then return null.
    if navigable == none:
        return none

    # 3. If navigable's parent is not null, then set navigable to navigable's parent.
    if let parent = html_navigable_parent(navigable else trap("unreachable")):
        navigable = parent

    # 4. Return navigable's active WindowProxy.
    return html_navigable_active_window_proxy(navigable else trap("unreachable"))

## Ported from Window.cpp:1127 Web::HTML::Window::frame_element.
# https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-frameelement
pub func html_window_frame_element(this: HtmlWindow*) -> DomElement*?:
    # 1. Let current be this's node navigable.
    let current = html_window_navigable(this)

    # 2. If current is null, then return null.
    let navigable = current else return none

    # 3. Let container be current's container.
    let container = html_navigable_container(navigable)

    # 4. If container is null, then return null.
    let element = container else return none

    # 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
    let container_origin = dom_document_origin(dom_node_document(element.dom_node()))
    if not web_url.origin_is_same_origin_domain(&container_origin, html_environment_settings_object_origin(html_current_settings_object())):
        return none

    # 6. Return container.
    return element.dom_element()

## Ported from Window.cpp:1152 Web::HTML::Window::open.
# https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-open
pub func html_window_open(this: HtmlWindow*, url: ak.String?, target: ak.String?, features: ak.String?) -> HtmlWindowProxy*?!:
    # The open(url, target, features) method steps are to run the window open steps with url, target, and features.
    let url_string = url else trap("Optional::operator*() on an empty optional")
    let target_string = target else trap("Optional::operator*() on an empty optional")
    let features_string = features else trap("Optional::operator*() on an empty optional")
    return try html_window_window_open_steps(this, ak.string_bytes_as_string_view(&url_string), ak.string_bytes_as_string_view(&target_string), ak.string_bytes_as_string_view(&features_string))

# mark: Objects created on demand ===============================================================

## Ported from Window.cpp:1159 Web::HTML::Window::navigator.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
pub func html_window_navigator(this: HtmlWindow*) -> HtmlNavigator*:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    # The navigator and clientInformation getter steps are to return this's associated Navigator.
    if this.m_navigator == none:
        this.m_navigator = realm_create_html_navigator(realm, realm)
    return this.m_navigator else trap("unreachable")

## Ported from Window.cpp:1170 Web::HTML::Window::close_watcher_manager.
# https://html.spec.whatwg.org/multipage/interaction.html#close-watcher-manager
pub func html_window_close_watcher_manager(this: HtmlWindow*) -> HtmlCloseWatcherManager*:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    if this.m_close_watcher_manager == none:
        this.m_close_watcher_manager = realm_create_html_close_watcher_manager(realm, realm)
    return this.m_close_watcher_manager else trap("unreachable")

## Ported from Window.cpp:1180 Web::HTML::Window::cookie_store.
# https://cookiestore.spec.whatwg.org/#Window
pub func html_window_cookie_store(this: HtmlWindow*) -> CookieStoreCookieStore*:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    # The cookieStore getter steps are to return this’s associated CookieStore.
    if this.m_cookie_store == none:
        this.m_cookie_store = realm_create_cookie_store_cookie_store(realm, realm, page_client(html_window_page(this)))
    return this.m_cookie_store else trap("unreachable")

## Ported from Window.cpp:1191 Web::HTML::Window::speech_synthesis.
# https://wicg.github.io/speech-api/#tts-section
pub func html_window_speech_synthesis(this: HtmlWindow*) -> SpeechSynthesis*:
    if this.m_speech_synthesis == none:
        this.m_speech_synthesis = speech_synthesis_create(bind_platform_object_realm(this.bind_platform_object()))
    return this.m_speech_synthesis else trap("unreachable")

# mark: Simple dialogs ==========================================================================

## Ported from Window.cpp:1199 Web::HTML::Window::alert.
# https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
pub func html_window_alert(this: HtmlWindow*, message: ak.String):
    # https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
    # Note: This method is defined using two overloads, instead of using an optional argument,
    #       for historical reasons. The practical impact of this is that alert(undefined) is
    #       treated as alert("undefined"), but alert() is treated as alert("").
    # FIXME: Make this fully spec compliant.
    page_did_request_alert(html_window_page(this), message)

## Ported from Window.cpp:1210 Web::HTML::Window::confirm.
# https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
pub func html_window_confirm(this: HtmlWindow*, message: ak.String?) -> bool:
    # FIXME: Make this fully spec compliant.
    # NOTE: `message` has an IDL-provided default value and is never empty.
    return page_did_request_confirm(html_window_page(this), message else trap("Optional::operator*() on an empty optional"))

## Ported from Window.cpp:1218 Web::HTML::Window::prompt.
# https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
pub func html_window_prompt(this: HtmlWindow*, message: ak.String?, default_: ak.String?) -> ak.String?:
    # FIXME: Make this fully spec compliant.
    return page_did_request_prompt(html_window_page(this), message else trap("Optional::operator*() on an empty optional"), default_ else trap("Optional::operator*() on an empty optional"))

# mark: postMessage =============================================================================

## Ported from Window.cpp:1225 Web::HTML::Window::window_post_message_steps.
# https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
func html_window_window_post_message_steps(this: HtmlWindow*, message: JsValue, options: HtmlWindowPostMessageOptions) -> !:
    # Steps 1-8 serialize the message with StructuredSerializeWithTransfer, queue a task that
    # deserializes it into the target realm and fire a MessageEvent at the window: a message is a
    # JS value, which only a script can post (phase 3).
    trap("unported (P3): Web::HTML::Window::window_post_message_steps (structured serialization and MessageEvent)")

## Ported from Window.cpp:1325 Web::HTML::Window::post_message.
# https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage-options
pub func html_window_post_message_html_window_post_message_optio(this: HtmlWindow*, message: JsValue, options: HtmlWindowPostMessageOptions) -> !:
    # The Window interface's postMessage(message, options) method steps are to run the window post message steps given
    # this, message, and options.
    return try html_window_window_post_message_steps(this, message, options)

## Ported from Window.cpp:1333 Web::HTML::Window::post_message.
# https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
pub func html_window_post_message_string(this: HtmlWindow*, message: JsValue, target_origin: ak.String, transfer: ak.Vector[JsObject*?]) -> !:
    # The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message
    # steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».
    var options = HtmlWindowPostMessageOptions()
    options.structured_serialize_options.transfer = transfer
    options.target_origin = target_origin
    return try html_window_window_post_message_steps(this, message, options)

# mark: The current event, computed style and media queries =====================================

## Ported from Window.cpp:1341 Web::HTML::Window::event.
# https://dom.spec.whatwg.org/#dom-window-event
pub func html_window_event(this: HtmlWindow*) -> DomEventOrEmpty:
    # The event getter steps are to return this’s current event.
    if let current_event = html_window_current_event_const(this):
        return DomEventOrEmpty.dom_event(current_event)
    return DomEventOrEmpty.empty

## Ported from Window.cpp:1350 Web::HTML::Window::get_computed_style.
# https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle
pub func html_window_get_computed_style(this: HtmlWindow*, element: DomElement*, pseudo_element: ak.String?) -> CssStyleProperties*:
    # 1. Let doc be elt’s node document.

    # 2. Let obj be elt.
    var object: DomAbstractElement? = DomAbstractElement(m_element = element, m_pseudo_element = none, m_inheritance_override = none)

    # 3. If pseudoElt is provided, is not the empty string, and starts with a colon, then:
    if let pseudo = pseudo_element:
        if ak.string_starts_with(&pseudo, (u32)':'):
            # 1. Parse pseudoElt as a <pseudo-element-selector>, and let type be the result.
            var params: CssParsingParams = ---
            css_parsing_params_construct_dom_document(&params, html_window_associated_document(this))
            let type_ = parse_pseudo_element_selector(params, ak.string_bytes_as_string_view(&pseudo))

            # 2. If type is failure, or is a ::slotted() or ::part() pseudo-element, let obj be null.
            var is_failure = true
            if let parsed = type_:
                let kind = css_selector_pseudo_element_selector_type(&parsed)
                is_failure = kind == css_data.PseudoElement.slotted or kind == css_data.PseudoElement.part
            if is_failure:
                object = none
            # 3. Otherwise let obj be the given pseudo-element of elt.
            else:
                let parsed = type_ else trap("unreachable")
                let kind = css_selector_pseudo_element_selector_type(&parsed)
                # TODO: Keep the function arguments of the pseudo-element if there are any.
                object = DomAbstractElement(m_element = element, m_pseudo_element = kind, m_inheritance_override = none)

                # https://drafts.csswg.org/css-view-transitions-1/#update-pseudo-element-styles
                # This algorithm must be executed to update styles in user-agent origin if its effects can be observed by a web API.
                # NB: View transition pseudo-elements only ever originate from the document element and only ::view-transition-group() and its descendants can be affected by update_pseudo_element_styles().
                if dom_element_is_document_element(element) and (kind == css_data.PseudoElement.view_transition_group or kind == css_data.PseudoElement.view_transition_image_pair or kind == css_data.PseudoElement.view_transition_old or kind == css_data.PseudoElement.view_transition_new):
                    if let transition = dom_document_active_view_transition(dom_node_document(element.dom_node())):
                        view_transition_view_transition_update_pseudo_element_styles(transition) catch:
                            # (void): the C++ drops the result.
                            recover ()

    # FIXME: Implement steps 4 and 5 when we can.
    # 4. Let decls be an empty list of CSS declarations.
    # 5. If obj is not null, and elt is connected, part of the flat tree, and its shadow-including root
    #    has a browsing context which either doesn’t have a browsing context container, or whose browsing
    #    context container is being rendered, set decls to a list of all longhand properties that are
    #    supported CSS properties, in lexicographical order, with the value being the resolved value
    #    computed for obj using the style rules associated with doc. Additionally, append to decls all
    #    the custom properties whose computed value for obj is not the guaranteed-invalid value.

    # 6. Return a live CSSStyleProperties object with the following properties:
    #    computed flag
    #        Set.
    #    readonly flag
    #        Set.
    #    declarations
    #        decls.
    #    parent CSS rule
    #        Null.
    #    owner node
    #        obj.
    return css_style_properties_create_resolved_style(dom_element_realm(element), object)

## Ported from Window.cpp:1406 Web::HTML::Window::match_media.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-matchmedia
pub func html_window_match_media(this: HtmlWindow*, query: ak.String) -> CssMediaQueryList*!:
    # 1. Let parsed media query list be the result of parsing query.
    var params: CssParsingParams = ---
    css_parsing_params_construct_dom_document(&params, html_window_associated_document(this))
    let parsed_media_query_list = parse_media_query_list(params, ak.string_bytes_as_string_view(&query))

    # 2. Return a new MediaQueryList object, with this's associated Document as the document, with parsed media query list as its associated media query list.
    let media_query_list = realm_create_css_media_query_list(bind_platform_object_realm(this.bind_platform_object()), html_window_associated_document(this), parsed_media_query_list)
    dom_document_add_media_query_list(html_window_associated_document(this), media_query_list)
    return media_query_list

## Ported from Window.cpp:1418 Web::HTML::Window::screen.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screen
pub func html_window_screen(this: HtmlWindow*) -> CssScreen*:
    # The screen attribute must return the Screen object associated with the Window object.
    if this.m_screen == none:
        this.m_screen = realm_create_css_screen(bind_platform_object_realm(this.bind_platform_object()), this)
    return this.m_screen else trap("unreachable")

## Ported from Window.cpp:1426 Web::HTML::Window::visual_viewport.
pub func html_window_visual_viewport(this: HtmlWindow*) -> CssVisualViewport*?:
    # If the associated document is fully active, the visualViewport attribute must return
    # the VisualViewport object associated with the Window object’s associated document.
    if dom_document_is_fully_active(html_window_associated_document(this)):
        return dom_document_visual_viewport(html_window_associated_document(this))

    # Otherwise, it must return null.
    return none

# mark: Inner size and moving ===================================================================

## Ported from Window.cpp:1438 Web::HTML::Window::inner_width.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerwidth
pub func html_window_inner_width(this: HtmlWindow*) -> i32:
    # The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
    # or zero if there is no viewport.
    if let navigable = dom_document_navigable(html_window_associated_document_const(this)):
        let viewport_rect = html_navigable_viewport_rect(navigable)
        return gfx.css_pixel_rect_width(&viewport_rect).to_int()
    return 0

## Ported from Window.cpp:1448 Web::HTML::Window::inner_height.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerheight
pub func html_window_inner_height(this: HtmlWindow*) -> i32:
    # The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
    # or zero if there is no viewport.
    if let navigable = dom_document_navigable(html_window_associated_document_const(this)):
        let viewport_rect = html_navigable_viewport_rect(navigable)
        return gfx.css_pixel_rect_height(&viewport_rect).to_int()
    return 0

## Ported from Window.cpp:1458 Web::HTML::Window::move_to.
# https://drafts.csswg.org/cssom-view/#dom-window-moveto
pub func html_window_move_to(this: HtmlWindow*, arg0: i64, arg1: i64):
    # 1. Optionally, return.
    return

    # NOTE: For now, the other steps are unimplemented because we always return in step 1.
    # FIXME: Implement these for popup windows?
    # 2. Let target be this's relevant global object's browsing context.
    # 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
    # 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not move outside the available space.
    # 5. Move target’s window such that the window’s top left corner is at coordinates (x, y) relative to the top left corner of the output device, measured in CSS pixels of target. The positive axes are rightward and downward.

## Ported from Window.cpp:1472 Web::HTML::Window::move_by.
# https://drafts.csswg.org/cssom-view/#dom-window-moveby
pub func html_window_move_by(this: HtmlWindow*, arg0: i64, arg1: i64):
    # 1. Optionally, return.
    return

    # NOTE: For now, the other steps are unimplemented because we always return in step 1.
    # FIXME: Implement these for popup windows?
    # 2. Let target be this's relevant global object's browsing context.
    # 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
    # 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not move outside the available space.
    # 5. Move target’s window x CSS pixels of target rightward and y CSS pixels of target downward.

## Ported from Window.cpp:1486 Web::HTML::Window::resize_to.
# https://drafts.csswg.org/cssom-view/#dom-window-resizeto
pub func html_window_resize_to(this: HtmlWindow*, arg0: i64, arg1: i64):
    # 1. Optionally, return.
    return

    # NOTE: For now, the other steps are unimplemented because we always return in step 1.
    # FIXME: Implement these for popup windows?
    # 2. Let target be this's relevant global object's browsing context.
    # 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
    # 4. Optionally, clamp width and height in a user-agent-defined manner so that the window does not get too small or bigger than the available space.
    # 5. Resize target’s window by moving its right and bottom edges such that the distance between the left and right edges of the viewport are width CSS pixels of target and the distance between the top and bottom edges of the viewport are height CSS pixels of target.
    # 6. Optionally, move target’s window in a user-agent-defined manner so that it does not grow outside the available space.

## Ported from Window.cpp:1501 Web::HTML::Window::resize_by.
# https://drafts.csswg.org/cssom-view/#dom-window-resizeby
pub func html_window_resize_by(this: HtmlWindow*, arg0: i64, arg1: i64):
    # 1. Optionally, return.
    return

    # NOTE: For now, the other steps are unimplemented because we always return in step 1.
    # FIXME: Implement these for popup windows?
    # 2. Let target be this's relevant global object's browsing context.
    # 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
    # 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not get too small or bigger than the available space.
    # 5. Resize target’s window by moving its right edge x CSS pixels of target rightward and its bottom edge y CSS pixels of target downward.
    # 6. Optionally, move target’s window in a user-agent-defined manner so that it does not grow outside the available space.

# mark: Scrolling ===============================================================================

## Ported from Window.cpp:1516 Web::HTML::Window::scroll_x.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollx
pub func html_window_scroll_x(this: HtmlWindow*) -> f64:
    # The scrollX attribute must return the x-coordinate, relative to the initial containing block origin,
    # of the left of the viewport, or zero if there is no viewport.
    if let navigable = dom_document_navigable(html_window_associated_document_const(this)):
        let viewport_rect = html_navigable_viewport_rect(navigable)
        return gfx.css_pixel_rect_x(&viewport_rect).to_double()
    return 0.0

## Ported from Window.cpp:1526 Web::HTML::Window::scroll_y.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly
pub func html_window_scroll_y(this: HtmlWindow*) -> f64:
    # The scrollY attribute must return the y-coordinate, relative to the initial containing block origin,
    # of the top of the viewport, or zero if there is no viewport.
    if let navigable = dom_document_navigable(html_window_associated_document_const(this)):
        let viewport_rect = html_navigable_viewport_rect(navigable)
        return gfx.css_pixel_rect_y(&viewport_rect).to_double()
    return 0.0

## Ported from Window.cpp:1536 Web::HTML::Window::scroll.
# https://drafts.csswg.org/cssom-view/#dom-window-scroll
pub func html_window_scroll_html_scroll_to_options(this: HtmlWindow*, options: HtmlScrollToOptions) -> JsPromiseCapability*:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    # 4. If there is no viewport, return a resolved Promise and abort the remaining steps.
    # AD-HOC: Done here as step 1 requires the viewport.
    let navigable = dom_document_navigable(html_window_associated_document(this)) else return idl_create_resolved_promise(realm, js_undefined())

    # 1. If invoked with one argument, follow these substeps:
    # NB: This Window::scroll() overload always has one argument.

    #    1. Let options be the argument.
    let css_viewport_rect = html_navigable_viewport_rect(navigable)
    let viewport_rect = gfx.css_pixel_rect_to_type_f32(&css_viewport_rect)

    #    2. Let x be the value of the left dictionary member of options, if present, or the viewport’s current scroll
    #    position on the x axis otherwise.
    var x = (f32)(options.left else (f64)viewport_rect.m_location.m_x)

    #    3. Let y be the value of the top dictionary member of options, if present, or the viewport’s current scroll
    #       position on the y axis otherwise.
    var y = (f32)(options.top else (f64)viewport_rect.m_location.m_y)

    # 2. If invoked with two arguments, follow these substeps:
    # NB: Implemented by other Window::scroll() overload.

    # 3. Normalize non-finite values for x and y.
    x = (f32)html_normalize_non_finite_values_f64((f64)x)
    y = (f32)html_normalize_non_finite_values_f64((f64)y)

    # AD-HOC: Step 4 is done at the start.

    # 5. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any.
    let viewport_width = viewport_rect.m_size.m_width

    # 6. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any.
    let viewport_height = viewport_rect.m_size.m_height

    let document = html_navigable_active_document(navigable) else trap("VERIFY: document")

    # OPTIMIZATION: If we're scrolling to (0, 0), we don't need to do any of the overflow calculations.
    #               This also means we don't need to update layout in that case.
    if x != 0.0f32 or y != 0.0f32:
        # NB: Make sure layout is up-to-date before looking at scrollable overflow metrics.
        dom_document_update_layout(document, DomUpdateLayoutReason.window_scroll)

        let paintable_box = dom_node_paintable_box(document.dom_node()) else trap("VERIFY: document->paintable_box()")
        let css_scrolling_area = paint_paintable_box_scrollable_overflow_rect(paintable_box) else trap("Optional::operator->() on an empty optional")
        let scrolling_area = gfx.css_pixel_rect_to_type_f32(&css_scrolling_area)

        # 7. FIXME: For now we always assume overflow direction is rightward
        # -> If the viewport has rightward overflow direction
        #    Let x be max(0, min(x, viewport scrolling area width - viewport width)).
        x = ak.max_f32(0.0f32, ak.min_f32(x, scrolling_area.m_size.m_width - viewport_width))
        # -> If the viewport has leftward overflow direction
        #    Let x be min(0, max(x, viewport width - viewport scrolling area width)).

        # 8. FIXME: For now we always assume overflow direction is downward
        # -> If the viewport has downward overflow direction
        #    Let y be max(0, min(y, viewport scrolling area height - viewport height)).
        y = ak.max_f32(0.0f32, ak.min_f32(y, scrolling_area.m_size.m_height - viewport_height))
        # -> If the viewport has upward overflow direction
        #    Let y be min(0, max(y, viewport height - viewport scrolling area height)).

    # FIXME: 9. Let position be the scroll position the viewport would have by aligning the x-coordinate x of the viewport
    #           scrolling area with the left of the viewport and aligning the y-coordinate y of the viewport scrolling area
    #           with the top of the viewport.

    # 10. If position is the same as the viewport’s current scroll position, and the viewport does not have an ongoing
    #     smooth scroll, return a resolved Promise and abort the remaining steps.
    if x == viewport_rect.m_location.m_x and y == viewport_rect.m_location.m_y:
        var temporary_execution_context: HtmlTemporaryExecutionContext = ---
        html_temporary_execution_context_construct_realm(&temporary_execution_context, realm)
        defer html_temporary_execution_context_destruct(&temporary_execution_context)
        return idl_create_resolved_promise(realm, js_undefined())

    # 11. Let document be the viewport’s associated Document.
    # NB: document is already defined above.

    # 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is
    #     one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.
    #     Let scrollPromise be the Promise returned from this step.
    let scroll_promise = html_navigable_perform_a_scroll_of_the_viewport(navigable, gfx.CssPixelPoint(m_x = gfx.CssPixels.from_f64((f64)x), m_y = gfx.CssPixels.from_f64((f64)y)))

    # 13. Return scrollPromise.
    return scroll_promise

## Ported from Window.cpp:1625 Web::HTML::Window::scroll.
# https://drafts.csswg.org/cssom-view/#dom-window-scroll
pub func html_window_scroll_f64(this: HtmlWindow*, x: f64, y: f64) -> JsPromiseCapability*:
    # NB: This just implements step 2, and then forwards to the other Window::scroll() overload.

    # 2. If invoked with two arguments, follow these substeps:

    #    1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
    var options = HtmlScrollToOptions()

    #    2. Let x and y be the arguments, respectively.
    options.left = x
    options.top = y

    return html_window_scroll_html_scroll_to_options(this, options)

## Ported from Window.cpp:1642 Web::HTML::Window::scroll_by.
# https://drafts.csswg.org/cssom-view/#dom-window-scrollby
pub func html_window_scroll_by_html_scroll_to_options(this: HtmlWindow*, a_options: HtmlScrollToOptions) -> JsPromiseCapability*:
    var options = a_options

    # 1. If invoked with two arguments, follow these substeps:
    # NB: Implemented by the other overload, which then calls this.

    # 2. Normalize non-finite values for the left and top dictionary members of options.
    let left = html_normalize_non_finite_values_optional(options.left)
    let top = html_normalize_non_finite_values_optional(options.top)

    # 3. Add the value of scrollX to the left dictionary member.
    options.left = left + html_window_scroll_x(this)

    # 4. Add the value of scrollY to the top dictionary member.
    options.top = top + html_window_scroll_y(this)

    # 5. Return the Promise returned from scroll() after the method is invoked with options as the only argument.
    return html_window_scroll_html_scroll_to_options(this, options)

## Ported from Window.cpp:1662 Web::HTML::Window::scroll_by.
# https://drafts.csswg.org/cssom-view/#dom-window-scrollby
pub func html_window_scroll_by_f64(this: HtmlWindow*, x: f64, y: f64) -> JsPromiseCapability*:
    # 1. If invoked with two arguments, follow these substeps:

    #    1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
    var options = HtmlScrollToOptions()

    #    2. Let x and y be the arguments, respectively.

    #    3. Let the left dictionary member of options have the value x.
    options.left = x

    #    4. Let the top dictionary member of options have the value y.
    options.top = y

    # NB: Complete the algorithm using the other overload.
    return html_window_scroll_by_html_scroll_to_options(this, options)

# mark: Screen position and the device pixel ratio ==============================================

## Ported from Window.cpp:1682 Web::HTML::Window::screen_x.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screenx
pub func html_window_screen_x(this: HtmlWindow*) -> i32:
    # The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed
    # screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing.
    return page_window_position(html_window_page_const(this)).m_x

## Ported from Window.cpp:1690 Web::HTML::Window::screen_y.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny
pub func html_window_screen_y(this: HtmlWindow*) -> i32:
    # The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the
    # Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing.
    return page_window_position(html_window_page_const(this)).m_y

## Ported from Window.cpp:1698 Web::HTML::Window::outer_width.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth
pub func html_window_outer_width(this: HtmlWindow*) -> i32:
    # The outerWidth attribute must return the width of the client window. If there is no client window this
    # attribute must return zero.
    return page_window_size(html_window_page_const(this)).m_width

## Ported from Window.cpp:1706 Web::HTML::Window::outer_height.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight
pub func html_window_outer_height(this: HtmlWindow*) -> i32:
    # The outerHeight attribute must return the height of the client window. If there is no client window this
    # attribute must return zero.
    return page_window_size(html_window_page_const(this)).m_height

## Ported from Window.cpp:1714 Web::HTML::Window::device_pixel_ratio.
# https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio
pub func html_window_device_pixel_ratio(this: HtmlWindow*) -> f64:
    # 1. If there is no output device, return 1 and abort these steps.
    # 2. Let CSS pixel size be the size of a CSS pixel at the current page zoom and using a scale factor of 1.0.
    # 3. Let device pixel size be the vertical size of a device pixel of the output device.
    # 4. Return the result of dividing CSS pixel size by device pixel size.
    return page_client_device_pixels_per_css_pixel(page_client(html_window_page_const(this)))