# 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](https://kurogane-rs.org/docs/guides/commands.md).

## Send an event

[`AppHandle::broadcast_json`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.broadcast_json) sends any value serde can write:

```rust
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:

```javascript
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`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.broadcast) sends raw bytes without JSON. The page's callback gets an `ArrayBuffer`:

```rust
use kurogane::AppHandle;

fn send_frame(app: &AppHandle, pixels: &[u8]) {
    app.broadcast("frame", pixels);
}
```

```javascript
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:

```rust
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();
}
```

```javascript
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`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.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_event`](https://kurogane-rs.org/docs/api/app/app.md#method.permit_event) opens it to the origins you name.
* [`App::permit_event_all`](https://kurogane-rs.org/docs/api/app/app.md#method.permit_event_all) opens it to every origin.
* [`App::deny_unlisted`](https://kurogane-rs.org/docs/api/app/app.md#method.deny_unlisted) closes 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:

```javascript
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::shutdown` has begun, broadcasting does nothing.
* An event name is non-empty and at most 65535 bytes of UTF-8.
