Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / external / lib_core / resource.lucb

#==============================================================================================
#
#   resource - Core::Resource: a file or directory named by a file:// or resource:// URI, and
#   the resource implementation that finds resource:// files under a base directory
#
#   DESCRIPTION:
#       Port of Libraries/LibCore/Resource.cpp (lines 13-115) with the inline functions of
#       Resource.h (lines 26-90), ResourceImplementation.cpp (lines 14-89) and
#       ResourceImplementationFile.cpp (lines 15-53): the LibCore seam of DESIGN.md §7.1 over
#       luce-std (system.lucb). ResourceImplementationFile, the one implementation, is the
#       CoreResourceImplementation struct; its pure virtuals are its functions. The embedder
#       installs it with the directory resource:// names (Ladybird's install directory's
#       share/Lagom; the tests use the repository's data/res); without one it is "/res", as in
#       C++. A mapped file is read into a ByteBuffer, and Resource::stream (a
#       FixedMemoryStream nothing in the engine reads) is not ported.
#
#       Copyright (c) 2023, Andrew Kaster <akaster@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Resource ================================================================================

## Ported from Libraries/LibCore/Resource.cpp:13 Core::Resource::Resource (the MappedFile constructor).
pub func core_resource_construct_mapped_file(this: CoreResource*, path: ak.String, scheme: CoreResourceScheme, file: ak.ByteBuffer, modified_time: i64):
    this.m_path = path
    this.m_scheme = scheme
    this.m_data = CoreResourceData.mapped_file
    this.m_bytes = file
    this.m_modified_time = modified_time

## Ported from Libraries/LibCore/Resource.cpp:21 Core::Resource::Resource (the ByteBuffer constructor).
pub func core_resource_construct_byte_buffer(this: CoreResource*, path: ak.String, scheme: CoreResourceScheme, buffer: ak.ByteBuffer, modified_time: i64):
    this.m_path = path
    this.m_scheme = scheme
    this.m_data = CoreResourceData.byte_buffer
    this.m_bytes = buffer
    this.m_modified_time = modified_time

## Ported from Libraries/LibCore/Resource.cpp:29 Core::Resource::Resource (the DirectoryTag constructor).
pub func core_resource_construct_directory_tag(this: CoreResource*, path: ak.String, scheme: CoreResourceScheme, modified_time: i64):
    this.m_path = path
    this.m_scheme = scheme
    this.m_data = CoreResourceData.directory_tag
    this.m_modified_time = modified_time

## `adopt_ref(*new Resource(...))`: a resource whose members the constructor sets.
func core_resource_new() -> CoreResource*:
    return new CoreResource(m_path = ak.String(), m_scheme = CoreResourceScheme.file, m_data = CoreResourceData.directory_tag, m_modified_time = 0) else trap("out of memory")

## Ported from Libraries/LibCore/Resource.cpp:37 Core::Resource::load_from_filesystem.
pub func core_resource_load_from_filesystem(path: ak.StringView) -> CoreResource*!:
    var filepath = ak.lexical_path_new(ak.byte_string_from_string_view(path))

    if ak.lexical_path_is_absolute(&filepath):
        let uri = core_resource_file_uri(path)
        return try core_resource_load_from_uri(ak.byte_string_view(&uri))

    let cwd = try core_system_getcwd()
    let prepended = ak.lexical_path_prepend(&filepath, ak.byte_string_view(&cwd))
    let prepended_string = ak.lexical_path_string(&prepended)
    let uri = core_resource_file_uri(ak.byte_string_view(&prepended_string))
    return try core_resource_load_from_uri(ak.byte_string_view(&uri))

## `String::formatted("file://{}", path)`.
func core_resource_file_uri(path: ak.StringView) -> ak.ByteString:
    var builder = ak.string_builder_new()
    ak.string_builder_append(&builder, "file://")
    ak.string_builder_append_string_view(&builder, path)
    return ak.string_builder_to_byte_string(&builder)

## Ported from Libraries/LibCore/Resource.cpp:48 Core::Resource::load_from_uri.
pub func core_resource_load_from_uri(uri: ak.StringView) -> CoreResource*!:
    return try core_resource_implementation_load_from_uri(core_resource_implementation_the(), uri)

## Ported from Libraries/LibCore/Resource.cpp:53 Core::Resource::uri.
pub func core_resource_uri(this: const CoreResource*) -> ak.String:
    var builder = ak.string_builder_new()
    ak.string_builder_append(&builder, "resource" if this.m_scheme == CoreResourceScheme.resource else "file")
    ak.string_builder_append(&builder, "://")
    ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&this.m_path))
    return ak.string_builder_to_string(&builder) else trap("MUST: String::formatted")

