Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.1

0.5.1 / src / layers.luc

## The Layers panel's list: a row per layer with its eye, thumbnails, name and
## blend, groups folding, selection of one or several layers by click, and
## pictures dropped on it placed as new layers.
from luce_ui.ui import Widget, Layout, Size, Constraints, Event, Painter, Font, Point, draw_icon
from luce_gpu.gpu import RenderTarget, Rect, Color
from luce_window.input import EventKind, Cursor
from workspace import Workspace
import theme
from luce_std import math
import time
from kit import dropped_paths
from layer_groups import shown_rows, toggle_folded, is_folded, drop_layer, drop_inside, drop_above, drop_below
from layer_ops import duplicate_selected, OpacityKeys, set_opacity_all
from view_keys import digit_value
from layer_effects import EffectRows

## The layer list: one 52-point row per shown layer, top layer first, each with
## an eye, a thumbnail of the layer's own pixels, its mask's thumbnail when it
## has one, the name and a subtitle, indented when clipped and for each group
## holding it. A group shows a folder instead, which folds it shut or open;
## an adjustment layer its icon (its settings show in Properties).
##
## As in Photoshop: a click selects a row, Cmd-click adds it to the selection
## or takes it out, Shift-click selects a run; the eye toggles visibility, and
## dragging on down the eyes sets theirs the same; the mask thumbnail targets
## the mask for painting, the layer thumbnail the pixels again; Cmd-click on a
## thumbnail loads it as the selection (Shift adds, Alt subtracts) and
## Shift-click on the mask thumbnail disables the mask; a click on the chain
## between the thumbnails unlinks the mask from the pixels (or links it). A
## double-click on the name renames the layer there. Alt-click on the line
## between two rows clips the upper to the lower (or releases it). A row
## dragged lands above the row it is dropped on, or inside a group dropped on
## its middle; with Alt a copy lands there instead. Under a styled layer its
## effects are listed, a line each (layer_effects.luc): the eye hides one,
## the cross deletes it, Alt-drag onto another layer copies it, and a
## double-click opens Layer Style.
pub class LayerList: Widget:
    let box: Layout
    pub let workspace: Workspace
    let font: Font
    let row_height: float = 52.0
    ## A line per effect under a styled layer's row.
    let effect_height: float = 20.0
    pub let effects: EffectRows
    ## An effect line pressed: its layer index and effect kind, or -1.
    var effect_index: int = -1
    var effect_kind: int = -1
    var effect_y: float = 0.0
    ## A double-click on an effect line: open Layer Style for its layer.
    pub var on_open_style: func() -> unit!? = none
    ## A row being dragged to a new place: its layer index and the pointer's y, or -1.
    var drag_index: int = -1
    var drag_y: float = 0.0
    var drag_started: bool = false
    ## A drag down the eyes: the visibility it gives each row it crosses, or none.
    var eye_swipe: bool = false
    var eye_visible: bool = false
    ## The last press, for a double-click: its row's layer and when (ms).
    var last_index: int = -1
    var last_time: int = 0
    ## Digits typed for opacity (layer_ops.OpacityKeys).
    let opacity_keys: OpacityKeys
    ## Pictures dropped on the list: placed as new layers.
    pub var on_place_files: func(list[str]) -> unit!? = none
    ## The layers changed from here (a row dropped): the window refreshes.
    pub var on_changed: func() -> unit!? = none
    ## Layers dragged out of the panel and let go at a window point.
    pub var on_drop_outside: func(float, float) -> unit!? = none
    ## A double-click on a name: rename the layer at that index, its name at (x, y).
    pub var on_rename: func(int, float, float) -> unit!? = none

    pub func init(self, workspace: Workspace, font: Font) -> unit!:
        self.workspace = workspace
        self.font = font
        self.opacity_keys = OpacityKeys()
        self.effects = EffectRows()
        self.box = Layout()
        self.box.set_focusable(true)
        self.box.set_cursor(Cursor.pointer)
        self.box.set_flex()
        # Pictures dropped on the list become layers of the document.
        self.box.set_drop_target(true)

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        let tops = self.tops()
        return Size(252.0, math.max(self.row_height, tops[tops.length - 1]))

    ## A shown row's full height: the layer's own, then a line per listed effect.
    func height_of(self, index: int) -> float!:
        return self.row_height + self.effect_height * float(self.effects.listed(self.workspace.canvas, index).length)

    ## Every shown row's top, top layer first, and past the last the whole height.
    func tops(self) -> list[float]!:
        var tops: list[float] = []
        var y = 0.0
        for index in shown_rows(self.workspace):
            tops.append(y)
            y += self.height_of(index)
        tops.append(y)
        return tops

    ## The layer index of the row at `y` (its effect lines too), or -1.
    func row_of(self, y: float) -> int!:
        let rows = shown_rows(self.workspace)
        let tops = self.tops()
        var row = 0
        while row < rows.length:
            if y >= tops[row] and y < tops[row + 1]:
                return rows[row]
            row += 1
        return -1

    ## Where the row of the layer at `index` starts, or -1 when it is not shown.
    pub func row_top(self, index: int) -> float!:
        let rows = shown_rows(self.workspace)
        let tops = self.tops()
        var row = 0
        while row < rows.length:
            if rows[row] == index:
                return tops[row]
            row += 1
        return -1.0

    ## The effect whose line is at `y` in the row of the layer at `index`, or -1.
    func effect_at(self, index: int, y: float) -> int!:
        let below = y - self.row_top(index) - self.row_height
        if below < 0.0:
            return -1
        let listed = self.effects.listed(self.workspace.canvas, index)
        let line = int(math.floor(below / self.effect_height))
        return listed[line] if line < listed.length else -1

    ## The row edge nearest `y`: its number among the edges (0 above the top
    ## row, the row count below the last) and where it is.
    func edge_near(self, y: float) -> int!:
        let tops = self.tops()
        var best = 0
        var index = 1
        while index < tops.length:
            if math.abs(tops[index] - y) < math.abs(tops[best] - y):
                best = index
            index += 1
        return best

    ## Where the name of the layer at `index` starts.
    pub func name_left(self, index: int) -> float!:
        let masked = self.workspace.canvas.layer_masked(index)
        return self.thumb_left(index) + 44.0 + (38.0 if masked else 0.0)

    ## Where a row's thumbnail starts: past the eye, a step in per group
    ## holding it, and further when clipped.
    func thumb_left(self, index: int) -> float!:
        let canvas = self.workspace.canvas
        return 32.0 + 16.0 * float(canvas.layer_depth(index)) + (24.0 if canvas.layer_clipped(index) else 0.0)

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        let size = target.size()
        let workspace = self.workspace
        let canvas = workspace.canvas
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.surface())
        # As eleusis's tables: the accent while this list has focus, its muted form otherwise.
        let focused = self.box.contains_focus()
        let thumb = 36.0
        let mask_thumb = 30.0
        let tops = self.tops()
        var row = 0
        for index in shown_rows(workspace):
            let top = tops[row]
            let selected = workspace.layers.is_selected(index)
            let group = canvas.layer_is_group(index)
            let clipped = canvas.layer_clipped(index)
            let masked = canvas.layer_masked(index)
            let visible = canvas.layer_visible(index)
            if selected:
                painter.rectangle(Rect(0.0, top, size.width, self.row_height), workspace.look.accent if focused else workspace.look.selection_inactive)
            let ink = theme.on_accent() if selected and focused else (theme.text() if visible else theme.text_muted())
            let soft = theme.on_accent() if selected and focused else theme.text_muted()
            # The eye.
            draw_icon(target, "visible" if visible else "hidden", Rect(6.0, top + (self.row_height - 16.0) * 0.5, 16.0, 16.0), ink)
            var x = self.thumb_left(index)
            let aspect = float(workspace.canvas.width()) / float(workspace.canvas.height())
            let adjustment = canvas.layer_adjustment(index)
            if group:
                # A group: its folder, open or shut, where a layer has its thumbnail.
                let shut = is_folded(workspace, canvas.layer_id(index))
                draw_icon(target, "folder" if shut else "folder-open", Rect(x + 8.0, top + (self.row_height - 20.0) * 0.5, 20.0, 20.0), ink)
                x += thumb + 8.0
            elif adjustment >= 0:
                # An adjustment layer: no pixels, its icon instead.
                draw_icon(target, "color-correction", Rect(x + 8.0, top + (self.row_height - 20.0) * 0.5, 20.0, 20.0), ink)
                x += thumb + 8.0
            else:
                # The layer thumbnail: a checker-grey slot with the layer's own pixels in
                # the document's shape, bordered in the accent when it is the target.
                var tw = thumb
                var th = thumb
                if aspect > 1.0:
                    th = math.max(6.0, thumb / aspect)
                else:
                    tw = math.max(6.0, thumb * aspect)
                let ty = top + (self.row_height - th) * 0.5
                painter.rectangle(Rect(x, ty, tw, th), theme.checker_light())
                canvas.draw_layer(target, index, Rect(x, ty, tw, th), false)
                if index == workspace.layers.selected and not canvas.editing_mask():
                    self.frame(painter, Rect(x - 2.0, ty - 2.0, tw + 4.0, th + 4.0), self.workspace.look.accent)
                if canvas.layer_shaped(index):
                    # A vector layer: the pen's badge on the thumbnail's corner.
                    let badge = Rect(x + tw - 11.0, ty + th - 11.0, 13.0, 13.0)
                    painter.rectangle(badge, theme.grey(20.0))
                    draw_icon(target, "pen-tool", Rect(badge.x + 1.0, badge.y + 1.0, 11.0, 11.0), self.workspace.look.accent)
                x += thumb + 8.0
            if masked:
                # Linked, a chain between the thumbnails, as Photoshop shows it; a click there unlinks.
                if canvas.layer_mask_linked(index):
                    let cx = math.floor(x - 4.0)
                    let cy = math.floor(top + self.row_height * 0.5)
                    painter.rectangle(Rect(cx - 1.0, cy - 6.0, 3.0, 5.0), soft)
                    painter.rectangle(Rect(cx - 1.0, cy + 1.0, 3.0, 5.0), soft)
                    painter.rectangle(Rect(cx, cy - 2.0, 1.0, 4.0), soft)
                var mw = mask_thumb
                var mh = mask_thumb
                if aspect > 1.0:
                    mh = math.max(5.0, mask_thumb / aspect)
                else:
                    mw = math.max(5.0, mask_thumb * aspect)
                let my = top + (self.row_height - mh) * 0.5
                painter.rectangle(Rect(x, my, mw, mh), Color(1.0, 1.0, 1.0))
                canvas.draw_layer(target, index, Rect(x, my, mw, mh), true)
                if not canvas.layer_mask_enabled(index):
                    # Disabled: struck through with a red cross, as Photoshop shows it.
                    let cross = Color(0.85, 0.1, 0.08)
                    painter.line(Point(x, my), Point(x + mw, my + mh), 2.0, cross)
                    painter.line(Point(x + mw, my), Point(x, my + mh), 2.0, cross)
                if index == workspace.layers.selected and canvas.editing_mask():
                    self.frame(painter, Rect(x - 2.0, my - 2.0, mw + 4.0, mh + 4.0), self.workspace.look.accent)
                x += mask_thumb + 8.0
            let name = canvas.layer_name(index)
            painter.text(name, x, top + 10.0, ink, self.font)
            let opacity = int(canvas.layer_opacity(index) * 100.0 + 0.5)
            var subtitle = f"{workspace.edits.blend_name(index)} · {opacity}%"
            if group:
                subtitle = f"Group · {opacity}%"
            elif adjustment >= 0:
                subtitle = f"Adjustment · {opacity}%"
            elif clipped:
                subtitle = f"Clipped · {workspace.edits.blend_name(index)} · {opacity}%"
            elif canvas.layer_shaped(index):
                subtitle = f"Vector · {workspace.edits.blend_name(index)} · {opacity}%"
            painter.text(subtitle, x, top + 30.0, soft, self.font)
            self.draw_effects(painter, target, index, top + self.row_height, size.width)
            painter.rectangle(Rect(0.0, tops[row + 1] - 1.0, size.width, 1.0), theme.border())
            row += 1
        self.draw_drop_indicator(painter, size.width)
        painter.close()

    ## The effect lines under the row of the layer at `index`, from `y`: the
    ## eye, "fx" and the effect's name, a cross at the right.
    func draw_effects(self, painter: Painter, target: RenderTarget, index: int, y: float, width: float) -> unit!:
        let canvas = self.workspace.canvas
        var line = 0
        for kind in self.effects.listed(canvas, index):
            let top = y + float(line) * self.effect_height
            let showing = self.effects.showing(canvas, index, kind)
            let ink = theme.text() if showing else theme.text_muted()
            draw_icon(target, "visible" if showing else "hidden", Rect(8.0, top + 3.0, 14.0, 14.0), ink)
            painter.text("fx  " + self.effects.kind(kind).name, self.thumb_left(index) + 8.0, top + 3.0, ink, self.font)
            painter.text("×", width - 18.0, top + 2.0, theme.text_muted(), self.font)
            line += 1

    ## The drop indicator while a row (or an effect, Alt copying it) is dragged:
    ## an accent line at the row edge it lands on, or a frame round the group
    ## (or the layer) it goes into.
    func draw_drop_indicator(self, painter: Painter, width: float) -> unit!:
        if self.effect_index >= 0 and math.abs(self.drag_y - self.effect_y) > 4.0:
            let target = self.row_of(self.drag_y)
            if target >= 0 and target != self.effect_index:
                self.frame(painter, Rect(0.0, self.row_top(target), width, self.row_height), self.workspace.look.accent)
            return
        if self.drag_index < 0 or not self.drag_started:
            return
        if self.into_group(self.drag_y):
            let group = self.row_of(self.drag_y)
            self.frame(painter, Rect(0.0, self.row_top(group), width, self.row_height), self.workspace.look.accent)
            return
        let tops = self.tops()
        painter.rectangle(Rect(0.0, tops[self.edge_near(self.drag_y)] - 1.0, width, 2.0), self.workspace.look.accent)

    func frame(self, painter: Painter, rect: Rect, color: Color) -> unit!:
        painter.rectangle(Rect(rect.x, rect.y, rect.width, 2.0), color)
        painter.rectangle(Rect(rect.x, rect.y + rect.height - 2.0, rect.width, 2.0), color)
        painter.rectangle(Rect(rect.x, rect.y, 2.0, rect.height), color)
        painter.rectangle(Rect(rect.x + rect.width - 2.0, rect.y, 2.0, rect.height), color)

    ## Whether a drop at `y` is on the middle of a group's row: into the group.
    func into_group(self, y: float) -> bool!:
        let index = self.row_of(y)
        if index < 0 or not self.workspace.canvas.layer_is_group(index):
            return false
        let within = (y - self.row_top(index)) / self.row_height
        return within > 0.3 and within < 0.7

    ## A drop at `y`: onto a group's middle it goes in; otherwise at the row
    ## edge nearest the pointer, above the row below that edge — or, past the
    ## last row, below it. With `copy` (Alt) a copy goes there instead.
    func drop(self, y: float, copy: bool) -> unit!:
        let workspace = self.workspace
        let canvas = workspace.canvas
        # Where it lands, by layer id: a copy shifts the rows.
        let rows = shown_rows(workspace)
        let slot = clamp_int(self.edge_near(y), 0, rows.length)
        let into = self.into_group(y)
        let how = drop_inside if into else (drop_above if slot < rows.length else drop_below)
        let target = canvas.layer_id(self.row_of(y) if into else (rows[slot] if slot < rows.length else rows[rows.length - 1]))
        let dragged = canvas.layer_id(self.drag_index)
        workspace.edits.as_one("Duplicate Layer" if copy else "Move Layer", func () -> unit!:
            var id = dragged
            if copy:
                duplicate_selected(workspace)
                id = workspace.layers.selected_id()
            drop_layer(workspace, id, workspace.layers.index_of(target), how))

    ## The dragged files that can become layers.
    pub func event(self, event: Event) -> unit!:
        # Digits set the selected layers' opacity here too, as on the canvas.
        if event.kind == EventKind.key_down and not event.meta and not event.control and not event.repeated and digit_value(event.key) >= 0:
            set_opacity_all(self.workspace, self.opacity_keys.typed(digit_value(event.key), time.now() // 1000000))
            if let changed = self.on_changed:
                changed()
            return
        if event.kind == EventKind.drag_entered:
            self.box.set_drop_accepted(dropped_paths(self.box, self.workspace.documents.can_place).length > 0)
            return
        if event.kind == EventKind.drop:
            let files = dropped_paths(self.box, self.workspace.documents.can_place)
            if let place = self.on_place_files:
                place(files)
            return
        if event.kind == EventKind.drag_moved or event.kind == EventKind.drag_left:
            return
        if event.kind == EventKind.pointer_down and event.button == 0 and event.inside:
            self.box.request_focus()
            # Alt on the line between two rows clips the upper to the lower.
            if event.alt and not (event.meta or event.control) and self.clip_line(event.y):
                self.box.invalidate()
                return
            let index = self.row_of(event.y)
            if index >= 0 and self.effect_at(index, event.y) >= 0:
                self.press_effect(index, self.effect_at(index, event.y), event)
            elif index >= 0:
                self.press(index, event)
                # The selection or a layer's state changed: Properties and the rest follow.
                if let changed = self.on_changed:
                    changed()
            self.box.invalidate()
        elif event.kind == EventKind.pointer_moved and self.eye_swipe:
            let index = self.row_of(event.y)
            if index >= 0 and self.workspace.canvas.layer_visible(index) != self.eye_visible:
                let canvas = self.workspace.canvas
                canvas.set_layer(canvas.layer_id(index), self.eye_visible, canvas.layer_opacity(index), canvas.layer_blend(index))
                self.workspace.touch()
                self.box.invalidate()
        elif event.kind == EventKind.pointer_up and event.button == 0 and self.eye_swipe:
            self.eye_swipe = false
        elif event.kind == EventKind.pointer_moved and self.effect_index >= 0:
            self.drag_y = event.y
            self.box.invalidate()
        elif event.kind == EventKind.pointer_up and event.button == 0 and self.effect_index >= 0:
            # An effect dragged with Alt onto another layer is copied there.
            let target = self.row_of(event.y)
            if event.alt and target >= 0 and target != self.effect_index and math.abs(event.y - self.effect_y) > 4.0:
                self.effects.copy(self.workspace, self.effect_index, self.effect_kind, target)
                if let changed = self.on_changed:
                    changed()
            self.effect_index = -1
            self.effect_kind = -1
            self.box.invalidate()
        elif event.kind == EventKind.pointer_moved and self.drag_index >= 0:
            if math.abs(event.y - self.drag_y) > 4.0:
                self.drag_started = true
            if self.drag_started:
                self.drag_y = event.y
                self.box.invalidate()
        elif event.kind == EventKind.pointer_up and event.button == 0 and self.drag_index >= 0:
            let dropped_outside = not event.inside
            if self.drag_started and dropped_outside:
                # Onto another document's tab, say.
                if let outside = self.on_drop_outside:
                    let bounds = self.box.bounds()
                    outside(bounds.x + event.x, bounds.y + event.y)
            elif self.drag_started:
                self.drop(event.y, event.alt)
                if let changed = self.on_changed:
                    changed()
            self.drag_index = -1
            self.drag_started = false
            self.box.invalidate()
        elif event.cancelled:
            self.effect_index = -1
            self.drag_index = -1
            self.drag_started = false
            self.eye_swipe = false
            self.box.invalidate()

    ## An Alt-click at `y`: on the line between two rows (within 5 points), the
    ## upper row's layer clipped to the one below, or released. Whether it was.
    func clip_line(self, y: float) -> bool!:
        let rows = shown_rows(self.workspace)
        let tops = self.tops()
        let line = self.edge_near(y)
        if line < 1 or line >= rows.length or math.abs(y - tops[line]) > 5.0:
            return false
        let upper = rows[line - 1]
        let canvas = self.workspace.canvas
        if canvas.layer_is_group(upper):
            return false
        self.workspace.edits.as_one("Clipping Mask", func () -> unit!:
            canvas.set_clipped(canvas.layer_id(upper), not canvas.layer_clipped(upper)))
        self.workspace.touch()
        return true

    ## A press on an effect's line under the layer at `index`: its eye hides or
    ## shows it, its cross deletes it, a double-click opens Layer Style, and a
    ## drag (with Alt) copies it to another layer.
    func press_effect(self, index: int, kind: int, event: Event) -> unit!:
        let workspace = self.workspace
        workspace.layers.select(index)
        if event.x < 28.0:
            self.effects.toggle(workspace, index, kind)
            return
        if event.x > self.box.bounds().width - 24.0:
            self.effects.remove(workspace, index, kind)
            return
        let now = time.now() // 1000000
        if index == self.last_index and now - self.last_time <= 400:
            self.last_index = -1
            if let open = self.on_open_style:
                open()
            return
        self.last_index = index
        self.last_time = now
        self.effect_index = index
        self.effect_kind = kind
        self.effect_y = event.y
        self.drag_y = event.y

    ## A press on the row of the layer at `index`.
    func press(self, index: int, event: Event) -> unit!:
        let workspace = self.workspace
        let canvas = workspace.canvas
        let command = event.meta or event.control
        let thumb = self.thumb_left(index)
        let mask_left = thumb + 44.0
        let on_thumb = event.x >= thumb and event.x < thumb + 36.0
        let on_mask = canvas.layer_masked(index) and event.x >= mask_left and event.x < mask_left + 30.0
        let on_link = canvas.layer_masked(index) and event.x >= thumb + 36.0 and event.x < mask_left
        let mode = 1 if event.shift else (2 if event.alt else 0)
        if event.x < 28.0:
            # The eye; a drag on down the eyes gives them the same.
            canvas.set_layer(canvas.layer_id(index), not canvas.layer_visible(index), canvas.layer_opacity(index), canvas.layer_blend(index))
            self.eye_swipe = true
            self.eye_visible = canvas.layer_visible(index)
            workspace.touch()
        elif canvas.layer_is_group(index) and on_thumb:
            toggle_folded(workspace, canvas.layer_id(index))
        elif command and (on_thumb or on_mask):
            # Cmd-click on a thumbnail: its pixels' transparency (or the mask) as the selection.
            canvas.select_from_layer(canvas.layer_id(index), on_mask, mode)
            workspace.touch()
        elif on_link:
            # Between the thumbnails: link the mask to the pixels, or unlink it.
            canvas.link_mask(canvas.layer_id(index), not canvas.layer_mask_linked(index))
            workspace.touch()
        elif on_mask and event.shift:
            canvas.enable_mask(canvas.layer_id(index), not canvas.layer_mask_enabled(index))
            workspace.touch()
        elif command:
            workspace.layers.toggle_picked(index)
        elif event.shift:
            workspace.layers.pick_range(index)
        else:
            # A second press on the name soon after the first renames it.
            let now = time.now() // 1000000
            let again = index == self.last_index and now - self.last_time <= 400
            self.last_index = index
            self.last_time = now
            if again and event.x >= self.name_left(index):
                self.last_index = -1
                if let rename = self.on_rename:
                    rename(index, self.name_left(index), self.row_top(index) + 6.0)
                return
            workspace.layers.select(index)
            self.drag_index = index
            self.drag_y = event.y
            self.drag_started = false
            if on_mask:
                canvas.edit_mask(true)
            elif on_thumb or event.x < mask_left:
                canvas.edit_mask(false)
            workspace.touch()

func clamp_int(value: int, low: int, high: int) -> int:
    return low if value < low else (high if value > high else value)