# Runtime and event loop

> Who drives Chromium's message loop and who owns the windows.

Chromium's browser process runs a message loop on the thread that started it. Something has to drive that loop. Kurogane can drive it for you or your app can drive it from a loop of its own.

## Three ways to start

| Call | Who runs the loop | Who owns the windows |
|---|---|---|
| [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) | Kurogane | Kurogane |
| [`App::start`](https://kurogane-rs.org/docs/api/app/app.md#method.start) | your app | Kurogane |
| [`App::start_embedded`](https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded) | your app | your app |

The thread that makes the call becomes Chromium's UI thread. Every handler and callback of your app runs there.

## Kurogane runs the loop

`App::run` opens the start window and blocks on Chromium's message loop. The loop ends once the app's last browser has closed. That happens when the last window closes, when [`AppHandle::shutdown`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown) closes them all or on Ctrl+C. Then `run` shuts Chromium down and returns.

[`App::run_or_exit`](https://kurogane-rs.org/docs/api/app/app.md#method.run_or_exit) does the same for binaries. It prints the error and its causes and exits when the app can't start.

```rust
use kurogane::App;

fn main() {
    App::new("content").run_or_exit();
}
```

Use it unless your app has a loop of its own.

## Your app runs the loop

`App::start` starts Chromium and returns an [`AppInstance`](https://kurogane-rs.org/docs/api/app/appinstance.md) without entering a loop. Your loop then does three things:

1. It calls [`AppInstance::pump`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.pump) regularly. Each call runs one round of Chromium's work.
2. It stops once [`AppInstance::should_shutdown`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.should_shutdown) turns true.
3. It calls [`AppInstance::shutdown`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown) to shut Chromium down.

`pump` runs only on the thread that started the app. `AppInstance` isn't `Send` and dropping it shuts Chromium down. [`AppInstance::handle`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.handle) gives an [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md) for other threads.

### When to pump

[`App::scheduler`](https://kurogane-rs.org/docs/api/app/app.md#method.scheduler) lets Chromium say when it next needs a pump. It calls your closure with a [`PumpRequest`](https://kurogane-rs.org/docs/api/app/pumprequest.md) from any thread. [`PumpRequest::deadline`](https://kurogane-rs.org/docs/api/app/pumprequest.md#method.deadline) turns it into an instant. CEF recommends a scheduler for every app that pumps from its own loop.

```rust
use std::sync::mpsc;
use std::time::{Duration, Instant};

use kurogane::{App, PumpRequest};

// The longest the loop waits between pumps, as CEF's cefclient does
const MAX_PUMP_DELAY: Duration = Duration::from_millis(1000 / 30);

fn main() {
    // CEF may call the scheduler from any thread
    let (wake, deadlines) = mpsc::channel::<Instant>();

    let runtime = App::url("https://example.com")
        .scheduler(move |request: PumpRequest| {
            let _ = wake.send(request.deadline(Instant::now()));
        })
        .start()
        .expect("Kurogane failed to start");

    let mut next = Instant::now();
    while !runtime.should_shutdown() {
        let now = Instant::now();
        if now >= next {
            next = now + MAX_PUMP_DELAY;
            runtime.pump();
        }
        // Sleep until the deadline or a new request; the earliest wins
        let wait = next.saturating_duration_since(Instant::now());
        if let Ok(deadline) = deadlines.recv_timeout(wait) {
            next = next.min(deadline);
        }
    }

    runtime.shutdown();
}
```

A scheduler turns on Chromium's external message pump. `App::run` refuses one with [`ConfigError::SchedulerWithRunLoop`](https://kurogane-rs.org/docs/api/app/configerror.md#variant.SchedulerWithRunLoop).

An app without a scheduler can pump on a fixed interval or on every turn of its loop. Both work. A fixed interval wakes the app while Chromium is idle. Pumping on every turn keeps a core busy.

On Linux `pump` also runs glib's default main context. Chromium reads its X11 and Wayland events there. Your loop needs no glib of its own.

## Embedded mode

`App::start_embedded` starts Chromium without any window of its own. Your app owns the windows and places browsers inside them with [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser):

* A browser is a native child window of your window. It draws inside it at the bounds you give.
* Your window must outlive the browsers in it. Close the browsers first.
* Closing a browser leaves your window open.
* Kurogane installs no Ctrl+C handler. Your app owns its lifecycle.
* [`App::window`](https://kurogane-rs.org/docs/api/app/app.md#method.window) describes a start window and is a configuration error here.

On Linux the parent must be an X11 window. In a Wayland session that window runs under XWayland. Kurogane runs Chromium itself on X11 in embedded mode. Under Wayland it would draw the page beside your window instead of inside it.

## Threads

Your handlers run on the UI thread. That thread also runs every window and receives every message from every page. Return promptly and move slow work to a thread of your own.

`AppHandle` and [`BrowserHandle`](https://kurogane-rs.org/docs/api/app/browserhandle.md) work from any thread. Closing and ending run on the UI thread. They run at once when called there and are posted there otherwise. Once `AppInstance::shutdown` has begun, calls that would reach Chromium do nothing. Stop using handles on other threads before you shut down.
