Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.5

0.19.5 / src / widgets / dstack.lucb

## Dynamic workspace composition. Applications supply panels and respond to add
## and close requests; the framework owns all geometry and docking interaction.
from luce_gpu import gpu
import interop
import memory
from luce_std import math
import ownership
import layout
import result
import docking.chrome
from layout import Widget, Layout, Size, Constraints, Event
from arrangement import Arrangement
from cursor import CursorSource
from font import Font, selected_font
from command import Command, command_type
from widgets.panel import Panel
from widgets.action_popup import ActionPopup, action_popup_type
from docking.state import State, DockRequest, state_type
from docking.model import DockPosition

## The top child of the stack: draws the drag previews (drop target, floating
## window outline, the label following a dragged tab) over the panels and is
## transparent to hover.
struct Overlay: Widget:
    let box: interop.Reference[Layout]
    let state: interop.WeakReference[State]

    pub func init(state: interop.Reference[State]) -> !:
        let box = try layout.make_layout()
        box.value().set_hover_transparent(true)
        self.box = box
        self.state = interop.WeakReference[State](state)

    pub func layout() -> interop.Reference[Layout]:
        return self.box.clone()

    pub func measure(available: Constraints) -> interop.Outcome[Size]:
        return result.success[Size](Size())

    pub func draw(target: interop.View[gpu.RenderTarget]) -> interop.Outcome[unit]:
        let state = self.state.get() else return result.success[unit](())
        defer state.release()
        chrome.preview(state.value(), target) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    pub func event(event: Event) -> interop.Outcome[unit]:
        return result.success[unit](())

    pub func close():
        self.state.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        self.box.trace(visit, context)

let overlay_type: interop.Type[Overlay] = interop.Type[Overlay]("Dock preview", Overlay.close, Overlay.trace, closeable = true, main_thread = true)

