Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.1

0.5.1 / src / text_editing.luc

## Live type, after Compositor's: the Text tool clicks a new text layer into
## place (or drags a box for it to wrap in), or clicks an existing one to edit
## it, and the words are typed in a floating editor while the layer is set
## again at every keystroke. Commit (Cmd-Return) keeps it — a new layer named
## by its first words, or gone if left empty; Cancel puts it back as it was.
from luce_ui.ui import Text, HStack, Spacer, Size, Dialog, TextEditor, Command
from interop import Connection
from workspace import Workspace
from kit import Kit

pub class TextEditing:
    pub let dialog: Dialog
    let editor: TextEditor
    ## The text layer being edited (0: none), and whether it was made for this.
    pub var id: int = 0
    var created: bool = false
    ## Where it is set: the first line's top-left, and the box it wraps in (0: point text).
    var x: float = 0.0
    var y: float = 0.0
    var box_width: float = 0.0
    ## The history step before the edit began: Cancel undoes back to it.
    var start: int = 0
    ## A new layer's making, naming and typing are one undo step, "Add Text",
    ## held open until it is committed or cancelled.
    var grouping: bool = false
    ## Set while the editor is filled from code, so that is not taken as typing.
    var loading: bool = false
    let connections: list[Connection]
    ## The window redraws after each change; what failed is said.
    pub var changed: func() -> unit!? = none
    pub var failed: func(str) -> unit!? = none
    let workspace: Workspace

    ## `commit` is the command that commits (its shortcut is shown).
    pub func init(self, workspace: Workspace, kit: Kit, commit: Command) -> unit!:
        self.workspace = workspace
        self.connections = []
        self.editor = TextEditor("", line_numbers = false, font = kit.font, wrap = true)
        self.editor.layout().set_limits(Size(360.0, 120.0), Size(360.0, 240.0))
        self.connections.append(self.editor.on_change(self.typed))
        self.dialog = Dialog([Text("Text", font = kit.font), self.editor,
                              HStack([Text(commit.shortcut().text() + " commits", font = kit.font, muted = true), Spacer(), kit.button("Cancel", self.cancel),
                                      kit.button("Commit", self.commit)], spacing = 8.0)], width = 400.0)
        kit.dialog_keys(self.dialog, self.cancel, self.commit)
        self.dialog.layout().set_modal(false)

    pub func active(self) -> bool:
        return self.id != 0

    ## A new text layer, its first line's top-left at (`x`, `y`), wrapping in
    ## `box_width` pixels (0: point text).
    pub func begin_new(self, x: float, y: float, box_width: float) -> unit!:
        self.finish_any()
        let workspace = self.workspace
        self.start = workspace.canvas.step_serial()
        workspace.canvas.begin_edit("Add Text")
        self.grouping = true
        workspace.edits.add_layer()
        self.id = workspace.layers.selected_id()
        # Named by its words when committed; until then, plainly a text layer.
        workspace.canvas.rename_layer(self.id, "Text")
        self.created = true
        self.x = x
        self.y = y
        self.box_width = box_width
        self.set_words("")
        self.open("")

    ## The text layer at `index`, edited where it is.
    pub func begin_existing(self, index: int) -> unit!:
        self.finish_any()
        let canvas = self.workspace.canvas
        self.workspace.layers.select(index)
        self.id = canvas.layer_id(index)
        self.created = false
        self.x = canvas.layer_type_value(index, 4)
        self.y = canvas.layer_type_value(index, 5)
        self.box_width = canvas.layer_type_value(index, 6)
        self.workspace.tools.typing.take(canvas, index)
        # This edit is its own step, even after typing into the same layer before.
        canvas.separate_next_step()
        self.start = canvas.step_serial()
        self.open(canvas.layer_text(index))

    func open(self, text: str) -> unit!:
        self.loading = true
        self.editor.set_text(text)
        self.loading = false
        self.dialog.open()
        self.editor.layout().request_focus()
        self.refresh()

    ## A keystroke: the layer set again from the editor's words.
    func typed(self) -> unit!:
        if self.loading or self.id == 0:
            return
        self.set_words(self.editor.text()) catch failure:
            self.fail(f"Text: {failure.message}")

    ## The editor's words replaced, as if typed.
    pub func replace_text(self, text: str) -> unit!:
        self.editor.set_text(text)

    ## The header changed the family, size or the like: the text being
    ## edited is set again, or else the selected text layer takes it.
    pub func restyle(self) -> unit!:
        if self.id != 0:
            self.set_words(self.editor.text())
            return
        let workspace = self.workspace
        let index = workspace.layers.selected
        if index < 0 or index >= workspace.canvas.layer_count() or not workspace.canvas.layer_typed(index):
            return
        let canvas = workspace.canvas
        let options = workspace.tools.typing
        workspace.canvas.set_type(canvas.layer_id(index), canvas.layer_text(index), options.family, options.style, options.size,
                                  canvas.layer_type_value(index, 1), canvas.layer_type_value(index, 2), canvas.layer_type_value(index, 3),
                                  canvas.layer_type_value(index, 4), canvas.layer_type_value(index, 5), canvas.layer_type_value(index, 6),
                                  options.alignment, options.tracking, options.leading)
        workspace.touch()
        self.refresh()

    func set_words(self, text: str) -> unit!:
        let workspace = self.workspace
        let options = workspace.tools.typing
        workspace.canvas.set_type(self.id, text, options.family, options.style, options.size, workspace.colors.red, workspace.colors.green, workspace.colors.blue,
                                  self.x, self.y, self.box_width, options.alignment, options.tracking, options.leading)
        workspace.touch()
        self.refresh()

    ## Keep it: a new layer takes its first words as its name, or goes if empty.
    pub func commit(self) -> unit!:
        if self.id == 0:
            return
        self.keep_words()
        self.end_group()

    func keep_words(self) -> unit!:
        let id = self.id
        let text = self.editor.text()
        self.close()
        let workspace = self.workspace
        let index = workspace.layers.index_of(id)
        if index < 0 or not self.created:
            return
        if text.trim() == "":
            workspace.canvas.remove_layer(id)
            workspace.layers.select(0 if workspace.canvas.layer_count() > 0 else 0)
        else:
            workspace.canvas.rename_layer(id, layer_name_of(text))
        workspace.touch()
        self.refresh()

    ## Put it back as it was: the edit's steps are undone, so a new layer goes
    ## and an existing one has its words and style again; an edit that changed
    ## nothing leaves the document unmodified.
    pub func cancel(self) -> unit!:
        if self.id == 0:
            return
        self.close()
        self.end_group()
        let workspace = self.workspace
        let canvas = workspace.canvas
        while canvas.step_serial() != self.start and canvas.can_undo() and not canvas.previewing():
            workspace.undo()
        self.refresh()

    ## Close the "Add Text" step, if one is open.
    func end_group(self):
        if self.grouping:
            self.grouping = false
            self.workspace.canvas.end_edit()

    func close(self):
        self.id = 0
        self.dialog.hide()

    ## Another edit starting keeps what the last one typed.
    func finish_any(self) -> unit!:
        if self.id != 0:
            self.commit()

    func refresh(self) -> unit!:
        if let changed = self.changed:
            changed()

    func fail(self, message: str) -> unit!:
        if let failed = self.failed:
            failed(message)

    pub func close_all(self):
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()

## A layer's name from its words: the first line, at most 32 letters.
func layer_name_of(text: str) -> str:
    let first = text.trim().lines()[0] if text.trim() != "" else "Text"
    return first[..<32] if first.length > 32 else first