English

クリップボード

Os::clipboard を使うと、ハンドラから OS のクリップボードのテキストを読み書きできます。

テキストを読み書きする

impl Os {
    pub fn clipboard(&self) -> Clipboard<'_>;
}

impl Clipboard<'_> {
    pub async fn read_text(&self) -> Result<Option<String>, Error>;
    pub async fn write_text(&self, text: impl Into<String>) -> Result<(), Error>;
}

Os::clipboard は、Os を借用する Clipboard を返します。Clipboard は Copy で、ハンドラでは state.os.clipboard().write_text(text).await のように、受け取ってすぐにメソッドを 1 つ呼ぶのが普通です。どちらのメソッドもテキストだけを扱います。

呼び出し戻り値
read_textクリップボードのテキストを持つ Ok(Some(text))
read_textクリップボードにテキストがないときは Ok(None)
write_texttext をクリップボードに置いたら Ok(())
どちらもOS のクリップボードを開けない、読めない、書けないときは、kind() が ErrorKind::Clipboard の Err

エラーは Error で、Display が原因を示します。ほかの種類のエラーとは ErrorKind::Clipboard で見分けます。テキストがないクリップボードはエラーではなく Ok(None) になるので、貼り付けのハンドラはそれに専用のメッセージで応じます。

コピーと貼り付けのボタン

クリップボードを読み書きするのはハンドラで、アプリのプロセスの中で動きます。ページのテキストは COPY.call_with(Editor::text()) のようにアクションの引数としてハンドラに届き、クリップボードのテキストはハンドラが返す patch としてページに届きます。ページ自身はクリップボードを読み書きしません。Os はダイアログのときと同じく、ルーターの状態から取り出します。

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

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

hypersig::routes! {
    fn actions(Router<AppState>);
    action COPY: Action<Editor, String> = post "/copy" => copy;
    action PASTE: Action<Editor> = post "/paste" => paste;
}

fn editor() -> Page<Editor> {
    Page::new("Editor", Editor { text: String::new(), status: String::new() }).child(
        div()
            .child(textarea().bind(Editor::text()))
            .child(button().on_click(COPY.call_with(Editor::text())).text("Copy"))
            .child(button().on_click(PASTE.call()).text("Paste"))
            .child(p().bind_text(Editor::status())),
    )
}

/// Puts the text the page sent on the clipboard.
async fn copy(state: AppState, text: String) -> Patches<Editor> {
    match state.os.clipboard().write_text(text).await {
        Ok(()) => Editor::status().patch("Copied.".to_owned()).into(),
        Err(error) => Editor::status().patch(format!("Not copied: {error}")).into(),
    }
}

/// Replaces the page's text with the clipboard's.
async fn paste(state: AppState, (): ()) -> Patches<Editor> {
    match state.os.clipboard().read_text().await {
        Ok(Some(text)) => Editor::text().patch(text).into(),
        Ok(None) => Editor::status().patch("The clipboard holds no text.".to_owned()).into(),
        Err(error) => Editor::status().patch(format!("Not pasted: {error}")).into(),
    }
}

examples/notes にも同じコピーのボタンがあります。テストでは FakeOs が専用のクリップボードを持ちます。set_clipboard_text はほかのプログラムがするようにテキストを置き、clipboard_text はハンドラが書いたテキストを返します。

Linux で書いたテキスト

Linux では、X11 でも Wayland でも、クリップボードのテキストはそれを書いたプログラムが提供します。ほかのプログラムが貼り付けるときは、書いたプログラムからテキストを読み出します。hypersig_desktop は最初の呼び出しからアプリが終わるまでクリップボードを開いたままにするので、一度書いたテキストはアプリが動いているあいだずっと読み出せます。アプリが終わったあとは、ほかのプログラムからそのテキストを読み出せなくなることがあります。

次に読むページ