Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.0

0.5.0 / src / script_commands.luc

## What a script's lines do. A script run by the editor prints one line for
## each call into the scripting API (scripting/luced.luc): `@l2d`, the
## action's name and its fields, tab-separated, with tabs, newlines and
## backslashes escaped. `parse_line` reads such a line back; `ScriptCommands`
## does the action to the workspace, as the menus and tools would.
from workspace import Workspace
from actions import Actions
from luce_image.canvas import Canvas
from adjustments import Adjustment, adjustments, filter_table, gradient_map, blur_kind, noise_kind, first_filter_kind
from script_transforms import is_transform_action, apply_transform
from script_vectors import is_vector_action, apply_vector
from script_nodes import NodeNames, is_node_action, apply_node
from alpha_channels import save_selection, load_selection, delete_channel, channel_named
from luce_color import transfer
from luce_ui import ui

## One action a script asked for: its name and fields.
pub class ScriptLine:
    pub let action: str
    pub let fields: list[str]

    pub func init(self, action: str, fields: list[str]):
        self.action = action
        self.fields = fields

## The action in a line a script printed, or none for plain output.
pub func parse_line(text: str) -> ScriptLine?:
    if not text.starts_with("@l2d "):
        return none
    let parts = text[5..<text.length].split("\t")
    var fields: list[str] = []
    var index = 1
    while index < parts.length:
        fields.append(unescape(parts[index]))
        index += 1
    return ScriptLine(parts[0], fields)

## A field with its escapes (\\t, \\n, \\\\) undone.
func unescape(text: str) -> str:
    if not text.contains("\\"):
        return text
    var plain = ""
    var escaped = false
    for character in text:
        if escaped:
            plain = plain + ("\t" if character == "t" else ("\n" if character == "n" else character))
            escaped = false
        elif character == "\\":
            escaped = true
        else:
            plain = plain + character
    return plain

