Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.7

0.11.7 / src / marking_menu.luc

## Marking menus: holding A shows what can be created here, S what can
## modify, D what can select (in a sketch its constraints), as labeled
## entries around the pointer: columns of an icon and a name, a family's
## (a group's) entries under its heading, half the columns left of the
## pointer and half right so it starts on none. It shows while the key is
## held: click an entry to use it; letting the key go, Esc or a click
## outside closes it. A family of tools (the rectangles) is one entry, the
## one used last: a click uses it, a long press lists them all above it to
## pick from. What the items are is marking_items.luc's.
from luce_ui.ui import Painter, Event, Point
import time
from luce_gpu.gpu import Rect
from luce_window.input import EventKind, Key
from luce_std import math
from luce_ui import ui
import theme

## One entry of a marking menu: its name, icon (a luciaos-assets name),
## whether it can be used now, and what using it does; or a family's: its
## `variants`, one used at a time. Entries of one `group` (a tool family:
## "Loops", "Find") stand in a column under its name.
pub class MarkItem:
    pub let name: str
    pub let icon: str
    pub let enabled: bool
    pub let run: func() -> unit!
    pub let variants: list[MarkItem]
    pub let group: str

    pub func init(self, name: str, icon: str, enabled: bool, run: func() -> unit!, variants: list[MarkItem] = [], group: str = ""):
        self.name = name
        self.icon = icon
        self.enabled = enabled
        self.run = run
        self.variants = variants
        self.group = group

## How long a press on a family opens its variants (nanoseconds).
let long_press = 350000000

## An entry's height (a heading's too), the width a label character takes
## (the UI's monospace font), the room an icon takes left of its label, the
## gap left around the pointer, and the most rows a column holds with
## headings and without.
let row_height = 26.0
let char_width = 7.2
let icon_room = 30.0
let gap = 28.0
let column_rows = 13
let plain_rows = 8

## One column of the menu: its entries' rows (an item's index, or -1 for
## a heading), the headings' texts, its left edge and width.
class Column:
    pub let rows: list[int]
    pub let titles: list[str]
    pub var x: float = 0.0
    pub var width: float = 0.0

    pub func init(self):
        self.rows = []
        self.titles = []

