Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / webview_api / api.lucb

#==============================================================================================
#
#   api - the functions an application calls
#
#   DESCRIPTION:
#       The face of the module for an application, written for Luce's Base boundary: a view is
#       a handle (Luce sees a class whose close() destroys it), and every function takes and
#       answers scalars, text, the WebViewEvent enum or the handle, so a Luce program can call
#       each one once per event or frame (the module's own types, with pointers and engine
#       structs, stay Base's). Each call runs with the main thread VM's heap as the current
#       allocator. Coordinates are the widget's logical points; the view scales them by its
#       device pixel ratio, as WebViewBridge::to_content_position does. Mouse buttons are
#       UIEvents::MouseButton masks (primary 1, secondary 2, middle 4, back 8, forward 16),
#       modifiers UIEvents::KeyModifier masks (alt 1, ctrl 2, shift 4, super 8), keys
#       UIEvents::KeyCode values.
#
#       A Base embedder (an application's own .lucb) also has webview_copy_frame through
#       copy_frame, which writes into a buffer it owns.
#
#       Copyright (c) 2026 the luce-browser authors.
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: The process =============================================================================

## A view: one page in a widget of the application.
pub handle View:
    destroy close

## What a view reports: webview's WebViewEvent, case for case (an enum of this module, so that
## the module's description names no other).
pub enum Event as u8:
    none_ = 0
    load_started = 1
    load_finished = 2
    title_changed = 3
    url_changed = 4
    cursor_changed = 5
    link_hovered = 6
    link_unhovered = 7
    navigation_buttons_changed = 8
    frame_ready = 9

## Sets up the engine for this process (see platform.lucb): the resources it needs are written
## into `resource_directory`, then the fonts of the system are loaded. Once per process, on
## the thread that runs the application's loop.
pub func initialize(resource_directory: str) -> !:
    try webview.webview_initialize(resource_directory)

## The embedder's last call before it exits, after closing its views: ends what Ladybird's
## process exit ends (the font files the FontDatabase mapped), since the runtime requires every
## owned value to be released by then. Nothing of the engine may run afterwards.
pub func shutdown():
    web_fonts.core_mapped_file_release_all()

## Makes `hook` the event loop's wake-up (event_loop.lucb): a function that makes the
## application's loop stop waiting, such as luce-window's window.wake.
pub func set_wake(hook: func() -> unit):
    webview.webview_set_wake_hook(hook)

## Runs the engine's work that is due (tasks, timers, painting), never waiting and never longer
## than a slice. Answers how many events ran. Call it every turn of the application's loop.
pub func process_events() -> i64:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        return (i64)webview.webview_event_loop_process(webview.webview_event_loop())

## Seconds until the engine next has work: 0 when work is due, -1 when nothing is scheduled.
## The application's loop may sleep that long (input and the wake hook end it earlier).
pub func next_due() -> f64:
    let due = webview.webview_event_loop_next_due(webview.webview_event_loop()) else return -1.0
    let now = time.now()
    if due <= now:
        return 0.0
    return (f64)(due - now) / 1000000000.0

# mark: Sockets =================================================================================

## Hands the engine's sockets to an application whose loop watches descriptors itself (luce-ui's
## Application.watch), so its loop sleeps until one is ready instead of coming back every few
## milliseconds while sockets are open (next_due stops counting them). From then on the engine
## reports each socket whose wanted readiness changed (take_socket_change, the wake hook called
## when one is waiting); the application watches it to read when socket_readable, to write when
## socket_writable, or stops watching it when neither, and calls process_events when it is
## ready. Every socket open now is reported first.
pub func hand_over_sockets():
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_event_loop_hand_over_sockets(webview.webview_event_loop(), true)

## The next socket whose wanted readiness changed since it was last taken, -1 when none is.
pub func take_socket_change() -> i64:
    let fd = webview.webview_event_loop_take_socket_change(webview.webview_event_loop()) else return -1
    return (i64)fd

