Guides
Events
Send named messages from your Rust code to every page subscribed to them.
An event is a named message your app sends to every page subscribed to it. Events go from Rust to pages. A page reaches Rust with a command.
Send an event
AppHandle::broadcast_json sends any value serde can write:
use kurogane::{App, AppHandle, IpcError};
fn main() {
App::new("content")
.command("save", |text: String, app: &AppHandle| -> Result<(), IpcError> {
std::fs::write(std::env::temp_dir().join("notes.txt"), &text).map_err(|e| e.to_string())?;
app.broadcast_json("saved", &text.len());
Ok(())
})
.run_or_exit();
}
Every hook and command gets an AppHandle. The call returns at once. Delivery to each page happens after.
Subscribe in the page
A page subscribes with kurogane.on and gets the JSON text. kurogane.off ends the subscription:
const id = window.kurogane.on("saved", (json) => showSaved(JSON.parse(json)));
window.kurogane.off(id);
Every subscribed page in every window gets the event, popups included.
Send bytes
AppHandle::broadcast sends raw bytes without JSON. The page’s callback gets an ArrayBuffer:
use kurogane::AppHandle;
fn send_frame(app: &AppHandle, pixels: &[u8]) {
app.broadcast("frame", pixels);
}
window.kurogane.on("frame", (buffer) => draw(new Uint8Array(buffer)));
Send from another thread
AppHandle works from any thread. Clone it into the thread that does the work:
use std::time::Duration;
use kurogane::{App, AppHandle, Responder};
fn main() {
App::new("content")
.async_command("import", |files: Vec<String>, responder: Responder<usize>, app: &AppHandle| {
let app = app.clone();
std::thread::spawn(move || {
for (done, _file) in files.iter().enumerate() {
std::thread::sleep(Duration::from_millis(100));
app.broadcast_json("import-progress", &(done + 1, files.len()));
}
responder.resolve(Ok(files.len()));
});
})
.run_or_exit();
}
window.kurogane.on("import-progress", (json) => {
const [done, total] = JSON.parse(json);
progress.value = done / total;
});
const imported = await window.kurogane.invoke("import", ["a.csv", "b.csv"]);
An app that runs its own loop gets a handle from AppInstance::handle.
Who may subscribe
Subscriptions follow the same rule as commands. Only your app’s own origin subscribes by default. Open an event to other origins:
App::permit_eventopens it to the origins you name.App::permit_event_allopens it to every origin.App::deny_unlistedcloses every command and event without a rule.
A refused subscription calls the third argument of kurogane.on with an error of code -4. Without one it logs a warning:
window.kurogane.on("saved", onSaved, (error) => console.warn(`refused with ${error.code}`));
Delivery
- A page back from the back-forward cache keeps its subscriptions. The events sent while it was away don’t reach it.
- Once
AppInstance::shutdownhas begun, broadcasting does nothing. - An event name is non-empty and at most 65535 bytes of UTF-8.