pub class MarkingMenu:
    pub var title: str = ""
    pub var items: list[MarkItem]
    ## The key holding it open (Key.a, Key.s, Key.d).
    pub var key: Key = Key.a
    var opened: bool = false
    ## Its key still down after a click closed it: its repeats and its
    ## release are swallowed.
    var held: bool = false
    var x: float = 0.0
    var y: float = 0.0
    pub var hover: int = -1
    ## A family pressed (its item) and since when; its variants shown (the
    ## item, -1 none) and the one under the pointer.
    var pressing: int = -1
    var pressed_at: int = 0
    pub var family: int = -1
    var family_hover: int = -1
    ## Each family's variant used last, by the family's name.
    let chosen: map[str, int]
    ## The columns as last laid out, for a viewport of `laid_out` size, and
    ## each item's cell.
    var columns: list[Column]
    var cells: list[Rect]
    var laid_out: list[float]
    var top: float = 0.0
    var tallest: int = 0

    pub func init(self):
        self.items = []
        self.chosen = {}
        self.columns = []
        self.cells = []
        self.laid_out = []

    pub func is_open(self) -> bool:
        return self.opened

    ## Open `items` titled `title` around (`x`, `y`) while `key` is held.
    pub func show(self, title: str, items: list[MarkItem], key: Key, x: float, y: float):
        self.title = title
        self.items = items
        self.key = key
        self.x = x
        self.y = y
        self.opened = true
        self.hover = -1
        self.laid_out = []

    pub func close(self):
        self.opened = false
        self.hover = -1
        self.pressing = -1
        self.family = -1
        self.family_hover = -1

    ## What item `at` does on a click: itself, or its family's variant
    ## used last.
    func shown(self, at: int) -> MarkItem:
        let item = self.items[at]
        if item.variants.length == 0:
            return item
        let index = self.chosen[item.name] else return item.variants[0]
        return item.variants[index] if index < item.variants.length else item.variants[0]

    ## Nanoseconds from `now` until a press held on a family opens its
    ## variants (poll then), or -1: no press waits.
    pub func waits(self, now: int) -> int:
        if self.opened and self.pressing >= 0 and self.family < 0:
            let left = long_press - (now - self.pressed_at)

            return left if left > 0 else 0
        return -1

    ## A press held long enough on a family opens its variants (the
    ## viewport polls; `now` the time). Whether to draw again.
    pub func poll(self, now: int) -> bool:
        if self.opened and self.pressing >= 0 and self.family < 0 and now - self.pressed_at >= long_press:
            self.family = self.pressing
            return true
        return false

    ## Lay the items out for a viewport `width` by `height`: each group's
    ## run of items under its heading, groups stacked in a column while it
    ## has room (`column_rows` rows; items without groups in columns of
    ## `plain_rows`), half the columns left of the pointer and half right,
    ## the panel kept inside the viewport.
    func layout(self, width: float, height: float):
        if self.laid_out == [width, height]:
            return
        self.laid_out = [width, height]
        self.columns = [Column()]
        var at = 0
        while at < self.items.length:
            let group = self.items[at].group
            var end = at
            while end < self.items.length and self.items[end].group == group:
                end += 1
            let limit = column_rows if group != "" else plain_rows
            let need = end - at + (1 if group != "" else 0)
            var column = self.columns[-1]
            if column.rows.length > 0 and column.rows.length + need > limit:
                column = Column()
                self.columns.append(column)
            if group != "":
                column.titles.append(group)
                column.rows.append(-1)
            for index in at..<end:
                if column.rows.length >= limit:
                    column = Column()
                    self.columns.append(column)
                column.rows.append(index)
            at = end
        self.tallest = 0
        for column in self.columns:
            var widest = 0.0
            for title in column.titles:
                widest = math.max(widest, float(title.length) * char_width)
            for index in column.rows:
                if index >= 0:
                    widest = math.max(widest, icon_room + float(self.shown(index).name.length) * char_width)
            column.width = math.max(96.0, widest + 14.0)
            if column.rows.length > self.tallest:
                self.tallest = column.rows.length
        # Columns left of the pointer, then right of it.
        let left = (self.columns.length + 1) // 2
        var left_width = 0.0
        var right_width = 0.0
        for index in 0..<self.columns.length:
            if index < left:
                left_width += self.columns[index].width
            else:
                right_width += self.columns[index].width
        let total_height = float(self.tallest) * row_height
        let cx = math.max(left_width + gap * 0.5 + 8.0, math.min(width - right_width - gap * 0.5 - 8.0, self.x))
        self.top = math.max(40.0, math.min(height - total_height - 8.0, self.y - total_height * 0.5))
        var x = cx - gap * 0.5 - left_width
        self.cells = []
        for index in 0..<self.items.length:
            self.cells.append(Rect(0.0, 0.0, 0.0, 0.0))
        for index in 0..<self.columns.length:
            if index == left:
                x = cx + gap * 0.5
            let column = self.columns[index]
            column.x = x
            for row in 0..<column.rows.length:
                if column.rows[row] >= 0:
                    self.cells[column.rows[row]] = Rect(x, self.top + float(row) * row_height, column.width, row_height)
            x += column.width

    ## Item `at`'s cell.
    func cell_of(self, at: int, width: float, height: float) -> Rect:
        self.layout(width, height)
        return self.cells[at]

    ## Item `at`'s center in the viewport (tests point at it).
    pub func center_of(self, at: int, width: float, height: float) -> list[float]:
        let r = self.cell_of(at, width, height)
        return [r.x + r.width * 0.5, r.y + r.height * 0.5]

    func item_at(self, px: float, py: float, width: float, height: float) -> int:
        for at in 0..<self.items.length:
            let r = self.cell_of(at, width, height)
            if px >= r.x and px < r.x + r.width and py >= r.y and py < r.y + r.height:
                return at
        return -1

    ## Variant `at` of the family shown: a column of entries above the
    ## family's own cell (below it when there is no room above).
    func variant_cell(self, at: int, width: float, height: float) -> Rect:
        let base = self.cell_of(self.family, width, height)
        let variants = self.items[self.family].variants
        var widest = base.width
        for variant in variants:
            widest = math.max(widest, icon_room + float(variant.name.length) * char_width + 14.0)
        let room = float(variants.length) * row_height + 8.0
        let above = base.y - room >= 4.0
        let y = base.y - room + 4.0 if above else base.y + row_height + 4.0
        return Rect(math.min(base.x, width - widest - 4.0), y + float(at) * row_height, widest, row_height)

    ## Variant `at`'s center (tests point at it).
    pub func variant_center(self, at: int, width: float, height: float) -> list[float]:
        let r = self.variant_cell(at, width, height)
        return [r.x + r.width * 0.5, r.y + r.height * 0.5]

    func variant_at(self, px: float, py: float, width: float, height: float) -> int:
        if self.family < 0:
            return -1
        for at in 0..<self.items[self.family].variants.length:
            let r = self.variant_cell(at, width, height)
            if px >= r.x and px < r.x + r.width and py >= r.y and py < r.y + r.height:
                return at
        return -1

    pub func draw(self, painter: Painter, width: float, height: float) -> unit!:
        if not self.opened:
            return
        if self.items.length == 0:
            painter.rounded_rectangle(Rect(self.x - 80.0, self.y - 16.0, 160.0, 32.0), theme.surface(), 4.0)
            painter.text(f"Nothing to {self.title.lower()} here", self.x - 72.0, self.y - 8.0, theme.text_muted())
            return
        self.layout(width, height)
        let first = self.columns[0]
        let last = self.columns[-1]
        let bottom = self.top + float(self.tallest) * row_height
        let panel_top = self.top - 24.0
        painter.rounded_rectangle(Rect(first.x - 6.0, panel_top, last.x + last.width - first.x + 12.0, bottom - panel_top + 6.0), theme.surface(), 6.0)
        painter.text(self.title, first.x + 4.0, panel_top + 5.0, theme.text_muted())
        for column in self.columns:
            var title = 0
            for row in 0..<column.rows.length:
                if column.rows[row] < 0:
                    painter.text(column.titles[title], column.x + 6.0, self.top + float(row) * row_height + 8.0, theme.grey(110.0))
                    title += 1
        for at in 0..<self.items.length:
            self.draw_entry(painter, self.shown(at), self.cell_of(at, width, height), at == self.hover or at == self.family, self.items[at].variants.length > 0)
        # A family's variants, in a column over it.
        if self.family >= 0:
            let variants = self.items[self.family].variants
            let top = self.variant_cell(0, width, height)
            painter.rounded_rectangle(Rect(top.x - 4.0, top.y - 4.0, top.width + 8.0, float(variants.length) * row_height + 8.0), theme.surface_raised(), 6.0)
            for at in 0..<variants.length:
                self.draw_entry(painter, variants[at], self.variant_cell(at, width, height), at == self.family_hover, false)

    ## One entry: its icon and name in `r`, lit when `lit`; a family gets a
    ## mark in its corner (press long for the others).
    func draw_entry(self, painter: Painter, item: MarkItem, r: Rect, lit: bool, family: bool) -> unit!:
        let on = lit and item.enabled
        if on:
            painter.rounded_rectangle(Rect(r.x + 1.0, r.y + 1.0, r.width - 2.0, r.height - 2.0), theme.accent(), 4.0)
        # A tool that does not apply now draws pale and takes no click.
        let ink = theme.grey(0.0) if on else (theme.text() if item.enabled else theme.disabled(theme.text()))
        ui.draw_icon(painter.target(), item.icon, Rect(r.x + 6.0, r.y + 4.0, 18.0, 18.0), ink)
        painter.text(item.name, r.x + icon_room, r.y + 6.0, ink)
        if family:
            painter.mesh([Point(r.x + r.width - 4.0, r.y + r.height - 10.0), Point(r.x + r.width - 4.0, r.y + r.height - 4.0), Point(r.x + r.width - 10.0, r.y + r.height - 4.0)], ink)

    ## Its events while open (true: taken), and its key's until it is let
    ## go (its repeats must not reach a tool's letter). Opening is the
    ## viewport's: it knows what the items are.
    pub func event(self, event: Event, width: float, height: float) -> bool!:
        if not self.opened:
            if self.held and event.key == self.key and event.kind in [EventKind.key_down, EventKind.key_up]:
                if event.kind == EventKind.key_up:
                    self.held = false
                return true
            return false
        if event.cancelled or event.kind == EventKind.focus_lost or (event.kind == EventKind.key_down and event.key == Key.escape):
            self.close()
            return true
        if event.kind == EventKind.key_down and event.key == self.key:
            return true
        if event.kind == EventKind.pointer_moved:
            self.hover = self.item_at(event.x, event.y, width, height)
            self.family_hover = self.variant_at(event.x, event.y, width, height)
            return true
        # Let go: it goes away.
        if event.kind == EventKind.key_up and event.key == self.key:
            self.close()
            self.held = false
            return true
        # A click on a tool uses it (a family: wait, a long press shows
        # its variants); elsewhere nothing. Either way it goes.
        if event.kind == EventKind.pointer_down:
            let variant = self.variant_at(event.x, event.y, width, height)
            if variant >= 0:
                self.held = true
                self.use_variant(self.family, variant)
                return true
            let at = self.item_at(event.x, event.y, width, height)
            if at >= 0 and self.items[at].variants.length > 0:
                self.pressing = at
                self.pressed_at = time.now()
                self.family = -1
                return true
            self.held = true
            if at >= 0:
                self.use(self.shown(at))
            else:
                self.close()
            return true
        # A family let go: before the long press, its last variant; after,
        # the variant under the pointer (else they stay up to click).
        if event.kind == EventKind.pointer_up and self.pressing >= 0:
            let at = self.pressing
            self.pressing = -1
            if self.family < 0:
                self.held = true
                self.use(self.shown(at))
                return true
            let variant = self.variant_at(event.x, event.y, width, height)
            if variant >= 0:
                self.held = true
                self.use_variant(at, variant)
            return true
        return event.kind in [EventKind.pointer_up, EventKind.key_down, EventKind.key_up, EventKind.scroll]

    func use(self, item: MarkItem) -> unit!:
        if not item.enabled:
            return
        self.close()
        let run = item.run
        run()

    ## Variant `variant` of family item `at`: used, and remembered.
    func use_variant(self, at: int, variant: int) -> unit!:
        let family = self.items[at]
        self.chosen[family.name] = variant
        self.use(family.variants[variant])