pub class ScriptCommands:
    let workspace: Workspace
    ## The menu commands, for `run`; none headless without them.
    let actions: Actions?
    ## A tiny canvas on the documents' device, alive for the whole run, that
    ## documents a script opens bind beside (the one open when it started may
    ## close: opening a file replaces an untouched Untitled).
    var anchor: Canvas? = none
    ## The names the run gave the nodes it added.
    let node_names: NodeNames

    pub func init(self, workspace: Workspace, actions: Actions? = none):
        self.workspace = workspace
        self.actions = actions
        self.node_names = NodeNames()

    ## Before a run: the anchor on the device the open document is bound to
    ## (drawn in the window, or bound headless).
    pub func prepare(self) -> unit!:
        if self.anchor != none or not self.workspace.canvas.is_bound():
            return
        let anchor = Canvas(1, 1)
        anchor.bind_beside(self.workspace.canvas)
        self.anchor = anchor

    ## A document just opened or made, ready to edit at once — without a
    ## window to draw it first — on the documents' device.
    func bind_new(self) -> unit!:
        let anchor = self.anchor else return
        if not self.workspace.canvas.is_bound():
            self.workspace.canvas.bind_beside(anchor)

    pub func close(self):
        if let anchor = self.anchor:
            anchor.close()
        self.anchor = none

    ## Do `line`'s action; a wrong field or a failed action fails with why.
    pub func apply(self, line: ScriptLine) -> unit!:
        let workspace = self.workspace
        let action = line.action
        let fields = line.fields
        if action == "new_document":
            workspace.documents.create(number(fields, 0), number(fields, 1))
            self.bind_new()
        elif action == "open":
            workspace.documents.open(field(fields, 0))
            self.bind_new()
            # The script's next line acts on the picture: it waits for it.
            workspace.canvas.finish_opening()
        elif action == "save":
            workspace.documents.save(field(fields, 0))
        elif action == "export":
            workspace.documents.export(field(fields, 0), number(fields, 1))
        elif action == "place":
            workspace.documents.place_file(field(fields, 0), float(workspace.canvas.width()) * 0.5, float(workspace.canvas.height()) * 0.5)
            workspace.canvas.finish_opening()
        elif action == "undo":
            workspace.undo()
        elif action == "redo":
            workspace.redo()
        elif action == "run":
            self.run(field(fields, 0))
        else:
            self.apply_layers(action, fields)

    ## The alpha channel called `name`, or why there is none.
    func channel(self, name: str) -> int!:
        let index = channel_named(self.workspace, name)
        if index < 0:
            error(ui.invalid, f"there is no channel {name}")
        return index

    ## Layers, painting and selections.
    func apply_layers(self, action: str, fields: list[str]) -> unit!:
        let workspace = self.workspace
        if action == "add_layer":
            workspace.edits.add_layer()
            workspace.edits.rename(field(fields, 0))
        elif action == "select_layer":
            let index = number(fields, 0)
            if index < 0 or index >= workspace.canvas.layer_count():
                error(ui.invalid, f"there is no layer {index}")
            workspace.layers.select(index)
        elif action == "select_layer_named":
            workspace.layers.select(self.layer_named(field(fields, 0)))
        elif action == "rename_layer":
            workspace.edits.rename(field(fields, 0))
        elif action == "delete_layer":
            workspace.edits.delete_layer()
        elif action == "duplicate_layer":
            workspace.edits.duplicate()
        elif action == "merge_down":
            workspace.edits.merge_down()
        elif action == "reorder":
            let steps = number(fields, 0)
            var moved = 0
            while moved < (steps if steps > 0 else -steps):
                workspace.edits.reorder(1 if steps > 0 else -1)
                moved += 1
        elif action == "set_opacity":
            workspace.edits.set_opacity(decimal(fields, 0))
        elif action == "set_blend":
            workspace.edits.set_blend(blend_named(field(fields, 0)))
        elif action == "set_visible":
            if workspace.canvas.layer_visible(workspace.layers.selected) != flag(fields, 0):
                workspace.edits.toggle_visibility()
        elif action == "move_by":
            workspace.edits.move_layer(number(fields, 0), number(fields, 1))
        elif action == "add_mask":
            if not workspace.canvas.layer_masked(workspace.layers.selected):
                workspace.edits.toggle_mask()
        else:
            self.apply_painting(action, fields)

    func apply_painting(self, action: str, fields: list[str]) -> unit!:
        let workspace = self.workspace
        if action == "set_color":
            workspace.colors.set_palette(linear(fields, 0), linear(fields, 1), linear(fields, 2), false)
        elif action == "set_background":
            workspace.colors.set_palette(linear(fields, 0), linear(fields, 1), linear(fields, 2), true)
        elif action == "set_brush":
            workspace.tools.brush.diameter = decimal(fields, 0)
            workspace.tools.brush.hardness = decimal(fields, 1)
            workspace.tools.brush.opacity = decimal(fields, 2)
        elif action == "stroke":
            self.stroke(flag(fields, 0), fields)
        elif action == "fill":
            workspace.painting.fill_selection(false)
        elif action == "clear":
            workspace.painting.fill_selection(true)
        elif action == "gradient":
            let radial = workspace.tools.gradient_radial
            workspace.tools.gradient_radial = flag(fields, 4)
            workspace.painting.fill_gradient(decimal(fields, 0), decimal(fields, 1), decimal(fields, 2), decimal(fields, 3)) catch failure:
                workspace.tools.gradient_radial = radial
                error(failure.code, failure.message)
            workspace.tools.gradient_radial = radial
        elif action == "text":
            self.text_layer(decimal(fields, 0), decimal(fields, 1), field(fields, 2), decimal(fields, 3))
        elif action == "select_rectangle":
            workspace.canvas.select_rectangle(number(fields, 0), number(fields, 1), number(fields, 2), number(fields, 3), number(fields, 4))
        elif action == "select_ellipse":
            workspace.canvas.select_ellipse(number(fields, 0), number(fields, 1), number(fields, 2), number(fields, 3), number(fields, 4))
        elif action == "select_all":
            workspace.selection.select_all()
        elif action == "deselect":
            workspace.selection.deselect()
        elif action == "invert_selection":
            workspace.selection.invert_selection()
        elif action == "modify_selection":
            workspace.selection.adjust_selection(number(fields, 0), number(fields, 1))
        elif action == "border_selection":
            workspace.selection.border_selection(number(fields, 0))
        elif action == "smooth_selection":
            workspace.selection.smooth_selection(number(fields, 0))
        elif action == "grow_selection":
            let tolerance = workspace.tools.tolerance
            workspace.tools.tolerance = decimal(fields, 1)
            workspace.selection.grow_selection(flag(fields, 0)) catch failure:
                workspace.tools.tolerance = tolerance
                error(failure.code, failure.message)
            workspace.tools.tolerance = tolerance
        elif action == "magnetic_lasso":
            let canvas = workspace.canvas
            if fields.length < 10:
                error(ui.invalid, "the Magnetic Lasso needs three points or more")
            canvas.begin_magnetic(decimal(fields, 4), decimal(fields, 5), 0, decimal(fields, 0), decimal(fields, 1), number(fields, 2))
            var at = 6
            while at + 1 < fields.length:
                canvas.anchor_magnetic(decimal(fields, at), decimal(fields, at + 1)) catch failure:
                    canvas.cancel_magnetic()
                    error(failure.code, failure.message)
                at += 2
            workspace.tools.selecting.apply(canvas, false)
            canvas.close_magnetic(number(fields, 3))
            workspace.touch()
        elif action == "select_and_mask":
            workspace.selection.begin_refine()
            workspace.selection.finish_refine(true, number(fields, 0), number(fields, 1), number(fields, 2), decimal(fields, 3), decimal(fields, 4)) catch failure:
                workspace.selection.finish_refine(false, 0, 0, 0, 0.0, 0.0)
                error(failure.code, failure.message)
        elif action == "quick_mask":
            if flag(fields, 0) != workspace.canvas.quick_mask():
                workspace.selection.toggle_quick_mask()
        elif action == "save_selection":
            _ = save_selection(workspace, field(fields, 0))
        elif action == "load_selection":
            load_selection(workspace, self.channel(field(fields, 0)), number(fields, 1))
        elif action == "delete_channel":
            delete_channel(workspace, self.channel(field(fields, 0)))
        elif action == "transform_selection":
            workspace.canvas.begin_selection_transform()
            workspace.canvas.preview_selection_transform(decimal(fields, 0), decimal(fields, 1), decimal(fields, 2), decimal(fields, 3), decimal(fields, 4), decimal(fields, 5), decimal(fields, 6)) catch failure:
                workspace.canvas.end_selection_transform(false)
                error(failure.code, failure.message)
            workspace.canvas.end_selection_transform(true)
        elif action == "select_color_range":
            var colors: list[float] = []
            var subtract: list[bool] = []
            var at = 3
            while at + 3 < fields.length:
                colors = colors + [decimal(fields, at), decimal(fields, at + 1), decimal(fields, at + 2)]
                subtract.append(flag(fields, at + 3))
                at += 4
            workspace.selection.select_color_range(number(fields, 0), decimal(fields, 1), flag(fields, 2), colors, subtract)
        else:
            self.apply_pixels(action, fields)

    ## Adjustments, filters and the canvas.
    func apply_pixels(self, action: str, fields: list[str]) -> unit!:
        let workspace = self.workspace
        if action == "adjust" or action == "adjustment_layer":
            let spec = find(adjustments(), field(fields, 0))
            var numbers = spec.engine(settings(spec, fields))
            if spec.kind == gradient_map:
                numbers = numbers + workspace.colors.colors_encoded()
            if action == "adjust":
                workspace.previews.adjust(spec.kind, numbers)
            else:
                _ = workspace.previews.add_adjustment_layer(spec.kind, spec.name, numbers)
        elif action == "filter":
            self.filter(field(fields, 0), fields)
        elif action == "resize_image":
            workspace.image.resize_image(number(fields, 0), number(fields, 1))
        elif action == "resize_canvas":
            workspace.image.resize_canvas(number(fields, 0), number(fields, 1), number(fields, 2), number(fields, 3))
        elif action == "crop":
            workspace.image.resize_canvas(number(fields, 2), number(fields, 3), -number(fields, 0), -number(fields, 1))
        elif action == "flip_canvas":
            workspace.image.flip_canvas(flag(fields, 0))
        elif action == "set_linear_blend":
            workspace.image.set_linear_blend(flag(fields, 0))
        elif is_transform_action(action):
            apply_transform(workspace, action, fields)
        elif is_vector_action(action):
            apply_vector(workspace, action, fields)
        elif is_node_action(action):
            apply_node(workspace, self.node_names, action, fields)
        else:
            error(ui.invalid, f"no such action: {action}")

    ## A menu command by id, as the user would choose it.
    func run(self, id: str) -> unit!:
        let actions = self.actions else error(ui.invalid, "menu commands need the editor's window")
        # Which commands can run follows the document as it is now: headless,
        # no window refreshes it.
        actions.update(self.workspace)
        for command in actions.all:
            if command.id() == id:
                if not command.is_enabled():
                    error(ui.invalid, f"{id} cannot be done now")
                command.trigger()
                return
        error(ui.invalid, f"no such command: {id}")

    ## One stroke through the x, y pairs after the first field, with the brush
    ## or, erasing, the eraser — whatever tool is in hand.
    func stroke(self, erase: bool, fields: list[str]) -> unit!:
        let workspace = self.workspace
        if fields.length < 3:
            error(ui.invalid, "a stroke needs at least one point")
        let tool = workspace.tools.tool
        let erasing = workspace.tools.erasing
        workspace.tools.tool = "eraser" if erase else "brush"
        workspace.tools.erasing = erase
        self.draw(fields) catch failure:
            workspace.tools.tool = tool
            workspace.tools.erasing = erasing
            error(failure.code, failure.message)
        workspace.tools.tool = tool
        workspace.tools.erasing = erasing

    func draw(self, fields: list[str]) -> unit!:
        let workspace = self.workspace
        workspace.painting.begin_stroke(decimal(fields, 1), decimal(fields, 2))
        var index = 3
        while index + 1 < fields.length:
            workspace.painting.extend_stroke(decimal(fields, index), decimal(fields, index + 1))
            index += 2
        workspace.painting.end_stroke()

    ## A text layer of `words` at (`x`, `y`), `size` points, in the foreground color.
    func text_layer(self, x: float, y: float, words: str, size: float) -> unit!:
        let workspace = self.workspace
        let options = workspace.tools.typing
        workspace.edits.as_one("Add Text", func () -> unit!:
            workspace.edits.add_layer()
            workspace.canvas.set_type(workspace.layers.selected_id(), words, options.family, options.style, size, workspace.colors.red, workspace.colors.green, workspace.colors.blue, x, y)
            workspace.edits.rename(words))

    ## A filter by its dialog's name, with its settings as the dialog shows them.
    func filter(self, name: str, fields: list[str]) -> unit!:
        let workspace = self.workspace
        let spec = find(filter_table(), name)
        let values = settings(spec, fields)
        let numbers = spec.engine(values)
        if spec.kind == blur_kind:
            workspace.previews.blur(values[0])
        elif spec.kind == noise_kind:
            workspace.canvas.add_noise(workspace.layers.selected_id(), numbers[0], values[1] != 0.0, 1, values[2] != 0.0)
            workspace.touch()
        else:
            let padded = numbers + [0.0, 0.0]
            workspace.canvas.filter_layer(workspace.layers.selected_id(), spec.kind - first_filter_kind, padded[0], padded[1], padded[2])
            workspace.touch()

    ## The topmost layer called `name`.
    func layer_named(self, name: str) -> int!:
        var index = self.workspace.canvas.layer_count() - 1
        while index >= 0:
            if self.workspace.canvas.layer_name(index) == name:
                return index
            index -= 1
        error(ui.invalid, f"no layer is called {name}")

