English

ファイルのダイアログ

Os::dialog は、ファイル、複数のファイル、フォルダを開くときや、保存先を選ぶときの OS のダイアログを表示します。Os::tell、Os::confirm、Os::ask は OS のメッセージボックスを表示します。

ダイアログを設定する

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 は Dialog を返します。各メソッドは Dialog を値で受け取って返すので、呼び出しをつなげて書けます。下の 4 つの async メソッドのどれかを await するまで、画面には何も表示されません。Dialog には #[must_use] が付いているので、そのどれも呼ばずに終わる呼び出しはコンパイラの警告になります。

メソッド設定するもの
titleダイアログのウィンドウのタイトル。
filter拡張子が extensions のどれかに当たるファイルを表示する、name という名前のフィルター。呼ぶたびに 1 つ増えます。examples/notes では &["txt", "md"] のように拡張子をドットなしで書いています。
directoryダイアログを開いたときに表示するディレクトリ。
file_name保存するときにあらかじめ入れておくファイル名。別名で保存するときの元のファイル名などを入れます。

ダイアログを表示する

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>;
}
メソッドダイアログSome の中身
open_file1 つのファイルを開く選ばれたファイル
open_files1 つ以上のファイルを開く選ばれたすべてのファイル
pick_folderフォルダを選ぶ選ばれたフォルダ
save_file保存先を選ぶ保存先のパス

どのメソッドも Dialog を消費して OS のダイアログを表示し、利用者がダイアログを閉じた時点で完了します。キャンセルされたときは None を返します。下の例のハンドラは、パスを使う前に、その場合を let ... else や match で扱います。save_file はファイルを書きません。返されたパスにはまだファイルがないこともあり、書き込むのはハンドラです。たとえば std::fs::write を使います。

ダイアログはハンドラから表示するので、ダイアログが画面にあるあいだ、アクションの HTTP リクエストは応答を待ったままになります。利用者が選んだあとにハンドラが返す patch がそのリクエストのレスポンスで、ページはほかのアクションの応答と同じようにそれを適用します。

ファイルを開くハンドラ

ハンドラは、App::run がセットアップのクロージャに渡す Os を通して OS の機能を使います。クロージャがそれをルーターの状態に入れ、ハンドラは state.os として読み出します。Os は Clone を実装しているので、Os を持つ状態の構造体にも Clone を derive できます。axum はルーターの状態に Clone を求めます。下の例では、ページのボタンが OPEN を呼び、ハンドラはファイルのテキストか、読めなかった理由を返します。

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)
    })
}

利用者がキャンセルすると、ハンドラは空の Patches を返し、ページはそのまま変わりません。examples/notes の open ハンドラは、キャンセルされると状態の行を空にし、ファイルが選ばれると Windows::open でそのファイルを別のウィンドウに開きます。

複数のファイル、フォルダ、保存先

残りの 3 つのメソッドも同じように使います。open_files は選ばれたすべてのファイルを返し、pick_folder は directory で指定したディレクトリから始まり、save_file には file_name で指定した名前が入った状態で表示されます。

/// 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(),
    }
}

利用者に伝える、確かめる

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;
}

OS のメッセージボックスは Message を表示します。Message は、タイトル、省略できる本文、アイコンを決める Level(Info、Warning、Error)からなります。Os::tell は OK ボタンだけで表示し、Os::confirm は OK と Cancel で表示して OK なら true を返し、Os::ask は Yes、No、Cancel で表示して Answer を返します。ボックスを閉じたときは Cancel として扱います。ボタンはメソッドごとに決まっているので、ハンドラはそのボックスが返しうる答えだけを match し、ボタンを文字列で指定することはありません。

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,
    }
}

テストでは、ファイルのダイアログの answer_dialog と同じように、FakeOs::choose で次にボタンを待つボックスの答えを渡し、FakeOs::messages で表示したボックスを確かめます。macOS では、ask が警告のアイコン、タイトル、本文、3 つのボタンを表示し、Return で Yes が選ばれることを実行して確かめました。ボタンの名前を変えるには Windows でコモンコントロールのバージョン 6 を有効にするマニフェストが必要になるので、その機能は用意していません。

検査されないもの

  • フィルターは OS のダイアログに渡されるだけで、hypersig_desktop は返されたパスの拡張子を検査しません。特定の種類のファイルが必要なハンドラは、上の例の Err の分岐のように、ファイルを読んだ時点でそれを確かめます。
  • open_file が返したパスでも、読み込みに失敗することがあります。たとえば利用者に読む権限がない場合や、ハンドラが読む前にファイルが消された場合です。そのため、読み込みが返す Result にもハンドラで応じます。

次に読むページ