Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / page / tests_page.lucb

#==============================================================================================
#
#   tests_page - heap test pages and documents for every region's tests, and their tests
#
#   DESCRIPTION:
#       The helpers at the top give tests what an embedder gives LibWeb: a Page in the heap
#       (Page::create) with a test PageClient, which a full collection marks (Page::visit_edges,
#       ported ahead of region r28), and real Documents made by Document::create in a principal
#       realm of tests_environments, so that tests no longer defer collections or build
#       documents outside the heap. The tests pin Page::visit_edges, a full collection over a
#       page, a document, its elements and its FontFaceSet, and how far Document::create and
#       create_and_initialize get in phase 1.
#
#       web_test_create_page(vm)            a heap Page with a test PageClient
#       web_test_create_document(realm)     a Document as Document::create makes it, in a realm
#                                           of web_test_create_settings_realm, with its page
#       web_test_create_vm_realm_and_document()   both, for one test
#       web_test_install_event_loop_plugin()        an EventLoopPlugin over the test Core loop
#       test_page_still_unported(stub, name)        whether a stop is still a stub (traps
#                                                   cannot be caught)
#
#==============================================================================================

# mark: The test PageClient =====================================================================

## What the test PageClients saw (one test at a time).
struct TestDocumentClientLog:
    var frames_requested: i32
    var titles_changed: i32

## The log of the test PageClients (reset by web_test_create_page).
var test_document_client_log: TestDocumentClientLog

## A test PageClient: a PageClient that knows its page.
struct TestPageClient: gc.IsCell:
    var page_client: PageClient
    var m_page: Page*?

    func cell() -> gc.Cell*: return (gc.Cell*)&self

