# Effects, the clock and the world

<a data-kui-example="280" href="live/gallery.html?example=tutorial/09_effects">Live chapter example</a>

At the end of this chapter, the window's title counts seconds, a button
copies to the clipboard, another pastes, and a third closes the window.

So far the app was pure: a model, a view of it, events that change it.
Real apps touch the world — the clipboard, a file, a socket, a timer.
kui has three doors for that, and each keeps the loop's shape.

## Door one: the handler gets the core

`on_event` is `&mut self` and an event. Its sibling `on_event_with`
also gets the **core** of the window the event came from. The core is
where the clipboard, focus and scrolling live:

```rust,noplayground
    /// `on_event` with the core of the window the event came from. What
    /// an app does about an event beyond its model — the clipboard, a
    /// paste, focus — is a call on it here.
    fn on_event_with(&mut self, ev: UiEvent, core: &mut Core) {
        match ev.message::<Msg>() {
            Some(Msg::Copy) => {
                let ticks = *self.ticks.lock().unwrap();
                core.set_clipboard(format!("{ticks}s"), None);
            }
            // The core cannot read the clipboard; the host can. Ask, and
            // the text comes back as an event on the focused sink.
            Some(Msg::Paste) => core.request_paste(),
            Some(Msg::Sink) => {
                if let Some(t) = ev.text() {
                    self.pasted = t.text.to_string();
                }
            }
            Some(Msg::Quit) => self.quit = true,
            _ => {}
        }
    }
```

`core.set_clipboard(text, None)` writes. There is no `read_clipboard`,
because the core never reads the OS clipboard itself — the host does.
`core.request_paste()` asks, and the text comes back as an event: a
`text` event on the focused key sink. That is why the root of this app
is a sink with focus, as in the keyboard chapter.

Override `on_event_with` and the default `on_event` is not called.
Override only `on_event` and nothing changes.

## Door two: a thread wakes the loop

The loop sleeps between events. A thread that has news — a socket read,
a timer — cannot draw, but it can wake the loop, and then `view` runs:

```rust,noplayground
    /// Once, before the window opens. The loop sleeps between events, so
    /// a thread with news calls `wake()` and the loop draws a frame.
    #[cfg(not(target_arch = "wasm32"))]
    fn setup(&mut self, waker: Waker) {
        let ticks = Arc::clone(&self.ticks);
        std::thread::spawn(move || {
            loop {
                std::thread::sleep(Duration::from_secs(1));
                *ticks.lock().unwrap() += 1;
                waker.wake();
            }
        });
    }
```

`setup` is called once before the window opens, with a `Waker`. Clone
it into as many threads as you like. `waker.wake()` is cheap and safe
at any rate; wakes coalesce into the next turn of the loop.

The thread writes into shared state; the view reads it. There is no
channel into `on_event` — the model *is* the channel.

## Door three: the window is declared

```rust,noplayground
        // The window is declared like everything else: say the title
        // every frame, and the runner applies it when it changes.
        ui.window_title(&format!("Effects · {ticks}s"));
        if self.quit {
            ui.window_command(WindowCommand::Close(ui.env().window.id));
        }
```

`ui.window_title(..)` is said every frame, and applied when it changes.
`ui.window_command(WindowCommand::Close(id))` asks the runner to close
a window; `ui.env().window.id` is this one's id. A second window is
declared the same way, with `ui.window(name, ..)`, or `ui.window_with`
to hear it open and close; and what the window itself does — a resize,
losing the keyboard — reaches `on_event` only as the messages
`ui.window_events(..)` declares for it.
[`docs/design.md`](https://github.com/qxuken/kui/blob/main/docs/design.md) has the multi-window rules under
*Window chrome is data*.

## The messages

```rust,noplayground
#[derive(Message, Clone, Debug, PartialEq)]
enum Msg {
    Copy,
    Paste,
    Quit,
    /// The root sink's message: a paste's text arrives inside it, under
    /// `text`.
    Sink,
}
```

## Try this

- Print something from `teardown`. It runs once as the window goes.
- Make the tick thread stop after 10 seconds. The loop keeps running;
  only the wakes stop.
- Copy, then paste into another app. Then paste from another app into
  this one.

## Where this is decided

- `on_event_with`, `setup` and `teardown`:
  [`kui_native::App`](https://docs.rs/kui-native/latest/kui_native/trait.App.html).
- Effects as data, the Node driver's version of the same idea:
  `withEffects` in the [Node package](https://github.com/qxuken/kui/blob/main/packages/kui/README.md).
- The reference examples:
  [`features/waker.rs`](examples/features/waker.md),
  [`features/clipboard.rs`](examples/features/clipboard.md).