## Ported from Libraries/LibCore/Resource.cpp:58 Core::Resource::filesystem_path.
pub func core_resource_filesystem_path(this: const CoreResource*) -> ak.String:
    return core_resource_implementation_filesystem_path(core_resource_implementation_the(), this)

## Ported from Libraries/LibCore/Resource.cpp:63 Core::Resource::file_url.
pub func core_resource_file_url(this: const CoreResource*) -> ak.String:
    if this.m_scheme == CoreResourceScheme.file:
        return core_resource_uri(this)

    let filesystem_path = core_resource_filesystem_path(this)
    let uri = core_resource_file_uri(ak.string_bytes_as_string_view(&filesystem_path))
    return ak.string_from_utf8(ak.byte_string_view(&uri)) else trap("MUST: String::formatted")

## Ported from Libraries/LibCore/Resource.cpp:71 Core::Resource::modified_time.
pub func core_resource_modified_time(this: const CoreResource*) -> i64?:
    return this.m_modified_time

## Ported from Libraries/LibCore/Resource.cpp:76 Core::Resource::filename.
pub func core_resource_filename(this: const CoreResource*) -> ak.String:
    var path = ak.lexical_path_new(ak.string_to_byte_string(&this.m_path))
    return ak.string_from_utf8(ak.lexical_path_basename_lexical_path_strip_extension(&path)) else trap("MUST: String::from_utf8")

## Ported from Libraries/LibCore/Resource.cpp:81 Core::Resource::children.
pub func core_resource_children(this: const CoreResource*) -> ak.Vector[ak.String]:
    return core_resource_implementation_child_names(core_resource_implementation_the(), this)

## Ported from Libraries/LibCore/Resource.cpp:86 Core::Resource::clone_data.
pub func core_resource_clone_data(this: const CoreResource*) -> ak.ByteBuffer:
    return match this.m_data:
        .mapped_file => ak.byte_buffer_copy_span_u8(ak.byte_buffer_bytes_const(&this.m_bytes)) else trap("MUST: ByteBuffer::copy")
        .byte_buffer => ak.byte_buffer_clone(&this.m_bytes)
        _ => trap("VERIFY_NOT_REACHED")

## Ported from Libraries/LibCore/Resource.cpp:94 Core::Resource::release_data.
pub func core_resource_release_data(this: CoreResource*) -> ak.ByteBuffer:
    assert(core_resource_is_file(this))

    if this.m_data == CoreResourceData.mapped_file:
        return ak.byte_buffer_copy_span_u8(ak.byte_buffer_bytes_const(&this.m_bytes)) else trap("MUST: ByteBuffer::copy")
    # move(m_data).get<ByteBuffer>(): the buffer's storage is shared, as a move leaves nothing behind.
    return this.m_bytes

## Ported from Libraries/LibCore/Resource.cpp:103 Core::Resource::data.
pub func core_resource_data(this: const CoreResource*) -> const u8[]:
    if this.m_data == CoreResourceData.directory_tag:
        trap("VERIFY_NOT_REACHED")
    return ak.byte_buffer_bytes_const(&this.m_bytes)

## Ported from Libraries/LibCore/Resource.h:28 Core::Resource::is_file.
pub func core_resource_is_file(this: const CoreResource*) -> bool:
    return this.m_data != CoreResourceData.directory_tag

## Ported from Libraries/LibCore/Resource.h:29 Core::Resource::is_directory.
pub func core_resource_is_directory(this: const CoreResource*) -> bool:
    return not core_resource_is_file(this)

## Ported from Libraries/LibCore/Resource.h:70 Core::Resource::for_each_descendant: depth first, the callback
## answering whether to go on.
pub func core_resource_for_each_descendant(this: const CoreResource*, callback: ak.Function1[const CoreResource*, ak.IterationDecision]) -> ak.IterationDecision:
    let children = core_resource_children(this)
    let uri = core_resource_uri(this)
    for child in ak.vector_span_const(&children):
        var builder = ak.string_builder_new()
        ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&uri))
        ak.string_builder_append(&builder, "/")
        ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&child))
        let child_resource: CoreResource*? = core_resource_load_from_uri(ak.string_builder_string_view(&builder)) catch:
            recover none
        if let resource = child_resource:
            if ak.function1_call(&callback, resource) == ak.IterationDecision.break_:
                return ak.IterationDecision.break_
            if core_resource_for_each_descendant(resource, callback) == ak.IterationDecision.break_:
                return ak.IterationDecision.break_
    return ak.IterationDecision.continue_

