Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-browser

Source of release 0.3.1

0.3.1 / src / app.luc

## luced-browser's application: the window (tab strip, toolbar, loading bar,
## the current tab's page), the commands, and the loop that runs the engine:
## each turn it processes the engine's due work, takes what each page
## reported, hands the engine's sockets to the window's loop to watch, and asks
## it to wake when the engine is next due.

from luce_ui.ui import Application, Font, VStack, Widget
from luce_gpu import gpu
from interop import Connection
from luce_browser_engine import webview_api as webview
from engine_hooks import start_engine, copy_text
from page_view import PageView
from toolbar import BrowserToolbar
from tabs import TabStrip
from commands import BrowserCommands
from recovery import SessionTabs, tabs_path, crashed_tabs, note_saved_tabs, tabs_text, parse_tabs
from luce_std import files
from luce_window.input import Appearance
import theme

## What a new tab shows.
pub let new_tab_page: str = "about:blank"

## The engine that answers what is typed and is not an address.
pub let search_engine: str = "DuckDuckGo"

## One tab: its page and what the page last reported.
pub class Tab:
    pub let page: PageView
    pub var title: str = ""
    pub var url: str = ""
    pub var loading: bool = false
    ## The current document's address once its load finished, "" while it loads.
    pub var loaded_url: str = ""

    pub func init(self) -> unit!:
        self.page = PageView()

    ## The tab's label: its title, else its address, else "New Tab".
    pub func label(self) -> str:
        if self.title.length > 0:
            return self.title
        if self.url.length > 0 and self.url != "about:blank":
            return self.url
        return "New Tab"

