Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.4

0.19.4 / src / text / line_input.lucb

## Shared single-line editing for command search and prompts. The document owns
## Unicode selection and history; popup widgets supply focus and submission. A
## `masked` input (a password) shows each character as a bullet in one cell and
## never copies its text out.
from luce_clipboard import clipboard
from luce_gpu import gpu
from luce_window import input
import interop
from luce_std import math
import memory
from luce_std import utf8
from luce_window import window
import text.cells as cell_widths
import text.editing
import result
from text.document import Document
from layout import Event
from font import Font
from painter import Painter
from theme import Theme

pub struct LineInput:
    var document: Document
    var dragging: bool
    var first: usize
    pub var masked: bool

    pub func init() -> !:
        self.document = try Document()
        self.dragging = false
        self.first = 0
        self.masked = false

    ## The text from scalar `start` to `end` as shown: bullets when masked.
    pub func shown(start: usize, end: usize) -> interop.Owned[str]!:
        if not self.masked:
            return try self.document.text(start, end)
        let count = end - start if end > start else 0
        let bullets = try new u8[count * 3] --- in memory.heap
        defer free(bullets) in memory.heap
        for at in 0..<count:
            bullets[at * 3] = (u8)0xE2
            bullets[at * 3 + 1] = (u8)0x80
            bullets[at * 3 + 2] = (u8)0xA2
        return try interop.copy_text((str)bullets)

    ## The whole text as shown.
    pub func shown_text() -> interop.Owned[str]!:
        return try self.shown(0, self.document.length())

    ## The cells scalar `at` takes: one bullet each when masked.
    func cells_at(at: usize) -> usize:
        return 1 if self.masked else cell_widths.grid(self.document.scalar(at), 0)

    ## The cells from scalar `start` to `end`.
    func span(start: usize, end: usize) -> usize:
        return end - start if self.masked else cell_widths.span(&self.document, start, end)

    pub func text() -> interop.Owned[str]!:
        return try self.document.text()

    pub func set_text(text: str) -> !:
        _ = try validate(text)
        try self.document.set_text(text)
        try self.document.select(0, self.document.length())
        self.dragging = false

    ## Select the whole text.
    pub func select_all() -> !:
        try self.document.select(0, self.document.length())

    pub func event(event: Event) -> bool!:
        let before = self.document.version()
        let command = event.control or event.meta
        if event.cancelled:
            self.dragging = false
            return false
        if event.kind == input.EventKind.text_input and not command:
            if event.codepoint >= 32 and event.codepoint != 127 and self.document.length() - (self.document.last() - self.document.first()) < 1024:
                var bytes: u8[4]
                let count = utf8.encode((u32)event.codepoint, bytes) else return false
                try self.document.insert((str)bytes[..<count])
        elif event.kind == input.EventKind.key_down:
            if command and event.key == input.Key.a:
                try self.select_all()
            elif command and (event.key == input.Key.c or event.key == input.Key.x):
                # A masked input keeps its text to itself, as a password field does.
                if self.document.first() != self.document.last() and not self.masked:
                    let text = try self.document.text(self.document.first(), self.document.last())
                    defer text.release()
                    # Without a desktop clipboard (no X display) a copy does nothing.
                    clipboard.write_text(text.value) catch failure:
                        if failure.code != window.unsupported:
                            error(failure.code, failure.message)
                        return true
                    if event.key == input.Key.x:
                        try self.document.insert("")
            elif command and event.key == input.Key.v:
                # Without a desktop clipboard a paste does nothing.
                let text = clipboard.read_text() catch failure:
                    if failure.code != window.unsupported:
                        error(failure.code, failure.message)
                    return true
                defer text.release()
                # Pasted text is made one line first: a path copied with its line
                # break (PowerShell's Set-Clipboard adds one) still pastes.
                let line = try new u8[text.value.length] --- in memory.heap
                defer free(line) in memory.heap
                # What does not fit in the 1024 characters is cut, as a browser's
                # maxlength does, rather than failing the paste.
                let one_line = (str)line[..<single_line(text.value, line)]
                let room = 1024 - (self.document.length() - (self.document.last() - self.document.first()))
                let pasted = (str)one_line.bytes[..<fitting(one_line, room)]
                _ = try validate(pasted)
                try self.document.insert(pasted)
            elif command and event.key == input.Key.z:
                _ = try self.document.redo() if event.shift else try self.document.undo()
            elif event.key == input.Key.backspace or event.key == input.Key.delete:
                try editing.erase(&self.document, event.key == input.Key.backspace, command or event.alt)
            elif event.key == input.Key.home:
                try editing.move(&self.document, 0, event.shift)
            elif event.key == input.Key.end:
                try editing.move(&self.document, self.document.length(), event.shift)
            elif event.key == input.Key.left:
                let caret = self.document.caret()
                var offset = caret - 1 if caret > 0 else 0
                if command or event.alt:
                    # Masked text has no words to show: a word jump goes to the start.
                    offset = 0 if self.masked else editing.word_left(&self.document, caret)
                try editing.move(&self.document, self.document.first() if not event.shift and self.document.first() != self.document.last() else offset, event.shift)
            elif event.key == input.Key.right:
                let caret = self.document.caret()
                var offset = caret + 1 if caret < self.document.length() else caret
                if command or event.alt:
                    offset = self.document.length() if self.masked else editing.word_right(&self.document, caret)
                try editing.move(&self.document, self.document.last() if not event.shift and self.document.first() != self.document.last() else offset, event.shift)
        return before != self.document.version()

    pub func pointer(event: Event, font: interop.Reference[Font], x: f64, y: f64, width: f64, height: f64) -> !:
        if event.kind == input.EventKind.pointer_up or event.cancelled:
            self.dragging = false
            return
        if event.kind == input.EventKind.pointer_down and event.button == 0 and event.x >= x and event.x < x + width and event.y >= y and event.y < y + height:
            self.first = self.window_start(visible_cells(font, width))
            let offset = self.offset_at(font.value().advance(), event.x - x)
            try self.document.select(self.document.anchor() if event.shift else offset, offset)
            self.dragging = true
        elif event.kind == input.EventKind.pointer_moved and self.dragging:
            try self.document.select(self.document.anchor(), self.offset_at(font.value().advance(), event.x - x))

    ## The caret boundary nearest a point `x` points right of the shown text's left
    ## edge, in cells of `advance` points from the first shown scalar.
    func offset_at(advance: f64, x: f64) -> usize:
        if self.masked:
            let nearest = self.first + (usize)(math.max(0.0, x) / advance + 0.5)
            return nearest if nearest < self.document.length() else self.document.length()
        return cell_widths.nearest(&self.document, self.first, self.document.length(), math.max(0.0, x) / advance)

    ## The first scalar shown in a window `columns` cells wide: the start, unless the
    ## caret would fall past the window, when the caret is kept at its right edge.
    func window_start(columns: usize) -> usize:
        let caret = self.document.caret()
        var start = caret
        var used: usize = 0
        while start > 0:
            let span = self.cells_at(start - 1)
            if used + span > columns:
                break
            used += span
            start -= 1
        return start

    pub func paint(painter: Painter*, font: interop.Reference[Font], theme: Theme,
                   x: f64, y: f64, width: f64) -> !:
        let advance = font.value().advance()
        let room = visible_cells(font, width)
        let caret = self.document.caret()
        let start = self.window_start(room)
        # Whole scalars that fit the window from `start`; a wide one at the edge waits.
        var end = start
        var used: usize = 0
        while end < self.document.length():
            let span = self.cells_at(end)
            if used + span > room:
                break
            used += span
            end += 1
        let first = start if start > self.document.first() else self.document.first()
        let last = end if end < self.document.last() else self.document.last()
        if last > first:
            let left = (f64)self.span(start, first) * advance
            try painter.rectangle(gpu.Rect(x + left, y, (f64)self.span(first, last) * advance, font.value().height()), theme.selection)
        let text = try self.shown(start, end)
        defer text.release()
        try painter.text(text.value, x, y, theme.foreground, font)
        try painter.rectangle(gpu.Rect(x + (f64)self.span(start, caret) * advance, y, 1.0, font.value().height()), theme.accent)

    pub func close():
        self.document.close()

