Opening windows
A handler opens another window with Windows::open, and a page opens one with window.open or a link with target="_blank". Every window shows a page of the same server.
Open a window from a handler
impl Os {
pub fn windows(&self) -> Windows<'_>
}
impl Windows<'_> {
pub async fn open(&self, page: &Url) -> Result<Window, Error>
}A handler reaches the windows through the Os that App::run gave the setup, which the setup puts in the router's state. Os::windows returns Windows, and Windows::open opens a page in a new window. The page is a Url, which only Route::url produces, so a window opens only a path that a route declares, with arguments of the route's types.
use axum::Router;
use hypersig::{Action, Page, Patches, Route, Signals};
use hypersig_desktop::Os;
use hypersig_desktop::testing::FakeOs;
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct ListPage {
status: String,
}
#[derive(Signals, Serialize, Deserialize)]
struct NotePage {
id: u64,
}
#[derive(Clone)]
struct AppState {
os: Os,
}
hypersig::routes! {
fn pages(Router<AppState>);
const NOTE: Route<u64> = "/notes/{id}" => note;
action SHOW: Action<ListPage, u64> = post "/show" => show;
}
async fn note(_state: AppState, id: u64) -> Page<NotePage> {
Page::new(format!("Note {id}"), NotePage { id })
}
/// Opens the note `id` in a window of its own.
async fn show(state: AppState, id: u64) -> Patches<ListPage> {
match state.os.windows().open(&NOTE.url(id)).await {
Ok(_window) => Patches::new(),
Err(error) => ListPage::status()
.patch(format!("The note could not be shown: {error}"))
.into(),
}
}
// `FakeOs` stands in for the system, so this opens no real window.
let fake = FakeOs::new();
let state = AppState { os: fake.os() };
show(state, 7).await;
assert_eq!(fake.open_windows(), [NOTE.url(7)]);open returns once the window has been made, before its page has loaded. The window stays hidden until its page has loaded, and comes to the front with the keyboard when it is shown. It has the size the App sets for every window. In a test, FakeOs records the page instead of opening a window, and open_windows returns the pages of the windows still open; Testing without a window covers it.
open fails with | When |
|---|---|
ErrorKind::Window | The window or its web view could not be made, or the first window's page did not load |
ErrorKind::Closed | The application is closing |
The Url is checked against the routes, not against the data behind them. NOTE.url(7) compiles when there is no note 7, and the window then shows what the handler answers, a 404 for a handler that returns None.
Close or focus a window
impl Window {
pub fn close(&self) -> Result<(), Error>
pub fn focus(&self) -> Result<(), Error>
}The Window that open returns closes the window with close, as its close button does, and brings it to the front with the keyboard with focus. Window is Clone, so a handler can keep it in its state, and Eq, so two values compare equal when they name the same window.
let fake = hypersig_desktop::testing::FakeOs::new();
let os = fake.os();
let first = os.windows().open(&NOTE.url(1)).await?;
let second = os.windows().open(&NOTE.url(2)).await?;
assert_ne!(first, second);
first.focus()?;
second.close()?;
assert_eq!(fake.open_windows(), [NOTE.url(1)]);Both fail only with ErrorKind::Closed, while the application is closing. A Window does not say whether its window is still open: after the person has closed it, close and focus return Ok(()) and do nothing.
Place, move, and size a window
impl Window {
pub fn place(&self, placement: Placement) -> Result<(), Error>
pub fn layer(&self, layer: Layer) -> Result<(), Error>
pub fn move_to(&self, x: i32, y: i32) -> Result<(), Error>
pub fn resize(&self, width: u32, height: u32) -> Result<(), Error>
}
impl Windows<'_> {
pub async fn focused(&self) -> Result<Option<Window>, Error>
}place maximizes, minimizes, or makes the window fullscreen, and Placement::Normal returns it. layer with Layer::AlwaysOnTop keeps it above the windows of every other application, as a call's small window does. move_to puts its top-left corner at a point in logical pixels from the top left of the primary screen, and resize sizes its page area, within App::min_size. Each returns Ok(()) on a window already closed and fails only while the application is closing, as close does.
Windows::focused returns the window that had the keyboard last, while it is open, so the handler of a button in a page finds that page's window there, and a global shortcut finds the window the person used last. In a test, FakeOs::window returns the Arranged record of what the handlers gave a window:
use hypersig_desktop::{Layer, Placement};
let fake = hypersig_desktop::testing::FakeOs::new();
let os = fake.os();
os.windows().open(&CALL.url(())).await?;
// A button in the call's page shrinks its window and keeps it on top.
if let Some(window) = os.windows().focused().await? {
window.place(Placement::Normal)?;
window.resize(320, 180)?;
window.layer(Layer::AlwaysOnTop)?;
let arranged = fake.window(&window).expect("the window is open");
assert_eq!(arranged.size, Some((320, 180)));
assert_eq!(arranged.layer, Layer::AlwaysOnTop);
}On macOS, a run saw resize, move_to, each placement, and the return to Placement::Normal reach the window. layer has not been looked at on any system yet. Wayland lets no application place its windows, so on Linux under Wayland move_to leaves the window where the compositor put it.
A window without the system's frame
App::frame with Frame::None opens each window without the system's title bar and border, and the page draws its own bar. moves_window marks the element the person drags the window by: pressing it moves the window, and a double click maximizes or restores it. A link, a button, a form control, or an element with tabindex inside it keeps its own clicks, so the bar's buttons call actions whose handlers close or place the window through Windows::focused:
use hypersig::html::{El, button, div, span};
use axum::Router;
use hypersig::{Action, Patches, Signals};
use hypersig_desktop::{App, Frame, MovesWindow as _};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
title: String,
}
const APP: App = App::new("dev.example.notes").frame(Frame::None);
/// The title bar the page draws: dragging it moves the window, and its
/// button keeps its clicks.
fn title_bar() -> El<Notes> {
div()
.moves_window()
.child(span().bind_text(Notes::title()))
.child(button().on_click(CLOSE.call()).text("Close"))
}On macOS, a run saw the window open without a title bar, a drag on the bar move it, a drag elsewhere on the page leave it, and a double click maximize and restore it. On macOS the window then lacks the system's close, minimize, and zoom buttons. Windows and Linux have not been looked at, and a Linux window manager may draw no shadow around a window without its border.
Open windows at start
The setup's future can await open before it returns the router. A window asked for before the first window's page has loaded is made at once, and loads its page once the first page has, because the later windows need what the first one receives. examples/notes opens the files named on its command line this way:
use hypersig_desktop::{App, Os};
const APP: App = App::new("dev.example.notes");
/// Opens a window for each of `ids`, until one fails to open.
async fn show_all(os: &Os, ids: Vec<u64>) {
for id in ids {
if os.windows().open(&NOTE.url(id)).await.is_err() {
break;
}
}
}
fn main() -> Result<(), hypersig_desktop::Error> {
APP.run(&INDEX.url(()), |os| async move {
show_all(&os, vec![1, 2]).await;
pages(Router::new()).hypersig_runtime().with_state(AppState { os })
})
}Open a window from a page
A page opens a window too, with a link whose target is _blank or with window.open in its own script. hypersig has no typed target method, so the link sets the attribute with attr::TARGET:
use hypersig::html::{a, attr};
let link = a::<ListPage>()
.href(NOTE.url(7))
.attr(attr::TARGET, "_blank")
.text("Open in a new window");
assert_eq!(
link.render(),
r#"<a href="/notes/7" target="_blank">Open in a new window</a>"#,
);What happens depends on the URL the page asks for:
| URL | Opens in |
|---|---|
A page of the application, such as /notes/7 | A new window of the application, as Windows::open opens one |
An http, https, or mailto URL of anything else | The person's browser or mail program; see Links to other sites |
| Any other URL | Nothing |
Nothing returns a Window for a window a page opened, so no handler can close or focus it. The href comes from a Url as in the sample, which keeps the path to a declared route; a URL that the page's own script builds is not checked.
window.open that no click started unless the web view allows it, and hypersig_desktop allows it, so a script opens a window on Linux as it does in WKWebView and WebView2.The window's title
A window's title is its page's <title>, the first argument of Page::new. The sample's note window is titled Note 7. The title is empty until the page has it, and follows the page whenever document.title changes, as on a navigation to another page. Nothing else sets it.
Every window shows the same server
All the windows show pages of the one server App::run started, and share their web view's cookies and localStorage, as two tabs of one browser do. A handler's state is the same value for every window, so two windows that open a StreamAction fed by one tokio::sync::broadcast channel show the same state: a change one window sends reaches the other over its stream.
examples/notes works this way: a note saved in its own window updates the save count in the list window. examples/todo does with --features desktop, and its CI run opens a second window and checks that a todo added there reaches the first. Streams covers StreamAction.
Closing the last window
Closing a window, with its close button or with Window::close, ends its page and its streams. Closing the last one closes the application, on macOS as well, where an application often stays open without windows, unless a tray icon is shown. The server is then given five seconds to finish the requests it is answering, and App::run returns; The application covers what it returns.
Next, File dialogs covers how a handler asks the person for a file to open or a place to save one.