Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.4

0.11.4 / src / code_editor.luc

## The Code node's editor: luce-ui's TextEditor with line numbers and Luce
## highlighting from luced's TextMate grammar (code_grammar.luc). What is
## typed goes to the node as one undo step when typing pauses, when the
## editor loses focus, or on Cmd/Ctrl+Enter: not every keystroke. Completions
## and hover text come from luce-geocore's Code.complete and Code.hover, which
## read the API's docs from its stubs; a Script node's from ScriptHelp, which
## reads its script's check package (script_check.luc) once that is warm: a
## completion asked before then is asked again when it is.
from luce_ui.ui import TextEditor, Highlight, Font, Diagnostic, Severity, CompletionList, CompletionKind
from luce_geocore.geocore import Code, ScriptHelp
from luce_gpu.gpu import Color
from luce_textmate.textmate import Grammar, Tokenizer
from interop import Connection
from code_grammar import luce_grammar
import theme
import time

## How long typing pauses before the text goes to the node (ns).
let pause = 400000000

pub class CodeEditor:
    pub let editor: TextEditor
    let tokens: Tokenizer
    ## The text as the node last took it, and when the editor last changed.
    var committed: str = ""
    var changed_at: int = 0
    var colored: int = -1
    ## Takes the text when it is committed.
    pub var on_commit: func(str) -> unit!? = none
    ## A check a pause runs before the text goes to the node (a Script node's
    ## `luc check`): it gets the text, and `checked` sends it on when clean.
    ## Leaving the editor sends what is held anyway.
    pub var on_pause: func(str) -> unit!? = none
    var held: bool = false
    ## The node's Run Over code, which text this editor holds (0 the body, 1 the
    ## header) and the editor of the other, for completions and hover.
    pub var run_over: int = 1
    pub var part: int = 0
    pub var partner: CodeEditor? = none
    ## For a Script node, the script file of its check package, which
    ## completion and hover read ("" the Code node's API), and whether its
    ## package set is warm (`set_script_ready`); a completion asked while it
    ## is not waits for it.
    pub var script_file: str = ""
    var script_ready: bool = true
    var completion_waits: bool = false
    let connections: list[Connection]

    pub func init(self, font: Font) -> unit!:
        self.editor = TextEditor("", font = font, line_numbers = true)
        self.tokens = Tokenizer(Grammar(luce_grammar()))
        self.connections = [self.editor.on_change(self.edited)]
        self.editor.set_completion_provider(self.complete)
        self.editor.set_hover_provider(self.hover)

    ## Show `text` (another node, an undo) unless it is what is being typed.
    pub func show(self, text: str) -> unit!:
        if text == self.committed and self.changed_at == 0:
            return
        if self.changed_at != 0 and self.editor.layout().is_focused():
            return
        self.committed = text
        self.changed_at = 0
        if self.editor.text() != text:
            self.editor.set_text(text)
        self.color()

    func edited(self) -> unit!:
        self.changed_at = time.now()
        self.color()

    ## Polled each frame: a pause in typing commits (or checks first), and so
    ## does the focus gone.
    pub func poll(self) -> unit!:
        if self.changed_at == 0:
            if self.held and not self.editor.layout().is_focused():
                self.commit()
            return
        if not self.editor.layout().is_focused():
            self.commit()
            return
        if time.now() - self.changed_at < pause:
            return
        if let check = self.on_pause:
            self.changed_at = 0
            self.held = true
            check(self.editor.text())
            return
        self.commit()

    ## The pause's check of `text` came back clean: send it, unless more was
    ## typed since.
    pub func checked(self, text: str) -> unit!:
        if self.held and self.changed_at == 0 and self.editor.text() == text:
            self.commit()

    ## Hand the text to the node now (Cmd/Ctrl+Enter, or a pause).
    pub func commit(self) -> unit!:
        self.changed_at = 0
        self.held = false
        let text = self.editor.text()
        if text == self.committed:
            return
        self.committed = text
        if let take = self.on_commit:
            take(text)

    ## Color the text by its tokens' scopes.
    func color(self) -> unit!:
        let version = self.editor.version()
        if version == self.colored:
            return
        let length = self.editor.length()
        let count = self.tokens.tokenize(self.editor.text_range(0, length))
        var spans: list[Highlight] = []
        for i in 0..<count:
            if let ink = scope_color(self.tokens.span_scope(i)):
                spans.append(Highlight(self.tokens.span_start(i), self.tokens.span_end(i), ink))
        if self.editor.update_highlights(0, length, spans, version):
            self.colored = version

    ## Mark the cook's error at `line`, columns `start`..<`end` (1-based, as
    ## the compiler counts), with `message` on hover; none when `line` is 0.
    pub func show_error(self, line: int, start: int, end: int, message: str) -> unit!:
        if line <= 0:
            self.editor.clear_diagnostics()
            return
        self.editor.set_diagnostics([Diagnostic(line, start, end, Severity.error, message)])

    ## What may come at the caret: the members after a dot, else the locals, the
    ## header's helpers, the lib and the keywords.
    func complete(self, items: CompletionList) -> unit!:
        if self.script_file != "" and not self.script_ready:
            self.completion_waits = true
            return
        let line = self.line_of(items.caret())
        let column = items.caret() - self.editor.line_start(items.caret()) + 1
        let found = ScriptHelp.complete(self.script_file, self.editor.text(), line, column) if self.script_file != "" else Code.complete(self.run_over, self.header_text(), self.body_text(), self.part, line, column)
        for at in 0..<found.count():
            let detail = found.detail(at)
            items.add(found.label(at), completion_kind(found.kind(at), detail), detail, found.doc(at))

    ## The signature and doc of the word at `offset`, or "".
    func hover(self, offset: int) -> str!:
        let column = offset - self.editor.line_start(offset) + 1
        if self.script_file != "":
            if not self.script_ready:
                return ""
            return ScriptHelp.hover(self.script_file, self.editor.text(), self.line_of(offset), column)
        return Code.hover(self.run_over, self.header_text(), self.body_text(), self.part, self.line_of(offset), column)

    ## Whether the Script node's package set is warm (polled each frame): when
    ## it becomes so, a completion asked meanwhile is asked again, if the
    ## caret is still where one would start (after a dot or in a word).
    pub func set_script_ready(self, ready: bool) -> unit!:
        let became = ready and not self.script_ready
        self.script_ready = ready
        if not became or not self.completion_waits:
            return
        self.completion_waits = false
        let caret = self.editor.caret()
        if not self.editor.layout().is_focused() or caret == 0:
            return
        let before = self.editor.text_range(caret - 1, caret)
        if before == "." or before == "_" or before.is_alnum():
            self.editor.complete()

    ## The 1-based line of `offset`.
    func line_of(self, offset: int) -> int!:
        return self.editor.text_range(0, self.editor.line_start(offset)).count("\n") + 1

    func header_text(self) -> str!:
        if self.part == 1:
            return self.editor.text()
        if let other = self.partner:
            return other.editor.text()
        return ""

    func body_text(self) -> str!:
        if self.part == 0:
            return self.editor.text()
        if let other = self.partner:
            return other.editor.text()
        return ""

    pub func close(self):
        self.editor.clear_completion_provider()
        self.editor.clear_hover_provider()
        self.partner = none
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()
        self.on_commit = none
        self.on_pause = none

## The popup's kind for one of Code.complete's ("module" items are types whose
## detail says so).
func completion_kind(kind: str, detail: str) -> CompletionKind:
    if kind == "function":
        return CompletionKind.function
    if kind == "method":
        return CompletionKind.method
    if kind == "field":
        return CompletionKind.field
    if kind == "type":
        return CompletionKind.module if detail == "module" else CompletionKind.datatype
    if kind == "keyword":
        return CompletionKind.keyword
    return CompletionKind.variable

## The editor's color for a token scope, in the editor's palette, or none
## (plain text).
pub func scope_color(scope: str) -> Color?:
    if scope.starts_with("comment"):
        return theme.text_muted()
    if scope.starts_with("string"):
        return theme.code_string()
    if scope.starts_with("constant.numeric") or scope.starts_with("constant.language"):
        return theme.code_number()
    if scope.starts_with("keyword"):
        return theme.accent()
    if scope.starts_with("storage.type") or scope.starts_with("entity.name.type"):
        return theme.code_type()
    if scope.starts_with("entity.name.function"):
        return theme.code_function()
    return none