## The test PageClient's visit_edges: its page.
func test_page_client_visit_edges(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (TestPageClient*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_page)

## PageClient::id of the test client.
func test_page_client_id(this: PageClient*) -> u64:
    return 1

## PageClient::page of the test client.
func test_page_client_page(this: PageClient*) -> Page*:
    return ((TestPageClient*)this).m_page else trap("the test PageClient has no page")

## PageClient::is_connection_open of the test client.
func test_page_client_is_connection_open(this: PageClient*) -> bool:
    return true

## PageClient::zoom_level, device_pixel_ratio and device_pixels_per_css_pixel of the test
## client: 1 (Ladybird's test mode).
func test_page_client_one(this: PageClient*) -> f64:
    return 1.0

## The color scheme the test client prefers: `auto`, unless a test sets another (the layout tests set `light`, what
## `auto` resolves to with the light palette Ladybird's test runner uses; Page::palette is region r28's).
var test_page_client_color_scheme: CssPreferredColorScheme = CssPreferredColorScheme.auto

## PageClient::preferred_color_scheme of the test client.
func test_page_client_preferred_color_scheme(this: PageClient*) -> CssPreferredColorScheme:
    return test_page_client_color_scheme

## PageClient::preferred_contrast of the test client.
func test_page_client_preferred_contrast(this: PageClient*) -> CssPreferredContrast:
    return CssPreferredContrast.auto

## PageClient::preferred_motion of the test client.
func test_page_client_preferred_motion(this: PageClient*) -> CssPreferredMotion:
    return CssPreferredMotion.auto

## PageClient::is_headless of the test client.
func test_page_client_is_headless(this: PageClient*) -> bool:
    return true

## PageClient::display_list_player_type of the test client: the CPU player (phase 1 has no
## GPU player).
func test_page_client_display_list_player_type(this: PageClient*) -> DisplayListPlayerType:
    return DisplayListPlayerType.skia_cpu

## PageClient::request_frame of the test client.
func test_document_request_frame(this: PageClient*):
    test_document_client_log.frames_requested += 1

## PageClient::page_did_change_title of the test client.
func test_document_page_did_change_title(this: PageClient*, title: ak.Utf16String):
    test_document_client_log.titles_changed += 1

## PageClient::palette of the test client (region r51b: recording a display list asks it): WebContent's
## PageClient::setup_palette, a zeroed system theme with magenta and cyan window colors, as the web_test worker's.
func test_page_client_palette(this: PageClient*) -> gfx.Palette:
    return test_palette()

## WebContent's PageClient::setup_palette as a palette.
func test_palette() -> gfx.Palette:
    let buffer = gfx.core_anonymous_buffer_create_with_size(memory.size_of(gfx.SystemTheme)) else trap("VERIFY: the theme buffer")
    let theme = (gfx.SystemTheme*)(gfx.core_anonymous_buffer_data(&buffer) else trap("VERIFY: the theme buffer"))
    let magenta = gfx.color_new_named_color(gfx.ColorNamedColor.magenta)
    let cyan = gfx.color_new_named_color(gfx.ColorNamedColor.cyan)
    theme.color[(i32)gfx.ColorRole.window] = gfx.color_value(&magenta)
    theme.color[(i32)gfx.ColorRole.window_text] = gfx.color_value(&cyan)
    var palette: gfx.Palette = ---
    gfx.palette_construct(&palette, gfx.palette_impl_create_with_anonymous_buffer(buffer))
    return palette

## The vtable of the test PageClient: PageClient's, with the client queries a page asks in
## phase 1, request_frame and page_did_change_title.
let test_page_client_vtable: PageClientVTable = PageClientVTable(cell_vtable = JsCellVTable(cell_vtable = gc.CellVTable(class_info = &test_page_client_class, visit_edges = test_page_client_visit_edges)), id = test_page_client_id, page = test_page_client_page, page_const = test_page_client_page, is_connection_open = test_page_client_is_connection_open, zoom_level = test_page_client_one, device_pixel_ratio = test_page_client_one, device_pixels_per_css_pixel = test_page_client_one, preferred_color_scheme = test_page_client_preferred_color_scheme, preferred_contrast = test_page_client_preferred_contrast, preferred_motion = test_page_client_preferred_motion, request_frame = test_document_request_frame, page_did_change_title = test_document_page_did_change_title, display_list_player_type = test_page_client_display_list_player_type, is_headless = test_page_client_is_headless, palette = test_page_client_palette)

## The class of the test PageClient (PageClient's class id).
let test_page_client_class: ak.ClassInfo = ak.ClassInfo(name = "TestPageClient", first_id = 316, last_id = 316, size = memory.size_of(TestPageClient), vtable = (const void*)&test_page_client_vtable)

# mark: Pages and documents =====================================================================

## The EventLoopPlugin of web_test_install_event_loop_plugin.
var web_test_event_loop_plugin: PlatformEventLoopPlugin

## Installs an EventLoopPlugin over the Core event loop (tests_platform's install_test_event_loop),
## as the embedder does; web_test_remove_event_loop_plugin removes it.
func web_test_install_event_loop_plugin():
    platform_s_the_2 = none
    platform_event_loop_plugin_install(&web_test_event_loop_plugin)

## The end of web_test_install_event_loop_plugin.
func web_test_remove_event_loop_plugin():
    platform_s_the_2 = none

## A Page in `vm`'s heap made by Page::create, with a test PageClient in the heap; the client
## log is reset. Nothing keeps it alive but what refers to it (an embedder's client holds its
## page: hold it, or give it to a realm's HostDefined as web_test_create_settings_realm does).
func web_test_create_page(vm: Vm*) -> Page*:
    test_document_client_log = TestDocumentClientLog(frames_requested = 0, titles_changed = 0)
    let heap = vm_heap(vm)
    let client = (TestPageClient*)web_heap_allocate_cell(heap, &test_page_client_class)
    gc.heap_defer_gc(heap)
    let page = page_create(vm, &client.page_client)
    client.m_page = page
    gc.heap_undefer_gc(heap)
    return page

## A Document as Document::create(realm, about:blank) makes it, in a realm of
## web_test_create_settings_realm: in the heap, through Document's constructor (its style
## computer, font computer, FontFaceSet, style scope, the realm's page, registered with the main
## thread event loop) and Document::initialize (its list of available images). An XML document
## as C++ makes it (`type_` html makes it an HTML document, as HTMLDocument::create would; r27
## owns HTMLDocument). The test fonts are installed first (tests_fonts' test_fonts_setup), as an
## embedder installs its FontPlugin.
func web_test_create_document(realm: Realm*, type_: DocumentDomDocumentType = DocumentDomDocumentType.xml) -> DomDocument*:
    test_fonts_setup()
    let document = dom_document_create(realm, web_url.about_blank())
    dom_document_set_document_type(document, type_)
    return document

## A VM with an agent, a principal realm and a document of web_test_create_document, for one test.
func web_test_create_vm_realm_and_document() -> (Vm*, Realm*, DomDocument*):
    let (vm, realm) = web_test_create_vm_and_settings_realm()
    return (vm, realm, web_test_create_document(realm))

# mark: Where Document::create and create_and_initialize stop ===================================

## Whether the stub fragment `stub_file` (of src/web/stubs/) still traps
## `unported: <cpp_name>` (or `unported (P2): <cpp_name>`, P3, P4). A trap cannot be caught, so
## the tests assert the stops this way: once the owning region ports the function, its stub is
## gone and the test fails, telling that region to extend the scenario past it.
func test_page_still_unported(stub_file: str, cpp_name: str) -> bool:
    var path = ak.string_builder_new()
    ak.string_builder_append(&path, "src/web/stubs/")
    ak.string_builder_append(&path, stub_file)
    let path_string = ak.string_builder_to_string_without_validation(&path)
    # (The stub fragments are larger than a test's fixed buffer: read into the C heap.)
    var source: web_fonts.FontData*? = none
    with memory.heap:
        source = web_fonts.font_data_create_from_file(ak.string_view_text(ak.string_bytes_as_string_view(&path_string)))
    let text = ak.string_view_from_bytes(web_fonts.font_data_bytes(source else trap("cannot read the stub fragment")))
    let prefixes: str[4] = ["trap(\"unported: ", "trap(\"unported (P2): ", "trap(\"unported (P3): ", "trap(\"unported (P4): "]
    for prefix in prefixes:
        var needle = ak.string_builder_new()
        ak.string_builder_append(&needle, prefix)
        ak.string_builder_append(&needle, cpp_name)
        ak.string_builder_append(&needle, "\")")
        let needle_string = ak.string_builder_to_string_without_validation(&needle)
        if ak.string_view_contains_string_view(&text, ak.string_bytes_as_string_view(&needle_string)):
            return true
    return false

test "Document::create completes":
    # Document::create runs Document's constructor in full (style computer, font computer,
    # FontFaceSet with its JS::Set and ready promise, CSS parsing params, the style scope, the
    # cursor blink timer, the event loop registration) and initialize: its list of available
    # images (r26), page_did_create_new_document and the cookie version index.
    web_initialize_strings()
    let (vm, realm, document) = web_test_create_vm_realm_and_document()
    defer web_test_destroy_vm(vm)
    let images = dom_document_list_of_available_images(document)
    assert(ak.hash_map_is_empty(&images.m_images))

    # Document::create_and_initialize runs end to end since region r28 (html/tests_html_browsing).

test "a document as Document::create makes it: in the heap, with its computers, FontFaceSet and page":
    web_initialize_strings()
    let (vm, realm, document) = web_test_create_vm_realm_and_document()
    defer web_test_destroy_vm(vm)
    assert(document.m_page == bind_principal_host_defined_page(realm))
    assert(dom_document_page(document) == bind_principal_host_defined_page(realm))
    assert(test_string_is(dom_document_content_type(document), "application/xml"))
    assert(test_string_is(dom_document_url_string(document), "about:blank"))
    assert(document.m_cookie_version_index == none)

    # The FontFaceSet: empty set entries (a JS::Set), "loaded" (the C++ default), pending on the
    # environment, its ready promise pending.
    let fonts = document.m_fonts
    assert(js_set_set_size(css_font_face_set_set_entries(fonts)) == 0)
    assert(css_font_face_set_status(fonts) == BindFontFaceSetLoadStatus.loaded)
    assert(fonts.m_is_pending_on_the_environment)
    assert(not idl_is_promise_fulfilled(css_font_face_set_ready(fonts)))
    assert(js_object_shape_realm((JsObject*)css_font_face_set_set_entries(fonts)) == realm)

    # No longer pending on the environment with no fonts loading, the set switches to loaded and
    # fulfills its ready promise with itself (a microtask then runs its reactions).
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    css_font_face_set_set_is_pending_on_the_environment(fonts, false)
    html_temporary_execution_context_destruct(&execution_context)
    let ready = css_font_face_set_ready(fonts)
    assert(idl_is_promise_fulfilled(ready))
    assert(js_value_as_object(js_promise_result(as_js_promise((gc.Cell*)js_promise_capability_promise(ready)))) == (JsObject*)fonts)

    # Registered with the main thread event loop, as Document::Document's last step does.
    let documents = html_event_loop_documents_in_this_event_loop_matching(html_main_thread_event_loop(), ak.Function1[DomDocument*, bool](call = test_html_any_document, context = none))
    assert(ak.vector_size(&documents) == 1)

    # An element made by create_element (a plain Element outside the HTML namespace) joins it.
    let element = dom_create_element(document, ak.fly_string_from_str("item"), none) else trap("create_element failed")
    _ = dom_node_append_child(document.dom_node(), element.dom_node()) else trap("append_child failed")
    assert(dom_document_document_element(document) == element)

test "a style sheet with @font-face rules loads its fonts into the document's FontFaceSet":
    web_initialize_strings()
    let test_loop = install_test_event_loop()
    web_test_install_event_loop_plugin()
    defer web_test_remove_event_loop_plugin()
    let (vm, realm, document) = web_test_create_vm_realm_and_document()
    defer web_test_destroy_vm(vm)
    let fonts = document.m_fonts
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)

    # StyleSheetList's "create a CSS style sheet" (a <style> element's path): adding the sheet runs
    # FontComputer::load_fonts_from_sheet, which makes a CSS-connected FontFace (with its status
    # promise) per valid @font-face rule and adds it to the FontFaceSet's entries (a JS::Set).
    let css = ak.string_from_str("@font-face { font-family: Remote; src: url(remote.ttf); } @font-face { font-family: Ranged; src: url(ranged.ttf); unicode-range: U+0100-017F; }")
    _ = css_style_sheet_list_create_a_css_style_sheet(dom_document_style_sheets(document), css, ak.string_from_str("text/css"), none, ak.string_from_str(""), ak.string_from_str(""), CssStyleSheetListAlternate.no, CssStyleSheetListOriginClean.yes, none, none, none)
    var entries = js_set_values(css_font_face_set_set_entries(fonts))
    assert(ak.vector_size(&entries) == 2)
    let remote = as_css_font_face((gc.Cell*)js_value_as_object(*ak.vector_at(&entries, 0)))
    let ranged = as_css_font_face((gc.Cell*)js_value_as_object(*ak.vector_at(&entries, 1)))
    assert(css_font_face_is_css_connected(remote) and css_font_face_is_css_connected(ranged))
    assert(test_string_is(css_font_face_family(remote), "Remote"))

    # The face without a unicode-range starts loading (FontFace::load, its fetch is phase 2 and
    # waits on the event loop plugin), which switches the set to "loading"; the ranged face is only
    # registered with the font computer until a rendered code point needs it.
    assert(css_font_face_status(remote) == BindFontFaceLoadStatus.loading)
    assert(css_font_face_status(ranged) == BindFontFaceLoadStatus.unloaded)
    assert(css_font_face_set_status(fonts) == BindFontFaceSetLoadStatus.loading)
    assert(ak.vector_size(css_font_face_set_loading_fonts(fonts)) == 1)
    assert(not idl_is_promise_fulfilled(css_font_face_font_status_promise(remote)))
    html_temporary_execution_context_destruct(&execution_context)
    # FontFace::load's steps wait for the loop to run its deferred invocation.
    assert(test_loop.deferred != none)

