日本語

Signals kept between runs

The server listens on the same port each time the application runs, so the signals a page keeps in the browser are found again.

The port is part of the origin

Page::persist keeps a signal in the browser's localStorage, as Signals kept across page loads describes, and the browser keeps localStorage per origin: the scheme, the host, and the port. A window shows http://127.0.0.1:<port>/, so a server on another port would be another origin, and a page there would start from the values Page::new was given.

So App::run records the port the system gave the server the first time, and listens on the same port each time the application starts again. In the example below, the page starts with the theme the person last chose, in every window and after a restart:

use hypersig::html::button;
use hypersig::{Page, Route, RouterExt, Signals};
use hypersig_desktop::App;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
enum Theme {
    Light,
    Dark,
}

#[derive(Signals, Serialize, Deserialize)]
struct Home {
    theme: Theme,
}

hypersig::routes! {
    fn pages(Router<()>);
    const HOME: Route = "/" => home;
}

async fn home((): (), (): ()) -> Page<Home> {
    Page::new("Home", Home { theme: Theme::Light })
        // The next start reads this back while the server keeps its port.
        .persist(Home::theme())
        .child(button().on_click(Home::theme().set(&Theme::Dark)).text("Dark"))
}

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

fn main() -> Result<(), hypersig_desktop::Error> {
    APP.run(&HOME.url(()), |_os| async {
        pages(Router::new()).hypersig_runtime()
    })
}

The web views of all the windows are made with one data store, so a value one window stores is the value the next page in any window starts from. On macOS, WKWebView keeps that data per application, by the bundle's identifier. On Windows and Linux it is kept under the directory App::data_dir returns, which the identifier App::new takes decides, where the port is recorded too.

When another program holds the port

When the recorded port is taken, the server listens on a new port the system gives it, and records that one for the next start. The pages are then on another origin, so the signals they persisted start over from the values Page::new was given, and the values stored under the old port are not read again. The application logs a warning through tracing when this happens. Nothing else tells the application or the person.

  • Persist a value the application can lose: a theme, a list's density, a panel left open. Keep a document or a setting the person would miss in a file under App::data_dir, which a handler reads and writes on the server.
  • A value a page stores just before its window closes is kept: after the last window closes, the application waits a second before it exits, so the web view can write localStorage to disk. This was checked in WKWebView, where the value was kept in each of four runs.

One copy at a time

A second copy of the application started while the first runs opens no window and starts no server. It hands its command-line arguments and its working directory to the first copy, which brings a window to the front, and its App::run returns Ok(()). The first copy hears of each start through Os::launches: a Launch has args(), the arguments after the program's name, and current_dir(), which a relative path is joined to. A Launches gets the starts handed over after it was made, so the setup takes it before it returns the router. examples/notes opens the files a later start names this way:

use hypersig_desktop::{App, Launches, Os};

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

/// Opens a window for each file a later start names.
async fn open_launched(os: Os, mut launches: Launches) {
    while let Some(launch) = launches.next().await {
        for arg in launch.args() {
            let id = keep(launch.current_dir().join(arg));
            if os.windows().open(&NOTE.url(id)).await.is_err() {
                return;
            }
        }
    }
}

fn main() -> Result<(), hypersig_desktop::Error> {
    APP.run(&INDEX.url(()), |os| {
        // Taken before the router exists, so no launch is missed.
        tokio::spawn(open_launched(os.clone(), os.launches()));
        async move { pages(Router::new()).hypersig_runtime().with_state(AppState { os }) }
    })
}

The second copy sends a token the first writes next to its lock, which shows that the same person started it: on macOS and Linux, only that person can read the file. When the first copy does not take the arguments within three seconds, as while it is still starting, App::run returns an Error whose kind() is ErrorKind::AlreadyRunning. A main that returns that error prints Error: another copy of this application is running and exits with a failure. To exit quietly, match the kind:

use std::process::ExitCode;

use hypersig_desktop::{App, ErrorKind};

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

fn main() -> ExitCode {
    let run = APP.run(&HOME.url(()), |_os| async {
        pages(Router::new()).hypersig_runtime()
    });
    match run {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) if error.kind() == ErrorKind::AlreadyRunning => {
            eprintln!("The application is already open.");
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("{error}");
            ExitCode::FAILURE
        }
    }
}

The check is per identifier, so applications with different identifiers run side by side. The first copy holds the check until its process ends, and the next start after that runs. In a test, testing::FakeOs::launch hands a Launch to the Launches of the fake Os, as a second start would.

Next

Who the server answers covers the checks on each request to that port. Limits covers the connections the windows share.