## A docking workspace of Panels: tab groups in a resizable split tree, plus
## panels floating in their own windows over it. Users drag tabs to regroup,
## split or float them, resize with the dividers, and add or close panels
## through the header buttons. A group's "+" lists the panels of the catalog
## (`set_catalog`) and the ways to split; the application makes a picked panel
## that is not open yet through `on_add`, and answers `on_close` and the close
## handler.
pub struct DStack: Widget:
    let box: interop.Reference[Layout]
    let state: interop.Reference[State]

    ## A stack holding `panels` as tabs of one group, the last one selected.
    pub func init(panels: const interop.Reference[Panel][], font: interop.Reference[Font]? = none) -> !:
        let selected = try selected_font(font)
        defer selected.release()
        let box = try layout.make_layout()
        errdefer box.release()
        box.value().set_focusable(true)
        try box.value().set_flex()
        let state = try interop.Reference[State].adopt(new State(box, selected) in memory.heap, state_type, memory.heap)
        errdefer state.release()
        errdefer state.close()
        state.value().set_owner(state)
        let arrangement = state.as_interface[Arrangement](state.value())
        defer arrangement.release()
        try box.value().set_arrangement(arrangement)
        let cursor = state.as_interface[CursorSource](state.value())
        defer cursor.release()
        try box.value().set_cursor_source(cursor)
        let overlay = try interop.Reference[Overlay].adopt(new Overlay(state) in memory.heap, overlay_type, memory.heap)
        defer overlay.release()
        let overlay_widget = overlay.as_interface[Widget](overlay.value())
        defer overlay_widget.release()
        # The add menu's rows after the catalog: a rule, the two splits, and the
        # heading a split's list of panels opens with.
        let divider = try interop.Reference[Command].adopt(new Command("", divider = true) in memory.heap, command_type, memory.heap)
        defer divider.release()
        let right = try interop.Reference[Command].adopt(new Command("Split Right…") in memory.heap, command_type, memory.heap)
        defer right.release()
        let down = try interop.Reference[Command].adopt(new Command("Split Down…") in memory.heap, command_type, memory.heap)
        defer down.release()
        let heading = try interop.Reference[Command].adopt(new Command("Dock beside:") in memory.heap, command_type, memory.heap)
        defer heading.release()
        heading.value().set_enabled(false)
        let picked = try interop.Callback[unit, unit].bind_mutating(state, State.pick_from_menu)
        defer picked.release()
        state.value().connections[0] = try right.value().on_trigger(picked)
        state.value().connections[1] = try down.value().on_trigger(picked)
        try state.value().set_fixed([divider, right, down, heading])
        let popup = try interop.Reference[ActionPopup].adopt(new ActionPopup([right, down], selected) in memory.heap, action_popup_type, memory.heap)
        defer popup.release()
        try state.value().install(overlay_widget, popup)
        for panel in panels:
            try state.value().add(panel, none, DockPosition.tab)
        self.box = box
        self.state = state

    pub func layout() -> interop.Reference[Layout]:
        return self.box.clone()

    ## Dock `panel` relative to `relative_to`, or to the active docked panel, and
    ## select and focus it. At most 128 panels.
    pub func add(panel: interop.Reference[Panel], relative_to: interop.Reference[Panel]? = none, position: DockPosition = DockPosition.tab) -> !:
        try self.state.value().add(panel, relative_to, position)

    ## Redock `panel` relative to `relative_to`, docking it back when it floats,
    ## and select it.
    pub func move(panel: interop.Reference[Panel], relative_to: interop.Reference[Panel], position: DockPosition = DockPosition.tab) -> !:
        try self.state.value().move(panel, relative_to, position)

    ## Take `panel` out and release it, then emit `on_close`. The close handler is
    ## not asked; it only guards the user's close button.
    pub func remove(panel: interop.Reference[Panel]) -> !:
        try self.state.value().remove(panel)

    ## Float a panel in its own window over the panes: a docked one leaves its
    ## group, one not in the stack yet is added. `window` is in the stack's
    ## coordinates; without one a new window is centered and a floating one stays.
    pub func float(panel: interop.Reference[Panel], window: gpu.Rect? = none) -> !:
        let state = self.state.value()
        let index = state.index(panel) catch failure:
            try state.add_floating(panel, window)
            return
        try state.make_floating(index, window else (state.float_bounds(index) if state.floating(index) else state.default_window(index)))

    ## Whether the panel is in this stack, docked or floating.
    pub func contains(panel: interop.Reference[Panel]) -> bool:
        _ = self.state.value().index(panel) catch failure: return false
        return true

    pub func is_floating(panel: interop.Reference[Panel]) -> bool!:
        return self.state.value().floating(try self.state.value().index(panel))

    ## A floating panel's window, title bar included, in the stack's coordinates.
    pub func float_bounds(panel: interop.Reference[Panel]) -> gpu.Rect!:
        let index = try self.state.value().index(panel)
        if not self.state.value().floating(index): error(result.invalid, "the panel is docked")
        return self.state.value().float_bounds(index)

    ## Show `panel` (raising its window when it floats), focus its content and emit
    ## `on_select`. Cancels any drag in progress.
    pub func select(panel: interop.Reference[Panel]) -> !:
        self.state.value().cancel()
        try self.state.value().select(try self.state.value().index(panel))

    ## Cycle visible groups in reading order; selection reveals that group's
    ## active tab and deferred focus finds its first keyboard-capable control.
    pub func focus_next(backwards: bool = false) -> !:
        let state = self.state.value()
        state.cancel()
        if state.model.root == 0: return
        let geometry = state.geometry(state.size())
        # From a floating window, move among the panes from the last docked one.
        let current = state.model.tabs[state.model.active if state.floating(state.active()) else state.active()].group
        var next: usize = 0
        var wrap: usize = 0
        for group in 1..<state.model.nodes.length:
            if not state.model.nodes[group].used or state.model.nodes[group].first != 0: continue
            let bounds = geometry.panes[group]
            if wrap == 0 or (earlier(bounds, geometry.panes[wrap]) != backwards): wrap = group
            let follows = earlier(bounds, geometry.panes[current]) if backwards else earlier(geometry.panes[current], bounds)
            if follows and (next == 0 or (earlier(bounds, geometry.panes[next]) != backwards)):
                next = group
        let chosen = next if next != 0 else wrap
        try state.select(state.model.nodes[chosen].selected)

    ## Focus the nearest visible pane in a direction: (-1, 0) left, (1, 0) right,
    ## (0, -1) up, (0, 1) down. Chooses the pane whose center lies furthest along
    ## the direction and least off its axis, so the jump stays predictable; does
    ## nothing when no pane sits that way.
    pub func focus_direction(dx: f64, dy: f64) -> !:
        let state = self.state.value()
        state.cancel()
        if state.model.root == 0: return
        let geometry = state.geometry(state.size())
        # From a floating window, move among the panes from the last docked one.
        let current = state.model.tabs[state.model.active if state.floating(state.active()) else state.active()].group
        let origin = geometry.panes[current]
        let cx = origin.x + origin.width * 0.5
        let cy = origin.y + origin.height * 0.5
        var best: usize = 0
        var best_score: f64 = 0.0
        for group in 1..<state.model.nodes.length:
            if not state.model.nodes[group].used or state.model.nodes[group].first != 0 or group == current: continue
            let bounds = geometry.panes[group]
            let ox = bounds.x + bounds.width * 0.5 - cx
            let oy = bounds.y + bounds.height * 0.5 - cy
            let along = ox * dx + oy * dy
            if along <= 0.0: continue
            let across = math.abs(ox * dy - oy * dx)
            let score = along + across * 2.0
            if best == 0 or score < best_score:
                best = group
                best_score = score
        if best != 0:
            try state.select(state.model.nodes[best].selected)

    ## The panel holding keyboard focus, else the last selected docked one, or none.
    pub func active_panel() -> interop.Reference[Panel]?!:
        let index = self.state.value().active()
        return none if index == 0 else try self.state.value().panel(index)

    ## Every panel in the stack, docked or floating.
    pub func panel_count() -> i64:
        return (i64)(self.state.value().model.count() + self.state.value().floating_count())

    ## The docked tab groups; floating windows do not count.
    pub func group_count() -> i64:
        return (i64)self.state.value().model.group_count()

    ## How many tabs share `panel`'s group; 0 for a floating panel.
    pub func tab_count(panel: interop.Reference[Panel]) -> i64!:
        let index = try self.state.value().index(panel)
        return (i64)self.state.value().model.tab_count(self.state.value().model.tabs[index].group)

    ## Whether two panels are tabs of one group.
    pub func same_group(first: interop.Reference[Panel], second: interop.Reference[Panel]) -> bool!:
        let a = try self.state.value().index(first)
        let b = try self.state.value().index(second)
        let group = self.state.value().model.tabs[a].group
        # Floating panels have no group; each window stands alone.
        return group != 0 and group == self.state.value().model.tabs[b].group

    ## The pane of `panel`'s group, header included, or its window when it floats,
    ## in the stack's coordinates.
    pub func panel_bounds(panel: interop.Reference[Panel]) -> gpu.Rect!:
        let index = try self.state.value().index(panel)
        if self.state.value().floating(index): return self.state.value().float_bounds(index)
        let geometry = self.state.value().geometry(self.state.value().size())
        let model = self.state.value().visible_model()
        return geometry.panes[model.tabs[index].group]

    ## Where `panel`'s tab sits in its group's header; fails for a floating panel.
    pub func tab_bounds(panel: interop.Reference[Panel]) -> gpu.Rect!:
        return try self.state.value().tab_bounds(try self.state.value().index(panel))

    ## The add button in the header of `panel`'s group; empty for a floating panel.
    pub func add_bounds(panel: interop.Reference[Panel]) -> gpu.Rect!:
        let index = try self.state.value().index(panel)
        let model = self.state.value().visible_model()
        let group = model.tabs[index].group
        return gpu.Rect() if group == 0 else self.state.value().strip(group, try self.panel_bounds(panel)).add

    ## The pane a dragged tab would take if released now, or an empty rectangle.
    pub func drop_preview() -> gpu.Rect:
        return self.state.value().current_drop().preview

    ## The label that follows a dragged tab, or an empty rectangle.
    pub func drag_bounds() -> gpu.Rect:
        return self.state.value().drag_bounds()

    ## Set the split directly containing `panel`'s group so that `fraction` of it
    ## goes to its first side. Fails for a group that is not in a split.
    pub func set_fraction(panel: interop.Reference[Panel], fraction: f64) -> !:
        self.state.value().cancel()
        let index = try self.state.value().index(panel)
        let group = self.state.value().model.tabs[index].group
        let branch = self.state.value().model.nodes[group].parent
        if branch == 0 or not math.is_finite(fraction) or fraction < 0.0 or fraction > 1.0:
            error(result.invalid, "panel must have a split parent and a fraction in 0..1")
        self.state.value().model.nodes[branch].fraction = fraction
        self.box.value().invalidate()

    ## Called with the panel whenever a selection shows it: a click on its tab,
    ## stepping through tabs, a focus move, `select` or `add`.
    pub func on_select(callback: interop.Callback[interop.Reference[Panel], unit]) -> interop.Reference[interop.Connection]!:
        return try self.state.value().selected.connect(callback)

    ## Offer panels `ids`, named `titles`, in every group's add menu, replacing
    ## what it offered. Give each panel made for an entry its id (`Panel(id =)`)
    ## so the menu ticks it while it is open and focuses it when picked again.
    pub func set_catalog(ids: const str[], titles: const str[]) -> !:
        try self.state.value().set_catalog(self.state, ids, titles)

    ## The arrangement as text, for keeping it across runs (docking/state/layout.lucb):
    ## the split tree with its fractions, each group's tabs by panel id and its
    ## selected one, then the floating windows. `restore_layout` rebuilds it.
    pub func layout_text() -> interop.Owned[str]!:
        return try self.state.value().arrangement_text()

    ## Rebuild the arrangement `layout_text` wrote: the split tree and its fractions,
    ## the tab groups and their selected tabs, and the floating windows, each panel
    ## found by its id among `panels` (the panels the stack may hold, in it now or
    ## not). Panels the text does not name are taken out, without `on_close`; ids no
    ## panel has are skipped, and a split left with one side gives it the room. A
    ## text that does not read is an error with the stack as it was.
    pub func restore_layout(text: str, panels: const interop.Reference[Panel][]) -> !:
        try self.state.value().restore_arrangement(text, panels)

    ## The open panel made from catalog entry `id`, or none.
    pub func find(id: str) -> interop.Reference[Panel]?!:
        let slot = self.state.value().catalog_slot(id)
        if slot == 0: return none
        return try self.state.value().panel(slot)

    ## Called with a DockRequest when the user picks a catalog panel that is not
    ## open: the application makes it with the request's id and adds it where the
    ## request says.
    pub func on_add(callback: interop.Callback[interop.Reference[DockRequest], unit]) -> interop.Reference[interop.Connection]!:
        return try self.state.value().added.connect(callback)

    ## Called with each panel after it is removed, by the user or `remove`.
    pub func on_close(callback: interop.Callback[interop.Reference[Panel], unit]) -> interop.Reference[interop.Connection]!:
        return try self.state.value().closed.connect(callback)

    ## Ask `callback` before a user close removes a closable panel; false keeps it.
    pub func set_close_handler(callback: interop.Callback[interop.Reference[Panel], bool]):
        self.state.value().set_close_handler(callback)

    pub func measure(available: Constraints) -> interop.Outcome[Size]:
        return result.success[Size](Size(400.0, 300.0))

    pub func draw(target: interop.View[gpu.RenderTarget]) -> interop.Outcome[unit]:
        chrome.draw(self.state.value(), target) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    pub func event(event: Event) -> interop.Outcome[unit]:
        self.state.value().handle(event) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    pub func close():
        self.state.close()
        self.state.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        self.state.trace(visit, context)
        self.box.trace(visit, context)

pub let dstack_type: interop.Type[DStack] = interop.Type[DStack]("DStack", DStack.close, DStack.trace, closeable = true, main_thread = true)

func earlier(first: gpu.Rect, second: gpu.Rect) -> bool:
    return first.y < second.y or (first.y == second.y and first.x < second.x)