# mark: Collections =============================================================================

test "Page::visit_edges: a heap page keeps its client, and both go when nothing refers to them":
    web_test_clobber_stack()
    run_page_collection()

## A heap page held by the root the caller gets, and weak references to it and its client.
noinline func make_test_page(vm: Vm*) -> (gc.Root[Page], gc.Weak[Page], gc.Weak[PageClient]):
    let page = web_test_create_page(vm)
    return (gc.root_create(page), gc.make_weak(page), gc.make_weak(page_client(page)))

noinline func run_page_collection():
    let vm = web_test_create_vm()
    var (root, weak_page, weak_client) = make_test_page(vm)
    web_test_clobber_stack()
    gc.heap_collect_garbage(vm_heap(vm))
    assert(web_test_alive(&weak_page))
    assert(web_test_alive(&weak_client))
    gc.root_release(&root)
    web_test_clobber_stack()
    gc.heap_collect_garbage(vm_heap(vm))
    assert(not web_test_alive(&weak_page))
    assert(not web_test_alive(&weak_client))
    web_test_destroy_vm(vm)

test "a full collection marks a heap page, its document, elements and FontFaceSet, and frees the document after":
    web_test_clobber_stack()
    run_document_collection()

## What make_test_document_graph made: the root of the document and weak references to the rest.
struct TestDocumentGraph:
    var root: gc.Root[DomDocument]
    var page: gc.Weak[Page]
    var element: gc.Weak[DomElement]
    var text: gc.Weak[DomText]
    var fonts: gc.Weak[CssFontFaceSet]
    var set_entries: gc.Weak[JsSet]
    var ready_promise: gc.Weak[JsPromiseCapability]
    var font_face: gc.Weak[CssFontFace]