## Whether the engine waits for `descriptor` to be readable.
pub func socket_readable(descriptor: i64) -> bool:
    let kind = webview.webview_event_loop_socket_interest(webview.webview_event_loop(), (i32)descriptor)
    return web.core_notification_type_has(kind, web.CoreNotificationType.read)

## Whether the engine waits for `descriptor` to be writable.
pub func socket_writable(descriptor: i64) -> bool:
    let kind = webview.webview_event_loop_socket_interest(webview.webview_event_loop(), (i32)descriptor)
    return web.core_notification_type_has(kind, web.CoreNotificationType.write)

# mark: Views ===================================================================================

## The view behind a handle.
func api_view(view: View) -> webview.WebView*:
    return (webview.WebView*)(void*)view

## A view of `width` by `height` points at `device_pixel_ratio`, on about:blank.
pub func open(width: f64, height: f64, device_pixel_ratio: f64) -> View:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let view = webview.webview_create(api_device_size(width, height, device_pixel_ratio), device_pixel_ratio)
        return (View)(void*)view

## Shows or hides the view, as a tab switched to or from is (ViewImplementation's
## set_system_visibility_state): a hidden view is not rendered and its page reports
## visibilityState "hidden", while its loads go on; shown, it paints at once. A new view is shown.
pub func set_visible(view: View, visible: bool):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let state = web.HtmlVisibilityState.visible if visible else web.HtmlVisibilityState.hidden
        webview.webview_set_system_visibility_state(api_view(view), state)

## Sets what the view's pages read as `prefers-color-scheme`: dark when `dark`, else light, as
## the browser passes the system's appearance (Ladybird's UI does the same on a theme change).
pub func set_dark(view: View, dark: bool):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let scheme = web.CssPreferredColorScheme.dark if dark else web.CssPreferredColorScheme.light
        webview.webview_set_preferred_color_scheme(api_view(view), scheme)

## Whether the view is shown (set_visible).
pub func is_visible(view: View) -> bool:
    return webview.webview_system_visibility_state(api_view(view)) == web.HtmlVisibilityState.visible

