Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / loader / generated_pages_loader.lucb

#==============================================================================================
#
#   generated_pages_loader - the error page and a file directory's index page, made from the
#   templates under resource://ladybird/templates
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp (lines 19-71). The templates
#       are Ladybird's (the repository's copy is data/res/ladybird/templates, the resource root
#       the tests install). AK's SourceGenerator, which fills a template's %key% placeholders,
#       is not in the pinned foundation: what the two pages use of it (set, get, append) is
#       ported here as the private PagesSourceGenerator.
#
#       Copyright (c) 2023, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: SourceGenerator =========================================================================

## AK::SourceGenerator (AK/SourceGenerator.h:19) over a StringBuilder, with its mapping of keys to
## values, the opening and closing delimiters and the escape character.
struct PagesSourceGenerator:
    var m_builder: ak.StringBuilder*
    var m_keys: ak.Vector[ak.ByteString]
    var m_values: ak.Vector[ak.String]
    var m_opening: u8
    var m_closing: u8
    var m_escape: u8

## Ported from AK/SourceGenerator.h:25 AK::SourceGenerator::SourceGenerator.
func pages_source_generator_create(builder: ak.StringBuilder*, opening: u8, closing: u8, escape: u8 = '\\') -> PagesSourceGenerator:
    return PagesSourceGenerator(m_builder = builder, m_opening = opening, m_closing = closing, m_escape = escape)

## Ported from AK/SourceGenerator.h:48 AK::SourceGenerator::set.
func pages_source_generator_set(this: PagesSourceGenerator*, key: ak.StringView, value: ak.String):
    if ak.string_view_find_u8(&key, this.m_opening) != none or ak.string_view_find_u8(&key, this.m_closing) != none:
        ak.dbgln("SourceGenerator keys cannot contain the opening/closing delimiters. (Keys are only wrapped in these when using them, not when setting them.)")
        trap("VERIFY_NOT_REACHED")
    # m_mapping.set(key, move(value))
    for index in 0..<ak.vector_size(&this.m_keys):
        let existing = ak.byte_string_view(ak.vector_at_const(&this.m_keys, index))
        if ak.string_view_eq_string_view(&existing, key):
            *ak.vector_at(&this.m_values, index) = value
            return
    ak.vector_append_t(&this.m_keys, ak.byte_string_from_string_view(key))
    ak.vector_append_t(&this.m_values, value)

## Ported from AK/SourceGenerator.h:57 AK::SourceGenerator::get.
func pages_source_generator_get(this: const PagesSourceGenerator*, key: ak.StringView) -> ak.String:
    for index in 0..<ak.vector_size(&this.m_keys):
        let existing = ak.byte_string_view(ak.vector_at_const(&this.m_keys, index))
        if ak.string_view_eq_string_view(&existing, key):
            return *ak.vector_at_const(&this.m_values, index)
    ak.dbgln(f"No key named `{ak.string_view_text(key)}` set on SourceGenerator")
    trap("VERIFY_NOT_REACHED")

## Ported from AK/SourceGenerator.h:71 AK::SourceGenerator::append.
func pages_source_generator_append(this: PagesSourceGenerator*, pattern: ak.StringView):
    let bytes = ak.string_view_bytes(&pattern)
    var position: usize = 0

    while position < bytes.length:
        # m_builder.append(lexer.consume_until([&](char ch) { return ch == m_opening || ch == m_escape; }))
        let start = position
        while position < bytes.length and bytes[position] != this.m_opening and bytes[position] != this.m_escape:
            position += 1
        ak.string_builder_append_string_view(this.m_builder, ak.string_view_from_bytes(bytes[start..<position]))
        if position < bytes.length and bytes[position] == this.m_escape:
            position += 1
            if not (position < bytes.length and (bytes[position] == this.m_opening or bytes[position] == this.m_escape)):
                if position >= bytes.length:
                    ak.dbgln("Unexpected EOF while parsing escape sequence on SourceGenerator")
                else:
                    ak.dbgln("Invalid escape sequence found on SourceGenerator")

                trap("VERIFY_NOT_REACHED")

            ak.string_builder_append_u8(this.m_builder, bytes[position])
            position += 1
            continue

        if position < bytes.length and bytes[position] == this.m_opening:
            position += 1
            let placeholder_start = position
            while position < bytes.length and bytes[position] != this.m_closing:
                position += 1
            let placeholder = ak.string_view_from_bytes(bytes[placeholder_start..<position])

            if position >= bytes.length:
                trap("VERIFY_NOT_REACHED")
            position += 1

            let value = pages_source_generator_get(this, placeholder)
            ak.string_builder_append_string_view(this.m_builder, ak.string_bytes_as_string_view(&value))
        else:
            assert(position >= bytes.length)

## `generator.set(key, ByteString value)` (SourceGenerator.h's deprecated ByteString overload).
func pages_source_generator_set_byte_string(this: PagesSourceGenerator*, key: ak.StringView, value: ak.ByteString):
    pages_source_generator_set(this, key, ak.string_from_byte_string(value) else trap("MUST: String::from_byte_string"))

# mark: The pages ===============================================================================

