日本語

The application

App names the application with a reverse domain name, sets the size of its windows, and decides where it keeps its files. App::run serves the router and opens the first window.

The identifier

pub const fn new(id: &'static str) -> App

App::new takes the application's identifier, a reverse domain name such as dev.example.notes: two or more parts joined by dots, each part one or more ASCII letters, digits, and hyphens. com.my-company.app2 is one; notes, dev..notes, dev/notes, and dev.example.my_notes are not. Every file system accepts such a name as a directory name, and the identifier names the directory the application keeps its files in.

App::new is a const fn that panics on any other text, and a panic while a const is evaluated is a compile error (E0080):

use hypersig_desktop::App;

// error[E0080]: evaluation panicked: an application identifier is a reverse
// domain name such as `dev.example.notes`: two or more parts joined by dots,
// each of ASCII letters, digits, and hyphens
const APP: App = App::new("notes");

Outside a const, the same call compiles and panics when it runs, so declare the application as a const:

use hypersig_desktop::App;

// Panics: an application identifier is a reverse domain name such as
// `dev.example.notes`: two or more parts joined by dots, each of ASCII
// letters, digits, and hyphens
let app = App::new("dev.example.my_notes");

The check covers only the form of the name. Two applications with the same identifier share one directory, so the second to start hands its command line to the first while the first runs. Packaging uses the same identifier for the package.

The window's size

Three const fn methods take the App and return it changed, so they chain inside the const. Each applies to every window the application opens, the first and those opened later.

MethodSetsDefault
size(width, height)The size the window opens at, in logical pixels1024 by 768
min_size(width, height)The smallest size the person can resize the window to, in logical pixelsNone
resizable(bool)Whether the person can resize the windowtrue

The arguments are u32. A size narrower or shorter than min_size panics, which in a const such as APP is a compile error.

The data directory

pub fn data_dir(&self) -> Result<PathBuf, hypersig_desktop::Error>

App::data_dir returns the directory where the application keeps its files, a directory named by the identifier under the system's place for application data:

SystemDirectoryFound from
macOS~/Library/Application Support/<id>HOME
Windows%LOCALAPPDATA%\<id>LOCALAPPDATA
Linux and others$XDG_DATA_HOME/<id>, or ~/.local/share/<id> without itXDG_DATA_HOME, then HOME
use hypersig_desktop::App;

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

// `~/Library/Application Support/dev.example.notes` on macOS.
let dir = APP.data_dir()?;
assert!(dir.ends_with("dev.example.notes"));

data_dir only computes the path. It fails with ErrorKind::NoDataDir when the variable is unset or not an absolute path. App::run creates the directory before it polls the future that builds the router, so that future can open a file inside it. run keeps the port and the lock there too, and on Windows and Linux the web view's data; WKWebView on macOS keeps its data per application under ~/Library/WebKit.

Running the application

pub fn run<S, F>(self, first_page: &Url, setup: S) -> Result<(), Error>
where
    S: FnOnce(Os) -> F,
    F: Future<Output: IntoRouter> + Send + 'static,

App::run takes the App by value, the first page as a Url from Route::url, and the setup closure. It does these in order:

  • Creates the data directory, and returns ErrorKind::NoDataDir or ErrorKind::Io if it cannot.
  • If another copy of the application is running, hands it this start's command line and returns Ok(()), or returns ErrorKind::AlreadyRunning when that copy does not take it.
  • Starts a multi-threaded Tokio runtime, and the server's listener on 127.0.0.1.
  • Calls the closure on the calling thread with an Os, and runs the future it returns on the runtime.
  • Makes the first window, hidden, and requests the first page. The server answers it once the future has returned the router, and the window is shown once the page has loaded.

The window is made while the future runs, so a setup that opens a database or reads a file does not hold back the window. The future is Send + 'static: it owns what it uses, which is why the samples write async move when they move the Os or a path into it.

The future's output implements IntoRouter, which two types do: Router, and Result<Router, E> for an E that converts into Box<dyn Error + Send + Sync>. An Err stops the run: run closes the window and returns ErrorKind::Setup, with the setup's error as its source().

use std::fs;

use axum::Router;
use hypersig::{Page, Route, RouterExt, Signals};
use hypersig_desktop::{App, Os};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Home {
    greeting: String,
}

#[derive(Clone)]
struct AppState {
    greeting: String,
    // The handlers open windows and dialogs through this.
    os: Os,
}

hypersig::routes! {
    fn pages(Router<AppState>);
    const INDEX: Route = "/" => index;
}

async fn index(state: AppState, (): ()) -> Page<Home> {
    Page::new("Home", Home { greeting: state.greeting })
}

const APP: App = App::new("dev.example.home")
    .size(800, 600)
    .min_size(480, 360)
    .resizable(true);

fn main() -> Result<(), hypersig_desktop::Error> {
    let file = APP.data_dir()?.join("greeting.txt");
    APP.run(&INDEX.url(()), |os| async move {
        // `run` made the directory before this future started, so the
        // read fails only when the file is missing.
        let greeting = fs::read_to_string(&file)?;
        let state = AppState { greeting, os };
        Ok::<_, std::io::Error>(pages(Router::new()).hypersig_runtime().with_state(state))
    })
}

Router here is Router<()>, a router whose state is already given. A Router<AppState> that has not had with_state called on it does not implement IntoRouter, and fails to compile (E0277):

// `pages` is a `Router<AppState>`, which still needs its state.
// error[E0277]: the trait bound `Router<AppState>: IntoRouter` is not satisfied
APP.run(&INDEX.url(()), |_os| async {
    pages(Router::new()).hypersig_runtime()
})

Nothing checks that the router the future returns serves the first page. A Url from a route that is not merged into this router compiles, and the first window then shows the router's answer to that path, a 404 when nothing serves it.

When the application closes

run returns after one of three things happens: the last window closes while no tray icon is shown, the person chooses Quit in the macOS menu or in the tray's menu, or Ctrl-C is pressed in the terminal that started the application. The last window's closing ends the application on macOS as well as on Windows and Linux. The server then stops taking requests and is given five seconds to finish the ones it is answering, and run returns once it has stopped.

It returns Ok(()) when the application closed this way, and the first error otherwise, such as the setup's Err or a server that stopped on an I/O error. Code after run in main runs after the windows are gone and the server has stopped.

Errors

Error has a kind() and, for most kinds, a source() with the cause. Its Debug writes the same message as its Display, so a main that returns Result<(), hypersig_desktop::Error> prints, for example, Error: another copy of this application is running. run returns these kinds of ErrorKind:

KindWhen
NoDataDirHOME, LOCALAPPDATA, or XDG_DATA_HOME, whichever the system uses, is unset or not an absolute path
AlreadyRunningAnother copy of the application is running and did not take this start's command line; this one opened no window
SetupThe setup's future returned an Err
WindowA window or its web view could not be made or could not load
IoA file, the port, or the server failed
SmokeA check of a smoke run failed

The other kinds come from the methods of Os: Closed from Windows::open, Window::close, or Window::focus called while the application is closing, Clipboard from the clipboard, NotExternal from Os::open_external, and Update from updates. ErrorKind is #[non_exhaustive], so a match on it needs a _ arm. A second copy started while the first runs can end quietly this way:

use std::process::ExitCode;

use hypersig_desktop::{App, ErrorKind};

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

fn main() -> ExitCode {
    let ran = APP.run(&INDEX.url(()), |_os| async {
        pages(Router::new()).hypersig_runtime()
    });
    let Err(error) = ran else {
        return ExitCode::SUCCESS;
    };
    match error.kind() {
        // The first copy goes on running; this one opened no window.
        ErrorKind::AlreadyRunning => {
            eprintln!("The application is already open.");
            ExitCode::SUCCESS
        }
        // `ErrorKind` is `#[non_exhaustive]`, so a match needs this arm.
        _ => {
            eprintln!("{error}");
            ExitCode::FAILURE
        }
    }
}
The second copy does not tell the first one anything: the first copy's window does not come to the front, and the second copy's setup closure is never called, so it opens nothing it was given on its command line.

The menu bar on macOS

macOS sends the shortcuts for copying, pasting, closing, and quitting to the menu bar, not to the web view, so without menu items for them a text field would take no pasted text. On macOS, run puts three menus in the menu bar:

MenuItems
The application's menuHiding the application (⌘H), hiding the others (⌥⌘H), showing all, and Quit (⌘Q)
EditUndo (⌘Z), Redo (⇧⌘Z), Cut (⌘X), Copy (⌘C), Paste (⌘V), and Select All (⌘A)
WindowMinimize (⌘M) and Close Window (⌘W)

Quit closes every window and stops the server as closing the last window does, with the same five seconds for the requests in progress. The menus cannot be changed or extended. Windows and Linux hand these keys to the web view, and the application has no menu bar there.

Next, Opening windows covers the windows after the first: from a handler through Os, and from a page.