# Open windows and remember their placement

> Shape the start window, open more windows and reopen each where the user left it.

See [Windows and browsers](https://kurogane-rs.org/docs/concepts/windows-and-browsers.md) for what a window is and who may open one.

## Shape the start window

[`App::window`](https://kurogane-rs.org/docs/api/app/app.md#method.window) describes the first window with [`WindowOptions`](https://kurogane-rs.org/docs/api/windows/windowoptions.md):

```rust
use kurogane::{App, WindowOptions, WindowState};

fn main() {
    App::new("content")
        .window(
            WindowOptions::new()
                .title("Notes")
                .size(1100, 720)
                .min_size(640, 480)
                .state(WindowState::Maximized),
        )
        .run_or_exit();
}
```

* **`title`** fixes the title. Without it the window takes its page's `<title>` and follows it.
* **`size`** is the content's size in density-independent pixels. 1100 by 720 is the page's 1100 by 720 CSS pixels at 100% zoom. Without it the window opens at 800 by 600.
* **`min_size`** is the smallest content size the user can drag the window down to.
* **`state`** opens the window `Normal`, `Minimized`, `Maximized`, `Fullscreen` or `Hidden`. A window opened maximized restores to its size, centered.

A window opens centered on the primary display. A size larger than the display's work area shrinks to fit. A size of 0 or a minimum larger than the size fails at startup.

## Open more windows

[`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) opens a page in another application window. Start the app with `App::start`, open the windows, then run the loop:

```rust
use kurogane::{App, RuntimeError, WindowOptions};

fn main() -> Result<(), RuntimeError> {
    let runtime = App::new("content").start()?;

    runtime.create_window(
        "app://app/settings.html",
        WindowOptions::new().name("settings").title("Settings").size(640, 480),
    )?;

    runtime.run()
}
```

A page of your app's own origin can open one too. `window.open` and a `target="_blank"` link to a page of your origin open in an application window:

```javascript
window.open("/settings.html");
```

Your app keeps running while any of its windows is open, a hidden one included.

## Remember where a window was

[`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing) reports each application window's name and [`WindowPlacement`](https://kurogane-rs.org/docs/api/windows/windowplacement.md) as it closes. Save the placement under the name. Give it back with [`WindowOptions::placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement) on the next run:

```rust
use std::path::{Path, PathBuf};

use kurogane::{App, WindowOptions, WindowPlacement};

fn placement_file(dir: &Path, name: &str) -> PathBuf {
    dir.join(format!("{name}.window.json"))
}

fn load(dir: &Path, name: &str) -> Option<WindowPlacement> {
    let json = std::fs::read(placement_file(dir, name)).ok()?;
    serde_json::from_slice(&json).ok()
}

fn save(dir: &Path, name: &str, placement: WindowPlacement) {
    if let Ok(json) = serde_json::to_vec(&placement) {
        let _ = std::fs::write(placement_file(dir, name), json);
    }
}

fn main() {
    let dir = std::env::temp_dir().join("notes");

    let mut main = WindowOptions::new().name("main").size(1100, 720);
    if let Some(placement) = load(&dir, "main") {
        main = main.placement(placement);
    }

    App::new("content")
        .window(main)
        .on_window_closing(move |closing, _app| {
            if let Some(name) = closing.name() {
                let _ = std::fs::create_dir_all(&dir);
                save(&dir, name, closing.placement());
            }
        })
        .run_or_exit();
}
```

Keep the files in your app's own data directory. A placement reads `{"x":200,"y":150,"width":900,"height":600,"state":"Maximized"}` in JSON.

* A maximized, minimized or fullscreen window reports the place and size it restores to. Its state is `Normal`, `Maximized` or `Fullscreen`.
* A window minimized as it closes reports how it showed before. A window maximized and then minimized comes back maximized.
* A placement no display shows anymore opens on the nearest display. A window larger than that display's work area shrinks to fit.
* Wayland lets no app place its windows. There only the size applies.
* `placement` decides the size over `size`. Keep `size` for the first run.

The hook runs once for each application window on the UI thread. Popups, DevTools and embedded browsers aren't reported. Saving a small file there is fine. Anything slow isn't.

> [!NOTE]
> Under xfwm4 a window the user maximized can report its maximized place and size as `Normal`. xfwm4 sends a maximize's geometry before its state.

## Put a window at an exact spot

Write the placement out yourself:

```rust
use kurogane::{WindowOptions, WindowPlacement, WindowState};

let options = WindowOptions::new().placement(WindowPlacement {
    x: 200,
    y: 150,
    width: 900,
    height: 600,
    state: WindowState::Normal,
});
```

Positions and sizes are in density-independent pixels.

## Find and close a window

A name is your app's handle on a window. [`AppHandle::find_window_by_name`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.find_window_by_name) finds the open window that holds it. Close it through its browser:

```rust
use kurogane::AppHandle;

fn close_settings(app: &AppHandle) {
    let browser = app
        .find_window_by_name("settings")
        .and_then(|window| app.browser_for_window(window))
        .and_then(|id| app.get_browser_handle(id));
    if let Some(browser) = browser {
        browser.close(false);
    }
}
```

`close(false)` lets the page's `beforeunload` ask the user first. `close(true)` skips the question.

One open window holds a name at a time. `create_window` with the name of a window still open fails with [`RuntimeError::WindowNameTaken`](https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.WindowNameTaken). The name is free again once that window's close is reported.

## Group windows on Linux

[`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) sets the class Linux desktops group your windows by. That's `WM_CLASS` under X11 and the `app_id` under Wayland:

```rust
App::new("content").window_class("com.example.notes").run_or_exit();
```

A launcher's icon attaches to your windows when its desktop entry names the same class. Give `window_class` the `identifier` from `kurogane.toml`. `kurogane bundle` writes that identifier into the AppImage's desktop entry. Windows and macOS ignore the class.

## Give windows an icon

[`App::window_icon`](https://kurogane-rs.org/docs/api/app/app.md#method.window_icon) gives every window your app's icon as a PNG:

```rust
App::new("content")
    .window_icon(include_bytes!("../icon.png").as_slice())
    .run_or_exit();
```

Windows shows it in the title bar, the taskbar and the window switcher. An X11 window manager shows it too. A 256 by 256 square is plenty. Wayland desktops take the icon from the desktop entry. macOS windows have no icon; the Dock shows the app's.