## Ported from Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp:19 Web::load_error_page.
pub func load_error_page(url: web_url.Url, error_message: ak.StringView) -> ak.String!:
    # Generate HTML error page from error template file
    # FIXME: Use an actual templating engine (our own one when it's built, preferably with a way to check these usages at compile time)
    let template_file = try core_resource_load_from_uri(ak.sv("resource://ladybird/templates/error.html"))
    var builder = ak.string_builder_new()
    var generator = pages_source_generator_create(&builder, '%', '%')
    let failed_url = web_url.url_to_byte_string(&url)
    pages_source_generator_set_byte_string(&generator, ak.sv("failed_url"), ak.escape_html_entities(ak.byte_string_view(&failed_url)))
    pages_source_generator_set_byte_string(&generator, ak.sv("error_message"), ak.escape_html_entities(error_message))
    pages_source_generator_append(&generator, ak.string_view_from_bytes(core_resource_data(template_file)))
    return try ak.string_from_utf8(ak.string_builder_string_view(&builder))

## The comparator of load_file_directory_page's quick_sort: ByteString's operator<.
func load_file_directory_page_name_less_than(context: void*?, a: const ak.ByteString*, b: const ak.ByteString*) -> bool:
    return ak.byte_string_lt(a, b)

## Ported from Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp:32 Web::load_file_directory_page.
pub func load_file_directory_page(url: web_url.Url) -> ak.String!:
    # Generate HTML contents entries table
    let lexical_path = ak.lexical_path_new(web_url.url_file_path(&url))
    let lexical_path_string = ak.lexical_path_string(&lexical_path)
    # Core::DirIterator: a directory that cannot be read has no entries.
    var names: ak.Vector[ak.ByteString] = core_dir_iterator_names(ak.byte_string_view(&lexical_path_string)) catch:
        recover ak.Vector[ak.ByteString]()
    ak.quick_sort_t_collection_t_less_than(ak.vector_span(&names), ak.Function2[const ak.ByteString*, const ak.ByteString*, bool](call = load_file_directory_page_name_less_than, context = none))

    var contents = ak.string_builder_new()
    ak.string_builder_append(&contents, "<table>")
    for name in ak.vector_span_const(&names):
        let path = ak.lexical_path_append(&lexical_path, ak.byte_string_view(&name))
        let path_string = ak.lexical_path_string(&path)
        let maybe_st: std_files.Metadata? = core_system_stat(ak.byte_string_view(&path_string)) catch:
            recover none
        if let st = maybe_st:
            let is_directory = core_system_is_directory(&st)

            ak.string_builder_append(&contents, "<tr>")
            ak.string_builder_append(&contents, "<td><span class=\"")
            ak.string_builder_append(&contents, "folder" if is_directory else "file")
            ak.string_builder_append(&contents, "\"></span></td>")
            ak.string_builder_append(&contents, "<td><a href=\"file://")
            ak.string_builder_append_string_view(&contents, ak.byte_string_view(&path_string))
            ak.string_builder_append(&contents, "\">")
            ak.string_builder_append_string_view(&contents, ak.byte_string_view(&name))
            ak.string_builder_append(&contents, "</a></td><td>&nbsp;</td>")
            # "<td>{:10}</td><td>&nbsp;</td>": the size, padded to ten characters (left-aligned, as AK formats strings).
            let size = ak.string_from_str("-") if is_directory else ak.human_readable_size((u64)st.size)
            let size_view = ak.string_bytes_as_string_view(&size)
            ak.string_builder_append(&contents, "<td>")
            ak.string_builder_append_string_view(&contents, size_view)
            let size_length = ak.string_view_length(&size_view)
            if size_length < 10:
                ak.string_builder_append_repeated_u8(&contents, ' ', 10 - size_length)
            ak.string_builder_append(&contents, "</td><td>&nbsp;</td>")
            let modified = ak.unix_date_time_from_seconds_since_epoch(st.modified.seconds)
            let modified_text = ak.unix_date_time_to_byte_string(&modified, ak.sv("%Y-%m-%d %H:%M:%S"))
            ak.string_builder_append(&contents, "<td>")
            ak.string_builder_append_string_view(&contents, ak.byte_string_view(&modified_text))
            ak.string_builder_append(&contents, "</td>")
            ak.string_builder_append(&contents, "</tr>\n")
    ak.string_builder_append(&contents, "</table>")

    # Generate HTML directory page from directory template file
    # FIXME: Use an actual templating engine (our own one when it's built, preferably with a way to check these usages at compile time)
    let template_file = try core_resource_load_from_uri(ak.sv("resource://ladybird/templates/directory.html"))
    var builder = ak.string_builder_new()
    var generator = pages_source_generator_create(&builder, '%', '%')
    pages_source_generator_set_byte_string(&generator, ak.sv("path"), ak.escape_html_entities(ak.byte_string_view(&lexical_path_string)))
    let parent = ak.lexical_path_parent(&lexical_path)
    let parent_string = ak.lexical_path_string(&parent)
    let escaped_parent = ak.escape_html_entities(ak.byte_string_view(&parent_string))
    var parent_url = ak.string_builder_new()
    ak.string_builder_append(&parent_url, "file://")
    ak.string_builder_append_string_view(&parent_url, ak.byte_string_view(&escaped_parent))
    pages_source_generator_set(&generator, ak.sv("parent_url"), try ak.string_builder_to_string(&parent_url))
    pages_source_generator_set_byte_string(&generator, ak.sv("contents"), ak.string_builder_to_byte_string(&contents))
    pages_source_generator_append(&generator, ak.string_view_from_bytes(core_resource_data(template_file)))
    return try ak.string_from_utf8(ak.string_builder_string_view(&builder))