## How many cells a field `width` points wide shows, keeping one for the caret.
func visible_cells(font: interop.Reference[Font], width: f64) -> usize:
    return (usize)math.max(1.0, width / font.value().advance() - 1.0)

## `text` as one line into `into` (as long as `text`); how many bytes it holds.
## Line breaks and tabs inside become one space each, other control characters
## go, and breaks and spaces at either end are dropped.
func single_line(text: str, into: u8[]) -> usize:
    var count: usize = 0
    for byte in text.bytes:
        if byte == 13 or byte == 10 or byte == 9:
            # A CR LF pair is one break: one space.
            if count > 0 and into[count - 1] != 32:
                into[count] = 32
                count += 1
        elif byte >= 32 and byte != 127:
            into[count] = byte
            count += 1
    var first: usize = 0
    while first < count and into[first] == 32:
        first += 1
    while count > first and into[count - 1] == 32:
        count -= 1
    if first > 0:
        for index in first..<count:
            into[index - first] = into[index]
        count -= first
    return count

## The bytes of `text`'s first `room` scalars, stopping early at bytes that are
## not UTF-8.
func fitting(text: str, room: usize) -> usize:
    var offset: usize = 0
    var count: usize = 0
    while offset < text.length and count < room:
        let scalar = utf8.decode(text.bytes, offset) else return offset
        count += 1
        offset += scalar.width
    return offset

