日本語

File dialogs

Os::dialog shows the system's dialog for opening a file, several files, or a folder, or for choosing where to save one, and Os::tell, Os::confirm, and Os::ask show its message box.

Setting up a dialog

impl Os {
    pub fn dialog(&self) -> Dialog;
}

impl Dialog {
    pub fn title(self, title: impl Into<String>) -> Self;
    pub fn filter(self, name: impl Into<String>, extensions: &[&str]) -> Self;
    pub fn directory(self, directory: impl Into<PathBuf>) -> Self;
    pub fn file_name(self, name: impl Into<String>) -> Self;
}

Os::dialog returns a Dialog, which each method takes by value and returns, so the calls chain. Nothing appears on screen until one of the four async methods below is awaited. Dialog is #[must_use], so a chain that ends without one of them is a compiler warning.

MethodWhat it sets
titleThe title of the dialog's window.
filterA filter named name that offers the files whose extension is one of extensions. Each call adds one; examples/notes writes the extensions without the dot, as in &["txt", "md"].
directoryThe directory the dialog opens in.
file_nameThe file name filled in for a save, such as the name of the file being saved under another name.

Showing the dialog

impl Dialog {
    pub async fn open_file(self) -> Option<PathBuf>;
    pub async fn open_files(self) -> Option<Vec<PathBuf>>;
    pub async fn pick_folder(self) -> Option<PathBuf>;
    pub async fn save_file(self) -> Option<PathBuf>;
}
MethodThe dialogSome holds
open_fileOpen one fileThe file chosen
open_filesOpen one or more filesEvery file chosen
pick_folderChoose a folderThe folder chosen
save_fileChoose where to saveThe path to save at

Each method consumes the Dialog, shows the system's dialog, and resolves when the person closes it. It returns None when they cancelled, and the handlers below answer that case with a let ... else or a match before they use the path. save_file writes nothing. The file at the returned path may not exist yet, and the handler writes it, with std::fs::write for example.

The dialog is shown from a handler, so the action's HTTP request stays open while it is on screen. The patches the handler returns once the person has chosen are that request's response, and the page applies them as it applies any other action's reply.

A handler that opens a file

The handler reaches the system through the Os that App::run passes to its setup closure. The closure puts it in the router's state, and the handler reads it from there as state.os. Os is Clone, so a state struct that holds it can derive Clone, as axum requires of a router's state. Below, the page's button calls OPEN, and the handler answers with the file's text or the reason it could not be read:

use std::fs;

use axum::Router;
use hypersig::html::{button, div, p, pre};
use hypersig::{Action, Page, Patches, Route, RouterExt, Signals};
use hypersig_desktop::{App, Os};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Viewer {
    text: String,
    status: String,
}

#[derive(Clone)]
struct AppState {
    os: Os,
}

hypersig::routes! {
    fn pages(Router<AppState>);
    const INDEX: Route = "/" => index;
    action OPEN: Action<Viewer> = post "/open" => open;
}

async fn index(_: AppState, (): ()) -> Page<Viewer> {
    let initial = Viewer { text: String::new(), status: String::new() };
    Page::new("Viewer", initial).child(
        div()
            .child(button().on_click(OPEN.call()).text("Open…"))
            .child(p().bind_text(Viewer::status()))
            .child(pre().bind_text(Viewer::text())),
    )
}

/// Asks for a text file and shows what it holds.
async fn open(state: AppState, (): ()) -> Patches<Viewer> {
    let chosen = state
        .os
        .dialog()
        .title("Open a note")
        .filter("Text", &["txt", "md"])
        .open_file()
        .await;
    let Some(path) = chosen else {
        // Cancelled: the page stays as it was.
        return Patches::new();
    };
    match fs::read_to_string(&path) {
        Ok(text) => Viewer::text()
            .patch(text)
            .and(Viewer::status().patch(path.display().to_string()))
            .into(),
        Err(error) => Viewer::status().patch(format!("Not read: {error}")).into(),
    }
}

