Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-dialogs

Source of release 0.6.1

0.6.1 / src / dialogs / linux / native.lucb

#==============================================================================================
#
#   native - Linux file dialogs through the desktop's own helper
#
#   DESCRIPTION:
#       GNOME's zenity, else KDE's kdialog, asks and prints the chosen path (a file's, or a
#       folder's with zenity's --directory and kdialog's --getexistingdirectory): the desktop's own
#       panel without linking a toolkit. It runs as a child and blocks the UI thread, modal
#       as the other platforms' panels are, and starts in the home folder (a save at the
#       suggested name there). Neither installed fails as unsupported; a helper that
#       is there but fails (killed, no display) fails as such, not as a cancel.
#
#==============================================================================================

func linux_choose(message: str, name: str, save: bool, multiple: bool, folders: bool = false) -> interop.Owned[str]?!:
    var title_text: u8[1024]
    var name_text: u8[4200]
    let title = try strings.format(title_text[..<1023], f"--title={message}")
    title_text[title.length] = 0
    # The home folder, where both helpers start: the app's working folder may be
    # `/` or its bundle when the desktop launched it.
    let home = files.home_directory() catch failure:
        recover interop.Owned[str](".")
    defer home.release()
    let suggested = try strings.format(name_text[..<4199], f"--filename={home.value}/{name}")
    name_text[suggested.length] = 0
    # zenity: exit 0 with the path, 1 when cancelled; 127 when it is not installed.
    var zenity_open: c.str[5] = ["--file-selection", (c.str)&title_text[0], (c.str)&name_text[0], "--multiple", "--separator=\n"]
    var zenity_save: c.str[5] = ["--file-selection", "--save", "--confirm-overwrite", (c.str)&title_text[0], (c.str)&name_text[0]]
    var zenity_folder: c.str[4] = ["--file-selection", "--directory", (c.str)&title_text[0], (c.str)&name_text[0]]
    let zenity = try linux_ask("zenity", zenity_folder[..<4] if folders else (zenity_save[..<5] if save else zenity_open[..<(5 if multiple else 3)]))
    if zenity.answered:
        return zenity.path
    var message_text: u8[1024]
    let plain = try strings.format(message_text[..<1023], f"{message}")
    message_text[plain.length] = 0
    var start_text: u8[4200]
    # kdialog starts at the suggested name, or in the home folder.
    let start = try strings.format(start_text[..<4199], f"{home.value}/{name}" if name.length > 0 else f"{home.value}")
    start_text[start.length] = 0
    let asking: c.str = "--getexistingdirectory" if folders else ("--getsavefilename" if save else "--getopenfilename")
    var kdialog: c.str[6] = ["--title", (c.str)&message_text[0], asking, (c.str)&start_text[0], "--multiple", "--separate-output"]
    let asked = try linux_ask("kdialog", kdialog[..<(6 if multiple and not save and not folders else 4)])
    if asked.answered:
        return asked.path
    error(window.unsupported, "no file dialog helper (zenity or kdialog) is installed")

## What a helper said: whether it was there to answer, and the path chosen
## (none when cancelled).
struct Asked:
    var answered: bool
    var path: interop.Owned[str]?

## Run `program` and read the path it printed.
func linux_ask(program: c.str, arguments: const c.str[]) -> Asked!:
    # A helper that is not installed exits 127 (exec's failure); run itself
    # fails only when the helper does (killed by a signal, no pipe, no fork).
    let ran = process.run(program, arguments) catch failure:
        _ = failure
        error(failed, "the desktop's file dialog helper failed")
    defer ran.release()
    let status = ran.value.exit_code
    let output = ran.value.output
    if status == 127:
        return Asked(answered = false, path = none)
    # 1 is a cancel, except that zenity exits 1 too when it cannot open a
    # display, which it says on its error output: "cannot open display" (GTK 3),
    # "Failed to open display" (GTK 4). With the desktop portal, GTK 4's zenity
    # needs no display of its own, so this is rare there.
    if status == 1:
        if contains(ran.value.error_output, "open display"):
            error(failed, "the desktop's file dialog helper cannot open a display")
        return Asked(answered = true, path = none)
    if status != 0:
        error(failed, "the desktop's file dialog helper failed")
    var length = output.length
    while length > 0 and (output.bytes[length - 1] == '\n' or output.bytes[length - 1] == '\r'):
        length -= 1
    if length == 0:
        return Asked(answered = true, path = none)
    return Asked(answered = true, path = try interop.copy_text((str)output.bytes[..<length]))

## Whether `text` holds `part`.
func contains(text: str, part: str) -> bool:
    if part.length > text.length:
        return false
    for at in 0..=text.length - part.length:
        if (str)text.bytes[at..<at + part.length] == part:
            return true
    return false