## Ends the view as a closed tab ends: its page's loads, tasks and timers stop and its documents
## are destroyed.
pub func close(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_destroy(api_view(view))

## The size in device pixels of `width` by `height` points (WebViewBridge's scale_for_device).
func api_device_size(width: f64, height: f64, device_pixel_ratio: f64) -> gfx.IntSize:
    return gfx.IntSize(m_width = (i32)math.max(1.0, width * device_pixel_ratio), m_height = (i32)math.max(1.0, height * device_pixel_ratio))

## Resizes the view to `width` by `height` points at `device_pixel_ratio`; the page lays out
## again.
pub func resize(view: View, width: f64, height: f64, device_pixel_ratio: f64):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_set_viewport(api_view(view), api_device_size(width, height, device_pixel_ratio), device_pixel_ratio)

## Loads what was typed in an address field: a file, a URL, a host, or else a search with the
## builtin engine called `search_engine` ("" for none). Text that is none of these loads
## LibWebView's error page. Answers whether it was a location.
pub func load(view: View, text: str, search_engine: str = "") -> bool:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let found = webview.webview_find_search_engine(search_engine)
        var engine: const webview.WebViewSearchEngine*? = none
        if let chosen = found:
            engine = &chosen
        if let url = webview.webview_sanitize_url(ak.sv(text), engine):
            webview.webview_load(api_view(view), url)
            return true
        webview.webview_load_navigation_error_page(api_view(view), ak.sv(text))
        return false

## Loads `url` exactly as it parses; answers false (and loads nothing) when it does not.
pub func load_url(view: View, url: str) -> bool:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let parsed = web_url.parser_basic_parse(ak.sv(url)) else return false
        webview.webview_load(api_view(view), parsed)
        return true

## Shows `html` as the page (about:srcdoc).
pub func load_html(view: View, html: str):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_load_html(api_view(view), ak.sv(html))

## Reloads the page.
pub func reload(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_reload(api_view(view))

## Stops loading.
pub func stop(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_stop(api_view(view))

## Goes back one step in the session history.
pub func go_back(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_traverse_the_history_by_delta(api_view(view), -1)

## Goes forward one step in the session history.
pub func go_forward(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_traverse_the_history_by_delta(api_view(view), 1)

# mark: Input ===================================================================================

## Sends a mouse event of `type_` (see webview_mouse_event).
func api_mouse(view: View, type_: web.MouseEventType, x: f64, y: f64, button: i64, buttons: i64, modifiers: i64, delta_x: i64, delta_y: i64, click_count: i64):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let event = webview.webview_mouse_event(api_view(view), type_, x, y, (u32)button, (u32)buttons, (u32)modifiers, (i32)delta_x, (i32)delta_y, (i32)click_count)
        webview.webview_enqueue_input_event(api_view(view), web.InputEvent.mouse_event(event))

## A button pressed at `x`, `y`; `click_count` counts the clicks of a double or triple click.
pub func mouse_down(view: View, x: f64, y: f64, button: i64, buttons: i64, modifiers: i64, click_count: i64):
    api_mouse(view, web.MouseEventType.mouse_down, x, y, button, buttons, modifiers, 0, 0, click_count)

## A button let go at `x`, `y`.
pub func mouse_up(view: View, x: f64, y: f64, button: i64, buttons: i64, modifiers: i64, click_count: i64):
    api_mouse(view, web.MouseEventType.mouse_up, x, y, button, buttons, modifiers, 0, 0, click_count)

## The pointer moved to `x`, `y` with `buttons` held.
pub func mouse_move(view: View, x: f64, y: f64, buttons: i64, modifiers: i64):
    api_mouse(view, web.MouseEventType.mouse_move, x, y, 0, buttons, modifiers, 0, 0, 0)

## The pointer left the view.
pub func mouse_leave(view: View):
    api_mouse(view, web.MouseEventType.mouse_leave, 0.0, 0.0, 0, 0, 0, 0, 0, 0)

## A wheel or trackpad scroll at `x`, `y` by `delta_x`, `delta_y` (positive scrolls the page
## right and down), in points as AppKit's scrolling deltas are; a notched wheel's lines are 24
## points each (ns_event_to_mouse_event's imprecise_scroll_multiplier).
pub func wheel(view: View, x: f64, y: f64, delta_x: f64, delta_y: f64, modifiers: i64):
    api_mouse(view, web.MouseEventType.mouse_wheel, x, y, 0, 0, modifiers, (i64)delta_x, (i64)delta_y, 0)

## A key pressed: a UIEvents::KeyCode, the modifiers, the character it types (0 for none).
pub func key_down(view: View, key: i64, modifiers: i64, code_point: i64, repeat: bool):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let event = web.KeyEvent(type_ = web.KeyEventType.key_down, key = (web.UiEventsKeyCode)key, modifiers = (web.UiEventsKeyModifier)(u32)modifiers,
                                 code_point = (u32)code_point, repeat = repeat, browser_data = none)
        webview.webview_enqueue_input_event(api_view(view), web.InputEvent.key_event(event))

## A key let go.
pub func key_up(view: View, key: i64, modifiers: i64, code_point: i64):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let event = web.KeyEvent(type_ = web.KeyEventType.key_up, key = (web.UiEventsKeyCode)key, modifiers = (web.UiEventsKeyModifier)(u32)modifiers,
                                 code_point = (u32)code_point, repeat = false, browser_data = none)
        webview.webview_enqueue_input_event(api_view(view), web.InputEvent.key_event(event))

## Selects everything (the page's Select All).
pub func select_all(view: View):
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        webview.webview_select_all(api_view(view))

# mark: State ===================================================================================

## The next thing the view reported, Event.none_ when there is nothing new.
pub func take_event(view: View) -> Event:
    return (Event)(u8)webview.webview_take_event(api_view(view))

## The page's title ("" before it has one).
pub func page_title(view: View) -> str:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let title = webview.webview_title(api_view(view))
        let text = ak.utf16_string_base_to_utf8(&title.utf16_string_base)
        return ak.string_view_text(ak.string_bytes_as_string_view(&text))

## The page's URL, serialized.
pub func page_url(view: View) -> str:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let url = webview.webview_url(api_view(view))
        let text = web_url.url_serialize(&url)
        return ak.string_view_text(ak.string_bytes_as_string_view(&text))

## The URL of the document whose load the Event.load_finished taken last reported, serialized ("" before
## one): a new view reports its initial about:blank's load too, often in the same turn as the
## page's, so what finished is told by its URL, as Ladybird's test-web tells it.
pub func finished_load_url(view: View) -> str:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let url = webview.webview_finished_load_url(api_view(view)) else return ""
        let text = web_url.url_serialize(&url)
        return ak.string_view_text(ak.string_bytes_as_string_view(&text))

## The link under the pointer, serialized ("" when there is none).
pub func hovered_link(view: View) -> str:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let link = webview.webview_hovered_link(api_view(view)) else return ""
        let text = web_url.url_serialize(&link)
        return ak.string_view_text(ak.string_bytes_as_string_view(&text))

## Whether the page is loading.
pub func is_loading(view: View) -> bool:
    return webview.webview_is_loading(api_view(view))

## Whether there is a page to go back to.
pub func can_go_back(view: View) -> bool:
    return webview.webview_can_go_back(api_view(view))

## Whether there is a page to go forward to.
pub func can_go_forward(view: View) -> bool:
    return webview.webview_can_go_forward(api_view(view))

## The cursor the page asks for: a Gfx::StandardCursor value (arrow 2, i_beam 4, hand 11, ...).
pub func page_cursor(view: View) -> i64:
    return (i64)webview.webview_cursor(api_view(view))

## The selected text ("" when nothing is selected).
pub func selected_text(view: View) -> str:
    let allocator: memory.Allocator = webview.webview_heap()
    with allocator:
        let text = webview.webview_selected_text(api_view(view))
        return ak.string_view_text(ak.string_bytes_as_string_view(&text))

# mark: Frames ==================================================================================

## The serial number of the presented frame: it changes whenever a new frame is presented.
pub func frame_serial(view: View) -> i64:
    return (i64)webview.webview_frame_serial(api_view(view))

## The presented frame's width in device pixels.
pub func frame_width(view: View) -> i64:
    return (i64)webview.webview_frame_size(api_view(view)).m_width

## The presented frame's height in device pixels.
pub func frame_height(view: View) -> i64:
    return (i64)webview.webview_frame_size(api_view(view)).m_height

## For a Base embedder: copies the presented frame into `pixels` (webview_copy_frame).
pub func copy_frame(view: View, pixels: u8[], width: i32, height: i32) -> bool:
    return webview.webview_copy_frame(api_view(view), pixels, width, height)

# mark: The GPU player ==========================================================================

## Turns the GPU player on or off for `view` (webview's view_gpu.lucb): on, the application
## draws the page with gpu_draw instead of copying frames out.
pub func set_gpu_player(view: View, enabled: bool):
    webview.webview_set_gpu_player(api_view(view), enabled)

## Whether the GPU player draws `view`.
pub func gpu_player_enabled(view: View) -> bool:
    return webview.webview_gpu_player_enabled(api_view(view))

## For a Base embedder: draws the page on `target` (a window frame's target) with the GPU
## player, its top left at the target's.
pub func gpu_draw(view: View, target: const gpu.RenderTarget*) -> !:
    try webview.webview_gpu_draw(api_view(view), target)