func validate(text: str) -> usize!:
    if text.length > 4096:
        error(result.limit, "single-line input is too long")
    for byte in text.bytes:
        if byte < 32 or byte == 127:
            error(result.invalid, "single-line input cannot contain control characters")
    var offset: usize = 0
    var count: usize = 0
    while offset < text.length:
        let scalar = utf8.decode(text.bytes, offset) else error(result.invalid, "single-line input must be UTF-8")
        count += 1
        offset += scalar.width
    if count > 1024:
        error(result.limit, "single-line input is limited to 1024 characters")
    return count

test "pasted text becomes one line: breaks at the ends go, inner ones become spaces":
    var into: u8[64]
    let path = "C:\\luced-scratch\r\n"
    assert((str)into[..<single_line(path, into)] == "C:\\luced-scratch")
    let lines = "  one\r\ntwo\tthree\n"
    assert((str)into[..<single_line(lines, into)] == "one two three")
    let bell = "a\u{7}b"
    assert((str)into[..<single_line(bell, into)] == "ab")
    assert(single_line("\r\n", into) == 0)

test "a paste longer than the room left is cut at a whole character":
    assert(fitting("abcdef", 4) == 4)
    assert(fitting("ab", 4) == 2)
    assert(fitting("田中abc", 1) == 3)
    assert(fitting("abc", 0) == 0)

test "the shown window and clicks count cells: wide scalars take two":
    var line = try LineInput()
    defer line.close()
    try line.set_text("田中abc")
    try line.document.select(5, 5)
    # Four cells keep the caret at the right edge: "abc" fits, 中 would not.
    assert(line.window_start(4) == 2 and line.window_start(5) == 1 and line.window_start(10) == 0)
    line.first = 0
    assert(line.offset_at(10.0, 9.0) == 0)
    assert(line.offset_at(10.0, 15.0) == 1)
    assert(line.offset_at(10.0, 29.0) == 1)
    assert(line.offset_at(10.0, 31.0) == 2)
    assert(line.offset_at(10.0, 46.0) == 3)
    assert(line.offset_at(10.0, 500.0) == 5)
    line.first = 2
    assert(line.offset_at(10.0, 6.0) == 3)

test "a masked input gives every scalar one cell and copies nothing":
    var line = try LineInput()
    defer line.close()
    line.masked = true
    try line.set_text("田中abc")
    try line.document.select(5, 5)
    # Five bullets, one cell each: four cells show the last four.
    assert(line.window_start(4) == 1 and line.window_start(5) == 0)
    line.first = 0
    assert(line.offset_at(10.0, 4.0) == 0 and line.offset_at(10.0, 6.0) == 1 and line.offset_at(10.0, 21.0) == 2)
    assert(line.offset_at(10.0, 500.0) == 5)
    let shown = try line.shown(0, 5)
    defer shown.release()
    assert(shown.value == "•••••")
    try line.document.select(0, 5)
    # Copy and cut leave the text where it is; the clipboard is not touched.
    _ = try line.event(Event(kind = input.EventKind.key_down, key = input.Key.x, meta = true))
    let kept = try line.text()
    defer kept.release()
    assert(kept.value == "田中abc")