## The adjustment or filter called `name` (case aside) in `table`.
func find(table: list[Adjustment], name: str) -> Adjustment!:
    for spec in table:
        if spec.name.lower() == name.lower() or spec.name.replace(" / ", "/").lower() == name.lower():
            return spec
    error(ui.invalid, f"no adjustment or filter is called {name}")

## `spec`'s shown values: the fields after its name in place of its defaults.
func settings(spec: Adjustment, fields: list[str]) -> list[float]!:
    var values = spec.defaults()
    var index = 1
    while index < fields.length and index - 1 < values.length:
        values[index - 1] = decimal(fields, index)
        index += 1
    return values

## The blend mode called `name` (case aside), by number.
func blend_named(name: str) -> int!:
    var mode = 0
    while mode < Canvas.blend_mode_count():
        if Canvas.blend_mode_name(mode).lower() == name.lower():
            return mode
        mode += 1
    error(ui.invalid, f"no blend mode is called {name}")

func field(fields: list[str], index: int) -> str!:
    if index >= fields.length:
        error(ui.invalid, f"field {index + 1} is missing")
    return fields[index]

func number(fields: list[str], index: int) -> int!:
    return int(float(field(fields, index)))

func decimal(fields: list[str], index: int) -> float!:
    return float(field(fields, index))

func flag(fields: list[str], index: int) -> bool!:
    return bool(field(fields, index))

## An sRGB field as the linear value the workspace keeps.
func linear(fields: list[str], index: int) -> float!:
    return transfer.srgb_decode(decimal(fields, index))