const APP: App = App::new("dev.example.viewer");

fn main() -> Result<(), hypersig_desktop::Error> {
    APP.run(&INDEX.url(()), |os| async move {
        let state = AppState { os };
        pages(Router::new()).hypersig_runtime().with_state(state)
    })
}

When the person cancels, the handler returns an empty Patches and the page stays as it was. The open handler of examples/notes answers a cancel by clearing its status line, and opens a chosen file in a window of its own with Windows::open.

Several files, a folder, and a place to save

The other three methods are used the same way. open_files returns every file chosen, pick_folder starts in the directory directory names, and save_file fills in the name file_name gives:

/// Asks for any number of images.
async fn import(state: AppState, (): ()) -> Patches<Library> {
    let Some(files) = state
        .os
        .dialog()
        .title("Import photos")
        .filter("Images", &["png", "jpg", "jpeg"])
        .open_files()
        .await
    else {
        return Patches::new();
    };
    Library::status().patch(format!("{} files chosen.", files.len())).into()
}

/// Asks for a folder, starting in `start`.
async fn choose_folder(state: AppState, start: PathBuf) -> Patches<Library> {
    match state.os.dialog().directory(start).pick_folder().await {
        Some(folder) => Library::status().patch(format!("Watching {}.", folder.display())).into(),
        None => Patches::new(),
    }
}

/// Asks where to save `text`, and writes it there.
async fn export(state: AppState, text: String) -> Patches<Library> {
    let Some(path) = state
        .os
        .dialog()
        .title("Export the list")
        .filter("Text", &["txt"])
        .file_name("photos.txt")
        .save_file()
        .await
    else {
        return Patches::new();
    };
    // The dialog chose the path; the file is written here.
    match fs::write(&path, text) {
        Ok(()) => Library::status().patch(format!("Saved {}.", path.display())).into(),
        Err(error) => Library::status().patch(format!("Not saved: {error}")).into(),
    }
}

Telling the person, and asking them

impl Os {
    pub async fn tell(&self, message: Message);
    pub async fn confirm(&self, message: Message) -> bool;
    pub async fn ask(&self, message: Message) -> Answer;
}

impl Message {
    pub fn new(level: Level, title: impl Into<String>) -> Self;
    pub fn body(self, text: impl Into<String>) -> Self;
}

The system's message box shows a Message: a title, an optional body, and a Level of Info, Warning, or Error, which picks its icon. Os::tell shows it with an OK button, Os::confirm with OK and Cancel and returns true for OK, and Os::ask with Yes, No, and Cancel and returns the Answer. Closing the box counts as Cancel. Each method shows its own buttons, so a handler matches only the answers its box can give, and no button is named by a string:

use hypersig_desktop::{Answer, Level, Message, Os};

/// Asks before the changes to a note are lost, and says whether to close it.
async fn may_close(os: &Os, unsaved: bool) -> bool {
    if !unsaved {
        return true;
    }
    let message = Message::new(Level::Warning, "Save the changes to this note?")
        .body("They are lost if you close it without saving.");
    match os.ask(message).await {
        Answer::Yes => save().await,
        Answer::No => true,
        Answer::Cancel => false,
    }
}

In a test, FakeOs::choose gives the button the next box that waits for one takes, as answer_dialog does for a file dialog, and FakeOs::messages returns each box shown. On macOS, a run saw ask show the warning icon, the title, the body, and the three buttons, and Return chose Yes. Custom labels for the buttons are not offered, since on Windows they need a manifest that turns on version 6 of the common controls.

What is not checked

  • The filters are handed to the system's dialog, and hypersig_desktop does not check the extension of the path it returns. A handler that needs a particular kind of file finds out when it reads the file, as the Err arm above does.
  • A path returned by open_file can still fail to read, for example when the person lacks permission or the file is removed before the handler reads it, so the read returns a Result the handler answers.

Next