pub class Browser:
    pub let app: Application
    pub let font: Font
    pub let strip: TabStrip
    pub let toolbar: BrowserToolbar
    pub let commands: BrowserCommands
    pub var tabs: list[Tab]
    pub var current: int = 0
    ## The engine's sockets, which the window's loop watches so that it sleeps
    ## until one is ready: each descriptor's watch handle.
    pub let sockets: map[int, int]
    ## The pages' area: every tab's page, only the current one visible.
    let pages: VStack
    let connections: list[Connection]
    ## The open tabs as a crash leaves them (recovery.luc), and the tabs a
    ## crashed run left, for run to open again.
    let session: SessionTabs
    let crashed: str
    ## Whether the system's appearance is dark: what every page reads as
    ## prefers-color-scheme, kept current through on_appearance.
    var dark: bool = false

    pub func init(self) -> unit!:
        let font = Font()
        self.font = font
        self.commands = BrowserCommands()
        self.strip = TabStrip(font)
        self.toolbar = BrowserToolbar(font)
        self.tabs = []
        let no_pages: list[Widget] = []
        self.pages = VStack(no_pages, spacing = 0.0)
        self.pages.layout().set_flex()
        let body = VStack([self.toolbar.bar, self.strip, self.toolbar.loading, self.pages], spacing = 0.0)

        # The Application first: a process luce-ui started again to show a crash
        # report shows it from here and ends, before the engine is set up.
        # An encoded window surface: pages blend on encoded values (as Skia and the CPU
        # player do), so the GPU player composites its tiles straight onto the window.
        self.app = Application(body, title = "luced-browser", width = 1280, height = 860, theme = theme.browser_theme(), blending = gpu.Blending.encoded)
        start_engine()
        webview.hand_over_sockets()
        self.sockets = {}
        self.dark = self.app.appearance() == Appearance.dark
        self.tabs = [Tab()]
        webview.set_dark(self.tabs[0].page.view, self.dark)
        self.rebuild_pages()
        self.connections = []
        self.connect()
        self.app.set_commands(self.commands.all())

        # The tabs a crashed run left, read before this run's replace them.
        self.crashed = crashed_tabs()
        self.session = SessionTabs(tabs_path())
        _ = self.app.on_crash(note_saved_tabs)  # Application keeps the hook and removes it at close
        self.select_tab(0)

    ## Buttons, the address field, the tab strip and the commands to what they do.
    func connect(self) -> unit!:
        let commands = self.commands
        # The system's light or dark mode, followed live by every page.
        self.connections.append(self.app.on_appearance(func (appearance: Appearance) -> unit!:
            self.dark = appearance == Appearance.dark
            for tab in self.tabs:
                webview.set_dark(tab.page.view, self.dark)))
        self.connections.append(commands.back.on_trigger(func () -> unit!:
            webview.go_back(self.view())))
        self.connections.append(commands.forward.on_trigger(func () -> unit!:
            webview.go_forward(self.view())))
        self.connections.append(commands.reload.on_trigger(func () -> unit!:
            webview.reload(self.view())))
        self.connections.append(commands.stop.on_trigger(func () -> unit!:
            webview.stop(self.view())))
        self.connections.append(commands.focus_address.on_trigger(func () -> unit!:
            self.app.focus(self.toolbar.address.layout())))
        self.connections.append(commands.copy.on_trigger(func () -> unit!:
            self.copy()))
        self.connections.append(commands.select_all.on_trigger(func () -> unit!:
            webview.select_all(self.view())))
        self.connections.append(commands.new_tab.on_trigger(func () -> unit!:
            self.open_tab(new_tab_page)))
        self.connections.append(commands.close_tab.on_trigger(func () -> unit!:
            self.close_tab(self.current)))
        self.connections.append(commands.next_tab.on_trigger(func () -> unit!:
            self.select_tab((self.current + 1) % self.tabs.length)))
        self.connections.append(commands.previous_tab.on_trigger(func () -> unit!:
            self.select_tab((self.current + self.tabs.length - 1) % self.tabs.length)))
        self.connections.append(self.toolbar.back.on_click(func () -> unit!:
            commands.back.trigger()))
        self.connections.append(self.toolbar.forward.on_click(func () -> unit!:
            commands.forward.trigger()))
        self.connections.append(self.toolbar.reload.on_click(func () -> unit!:
            commands.reload.trigger()))
        self.connections.append(self.toolbar.stop.on_click(func () -> unit!:
            commands.stop.trigger()))
        self.connections.append(self.toolbar.address.on_submit(func (text: str) -> unit!:
            self.go(text)))
        self.connections.append(self.toolbar.address.on_commit(func (text: str) -> unit!:
            self.address_left()))
        self.strip.on_switch = func (index: int) -> unit!:
            self.select_tab(index)
        self.strip.on_close = func (index: int) -> unit!:
            self.close_tab(index)
        self.strip.on_new = func () -> unit!:
            self.open_tab(new_tab_page)
        self.connections.append(self.app.on_frame(func (elapsed: float) -> unit!:
            self.turn(elapsed)))

    ## The current tab's page.
    pub func view(self) -> webview.View:
        return self.tabs[self.current].page.view

    # -- Loading.
    ## Loads what was typed (an address, a file, or a search), as the address
    ## field's Enter does, even when it is the page's own address.
    pub func go(self, text: str) -> unit!:
        let loaded = webview.load(self.view(), text, search_engine)
        _ = loaded
        self.app.focus(self.tabs[self.current].page.layout())

    ## The address field committed edited text (Enter commits it too, while it
    ## has focus): once focus has left it, it shows the page's address again.
    func address_left(self) -> unit!:
        if not self.toolbar.address.layout().is_focused():
            self.toolbar.address.set_text(self.tabs[self.current].url)

    ## Copies the page's selection, or the address while the field has focus.
    func copy(self) -> unit!:
        if self.toolbar.address.layout().is_focused():
            copy_text(self.toolbar.address.text())
        else:
            let selected = webview.selected_text(self.view())
            if selected.length > 0:
                copy_text(selected)

    # -- Tabs.
    ## A new tab loading `location`, made current.
    pub func open_tab(self, location: str) -> unit!:
        let tab = Tab()
        webview.set_dark(tab.page.view, self.dark)
        self.tabs.append(tab)
        self.rebuild_pages()
        self.select_tab(self.tabs.length - 1)
        self.go(location)
        if location == new_tab_page:
            self.app.focus(self.toolbar.address.layout())

    ## Closes the tab at `index`; closing the last one ends the run.
    pub func close_tab(self, index: int) -> unit!:
        if index < 0 or index >= self.tabs.length:
            return
        if self.tabs.length == 1:
            self.app.stop()
            return
        let closing = self.tabs[index]
        _ = self.tabs.remove_at(index)
        self.rebuild_pages()
        closing.page.close()
        var next = self.current
        if next >= self.tabs.length:
            next = self.tabs.length - 1
        elif index < self.current:
            next -= 1
        self.current = -1
        self.select_tab(next)

    ## Makes the tab at `index` current: its page shown, its state in the toolbar.
    pub func select_tab(self, index: int) -> unit!:
        if index < 0 or index >= self.tabs.length:
            return
        self.current = index
        # Only the current tab's page renders: the others are hidden from the
        # engine too, as Ladybird's UI hides a tab's view it switched from.

        var position = 0
        for tab in self.tabs:
            let shown = position == index
            tab.page.layout().set_visible(shown)
            if webview.is_visible(tab.page.view) != shown:
                webview.set_visible(tab.page.view, shown)
            position += 1
        let tab = self.tabs[index]
        self.toolbar.address.set_text(tab.url)
        self.toolbar.show_loading(tab.loading)
        self.show_navigation_buttons()
        self.show_tabs()
        self.app.focus(tab.page.layout())
        self.show_title()

    func rebuild_pages(self) -> unit!:
        var pages: list[Widget] = []
        for tab in self.tabs:
            pages.append(tab.page)
        self.pages.set_children(pages)

    ## The tab strip shows the tabs, and a crash would save them as they are now.
    func show_tabs(self):
        var titles: list[str] = []
        for tab in self.tabs:
            titles.append(tab.label())
        self.strip.show(titles, self.current)

        self.session.remember(self.urls(), self.current) catch failure:
            _ = failure

    ## The window's title follows the current tab's label.
    func show_title(self) -> unit!:
        let title = self.tabs[self.current].label()
        if title != self.app.title():
            self.app.set_title(title)

    func show_navigation_buttons(self):
        let view = self.view()
        self.toolbar.back.layout().set_enabled(webview.can_go_back(view))
        self.toolbar.forward.layout().set_enabled(webview.can_go_forward(view))

    # -- Each turn.
    ## One turn of the window's loop: the engine's due work, what each page
    ## reported, the loading bar, the sockets to watch, and the wake-up at the
    ## engine's next deadline (none when nothing is scheduled); the turn that
    ## answers the wake-up runs this again.
    pub func turn(self, elapsed: float) -> unit!:
        _ = webview.process_events()
        var index = 0
        for tab in self.tabs:
            self.take_events(tab, index == self.current)
            tab.page.poll()
            index += 1
        self.toolbar.loading.advance(elapsed)
        self.watch_sockets()
        let due = webview.next_due()
        if due < 0.0:
            self.app.wake_at(0)
        else:
            self.app.wake_after(due)

    ## Takes what `tab`'s page reported (ViewImplementation's callbacks).
    func take_events(self, tab: Tab, current: bool) -> unit!:
        let view = tab.page.view
        while true:
            let event = webview.take_event(view)
            if event == webview.Event.none_:
                return
            if event == webview.Event.load_started:
                tab.loading = true
                tab.loaded_url = ""
                tab.url = webview.page_url(view)
                if current:
                    self.toolbar.show_loading(true)
                    if not self.toolbar.address.layout().is_focused():
                        self.toolbar.address.set_text(tab.url)
                self.show_tabs()
            elif event == webview.Event.load_finished:
                tab.loading = false
                tab.loaded_url = webview.finished_load_url(view)
                if current:
                    self.toolbar.show_loading(false)
            elif event == webview.Event.url_changed:
                tab.url = webview.page_url(view)
                if current and not self.toolbar.address.layout().is_focused():
                    self.toolbar.address.set_text(tab.url)
                self.show_tabs()
                if current:
                    self.show_title()
            elif event == webview.Event.title_changed:
                tab.title = webview.page_title(view)
                self.show_tabs()
                if current:
                    self.show_title()
            elif event == webview.Event.cursor_changed:
                tab.page.update_cursor()
            elif event == webview.Event.navigation_buttons_changed:
                if current:
                    self.show_navigation_buttons()

    ## Watches the sockets the engine reported (webview.hand_over_sockets) for
    ## what it now waits for on each, or stops watching them. A ready socket
    ## runs the engine at once; the turn it wakes takes what the pages reported.
    func watch_sockets(self) -> unit!:
        while true:
            let descriptor = webview.take_socket_change()
            if descriptor < 0:
                return
            if let watch = self.sockets.remove(descriptor):
                self.app.unwatch(watch)
            let readable = webview.socket_readable(descriptor)
            let writable = webview.socket_writable(descriptor)
            if readable or writable:
                let ready = func () -> unit!:
                    _ = webview.process_events()
                self.sockets[descriptor] = self.app.watch(descriptor, ready, readable = readable, writable = writable)

    pub func run(self, arguments: list[str]) -> unit!:
        # Luce's `main` gets the arguments without the program: the first is a location to open.
        var location = ""
        for argument in arguments:
            if argument.length > 0 and argument[..<1] != "-":
                location = argument
                break
        # The tabs a crashed run left come back first; a location given opens after them.

        var restored = false
        if self.crashed != "":
            restored = self.restore_tabs_text(self.crashed)
        if location != "":
            if restored:
                self.open_tab(location)
            else:
                self.go(location)
        elif not restored:
            self.go(new_tab_page)
            self.app.focus(self.toolbar.address.layout())
        self.app.run(frame_limit = 3 if "--smoke" in arguments else 0)

    # -- Recovery.
    ## The open tabs' addresses, in order.
    func urls(self) -> list[str]:
        var urls: list[str] = []
        for tab in self.tabs:
            urls.append(tab.url if tab.url.length > 0 else new_tab_page)
        return urls

    ## Writes the open tabs' addresses, in order with the current one marked, to
    ## `path`, as a crash saves them.
    pub func save_tabs(self, path: str) -> unit!:
        files.write_text(path, tabs_text(self.urls(), self.current))

    ## Opens the tabs saved at `path` (save_tabs): the first in the current tab,
    ## the others in new ones, then the one that was current made current.
    ## Answers whether there were any.
    pub func restore_tabs(self, path: str) -> bool!:
        return self.restore_tabs_text(files.read_text(path))

    ## Opens the tabs `text` (a tabs file's) holds, as restore_tabs does.
    func restore_tabs_text(self, text: str) -> bool!:
        let saved = parse_tabs(text)
        if saved.urls.length == 0:
            return false
        var index = 0
        for url in saved.urls:
            if index == 0:
                self.go(url)
            else:
                self.open_tab(url)
            index += 1
        let first = self.tabs.length - saved.urls.length
        self.select_tab(first + saved.current)
        return true

    pub func close(self):
        for watch in self.sockets.values():
            self.app.unwatch(watch)
        self.sockets.clear()
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()
        for tab in self.tabs:
            tab.page.close()
        self.session.forget() catch failure:
            _ = failure
        self.app.close()
        # The engine's last step: it ends what Ladybird's process exit ends.
        webview.shutdown()