## The callback of for_each_descendant_file: directories are passed over.
struct CoreResourceForEachDescendantFile:
    var callback: ak.Function1[const CoreResource*, ak.IterationDecision]

    static func call(context: void*?, resource: const CoreResource*) -> ak.IterationDecision:
        let captures = (CoreResourceForEachDescendantFile*)(context else trap("for_each_descendant_file: no captures"))
        if core_resource_is_directory(resource):
            return ak.IterationDecision.continue_
        return ak.function1_call(&captures.callback, resource)

## Ported from Libraries/LibCore/Resource.h:86 Core::Resource::for_each_descendant_file.
pub func core_resource_for_each_descendant_file(this: const CoreResource*, callback: ak.Function1[const CoreResource*, ak.IterationDecision]):
    var captures = CoreResourceForEachDescendantFile(callback = callback)
    _ = core_resource_for_each_descendant(this, ak.Function1[const CoreResource*, ak.IterationDecision](call = CoreResourceForEachDescendantFile.call, context = &captures))

# mark: ResourceImplementation ==================================================================

## Ported from Libraries/LibCore/ResourceImplementation.cpp:16 Core::ResourceImplementation::install. The
## implementation lives in the C heap for the process (DESIGN.md §3.3 rule 7).
pub func core_resource_implementation_install(the: CoreResourceImplementation*):
    core_resource_implementation_s_the = the

## Ported from Libraries/LibCore/ResourceImplementation.cpp:21 Core::ResourceImplementation::the.
pub func core_resource_implementation_the() -> CoreResourceImplementation*:
    if core_resource_implementation_s_the == none:
        core_resource_implementation_install(core_resource_implementation_file_create(ak.sv("/res")))
    return core_resource_implementation_s_the else trap("VERIFY_NOT_REACHED")

## Ported from Libraries/LibCore/ResourceImplementation.cpp:28 Core::ResourceImplementation::make_resource (the MappedFile one).
func core_resource_implementation_make_resource_mapped_file(full_path: ak.String, file: ak.ByteBuffer, modified_time: i64) -> CoreResource*:
    let resource = core_resource_new()
    core_resource_construct_mapped_file(resource, full_path, CoreResourceScheme.resource, file, modified_time)
    return resource

## Ported from Libraries/LibCore/ResourceImplementation.cpp:33 Core::ResourceImplementation::make_resource (the ByteBuffer one).
pub func core_resource_implementation_make_resource_byte_buffer(full_path: ak.String, buffer: ak.ByteBuffer, modified_time: i64) -> CoreResource*:
    let resource = core_resource_new()
    core_resource_construct_byte_buffer(resource, full_path, CoreResourceScheme.resource, buffer, modified_time)
    return resource

## Ported from Libraries/LibCore/ResourceImplementation.cpp:38 Core::ResourceImplementation::make_directory_resource.
func core_resource_implementation_make_directory_resource(full_path: ak.String, modified_time: i64) -> CoreResource*:
    let resource = core_resource_new()
    core_resource_construct_directory_tag(resource, full_path, CoreResourceScheme.resource, modified_time)
    return resource

## Ported from Libraries/LibCore/ResourceImplementation.cpp:43 Core::ResourceImplementation::load_from_uri.
pub func core_resource_implementation_load_from_uri(this: CoreResourceImplementation*, uri: ak.StringView) -> CoreResource*!:
    let file_scheme = ak.sv("file://")
    let resource_scheme = ak.sv("resource://")

    if ak.string_view_starts_with_string_view(&uri, resource_scheme):
        return try core_resource_implementation_file_load_from_resource_scheme_uri(this, uri)

    if ak.string_view_starts_with_string_view(&uri, file_scheme):
        let path = ak.string_view_substring_view(&uri, ak.string_view_length(&file_scheme))
        let utf8_path = try ak.string_from_utf8(path)
        let st = try core_system_stat(ak.string_bytes_as_string_view(&utf8_path))
        let resource = core_resource_new()
        if core_system_is_directory(&st):
            core_resource_construct_directory_tag(resource, utf8_path, CoreResourceScheme.file, st.modified.seconds)
            return resource
        let mapped_file = try core_mapped_file_map(path)
        core_resource_construct_mapped_file(resource, utf8_path, CoreResourceScheme.file, mapped_file, st.modified.seconds)
        return resource

    ak.dbgln(f"ResourceImplementation: Unknown scheme for {ak.string_view_text(uri)}")
    error(ak.ak_error, "Invalid scheme")