## A document with an element, a text node and a FontFace in its FontFaceSet, made with managed
## memory as the current allocator (as when the embedder runs the event loop `with heap`).
noinline func make_test_document_graph(vm: Vm*, realm: Realm*) -> TestDocumentGraph:
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let document = web_test_create_document(realm)
        let element = dom_create_element(document, ak.fly_string_from_str("item"), none) else trap("create_element failed")
        _ = dom_node_append_child(document.dom_node(), element.dom_node()) else trap("append_child failed")
        let text = test_text(realm, document, "words")
        _ = dom_node_append_child(element.dom_node(), text.dom_node()) else trap("append_child failed")
        let font_face = test_fonts_face(realm)
        css_font_face_set_add_css_connected_font(document.m_fonts, font_face)
        return TestDocumentGraph(root = gc.root_create(document), page = gc.make_weak(dom_document_page(document)), element = gc.make_weak(element), text = gc.make_weak(text), fonts = gc.make_weak(document.m_fonts), set_entries = gc.make_weak(css_font_face_set_set_entries(document.m_fonts)), ready_promise = gc.make_weak(css_font_face_set_ready(document.m_fonts)), font_face = gc.make_weak(font_face))

noinline func run_document_collection():
    let (vm, realm) = web_test_create_vm_and_settings_realm()
    var graph = make_test_document_graph(vm, realm)
    web_test_clobber_stack()
    gc.heap_collect_garbage(vm_heap(vm))
    assert(web_test_alive(&graph.page))
    assert(web_test_alive(&graph.element))
    assert(web_test_alive(&graph.text))
    assert(web_test_alive(&graph.fonts))
    assert(web_test_alive(&graph.set_entries))
    assert(web_test_alive(&graph.ready_promise))
    assert(web_test_alive(&graph.font_face))

    # Without its root the document goes, and with it what only it held (its finalize
    # unregisters it from the event loop); the page stays with the realm.
    gc.root_release(&graph.root)
    web_test_clobber_stack()
    gc.heap_collect_garbage(vm_heap(vm))
    assert(web_test_alive(&graph.page))
    assert(not web_test_alive(&graph.element))
    assert(not web_test_alive(&graph.fonts))
    assert(not web_test_alive(&graph.set_entries))
    assert(not web_test_alive(&graph.font_face))
    let documents = html_event_loop_documents_in_this_event_loop_matching(html_main_thread_event_loop(), ak.Function1[DomDocument*, bool](call = test_html_any_document, context = none))
    assert(ak.vector_is_empty(&documents))
    web_test_destroy_vm(vm)