## Ported from Libraries/LibCore/ResourceImplementation.cpp:66 Core::ResourceImplementation::child_names.
pub func core_resource_implementation_child_names(this: CoreResourceImplementation*, resource: const CoreResource*) -> ak.Vector[ak.String]:
    if not core_resource_is_directory(resource):
        return ak.Vector[ak.String]()

    if resource.m_scheme == CoreResourceScheme.resource:
        return core_resource_implementation_file_child_names_for_resource_scheme(this, resource)

    assert(resource.m_scheme == CoreResourceScheme.file)

    let filesystem_path = core_resource_filesystem_path(resource)
    return core_resource_directory_children(ak.string_bytes_as_string_view(&filesystem_path))

## `Core::DirIterator it(path, SkipParentAndBaseDir)` and `children.append(String::from_byte_string(it.next_path()))`
## for each entry: the names in a directory, none when it cannot be read.
func core_resource_directory_children(path: ak.StringView) -> ak.Vector[ak.String]:
    var children: ak.Vector[ak.String]
    let names: ak.Vector[ak.ByteString] = core_dir_iterator_names(path) catch:
        recover ak.Vector[ak.ByteString]()
    for name in ak.vector_span_const(&names):
        ak.vector_append_t(&children, ak.string_from_byte_string(name) else trap("MUST: String::from_byte_string"))
    return children

## Ported from Libraries/LibCore/ResourceImplementation.cpp:82 Core::ResourceImplementation::filesystem_path.
pub func core_resource_implementation_filesystem_path(this: CoreResourceImplementation*, resource: const CoreResource*) -> ak.String:
    if resource.m_scheme == CoreResourceScheme.resource:
        return core_resource_implementation_file_filesystem_path_for_resource_scheme(this, &resource.m_path)

    assert(resource.m_scheme == CoreResourceScheme.file)

    return resource.m_path

# mark: ResourceImplementationFile ==============================================================

## Ported from Libraries/LibCore/ResourceImplementationFile.cpp:15 Core::ResourceImplementationFile::ResourceImplementationFile:
## an implementation over `base_directory`, made in the C heap (DESIGN.md §3.3 rule 7).
pub func core_resource_implementation_file_create(base_directory: ak.StringView) -> CoreResourceImplementation*:
    let saved_atomic_allocator = ak.atomic_allocator
    ak.atomic_allocator = none
    defer ak.atomic_allocator = saved_atomic_allocator
    with memory.heap:
        let base = ak.string_from_utf8(base_directory) else trap("MUST: String::from_utf8")
        return new CoreResourceImplementation(m_base_directory = base) else trap("out of memory")

## Ported from Libraries/LibCore/ResourceImplementationFile.cpp:20 Core::ResourceImplementationFile::load_from_resource_scheme_uri (override).
func core_resource_implementation_file_load_from_resource_scheme_uri(this: CoreResourceImplementation*, uri: ak.StringView) -> CoreResource*!:
    let resource_scheme = ak.sv("resource://")

    assert(ak.string_view_starts_with_string_view(&uri, resource_scheme))

    let path = try ak.string_from_utf8(ak.string_view_substring_view(&uri, ak.string_view_length(&resource_scheme)))
    let full_path_string = core_resource_implementation_file_join(this, &path)
    let full_path = ak.string_bytes_as_string_view(&full_path_string)

    let st = try core_system_stat(full_path)

    if core_system_is_directory(&st):
        return core_resource_implementation_make_directory_resource(path, st.modified.seconds)

    return core_resource_implementation_make_resource_mapped_file(path, try core_mapped_file_map(full_path), st.modified.seconds)

## Ported from Libraries/LibCore/ResourceImplementationFile.cpp:38 Core::ResourceImplementationFile::child_names_for_resource_scheme (override).
func core_resource_implementation_file_child_names_for_resource_scheme(this: CoreResourceImplementation*, resource: const CoreResource*) -> ak.Vector[ak.String]:
    let filesystem_path = core_resource_filesystem_path(resource)
    return core_resource_directory_children(ak.string_bytes_as_string_view(&filesystem_path))

## Ported from Libraries/LibCore/ResourceImplementationFile.cpp:48 Core::ResourceImplementationFile::filesystem_path_for_resource_scheme (override).
func core_resource_implementation_file_filesystem_path_for_resource_scheme(this: CoreResourceImplementation*, relative_path: const ak.String*) -> ak.String:
    return core_resource_implementation_file_join(this, relative_path)

## `String::from_byte_string(LexicalPath::join(m_base_directory, path).string())`.
func core_resource_implementation_file_join(this: CoreResourceImplementation*, path: const ak.String*) -> ak.String:
    let rest: ak.StringView[1] = [ak.string_bytes_as_string_view(path)]
    let joined = ak.lexical_path_join(ak.string_bytes_as_string_view(&this.m_base_directory), rest)
    return ak.string_from_byte_string(ak.lexical_path_string(&joined)) else trap("MUST: String::from_byte_string")