# Kurogane > A composable Chromium runtime for Rust. Kurogane embeds Chromium in your application through CEF and leaves your application in charge of its event loop, windows and lifecycle. These are the docs of Kurogane 0.0.6-beta.1. Every link leads to the Markdown copy of a page. [llms-full.txt](https://kurogane-rs.org/llms-full.txt) holds all of them in one file. ## Start - [Introduction](https://kurogane-rs.org/docs/start/introduction.md): What Kurogane is, what it's for and when another tool fits better. - [Install](https://kurogane-rs.org/docs/start/install.md): Install the kurogane CLI and the tools your apps build with. - [First app](https://kurogane-rs.org/docs/start/first-app.md): Create a project, run it, call Rust from the page and bundle it. - [Project layout](https://kurogane-rs.org/docs/start/project-layout.md): What each file in a Kurogane project does and how kurogane.toml ties them together. ## Concepts - [Process model](https://kurogane-rs.org/docs/concepts/process-model.md): Which processes a Kurogane app runs and which of your code runs in each. - [Runtime and event loop](https://kurogane-rs.org/docs/concepts/runtime-and-event-loop.md): Who drives Chromium's message loop and who owns the windows. - [Windows and browsers](https://kurogane-rs.org/docs/concepts/windows-and-browsers.md): What a window and a browser are, who opens them and how your app reaches them. - [Lifecycle and shutdown](https://kurogane-rs.org/docs/concepts/lifecycle-and-shutdown.md): How a browser closes, when your app ends and how Chromium shuts down. - [app:// and your frontend](https://kurogane-rs.org/docs/concepts/app-protocol.md): Where your app's page comes from and how Kurogane serves it from disk. - [IPC](https://kurogane-rs.org/docs/concepts/ipc.md): Commands, events and streams between your Rust code and your page. - [Capabilities and permissions](https://kurogane-rs.org/docs/concepts/capabilities-and-permissions.md): What a page may reach and who decides it. - [Sandbox](https://kurogane-rs.org/docs/concepts/sandbox.md): Run Chromium's helper processes in the operating system's sandbox. ## Guides - [Load a dev server or bundled assets](https://kurogane-rs.org/docs/guides/frontend-source.md): Point your app at a dev server during development and at its built frontend in release builds. - [Open windows and remember their placement](https://kurogane-rs.org/docs/guides/windows.md): Shape the start window, open more windows and reopen each where the user left it. - [Control links, popups and navigation](https://kurogane-rs.org/docs/guides/links-and-navigation.md): Decide which windows a page may open and where it may take its window. - [Keyboard shortcuts and Chromium commands](https://kurogane-rs.org/docs/guides/keyboard-shortcuts.md): Decide which keys your app takes, which the page gets and which of Chromium's commands run. - [Downloads](https://kurogane-rs.org/docs/guides/downloads.md): Decide where the files a page downloads are saved. - [Permissions](https://kurogane-rs.org/docs/guides/permissions.md): Allow a camera, a microphone, the location and Chromium's other permissions, or ask the user first. - [The context menu](https://kurogane-rs.org/docs/guides/context-menu.md): Edit the menu a right-click opens, add items of your own or let the page draw its own. - [File choosers](https://kurogane-rs.org/docs/guides/file-choosers.md): Answer the file choosers a page opens with the system's dialog, files of your choosing or a picker of your own. - [Drags into embedded browsers](https://kurogane-rs.org/docs/guides/drags.md): Decide what another application may drag into a browser embedded in your own window. - [Follow the page's title and fullscreen](https://kurogane-rs.org/docs/guides/title-and-fullscreen.md): Keep a window's title and fullscreen state in step with its page and hear when they change. - [One instance per profile](https://kurogane-rs.org/docs/guides/single-instance.md): Handle a second launch in the running app, run separate copies and choose where the profile lives. - [Commands in depth](https://kurogane-rs.org/docs/guides/commands.md): Synchronous, async and binary commands, their errors and how much data they carry. - [Events](https://kurogane-rs.org/docs/guides/events.md): Send named messages from your Rust code to every page subscribed to them. - [Streams](https://kurogane-rs.org/docs/guides/streams.md): Move chunks both ways between a page and a Rust handler until one side ends. - [WebAssembly](https://kurogane-rs.org/docs/guides/webassembly.md): Build a WebAssembly module and load it in your page. - [GPU mode](https://kurogane-rs.org/docs/guides/gpu-mode.md): Choose how Chromium renders your page and check what the GPU does on a machine. - [Credential storage](https://kurogane-rs.org/docs/guides/credential-storage.md): Choose how Chromium protects cookies and saved passwords at rest and stop Keychain prompts. - [Chromium flags and preferences](https://kurogane-rs.org/docs/guides/chromium-flags.md): Pass Chromium switches, set its preferences and turn back on what Kurogane turns off. - [Logging](https://kurogane-rs.org/docs/guides/logging.md): See what Kurogane and Chromium do and read the errors your app reports when it can't start. - [Browser and renderer delegates](https://kurogane-rs.org/docs/guides/delegates.md): Take part in Chromium's browser and renderer process lifecycles without replacing Kurogane's own. ## Embedding - [Drive Chromium from winit](https://kurogane-rs.org/docs/embedding/winit.md): Run Kurogane's windows from a winit event loop and pump Chromium when it asks. - [Embed a browser in your window](https://kurogane-rs.org/docs/embedding/child-browsers.md): Place Chromium browsers inside windows your app owns, keep them laid out and close them cleanly. ## Shipping - [Bundle your app](https://kurogane-rs.org/docs/shipping/bundling.md): Package your app with its frontend and the Chromium runtime for Linux, Windows and macOS. - [Bundle layouts](https://kurogane-rs.org/docs/shipping/bundle-layouts.md): What each bundle format holds, how a bundled app finds its Chromium and how that runtime is verified. - [Code signing](https://kurogane-rs.org/docs/shipping/signing.md): Sign your Windows binaries and installer or your macOS app as part of kurogane bundle. - [Platforms and requirements](https://kurogane-rs.org/docs/shipping/platforms.md): What each platform needs and what behaves differently on Linux, Windows, macOS and Nix. - [Templates](https://kurogane-rs.org/docs/shipping/templates.md): Start projects from the official starters or a template of your own. Write templates others can use. ## CLI and manifest - [CLI reference](https://kurogane-rs.org/docs/cli.md): every command of the kurogane CLI 0.0.6-beta.1 - [Manifest reference](https://kurogane-rs.org/docs/manifest.md): every table and key of kurogane.toml ## API reference - [API reference](https://kurogane-rs.org/docs/api.md): every public item of the kurogane crate, grouped by topic ### App and runtime - [App and runtime](https://kurogane-rs.org/docs/api/app.md): Configures an application, starts the runtime and reaches it once it runs. - [`App`](https://kurogane-rs.org/docs/api/app/app.md): Public application builder. - [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md): Shared lifecycle handle for a running Kurogane application. - [`AppInstance`](https://kurogane-rs.org/docs/api/app/appinstance.md): The running application, owned by the thread that started it. - [`BrowserBounds`](https://kurogane-rs.org/docs/api/app/browserbounds.md): A browser's place inside its parent window, for `AppInstance::create_child_browser` and `BrowserHandle::set_bounds`. It is a position and a size in that window's own coordinates, which CEF applies unconverted. Pixels from the top-left of the client area on Windows and X11; on macOS, points in the parent `NSView`, whose origin is its top-left corner when the view is flipped (winit's is) and its bottom-left corner otherwise. - [`BrowserHandle`](https://kurogane-rs.org/docs/api/app/browserhandle.md): A browser of the running application. - [`SecondInstance`](https://kurogane-rs.org/docs/api/app/secondinstance.md): A launch of the application while another instance is already running. - [`CefLocation`](https://kurogane-rs.org/docs/api/app/ceflocation.md): Where the application found its Chromium runtime, in the order it looks. - [`ConfigError`](https://kurogane-rs.org/docs/api/app/configerror.md): One problem in the [`App`](/docs/api/app/app) builder configuration, reported by `build()` / `run()` / `start_embedded()` as `RuntimeError::InvalidConfiguration`. - [`CredentialStorage`](https://kurogane-rs.org/docs/api/app/credentialstorage.md): Backend used to protect cookies and saved passwords at rest. - [`GpuMode`](https://kurogane-rs.org/docs/api/app/gpumode.md): GPU backend selection strategy. - [`PumpRequest`](https://kurogane-rs.org/docs/api/app/pumprequest.md): A request from CEF indicating when it next needs to be serviced. - [`RuntimeError`](https://kurogane-rs.org/docs/api/app/runtimeerror.md): Failure to start the application or to open a window or a browser. - [`SandboxMode`](https://kurogane-rs.org/docs/api/app/sandboxmode.md): Chromium process sandbox policy. - [`ClientAppBrowserDelegate`](https://kurogane-rs.org/docs/api/app/clientappbrowserdelegate.md): Customizes browser-process startup behavior. - [`ClientAppRendererDelegate`](https://kurogane-rs.org/docs/api/app/clientapprendererdelegate.md): Customizes render-process behavior. - [`SchemeHandler`](https://kurogane-rs.org/docs/api/app/schemehandler.md): Generates a `ResourceHandler` for requests on a custom scheme. - [`is_browser_process`](https://kurogane-rs.org/docs/api/app/is_browser_process.md): Returns whether this process is Chromium's browser process rather than one of its helper processes (renderer, GPU, utility) which run this same binary again with a `--type=` argument. - [`resource_dir`](https://kurogane-rs.org/docs/api/app/resource_dir.md): The directory a packaged application's bundled resources live in. - [`resource_handler_from_bytes`](https://kurogane-rs.org/docs/api/app/resource_handler_from_bytes.md): Builds a `ResourceHandler` serving `data` once with the given MIME type and status code. - [`sandbox_entry`](https://kurogane-rs.org/docs/api/app/sandbox_entry.md): Declares the entry points CEF's sandbox bootstrap calls. ### Windows and browsers - [Windows and browsers](https://kurogane-rs.org/docs/api/windows.md): Opens windows, places them and names the browsers inside them. - [`BrowserId`](https://kurogane-rs.org/docs/api/windows/browserid.md): Identifier of a browser, never reused while the application runs. - [`BrowserMetadata`](https://kurogane-rs.org/docs/api/windows/browsermetadata.md): What the runtime knows about an open browser, from [`AppHandle::browsers`](/docs/api/app/apphandle#method.browsers). - [`FullscreenChange`](https://kurogane-rs.org/docs/api/windows/fullscreenchange.md): A page entering or leaving fullscreen, passed to [`App::on_fullscreen_change`](/docs/api/app/app#method.on_fullscreen_change). - [`TitleChange`](https://kurogane-rs.org/docs/api/windows/titlechange.md): A page's new title, passed to [`App::on_title_change`](/docs/api/app/app#method.on_title_change). - [`WindowClosing`](https://kurogane-rs.org/docs/api/windows/windowclosing.md): A window of the application's closing, passed to [`App::on_window_closing`](/docs/api/app/app#method.on_window_closing). It says which window it is and where it was, to open it there again with [`WindowOptions::placement`](/docs/api/windows/windowoptions#method.placement). - [`WindowId`](https://kurogane-rs.org/docs/api/windows/windowid.md): Identifier of a window, never reused while the application runs. - [`WindowMetadata`](https://kurogane-rs.org/docs/api/windows/windowmetadata.md): What the runtime knows about an open window, from [`AppHandle::windows`](/docs/api/app/apphandle#method.windows). - [`WindowOptions`](https://kurogane-rs.org/docs/api/windows/windowoptions.md): How an application window opens. It holds the name the application knows it by, its title, size and place, the size it cannot be made smaller than and its state. - [`WindowPlacement`](https://kurogane-rs.org/docs/api/windows/windowplacement.md): Where a window's content is on the screen in density-independent pixels and how the window shows. A window maximized, minimized or fullscreen is placed where it restores to. - [`BrowserType`](https://kurogane-rs.org/docs/api/windows/browsertype.md): Kind of a browser. - [`WindowState`](https://kurogane-rs.org/docs/api/windows/windowstate.md): How a window shows when it opens (as its options say) and as it closes. ### IPC - [IPC](https://kurogane-rs.org/docs/api/ipc.md): Commands, streams and errors between your Rust code and the page. - [`IpcError`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md): A structured error with a numeric `ErrorCode` and human-readable message. - [`Origin`](https://kurogane-rs.org/docs/api/ipc/origin.md): Security origin of a frame as `scheme://host:port` or opaque. - [`OriginError`](https://kurogane-rs.org/docs/api/ipc/originerror.md): A configured origin that does not parse. - [`Responder`](https://kurogane-rs.org/docs/api/ipc/responder.md): The answer to one async request. - [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md): Responder for sending data from a browser-side stream handler to the renderer. - [`ErrorCode`](https://kurogane-rs.org/docs/api/ipc/errorcode.md): Classifies an `IpcError` by the numeric code exposed to the renderer. Runtime errors use the fixed codes `0` through `-9`; applications may use positive codes through `ErrorCode::App`. - [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md): Handles one stream a page opens. - [`BinaryResponder`](https://kurogane-rs.org/docs/api/ipc/binaryresponder.md): Responder of an async binary command, resolved with the reply's bytes ([`App::async_binary_command`](/docs/api/app/app#method.async_binary_command)). ### Capabilities - [Capabilities](https://kurogane-rs.org/docs/api/capabilities.md): Grants a page scoped access to the filesystem. - [`AuthorizedFs`](https://kurogane-rs.org/docs/api/capabilities/authorizedfs.md): The authority of one origin. Every operation runs the decision rules in the module documentation; nothing else reaches the filesystem for a renderer. - [`DirEntry`](https://kurogane-rs.org/docs/api/capabilities/direntry.md): One entry of a listed directory. Links and reparse points are never listed. - [`Filesystem`](https://kurogane-rs.org/docs/api/capabilities/filesystem.md): Filesystem capability configuration of named scopes and the grants that bind origins to them. - [`FilesystemBuilder`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md): Builder for `Filesystem`. - [`FsAccess`](https://kurogane-rs.org/docs/api/capabilities/fsaccess.md): A set of operational filesystem capabilities. - [`ScopeBuilder`](https://kurogane-rs.org/docs/api/capabilities/scopebuilder.md): Declares one scope inside [`FilesystemBuilder::scope`](/docs/api/capabilities/filesystembuilder#method.scope). - [`ScopeId`](https://kurogane-rs.org/docs/api/capabilities/scopeid.md): Handle to a scope declared on a `FilesystemBuilder`. Grants name scopes by handle. A grant cannot reference a scope that was never declared. - [`Denial`](https://kurogane-rs.org/docs/api/capabilities/denial.md): Why an in-grant request was refused. Each variant renders one fixed, class-level message. - [`EntryKind`](https://kurogane-rs.org/docs/api/capabilities/entrykind.md): The kind of a directory entry. - [`FsConfigError`](https://kurogane-rs.org/docs/api/capabilities/fsconfigerror.md): A `Filesystem` configuration that cannot be built. These are developer-facing and may name paths; they never reach a renderer. - [`FsError`](https://kurogane-rs.org/docs/api/capabilities/fserror.md): Failure of one filesystem operation performed for an origin. ### Requests and decisions - [Requests and decisions](https://kurogane-rs.org/docs/api/requests.md): What a page or Chromium asks of your application and the answers it can give. - [`AppItem`](https://kurogane-rs.org/docs/api/requests/appitem.md): An item of the application's in a `ContextMenu`. - [`ChromeCommandRequest`](https://kurogane-rs.org/docs/api/requests/chromecommandrequest.md): A command about to run, passed to [`App::on_chrome_command`](/docs/api/app/app#method.on_chrome_command). - [`ContextMenu`](https://kurogane-rs.org/docs/api/requests/contextmenu.md): The menu a right-click opens, passed to [`App::on_context_menu`](/docs/api/app/app#method.on_context_menu) to edit. - [`ContextMenuCommand`](https://kurogane-rs.org/docs/api/requests/contextmenucommand.md): An item of the application's chosen, passed to [`App::on_context_menu_command`](/docs/api/app/app#method.on_context_menu_command). - [`ContextMenuTarget`](https://kurogane-rs.org/docs/api/requests/contextmenutarget.md): What a right-click was on. - [`DownloadRequest`](https://kurogane-rs.org/docs/api/requests/downloadrequest.md): A download about to start, passed to [`App::on_download`](/docs/api/app/app#method.on_download). - [`DragEnter`](https://kurogane-rs.org/docs/api/requests/dragenter.md): A drag entering a window, passed to [`App::on_drag_enter`](/docs/api/app/app#method.on_drag_enter). - [`FileDialogRequest`](https://kurogane-rs.org/docs/api/requests/filedialogrequest.md): A page opening a file chooser, passed to [`App::on_file_dialog`](/docs/api/app/app#method.on_file_dialog). - [`FileDialogResponder`](https://kurogane-rs.org/docs/api/requests/filedialogresponder.md): Answers a `FileDialogRequest` the hook left for later (`FileDialogDecision::Later`), from any thread. - [`KeyPress`](https://kurogane-rs.org/docs/api/requests/keypress.md): A key the user pressed, passed to [`App::on_key`](/docs/api/app/app#method.on_key). - [`Modifiers`](https://kurogane-rs.org/docs/api/requests/modifiers.md): The modifier keys held with a key. - [`NavigationRequest`](https://kurogane-rs.org/docs/api/requests/navigationrequest.md): A page's navigation of the window it is in, passed to [`App::on_navigation`](/docs/api/app/app#method.on_navigation). - [`NewWindowRequest`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md): A page's request for a new window, passed to [`App::on_new_window`](/docs/api/app/app#method.on_new_window). - [`PermissionRequest`](https://kurogane-rs.org/docs/api/requests/permissionrequest.md): A page asking for a device or a permission, passed to [`App::on_permission`](/docs/api/app/app#method.on_permission). - [`PermissionResponder`](https://kurogane-rs.org/docs/api/requests/permissionresponder.md): Answers a `PermissionRequest` the hook left for later (`PermissionDecision::Later`), from any thread. - [`Submenu`](https://kurogane-rs.org/docs/api/requests/submenu.md): A submenu of a `ContextMenu`. Shown only when an item of it is. - [`ChromeCommand`](https://kurogane-rs.org/docs/api/requests/chromecommand.md): A command Chromium runs in a window of the application's, from a key shortcut or the context menu, as [`App::on_chrome_command`](/docs/api/app/app#method.on_chrome_command) is asked about it. Chromium's own commands are folded by what the user asked for. Every kind of reload is [`Reload`](/docs/api/requests/chromecommand#variant.Reload); the context menu's Copy and Ctrl+C are both [`Copy`](/docs/api/requests/chromecommand#variant.Copy). - [`CommandDecision`](https://kurogane-rs.org/docs/api/requests/commanddecision.md): The answer of [`App::on_chrome_command`](/docs/api/app/app#method.on_chrome_command). - [`DownloadDecision`](https://kurogane-rs.org/docs/api/requests/downloaddecision.md): The answer of [`App::on_download`](/docs/api/app/app#method.on_download). - [`DragDecision`](https://kurogane-rs.org/docs/api/requests/dragdecision.md): The answer of [`App::on_drag_enter`](/docs/api/app/app#method.on_drag_enter). - [`FileDialogDecision`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md): The answer of [`App::on_file_dialog`](/docs/api/app/app#method.on_file_dialog). - [`FileDialogKind`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md): What kind of file chooser a page opens (`FileDialogRequest::kind`). - [`Key`](https://kurogane-rs.org/docs/api/requests/key.md): A key by its place on the keyboard rather than what it types. Shift+W and W are both `Key::Char('W')`. - [`KeyDecision`](https://kurogane-rs.org/docs/api/requests/keydecision.md): The answer of [`App::on_key`](/docs/api/app/app#method.on_key). - [`MediaKind`](https://kurogane-rs.org/docs/api/requests/mediakind.md): What kind of media was right-clicked. - [`MenuItem`](https://kurogane-rs.org/docs/api/requests/menuitem.md): An item of a `ContextMenu`. - [`NavigationDecision`](https://kurogane-rs.org/docs/api/requests/navigationdecision.md): The answer of [`App::on_navigation`](/docs/api/app/app#method.on_navigation). - [`NewWindowDecision`](https://kurogane-rs.org/docs/api/requests/newwindowdecision.md): The answer of [`App::on_new_window`](/docs/api/app/app#method.on_new_window). - [`NewWindowKind`](https://kurogane-rs.org/docs/api/requests/newwindowkind.md): How a page asked for a window of its own (`NewWindowRequest::kind`). - [`Permission`](https://kurogane-rs.org/docs/api/requests/permission.md): What a page asks for, in a `PermissionRequest`. - [`PermissionDecision`](https://kurogane-rs.org/docs/api/requests/permissiondecision.md): The answer of [`App::on_permission`](/docs/api/app/app#method.on_permission). - [`StandardItem`](https://kurogane-rs.org/docs/api/requests/standarditem.md): One of Kurogane's items, which runs a command of Chromium's. --- # Introduction > What Kurogane is, what it's for and when another tool fits better. Kurogane is a composable Chromium runtime for Rust. It embeds Chromium in your application through [CEF](https://github.com/chromiumembedded/cef) and leaves your application in charge. Your interface is a web page. Your backend is Rust. Kurogane runs the page in Chromium and connects it to your Rust code. ## What you get * **One engine everywhere.** Your app renders with the same Chromium on Linux, Windows and macOS. No system WebView decides how your page looks or which GPU path it takes. * **Your own architecture.** Kurogane can run the event loop and the windows for you. Your app can also own both and drive Chromium from its own loop. * **A clear boundary to native code.** A page reaches Rust only through the commands, events and streams you register. Each request is checked against the page's origin before your handler runs. * **Tooling.** The `kurogane` CLI creates projects from starters, runs them during development and bundles them for distribution. ## How an app is put together Your app's binary is Chromium's browser process. Chromium starts its renderer, GPU and utility processes from the same binary. Your Rust code runs in the browser process. Your page runs in a renderer. [IPC](https://kurogane-rs.org/docs/concepts/ipc.md) connects the two. You describe the app with [`App`](https://kurogane-rs.org/docs/api/app/app.md). It names the frontend, the commands the page may call, the windows to open and how Chromium behaves. Starting it gives you an [`AppInstance`](https://kurogane-rs.org/docs/api/app/appinstance.md), the running application. An [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md) reaches it from any thread. An app runs one of two ways: * **Kurogane runs the loop.** [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) opens the windows and runs Chromium's message loop until the app ends. * **Your app runs the loop.** [`App::start_embedded`](https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded) starts the runtime without Chromium's loop. Your event loop drives Chromium and owns the windows Chromium draws into. > [!NOTE] > Chromium's helper processes run your binary again. Code before the call that starts the runtime runs once in every process. See [`App`](https://kurogane-rs.org/docs/api/app/app.md) for what belongs there. ## When to use Kurogane * **Your app already has an architecture.** It has its own event loop, window hierarchy or GUI framework. Kurogane adds Chromium as one component of it. * **Rendering has to match across platforms.** WebGL, Canvas and WASM-heavy visualizations behave the same on every OS. * **You want Chromium without Electron.** There is no bundled Node.js and no process model imposed on your app. * **You're building a custom shell or engine.** You need the browser's lifecycle, renderer-side extension points or fine-grained IPC between Rust and JavaScript. ## When to use something else * You want the smallest binary: use [Tauri](https://tauri.app). * You want Node.js APIs: use [Electron](https://www.electronjs.org). * You're building a standard CRUD interface: use either. Kurogane favors control over convenience and breadth. It isn't a replacement for Tauri or Electron. ## What Kurogane is not Kurogane is a platform foundation and not an application framework. It has none of these: * A DOM abstraction layer * A widget toolkit * Opinionated state management * A bundled JavaScript runtime ## Status Kurogane supports Linux, Windows and macOS. It is in early development. Its API may change between releases. --- # Install > Install the kurogane CLI and the tools your apps build with. The `kurogane` CLI creates, runs and bundles your apps. It also installs the Chromium runtime they need. ## Install the CLI On Linux and macOS: ```bash curl --proto '=https' --tlsv1.2 -LsSf https://kurogane-rs.org/install.sh | sh ``` On Windows: ```powershell powershell -c "irm https://kurogane-rs.org/install.ps1|iex" ``` The installers download the prebuilt CLI for your platform and check its SHA-256 checksum. Then they put it on your `PATH`. They need no administrator rights, no Rust toolchain and no package manager. ### With Nix On NixOS and other systems with Nix: ```bash nix profile add github:0x48piraj/kurogane ``` See [Nix and NixOS](#nix-and-nixos) for system flakes and GPU drivers. ### With Cargo With Rust already installed: ```bash cargo install kurogane-cli ``` The development version builds from the repository: ```bash cargo install --git https://github.com/0x48piraj/kurogane kurogane-cli ``` > [!IMPORTANT] > The development version may be ahead of the latest release and come with a few rough edges. ## What else you need The CLI is all the installers put on your machine. Building and running apps also needs these: | Tool | Needed for | Install | |---|---|---| | Rust 1.96 or newer | all platforms | [rustup.rs](https://rustup.rs) | | Visual Studio C++ Build Tools | Windows | Visual Studio Installer, workload **Desktop development with C++** (includes the Windows SDK) | | Xcode Command Line Tools | macOS | `xcode-select --install` | | C compiler and Chromium's libraries | Linux | Debian and Ubuntu: `sudo apt install build-essential libnss3 libgtk-3-0 libgbm1 libxkbcommon0 libasound2` (Ubuntu 24.04: `libgtk-3-0t64 libasound2t64`). Fedora: `sudo dnf install gcc nss gtk3 mesa-libgbm libxkbcommon alsa-lib` | | Node.js | starters with a JavaScript frontend | [nodejs.org](https://nodejs.org) | `kurogane run`, `dev` and `bundle` install the Chromium runtime when it is missing. `kurogane install` installs it ahead of time. Check your setup: ```bash kurogane doctor ``` It checks the Chromium runtime, the platform's build tools and the project in the current directory. ## Try it Run the showcase to see Kurogane at work: ```bash kurogane showcase ``` ## Supported platforms | Platform | Architectures | Minimum OS | |---|---|---| | Linux (glibc) | x86_64, aarch64 | glibc 2.31 (Ubuntu 20.04, Debian 11) | | macOS | Apple Silicon, Intel | macOS 12 | | Windows | x86_64, ARM64 | Windows 10 | | NixOS, Nix | x86_64-linux, aarch64-linux, aarch64-darwin | | The Linux CLI is a static binary and starts on any distribution. Apps need glibc because Chromium does. Alpine and other musl systems can install the CLI but can't run apps. An app needs at least the glibc of the machine that built it. Build Linux bundles on the oldest distribution you support. ## Upgrade Run the installer again. It replaces the CLI only after the new one has been downloaded, verified and run. An interrupted or failed upgrade keeps the previous version. ## Installer options `install.sh` takes options after `sh -s --`: ```bash curl --proto '=https' --tlsv1.2 -LsSf https://kurogane-rs.org/install.sh | sh -s -- --version ``` | `install.sh` | `install.ps1` | Environment | Effect | |---|---|---|---| | `--version ` | `-Version ` | `KUROGANE_VERSION` | installs a specific release instead of the latest | | `--install-dir ` | `-InstallDir ` | `KUROGANE_INSTALL_DIR` | installs the binary somewhere else | | | | `KUROGANE_HOME` | keeps the installation in another home than `~/.kurogane` (Unix) | | `--no-modify-path` | `-NoModifyPath` | `KUROGANE_NO_MODIFY_PATH=1` | leaves shell startup files and the user PATH alone | | `--force-generic` | | | installs the generic Linux binary on NixOS anyway | | `-q`, `--quiet` | | | prints only errors and the summary | | `-y`, `--yes` | | | accepted for compatibility; the installers never prompt | | | `-Arch ` | `KUROGANE_ARCH` | installs `x86_64` or `aarch64` instead of the detected architecture (Windows) | | | `-DownloadUrl ` | `KUROGANE_DOWNLOAD_URL` | sets a release mirror base URL (https only) | `irm | iex` can't pass arguments. On Windows set the variables first or run the script as a script block: ```powershell $env:KUROGANE_VERSION = ''; irm https://kurogane-rs.org/install.ps1 | iex ``` ```powershell & ([scriptblock]::Create((irm https://kurogane-rs.org/install.ps1))) -Version ``` The installers never prompt. They behave the same from a pipe, a terminal or CI. In GitHub Actions they also add the install directory to `$GITHUB_PATH`. ## Where things go | | Unix | Windows | |---|---|---| | CLI | `~/.kurogane/bin/kurogane` | `%LOCALAPPDATA%\kurogane\bin\kurogane.exe` | | PATH setup | `~/.kurogane/env`, sourced from `~/.profile`, `~/.bashrc`, `~/.bash_profile`, `~/.bash_login` and `~/.zshenv` where they exist; fish `conf.d/kurogane.fish` | user `Path` in `HKCU\Environment` | | Install receipt | `~/.kurogane/receipt.json` | `%LOCALAPPDATA%\kurogane\receipt.json` | | Chromium runtime | `~/.local/share/tanso/cef//` (Linux), `~/Library/Application Support/tanso/cef//` (macOS) | `%LOCALAPPDATA%\tanso\cef\\` | The installer creates `~/.profile` when it is missing. It creates `~/.zshenv` too when zsh is installed. `kurogane self uninstall` reads the receipt to know what it may remove. The Chromium runtime is shared with every project built with [tanso](https://github.com/kurogane-rs/tanso), Kurogane's CEF bindings. ## Verify a release The installers check every download against the SHA-256 published in the same release. They refuse to install on a mismatch or when no SHA-256 tool is available. Every release artifact carries a [GitHub artifact attestation](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations). `install.sh` and `install.ps1` carry one too. It proves the release workflow in [kurogane-rs/kurogane-install](https://github.com/kurogane-rs/kurogane-install) built the artifact. Check one with the GitHub CLI: ```bash gh release download v --repo 0x48piraj/kurogane --pattern 'kurogane-cli-x86_64-unknown-linux-musl.tar.gz' gh attestation verify kurogane-cli-x86_64-unknown-linux-musl.tar.gz --repo kurogane-rs/kurogane-install ``` Review the installer before you run it: ```bash curl --proto '=https' --tlsv1.2 -LsSf https://kurogane-rs.org/install.sh -o install.sh less install.sh sh install.sh ``` ## Nix and NixOS On NixOS install through the flake. The prebuilt Linux binaries and the Chromium runtime they download expect the usual `/lib` layout. NixOS has none. `install.sh` stops there and prints the Nix command instead. The flake builds the CLI from source. It includes the Chromium runtime, its libraries and the toolchain. `kurogane dev` works right away. ### In your system flake Add Kurogane to your flake inputs: ```nix inputs.kurogane.url = "github:0x48piraj/kurogane"; ``` On `nixos-unstable`, follow your system's `nixpkgs` revision: ```nix inputs.kurogane = { url = "github:0x48piraj/kurogane"; inputs.nixpkgs.follows = "nixpkgs"; }; ``` Pass `inputs` to your NixOS modules through `specialArgs` in `nixpkgs.lib.nixosSystem`: ```nix specialArgs = { inherit inputs; }; ``` Install Kurogane from any module: ```nix { inputs, pkgs, ... }: { environment.systemPackages = [ inputs.kurogane.packages.${pkgs.stdenv.hostPlatform.system}.default ]; } ``` On a stable NixOS release, change `inputs.nixpkgs.follows` to `"nixpkgs-unstable"` when your flake defines that input. Otherwise leave out the `follows` line and use Kurogane's own nixpkgs revision. Kurogane requires Rust 1.96 which a stable release may not provide. Its own nixpkgs revision may also bring newer GPU drivers than the release channel. The Home Manager module adds Kurogane to `home.packages`. `nixos-rebuild switch` activates it when Home Manager is part of the NixOS configuration. Standalone Home Manager uses `home-manager switch`. ### With your Nix profile ```bash nix profile add github:0x48piraj/kurogane # latest nix profile add github:0x48piraj/kurogane/v # a release nix run github:0x48piraj/kurogane -- --help # without installing ``` On `nixos-unstable` add `--override-input nixpkgs nixpkgs`. It builds Kurogane on your registry's nixpkgs which a NixOS system built from a flake points at its own: ```bash nix profile add github:0x48piraj/kurogane --override-input nixpkgs nixpkgs ``` `nix profile upgrade` drops the override and rebuilds on Kurogane's own nixpkgs. Upgrade by installing again: ```bash nix profile remove kurogane nix profile add github:0x48piraj/kurogane --override-input nixpkgs nixpkgs ``` `nix profile` and `nix run` work on other Linux distributions with Nix too. ### GPU drivers on NixOS The drivers come from your system's nixpkgs. An app built on an older nixpkgs can't load them. Chromium then renders without the GPU and so does any GPU code of your own. On `nixos-unstable`, follow your system's `nixpkgs` input to build Kurogane against the same revision. An app keeps the C library it was built with. Run `cargo clean` in projects built before you change nixpkgs. `kurogane clean` removes the showcase. `kurogane doctor` checks OpenGL with the libraries your apps load. The flake brings its own `glxinfo` for that. ## Uninstall ```bash kurogane self uninstall ``` It removes an installer-managed Kurogane installation with its CLI, PATH setup, Chromium runtimes and caches. It shows what it will remove and asks first. `--yes` skips the question. `--keep-data` keeps the runtimes and caches. The Chromium runtimes live in tanso's shared installation. Other projects built on tanso use it too. Uninstalling removes all of it. An installation in another home (`KUROGANE_HOME`) is found from its binary in that home's `bin` folder. Set `KUROGANE_HOME` again to uninstall an installation that used both another home and `--install-dir`. Kurogane keeps: * Application profiles in `kurogane/profiles` in the local data directory (`~/.local/share`, `~/Library/Application Support` or `%LOCALAPPDATA%`). They hold your apps' data such as cookies and storage. Uninstalling reports where they are. * Your shell startup files. Only the installer's own entries go. * An `--install-dir` and anything else installed there. * Rust, Node.js, build tools and other system dependencies. ### Installations without a receipt The receipt defines what Kurogane may remove. A binary the receipt doesn't name stays untouched and the command points you to the manual steps. Remove such a binary the way you installed it: ```bash cargo uninstall kurogane-cli ``` ```bash nix profile remove kurogane ``` Kurogane still removes its runtimes and caches in this case. ### Manual uninstall Remove the installation by hand when `kurogane self uninstall` can't run. On Linux: ```bash rm -r ~/.kurogane rm -r ~/.cache/kurogane ~/.local/share/tanso/cef ``` On macOS remove `~/.kurogane` and these directories: ```text ~/Library/Caches/kurogane ~/Library/Application Support/tanso/cef ``` Then remove the installer's line from your shell startup files. It names your home directory in full: ```bash . "/home/you/.kurogane/env" ``` Fish users remove `~/.config/fish/conf.d/kurogane.fish`. On Windows remove everything under `%LOCALAPPDATA%\kurogane` except `profiles`. Remove the Chromium runtimes in `%LOCALAPPDATA%\tanso\cef` too. Then remove `%LOCALAPPDATA%\kurogane\bin` from your user `Path` in **Edit environment variables for your account**. --- # First app > Create a project, run it, call Rust from the page and bundle it. This page takes a new project from `kurogane new` to a bundled app. You need the [CLI and the build tools](https://kurogane-rs.org/docs/start/install.md) installed. ## Create a project Create a project from the minimal starter: ```bash kurogane new minimal ``` The CLI asks for a project name and a language (TypeScript or JavaScript). Then it generates the project in a directory of that name. `kurogane new` without a starter asks which one to use. The official starters are `minimal`, `react`, `svelte` and `vue`. Each uses a Vite frontend. ## Run it From the new project: ```bash npm --prefix frontend install # install frontend dependencies once npm --prefix frontend run dev # start the dev server kurogane dev # launch the app at the dev server ``` Run the dev server and `kurogane dev` in two terminals. A window opens with "Hello from Kurogane!". `kurogane dev` builds your Rust code in debug mode and runs it. It installs the Chromium runtime first when it is missing. Changes to the frontend reload in the window. Changes to Rust need `kurogane dev` again. ## The Rust side `src/main.rs` holds the whole app: ```rust #![cfg_attr(target_os = "windows", windows_subsystem = "windows")] use kurogane::App; fn main() { #[cfg(debug_assertions)] App::url("http://localhost:5173").run_or_exit(); #[cfg(not(debug_assertions))] App::new("content").run_or_exit(); } ``` A debug build points the window at the dev server with [`App::url`](https://kurogane-rs.org/docs/api/app/app.md#method.url). A release build loads the built frontend from the `content` directory with [`App::new`](https://kurogane-rs.org/docs/api/app/app.md#method.new). A bundle carries that directory inside it. [`App::run_or_exit`](https://kurogane-rs.org/docs/api/app/app.md#method.run_or_exit) starts Chromium and runs until the last window closes. It prints the error and exits when the app can't start. The first line keeps a console window from opening next to your app on Windows. ## Call Rust from the page Register a command in `src/main.rs`: ```rust #![cfg_attr(target_os = "windows", windows_subsystem = "windows")] use kurogane::{App, AppHandle, IpcError}; fn greet(name: String, _: &AppHandle) -> Result { Ok(format!("Hello, {name}!")) } fn main() { #[cfg(debug_assertions)] let app = App::url("http://localhost:5173"); #[cfg(not(debug_assertions))] let app = App::new("content"); app.command("greet", greet).run_or_exit(); } ``` Call it from the page in `frontend/main.ts` or `frontend/main.js`: ```javascript window.kurogane.invoke("greet", "Kurogane").then((reply) => { document.querySelector("#app").textContent = reply; }); ``` Run `kurogane dev` again. The window now shows "Hello, Kurogane!". The page sends `"Kurogane"` as JSON. Kurogane decodes it into the handler's `String` and sends the reply back the same way. Any type serde can read or write works on either side. See [IPC](https://kurogane-rs.org/docs/concepts/ipc.md) for async commands, events and streams. > [!NOTE] > Kurogane doesn't ship TypeScript declarations for `window.kurogane` yet. Your editor reports it as unknown in `main.ts`. Vite runs the page all the same. ## Bundle it Package the app for your platform: ```bash kurogane bundle ``` It runs the frontend build from `kurogane.toml` and builds your Rust code in release mode. Then it packages both with the Chromium runtime. The finished app lands in `dist/`. Bundles are platform-specific. Build each platform's bundle on that platform. ## Already have a frontend? `kurogane init` adds Kurogane to an existing frontend project without touching your files: ```bash kurogane init ``` It asks for the frontend's build output directory and its dev server URL. Pass both to skip the questions: ```bash kurogane init --assets dist --dev-url http://localhost:5173 ``` It writes `Cargo.toml`, `build.rs`, `kurogane.toml` and `src/main.rs`. It refuses to run when any of them already exists. --- # Project layout > What each file in a Kurogane project does and how kurogane.toml ties them together. A Kurogane project is a Rust crate with a frontend inside it. The starters generate this layout: ```text my-app/ ├── Cargo.toml # the app crate ├── build.rs # calls kurogane_build::build() ├── kurogane.toml # the Kurogane manifest ├── src/ │ └── main.rs # the entry point └── frontend/ # a self-contained Vite project ├── index.html ├── main.ts ├── package.json └── vite.config.ts ``` Generated projects aren't git repositories and never join a parent Cargo workspace. ## Cargo.toml The app crate depends on `kurogane` and builds with `kurogane-build`. Both are pinned to the same release: ```toml [dependencies] kurogane = "=" serde_json = "1" [build-dependencies] kurogane-build = "=" [workspace] ``` The pin keeps every build of the project on the same Kurogane. The empty `[workspace]` table keeps the project out of any workspace above it. ## build.rs Every Kurogane app's build script calls `kurogane_build::build()`: ```rust fn main() { kurogane_build::build(); } ``` On Windows it embeds the application manifest CEF's own executables carry. Without it Windows tells your app and the Chromium inside it that they run on Windows 8. It does nothing on other platforms. ## src/main.rs The entry point builds an [`App`](https://kurogane-rs.org/docs/api/app/app.md) and runs it. [First app](https://kurogane-rs.org/docs/start/first-app.md#the-rust-side) walks through the starter's version. Chromium runs this binary again for each of its helper processes. Code before the call that starts the runtime runs once in every process. Keep files, output, sockets and spawned processes out of it. Guard them with [`is_browser_process`](https://kurogane-rs.org/docs/api/app/is_browser_process.md) instead. ## frontend/ The frontend is a normal Vite project. It works on its own as in any Vite app: ```bash cd frontend npm install npm run dev ``` Three directories hold the frontend at different stages: | Directory | Holds | Used by | |---|---|---| | `frontend/` | the frontend source | the dev server during development | | `frontend/dist/` | the built frontend | `kurogane bundle` | | `content/` | the built frontend inside a bundle | your app in release builds | `kurogane bundle` builds the frontend into `frontend/dist/` and copies it into the bundle's `content/`. A release build loads it from there with `App::new("content")`. `frontend/dist/` is a build-time path only. ## kurogane.toml The manifest tells the CLI where the frontend is and how to work with it. The starters write this: ```toml [app] name = "my-app" frontend = "frontend" frontend-dist = "frontend/dist" frontend-install = "npm --prefix frontend install" frontend-run = "npm --prefix frontend run dev" frontend-build = "npm --prefix frontend run build" ``` | Key | What it is | |---|---| | `name` | display name of the app; defaults to the Cargo package name | | `frontend` | frontend source directory | | `frontend-dist` | build output that `kurogane bundle` packages | | `frontend-install` | command that installs the frontend's dependencies | | `frontend-run` | command that starts the dev server | | `frontend-build` | command `kurogane bundle` runs before it builds your Rust code | Paths are relative to the project root. `kurogane new` prints `frontend-install` and `frontend-run` in its **Next steps**. `kurogane dev` expects the dev server to run already. `frontend-build` runs from the project root through the platform shell. That's `sh` on Linux and macOS and `cmd` on Windows. Shell syntax such as `&&` works. The file is optional. Without it or one of its keys the defaults apply. ### Other tables The manifest also describes how your app is packaged: | Table | What it configures | |---|---| | `[app]` | identity (`identifier`, `publisher`, `description`, `copyright`, `icon`) and `sandbox` | | `[[bundle.resources]]` | extra files a bundle carries | | `[linux]` | the AppImage's desktop entry | | `[macos]` | the `.app` bundle's `Info.plist` | | `[macos.privacy]` | what macOS shows when a page asks for the camera or microphone | | `[windows]` | the installer's shortcuts | | `[signing.windows]` and `[signing.macos]` | code signing | `[app]`, `[bundle]`, `[linux]` and `[windows]` ignore keys they don't know so older projects keep parsing. `[macos]`, the `[signing]` tables and each `[[bundle.resources]]` entry refuse an unknown key. The error names the key and its line. ## Projects from kurogane init `kurogane init` adds Kurogane to an existing frontend project. Its npm project stays at the project root: ```text my-vite-app/ ├── Cargo.toml ├── build.rs ├── kurogane.toml ├── src/ │ └── main.rs ├── index.html ├── package.json └── vite.config.ts ``` `init` leaves `frontend` unset. It writes `frontend-dist` to `kurogane.toml` and the dev server URL into `src/main.rs`. --- # Process model > Which processes a Kurogane app runs and which of your code runs in each. A Kurogane app runs as several processes, the way Chromium does. Every one of them is your binary. ## The processes | Process | What it does | Your code in it | |---|---|---| | Browser | creates windows, navigates, dispatches IPC | `main`, command and stream handlers, every `App` callback, browser delegates | | Renderer | runs your page's HTML, CSS and JavaScript in V8 | your page, renderer delegates | | GPU | composites and rasterizes | none | | Utility | runs networking, media and other services | none | The browser process is the one you start. Chromium starts the others as it needs them. It decides how many renderers run. ## One binary Chromium starts each helper process by running your binary again with a `--type=` argument (`--type=renderer`, `--type=gpu-process` and others). A helper runs `main` from the top until the call that starts the runtime. That's [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run), `run_or_exit`, `start`, `build` or `start_embedded`. In a helper that call becomes the helper and never returns. Everything before it runs once in every process: * **Building the `App` is fine.** It's configuration. The helpers need the same configuration for custom schemes and renderer delegates. * **Side effects aren't.** Files, output, sockets and spawned processes happen again in every helper at the same time as in the browser process. A helper that recreates a directory pulls it out from under a handle the browser process holds. Guard one-time work with [`is_browser_process`](https://kurogane-rs.org/docs/api/app/is_browser_process.md): ```rust fn main() { if kurogane::is_browser_process() { prepare_data_dir(); // once, not once per helper } kurogane::App::new("content").run_or_exit(); } ``` Work that needs Chromium running belongs in [`ClientAppBrowserDelegate::on_context_initialized`](https://kurogane-rs.org/docs/api/app/clientappbrowserdelegate.md). Only the browser process calls it. ## The boundary Your page can't reach native APIs. It runs in a renderer and talks to the browser process through [IPC](https://kurogane-rs.org/docs/concepts/ipc.md). The browser process checks every request against the page's origin before your handler runs. The renderer has no say in that check. [Renderer delegates](https://kurogane-rs.org/docs/api/app/clientapprendererdelegate.md) run your Rust code inside the renderer itself. They see V8 contexts, JavaScript exceptions and process messages. ## Panics Kurogane catches a panic in the code it runs to answer a page: * A command handler's panic rejects the page's call. * A stream factory's or stream handler's panic fails the stream. * A panic in [`SchemeHandler::create`](https://kurogane-rs.org/docs/api/app/schemehandler.md) fails the request. A panic in any other code Kurogane calls aborts the process it happens in. In the browser process that ends your app. In a renderer it ends that renderer. That covers renderer delegates too. This holds with Rust's default `panic = "unwind"`. An app built with `panic = "abort"` ends at any panic. ## The sandbox Helper processes run unsandboxed by default. [`SandboxMode::Chromium`](https://kurogane-rs.org/docs/api/app/sandboxmode.md) runs them in the operating system's sandbox. On Windows CEF's sandbox bootstrap then becomes the process you start and loads your app as a library. See [Sandbox](https://kurogane-rs.org/docs/concepts/sandbox.md) for what each platform needs. ## Helpers on macOS On macOS each helper runs from its own bundle in the app's `Contents/Frameworks`. `kurogane bundle` makes them. Each is a copy of your binary with its own bundle identifier: | Bundle | Identifier | |---|---| | `MyApp Helper.app` | `.helper` | | `MyApp Helper (GPU).app` | `.helper.gpu` | | `MyApp Helper (Plugin).app` | `.helper.plugin` | | `MyApp Helper (Renderer).app` | `.helper.renderer` | | `MyApp Helper (Alerts).app` | `.helper.alerts` | The helpers set `LSUIElement`. They stay out of the Dock and the app switcher. They carry neither resources nor the framework and find both through the app that owns them. --- # 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::(); 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. --- # Windows and browsers > What a window and a browser are, who opens them and how your app reaches them. A window is what the operating system shows. A browser is Chromium's page inside it. Kurogane tracks the two apart. Each has its own id and its own lifetime. ## Kinds of browsers [`BrowserType`](https://kurogane-rs.org/docs/api/windows/browsertype.md) says what a browser is: | Kind | What it is | Its parent | |---|---|---| | `Main` | the start window's browser, a `create_window` browser or an embedded browser | none | | `Popup` | a window a page opened | the browser that opened it | | `DevTools` | Chromium's developer tools | the browser it inspects | | `ChromeUi` | a window Chromium opened on its own, such as one restored from an earlier session | none | The app keeps running while any browser is open, a hidden window's browser included. A `ChromeUi` browser is the exception. It closes with the app instead of keeping it running. Closing DevTools or a popup never ends the app. ## Application windows The start window and every window from [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) are application windows. [`WindowOptions`](https://kurogane-rs.org/docs/api/windows/windowoptions.md) describes each one before it exists: ```rust use kurogane::{App, WindowOptions, WindowState}; App::new("content") .window( WindowOptions::new() .name("main") .title("Notes") .size(1100, 720) .min_size(640, 480) .state(WindowState::Maximized), ) .run_or_exit(); ``` * **Title.** A window without one takes its page's `` and follows it. Popups do the same. * **Size.** Sizes and positions are in density-independent pixels and measure the content without the frame. A window without a size opens at 800 by 600. A size larger than the display's work area shrinks to fit. * **Place.** A window without a [`WindowPlacement`](https://kurogane-rs.org/docs/api/windows/windowplacement.md) opens centered on the primary display. A placement no display shows anymore moves onto the nearest one. Wayland lets no app place its windows. There only the size applies. * **State.** [`WindowState`](https://kurogane-rs.org/docs/api/windows/windowstate.md) is `Normal`, `Minimized`, `Maximized`, `Fullscreen` or `Hidden`. * **Name.** A name is your app's handle on a window and is never shown. One open window holds a name at a time. `create_window` with a taken name 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. [`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing) reports each application window's name and placement as it closes. Save the placement and give it back with [`WindowOptions::placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement) to reopen the window where it was. [`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) sets the class Linux desktops group your windows by. [`App::window_icon`](https://kurogane-rs.org/docs/api/app/app.md#method.window_icon) gives every window your app's icon. ## Windows a page opens A page can't give itself a window. Kurogane decides before the window exists: * A page of your app's own origin opens in an application window. * An `http` or `https` link the user clicked opens in the system's default browser. * Anything else is refused. [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window) changes that per request. Chromium's own tabbed browser window never opens. Its new window and new tab shortcuts do nothing. A page can't take its window anywhere either. A window shows your app's own origin, the origins your app loaded there and the origins a hook let in. A navigation anywhere else is answered as a new window is. [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation) changes that per navigation. ## Embedded browsers An app started with [`App::start_embedded`](https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded) has no windows of Kurogane's. [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser) places a `Main` browser inside a window of your own. See [Runtime and event loop](https://kurogane-rs.org/docs/concepts/runtime-and-event-loop.md#embedded-mode). ## Reaching them from Rust Every hook and command gets an [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md). It works from any thread: | Group | Methods | |---|---| | Browsers | `browsers`, `browser_count`, `get_browser_handle`, `browser_for_window`, `browser_opener`, `browser_parent`, `children_of` | | Windows | `windows`, `window_ids`, `window_count`, `find_window_by_name`, `find_window_by_browser` | | Ending | `close_all_browsers`, `close_all_windows`, `shutdown`, `should_shutdown` | [`BrowserId`](https://kurogane-rs.org/docs/api/windows/browserid.md) and [`WindowId`](https://kurogane-rs.org/docs/api/windows/windowid.md) name a browser and a window. [`BrowserMetadata`](https://kurogane-rs.org/docs/api/windows/browsermetadata.md) holds a browser's kind, parent, opener and creation time. A [`BrowserHandle`](https://kurogane-rs.org/docs/api/app/browserhandle.md) drives one browser: | Group | Methods | |---|---| | Navigation | `navigate`, `reload`, `reload_ignore_cache`, `go_back`, `go_forward` | | State | `url`, `is_loading`, `can_go_back`, `can_go_forward` | | Page | `execute_javascript` | | DevTools | `show_devtools`, `close_devtools`, `has_devtools` | | Closing | `close` | | Embedding | `set_bounds`, `notify_move_or_resize_started` | `set_bounds` and `has_devtools` run only on the UI thread. Lookups reflect what is open now. A closed browser leaves its window's link at once even while Chromium is still destroying the window. --- # Lifecycle and shutdown > How a browser closes, when your app ends and how Chromium shuts down. Closing in Chromium is asynchronous. A close request starts a sequence. The browser is gone only once that sequence finishes. Your app ends when its last browser is gone. ## How a browser closes 1. **Something asks it to close.** The user closes its window, the page calls `window.close()` or your app calls [`BrowserHandle::close`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.close). 2. **The page's unload handlers run.** A page's `beforeunload` may ask the user to stay. A forced close skips that question. 3. **Chromium destroys the browser.** Its window goes with it. A browser embedded in your own window takes only its child window. 4. **Kurogane lets go of it.** The browser leaves [`AppHandle::browsers`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.browsers) and [`AppHandle::browser_count`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.browser_count) drops. No close call waits for that sequence. A browser counts as open until the last step. ## When your app ends Your app ends once its last browser has closed, whatever closed it: * The user closes the last window. * Your app calls [`AppHandle::shutdown`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown). * The user presses Ctrl+C in the terminal that started the app. * macOS asks the app to quit. Any open browser keeps the app running, a hidden window's browser and a popup included. A browser Chromium opened on its own (`ChromeUi`) closes with the app instead. [`AppHandle::should_shutdown`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.should_shutdown) turns true once the app has ended. Ctrl+C closes the browsers as closing their windows by hand would. Their unload handlers run. Kurogane installs that handler only when it owns the windows. An embedded app handles Ctrl+C itself. ## Ending on purpose [`AppHandle::shutdown`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown) ends the app from any thread: * No page can cancel it. A page's `beforeunload` leaves without asking. * Nothing opens after it begins. Popups are refused. `create_window` and `create_child_browser` fail with [`RuntimeError::ShuttingDown`](https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.ShuttingDown). * The call doesn't wait for the browsers to close. [`AppHandle::close_all_browsers`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.close_all_browsers) takes a `force` flag. With `force` it ends the app as `shutdown` does. Without it a page's `beforeunload` may keep its browser and the app running. [`BrowserHandle::close`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.close) takes the same flag for one browser. ## Hearing windows close [`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing) hears each application window close, however it closes. The user, the page, your app and Ctrl+C all count. It reports the window's name and its [placement](https://kurogane-rs.org/docs/api/windows/windowplacement.md) to save for the next run. The hook runs on the UI thread before the last window ends the app. Popups, DevTools and embedded browsers aren't reported. Saving a small file there is fine. Anything slow isn't. A hook that panics is logged and the window closes as it would. ## Shutting Chromium down [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) shuts Chromium down by itself once the app has ended. An app that runs its own loop keeps pumping until `should_shutdown` turns true. Then it calls [`AppInstance::shutdown`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown). Dropping the `AppInstance` does the same. Once Chromium is shut down, `AppHandle` and `BrowserHandle` calls that would reach it do nothing. Stop using handles on other threads before you shut down. ## Embedded apps An embedded app owns its windows. Closing a browser never closes your window. Your window decides when to close and your loop decides when to end: * On a close request, ask the browsers to close with `close_all_browsers(true)`. Don't leave the loop yet. * Keep pumping. The close sequence runs inside `pump`. * Once `should_shutdown` turns true, release your window, call `AppInstance::shutdown` and leave the loop. With winit: ```rust fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, event: WindowEvent) { if let WindowEvent::CloseRequested = event { // Ask the browsers to close and keep pumping self.runtime.handle().close_all_browsers(true); } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { // Pump at the deadline Chromium asked for if self.runtime.should_shutdown() { self.window = None; self.runtime.shutdown(); event_loop.exit(); } } ``` > [!WARNING] > Leaving the loop or dropping your window on the close request stops the pump. The close sequence never finishes, the browser count never reaches zero and `should_shutdown` never turns true. End the loop on `should_shutdown` and not on a flag of your own. Your window isn't the only way the browsers end. On macOS Quit closes them all without a close request to your window. --- # app:// and your frontend > Where your app's page comes from and how Kurogane serves it from disk. Your app's first page comes from a URL or from a directory. A directory is served under the `app://` scheme without an HTTP server. ## Two sources | Call | Loads | The page's origin | |---|---|---| | [`App::url`](https://kurogane-rs.org/docs/api/app/app.md#method.url) | any URL, such as a dev server | the URL's own origin | | [`App::new`](https://kurogane-rs.org/docs/api/app/app.md#method.new) | a directory on disk | `app://app` | The page's origin is your app's own origin. Commands, events and streams answer it without an [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit). See [IPC](https://kurogane-rs.org/docs/concepts/ipc.md#who-may-call). The starters load the dev server in debug builds and the bundled frontend in release builds: ```rust use kurogane::App; fn main() { #[cfg(debug_assertions)] App::url("http://localhost:5173").run_or_exit(); #[cfg(not(debug_assertions))] App::new("content").run_or_exit(); } ``` ## The app scheme `App::new("content")` serves the `content` directory at `app://app/`. `app://app` and `app://app/` both load its `index.html`. The scheme behaves like an `https` origin. Pages under it are same-origin with each other and count as a secure context. `fetch` and CORS work as they do on the web. Nothing listens on a port. Kurogane checks the directory before Chromium starts. A missing directory, a file in its place or a missing `index.html` fails startup with a [`RuntimeError`](https://kurogane-rs.org/docs/api/app/runtimeerror.md) that names the path. ### What it serves * A path names a file inside the directory. Its content type follows the file's extension. * Query strings and fragments don't change which file is served. * A path that names no file answers `404`. There is no fallback to `index.html`. Use hash-based routing for client-side routes. * A URL with a host other than `app` answers `400`. ### What it never serves A request resolves inside the directory and nowhere else: * No `..`, absolute path, drive letter or network path leaves it. * A link inside the directory is followed only while it stays inside. * Anything outside answers the same `404` as a missing file. A page can't tell what exists beyond the directory. Kurogane reads files on a worker thread. Reading a large asset doesn't hold up the thread that carries IPC. ## Relative directories in a bundle A packaged app can't rely on its working directory. macOS starts a `.app` from `/`. Windows and Linux start it from wherever it was launched. A relative directory resolves against the bundle's resource root instead: | Platform | Executable | Resource root | |---|---|---| | Linux | `<root>/runtime/<exe>` | `<root>` | | Windows | `<root>/<exe>.exe` | `<root>` | | macOS | `<name>.app/Contents/MacOS/<exe>` | `<name>.app/Contents/Resources` | An absolute directory is never rebased. An unbundled run such as `cargo run` has no resource root. It resolves against the working directory. [`resource_dir`](https://kurogane-rs.org/docs/api/app/resource_dir.md) gives the resource root to reach other files a bundle carries: ```rust let config = match kurogane::resource_dir() { Some(resources) => resources.join("config.toml"), None => std::path::PathBuf::from("config.toml"), }; ``` ## Your own schemes [`App::register_scheme`](https://kurogane-rs.org/docs/api/app/app.md#method.register_scheme) serves a scheme of your own from a [`SchemeHandler`](https://kurogane-rs.org/docs/api/app/schemehandler.md). It answers content that isn't on disk or is computed per request: ```rust use kurogane::tanso::{Browser, Frame, Request, ResourceHandler}; use kurogane::{App, SchemeHandler, resource_handler_from_bytes}; struct Greeting; impl SchemeHandler for Greeting { fn create( &self, _browser: Option<&mut Browser>, _frame: Option<&mut Frame>, _request: Option<&mut Request>, ) -> Option<ResourceHandler> { Some(resource_handler_from_bytes(b"hello".to_vec(), "text/plain", 200)) } } fn main() { App::new("content").register_scheme("greeting", Greeting).run_or_exit(); } ``` * Every request on the scheme reaches the handler whatever its host. * Chromium calls `create` on its IO thread. That thread also carries every IPC message. Decide there what to answer and leave slow work to the returned handler's `open` and `read`. Those run on a worker thread. * A panic in `create` fails the request as returning `None` does. * Your schemes behave like `app` does. They're standard, secure and allow `fetch` and CORS. * A page served from your scheme has that scheme's origin. It reaches commands only once `App::permit` names it. * `app` is reserved. A scheme name starts with a letter and holds letters, digits, `+`, `-` or `.`. An invalid or repeated name is a configuration error. [`resource_handler_from_bytes`](https://kurogane-rs.org/docs/api/app/resource_handler_from_bytes.md) answers with bytes already in memory. Implement `ResourceHandler` yourself for anything larger or slower. --- # IPC > Commands, events and streams between your Rust code and your page. Your page runs in a renderer process. Your Rust code runs in the browser process. IPC is the only path between them. A page reaches only what your app registers on that path. ## Three ways to talk | Kind | Started by | Shape | |---|---|---| | Command | The page | One request and one reply | | Event | Your app | One message to every page subscribed to it | | Stream | The page | Chunks in both directions until one side ends it | JavaScript values travel as JSON. Bytes travel as they are. A frame's messages arrive in the order they were sent. ## Commands A command is a named Rust handler. The page calls it with `window.kurogane.invoke` and gets a promise back. The promise settles with the handler's reply or its error. ```rust use kurogane::{App, AppHandle}; use serde_json::{Value, json}; App::new("dist") .command("ping", |payload: Value, _: &AppHandle| Ok(json!({ "echo": payload }))) .run_or_exit(); ``` ```javascript const reply = await window.kurogane.invoke("ping", { message: "hello" }); ``` Four registrations cover the shapes a command takes: * [`App::command`](https://kurogane-rs.org/docs/api/app/app.md#method.command) answers at once. * [`App::async_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_command) answers later through a [`Responder`](https://kurogane-rs.org/docs/api/ipc/responder.md). Any thread may resolve it. * [`App::binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.binary_command) takes and returns raw bytes without JSON. * [`App::async_binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command) is the async form of a binary command. Every call settles. A responder dropped unanswered rejects its call. A page that cancels its call, navigates away or closes marks the responder cancelled; a cancelled responder sends nothing. ## Events An event is a named message your app sends to every page subscribed to it. [`AppHandle::broadcast_json`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.broadcast_json) sends JSON. [`AppHandle::broadcast`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.broadcast) sends bytes. ```rust app.broadcast_json("progress", &42); ``` A page subscribes with `kurogane.on` and stops with `kurogane.off`: ```javascript const id = window.kurogane.on("progress", (json) => update(JSON.parse(json))); window.kurogane.off(id); ``` ## Streams A stream carries chunks in both directions between one page and one [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md). [`App::stream`](https://kurogane-rs.org/docs/api/app/app.md#method.stream) registers a factory that makes a handler for each stream a page opens. A stream moves through four steps: 1. The handler accepts or refuses the stream before the page holds it. 2. The page's `openStream` resolves. Both sides may send from here on. 3. The handler receives each chunk the page writes. 4. The page ends the stream or either side fails it. The first end or error sent closes the stream. Later sends fail. The page always hears back when it ends a stream. A [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md) sends to the page and works from any thread. ## Who may call Kurogane checks the calling page's origin before any handler runs. By default only your app's own origin passes. That's `app://app` for `App::new` and the start URL's origin for `App::url`. A page of any other origin is refused. That covers popups, iframes and windows that followed a link. * [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) opens a command or stream to the origins you name. * [`App::permit_event`](https://kurogane-rs.org/docs/api/app/app.md#method.permit_event) does the same for event subscriptions. * [`App::deny_unlisted`](https://kurogane-rs.org/docs/api/app/app.md#method.deny_unlisted) closes every name without a rule, your own pages included. A sandboxed frame has an opaque origin and matches no rule. ## Errors A handler fails with an [`IpcError`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md). A string converts into one. The page's promise rejects with an `Error` whose `code` names what failed. Kurogane's own codes are zero or negative. Your app may send positive codes of its own. [`ErrorCode`](https://kurogane-rs.org/docs/api/ipc/errorcode.md) lists every code. ## Threads 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. A `Responder` and a `StreamResponder` work from any thread. ## Size One message from a page has a size cap. A call over it rejects with [`ErrorCode::TooLarge`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.TooLarge) before anything is sent. Stream larger data in chunks. ## Pages that come back A page restored from the back-forward cache finds the calls it left open rejected with [`ErrorCode::Left`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Left). Its open streams fail. It keeps its event subscriptions but misses the events sent while it was away. --- # Capabilities and permissions > What a page may reach and who decides it. A page starts with nothing beyond the web platform. Your app grants each thing it may reach: | What the page reaches | Who decides | |---|---| | Your commands, events and streams | the origin rules of [IPC](https://kurogane-rs.org/docs/concepts/ipc.md#who-may-call) | | Files on disk | the filesystem capability's grants | | Camera, microphone, location and Chromium's other permissions | [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission) | | New windows, navigation, downloads and other requests | a hook for each request | Every grant binds pages only. Your Rust code isn't restricted by any of them. ## The filesystem capability A page reaches files only through `window.kurogane.fs` and only within the grants your app gives its origin. [`App::filesystem`](https://kurogane-rs.org/docs/api/app/app.md#method.filesystem) takes them: ```rust use kurogane::capability::{Filesystem, FsAccess}; use kurogane::{App, Origin}; fn main() { let root = std::env::temp_dir().join("notes"); let mut fs = Filesystem::builder(); let notes = fs.scope("notes", |scope| { scope.allow_directory_recursive(&root); scope.deny_path(root.join("private")); }); fs.grant( Origin::parse("app://app").unwrap(), notes, FsAccess::READ | FsAccess::LIST | FsAccess::WRITE | FsAccess::CREATE, ); App::new("content").filesystem(fs).run_or_exit(); } ``` In the page: ```javascript const bytes = await window.kurogane.fs.readFile("today.md"); const text = new TextDecoder().decode(bytes); await window.kurogane.fs.writeFile("today.md", text + "\n- done"); ``` ### Scopes and grants A scope names the directories a page may reach and the paths it may not. A grant gives an origin a set of capabilities over a scope. Several grants to one origin combine. | [`ScopeBuilder`](https://kurogane-rs.org/docs/api/capabilities/scopebuilder.md) method | What it does | |---|---| | `allow_directory` | allows a directory and its immediate children | | `allow_directory_recursive` | allows a directory and its whole subtree | | `deny_path` | denies a literal path and everything beneath it | | `deny_glob` | denies what a pattern such as `**/.git` matches beneath every allowed root | Deny rules always win over allow rules. Every allowed root must exist when the app starts. ### Operations Each `fs` method needs one [`FsAccess`](https://kurogane-rs.org/docs/api/capabilities/fsaccess.md) capability: | Method | Needs | |---|---| | `readFile(path)` | `READ` | | `writeFile(path, data)` | `WRITE` over an existing file, `CREATE` for a new one | | `exists(path)`, `size(path)` | `METADATA` | | `readDir(path)` | `LIST` | | `createDir(path)` | `CREATE` | | `removeFile(path)`, `removeDir(path)` | `DELETE` | | `renameFile(src, dst)` | `RENAME` over both paths | | `copyFile(src, dst)` | `READ` over `src` and `CREATE` over `dst` | `FsAccess::ALL` holds every capability. Paths are absolute or relative to the origin's one allowed root. ### What holds * Links, junctions and other reparse points are never followed, listed or opened. * The real location of an opened file is checked again before use. * A denied request never reveals whether the path exists. * `readFile` and `writeFile` move whole files up to a cap. [`FilesystemBuilder::max_file_size`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.max_file_size) changes it. `copyFile` stays in the browser process and has no cap. * A file with other names (hard links) is refused unless [`FilesystemBuilder::allow_hard_links`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.allow_hard_links) permits it. A refused call rejects with an `Error` whose `code` says why: | Code | Meaning | |---|---| | `-5` | no grant of the origin carries the capability | | `-6` | the path is outside the granted roots, denied or a link | | `-7` | the path is malformed | | `-8` | the file exceeds the transfer cap | | `0` | the operating system refused; `message` holds its error | [`Filesystem::authorize`](https://kurogane-rs.org/docs/api/capabilities/filesystem.md#method.authorize) gives the exact authority an origin holds. Use it to test your grants without a window. ## Chromium's permissions A page asks before it uses a camera, a microphone, the screen, the location, notifications or another [`Permission`](https://kurogane-rs.org/docs/api/requests/permission.md). Without a hook every request is denied and Chromium's own prompt never shows. `App::on_permission` decides instead: ```rust use kurogane::{App, Origin, Permission, PermissionDecision}; fn main() { let own = Origin::parse("app://app").unwrap(); App::new("content") .on_permission(move |request, _app| { let calls = request .permissions() .iter() .all(|kind| matches!(kind, Permission::Camera | Permission::Microphone)); if request.origin() == &own && calls { PermissionDecision::Allow } else { PermissionDecision::Deny } }) .run_or_exit(); } ``` * A request is granted or refused whole. A page asking for a camera and a microphone together gets both or neither. * `Later` waits for an answer from the request's [`PermissionResponder`](https://kurogane-rs.org/docs/api/requests/permissionresponder.md), from any thread. Ask the user that way. A responder dropped unanswered denies. * `Default` gives Kurogane's answer. That's `Deny`. * Requests from DevTools never reach the hook and are denied. > [!WARNING] > Allowing `Permission::ScreenVideo` lets the page record the whole screen with no picker. ### What Chromium remembers Chromium remembers its answer to an `http` or `https` site in the profile. The site's later requests get that answer without reaching the hook. [`AppHandle::forget_permissions`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.forget_permissions) makes it ask again after your policy changed. A camera, a microphone and the screen are never remembered. Nothing is remembered for your app's own pages either. A grant that has to outlast the request doesn't hold there. Such a page is told yes for notifications and the location but can't show a notification or read the location. ## Other requests Kurogane asks your app before Chromium acts on a page's other requests. Each hook takes a typed request and answers with a decision whose `Default` leaves the choice to Kurogane: | Hook | Request | |---|---| | [`on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window) | a page opens a window | | [`on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation) | a page leaves for another origin | | [`on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download) | a page starts a download | | [`on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog) | a page opens a file chooser | | [`on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu) | the user right-clicks | | [`on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key) | the user presses a key | | [`on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) | Chromium runs one of its commands | | [`on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter) | something is dragged into an embedded browser | Every hook runs on the UI thread and must not block. A hook that panics gets the safe answer. The [Requests and decisions](https://kurogane-rs.org/docs/api/requests.md) reference covers each request and its decisions. --- # Sandbox > Run Chromium's helper processes in the operating system's sandbox. Chromium's sandbox confines its helper processes. A renderer then runs your page with the few rights the operating system's sandbox leaves it, instead of the user's. Kurogane runs the helpers unsandboxed by default. [`App::sandbox_mode`](https://kurogane-rs.org/docs/api/app/app.md#method.sandbox_mode) turns the sandbox on: ```rust use kurogane::{App, SandboxMode}; fn main() { App::new("content") .sandbox_mode(SandboxMode::Chromium) .run_or_exit(); } ``` ## Choosing a mode | [`SandboxMode`](https://kurogane-rs.org/docs/api/app/sandboxmode.md) | Use it for | |---|---| | `Chromium` | production builds and untrusted content | | `Disabled` (default) | development without a usable sandbox, containers, CI and embedded targets | Both modes apply to apps that own their windows and to embedded apps. ## What each platform needs Each platform has a condition the sandbox needs. Kurogane checks it before Chromium starts. It refuses to start unsandboxed and says what is missing instead. | Platform | Condition | |---|---| | Linux | unprivileged user namespaces or a usable setuid `chrome-sandbox` | | macOS | the app runs from a `.app` bundle | | Windows | CEF's sandbox bootstrap starts the app | The process model stays the same under the sandbox. Helpers still run your binary, `is_browser_process` still guards one-time work and everything before `App::run` behaves as before. ## Linux Chromium uses unprivileged user namespaces where the kernel allows them. Most distributions do. Ubuntu 24.04 restricts them through AppArmor. Lift the restriction: ```bash sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 ``` Without user namespaces Chromium uses the setuid `chrome-sandbox` helper that ships with every Linux runtime. Make it setuid root: ```bash sudo chown root:root ~/.local/share/tanso/cef/<version>/cef_linux_x86_64/chrome-sandbox sudo chmod 4755 ~/.local/share/tanso/cef/<version>/cef_linux_x86_64/chrome-sandbox ``` When neither is usable the app prints these instructions and doesn't start. AppImages and Nix store installations can't use the setuid helper. They need user namespaces. ## macOS The app must run from a `.app` bundle. Build one with `kurogane bundle --format app`. An unbundled run such as `kurogane dev` refuses to start in `Chromium` mode. No entitlements need changing. ## Windows CEF's Windows sandbox starts your app from CEF's bootstrap executable. The bootstrap loads your app as a library and brokers the sandboxed helpers. That takes two changes to the crate and one line in `kurogane.toml`. Give the crate a library target and keep the binary. Unsandboxed runs and `cargo run` still use the binary: ```toml [lib] name = "myapp_lib" crate-type = ["cdylib", "rlib"] [[bin]] name = "myapp" ``` The library takes a name of its own. Cargo warns when a library and a binary of the same name write the same `.pdb`. The bootstrap and the bundle still take the binary's name. Move the app into `src/lib.rs` and declare the entry points the bootstrap calls with [`sandbox_entry!`](https://kurogane-rs.org/docs/api/app/sandbox_entry.md): ```rust // src/lib.rs pub fn run() { kurogane::App::new("content") .sandbox_mode(kurogane::SandboxMode::Chromium) .run_or_exit(); } kurogane::sandbox_entry!(run); ``` ```rust // src/main.rs fn main() { myapp_lib::run() } ``` Off Windows `sandbox_entry!` only checks the signature. The same source builds on every platform. Tell the CLI the app is sandboxed: ```toml [app] sandbox = true ``` `kurogane run` and `kurogane dev` then build the library and stage it in `target/<profile>/sandbox/` with the Chromium runtime and CEF's console bootstrap. They start the app from there. `kurogane bundle` packages it with the windowed bootstrap. No console appears. The `sandbox` key does nothing on Linux and macOS. One `kurogane.toml` serves every platform. An app that asks for `Chromium` mode without the bootstrap refuses to start and says why. It refuses as well when the bootstrap's sandbox ABI differs from the one `libcef.dll` was built with. ### The GPU on Windows Under the sandbox the GPU runs in a process of its own at low integrity. An out-of-process GPU restarts after a lost device and falls back to software rendering after repeated losses. Without the sandbox Kurogane runs GPU work in the browser process. It waits there for a lost device to recover. That GPU work runs with the user's full rights. --- # Load a dev server or bundled assets > Point your app at a dev server during development and at its built frontend in release builds. Your app loads its first page from a URL or from a directory. See [app:// and your frontend](https://kurogane-rs.org/docs/concepts/app-protocol.md) for how each is served. ## Load a dev server Point the app at the dev server with [`App::url`](https://kurogane-rs.org/docs/api/app/app.md#method.url): ```rust use kurogane::App; fn main() { App::url("http://localhost:5173").run_or_exit(); } ``` It works with Vite, React, Vue, Svelte and any HTTP server. Start the dev server before the app. `kurogane dev` doesn't start it for you. Changes to the frontend reload in the window as they do in a browser. ## Load bundled assets Load a built frontend from a directory with [`App::new`](https://kurogane-rs.org/docs/api/app/app.md#method.new): ```rust use kurogane::App; fn main() { App::new("content").run_or_exit(); } ``` The directory needs an `index.html`. A bundle carries your built frontend in `content`. A relative directory resolves inside the bundle wherever the app was started from. ## Switch between them Pick the source per build profile. The starters do this: ```rust use kurogane::App; fn main() { #[cfg(debug_assertions)] App::url("http://localhost:5173").run_or_exit(); #[cfg(not(debug_assertions))] App::new("content").run_or_exit(); } ``` Any condition works. An environment variable, a command-line flag or a Cargo feature can choose the source just as well: ```rust use kurogane::App; fn main() { let app = match std::env::var("APP_DEV_URL") { Ok(url) => App::url(url), Err(_) => App::new("content"), }; app.run_or_exit(); } ``` ## Use another dev server port The URL in `src/main.rs` and the dev server's port must match. Change both together. With Vite set the port in `frontend/vite.config.ts`: ```ts import { defineConfig } from "vite"; export default defineConfig({ server: { port: 3000, strictPort: true }, }); ``` Then point the app at it: ```rust App::url("http://localhost:3000") ``` `strictPort` makes Vite fail instead of moving to another port when this one is taken. Your app would otherwise load nothing. ## Serve a directory you build yourself `kurogane bundle` copies `frontend-dist` from `kurogane.toml` into the bundle's `content`. Point `frontend-dist` at your build output and `frontend-build` at the command that makes it: ```toml [app] frontend-dist = "web/build" frontend-build = "npm --prefix web run build" ``` Leave `frontend-build` out when you build the frontend yourself before bundling. ## Run without a frontend An app needs no HTML frontend of its own. `App::url` can open any site. An app that serves its own pages can do so from [its own scheme](https://kurogane-rs.org/docs/concepts/app-protocol.md#your-own-schemes). --- # 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. --- # Control links, popups and navigation > Decide which windows a page may open and where it may take its window. A page can't give itself a window or take its window anywhere it likes. Kurogane decides first and asks your app's hooks where you give them. ## What happens by default A page asks for a window with `window.open`, a `target="_blank"` link, a form that targets a new window or a link clicked with Ctrl (Cmd on macOS), the middle button or Shift: * A page of your app's own origin opens in an application window. A window the page fills in itself (`about:blank`) does too. * An `http` or `https` link the user clicked opens in the system's default browser. * Anything else is refused. That includes a script opening a website on its own, `mailto:`, `file:` and custom schemes. A page can also take its own window somewhere else with a link, `location = …`, a form or a redirect. A window shows only the origins let into it: * Your app's own origin * Every origin your app loaded there itself (the start URL, `create_window` and `BrowserHandle::navigate`) with the redirects they lead to * The origin `on_new_window` opened a popup to * Every origin `on_navigation` let in before Within those a page navigates freely. A navigation anywhere else is answered as a new window is. A clicked `http` or `https` link opens in the system browser. Anything else is refused and the window stays on its page. ## Keep a sign-in popup inside the app A sign-in provider often reports back to the page that opened it. It has to run inside your app. [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window) lets its origin open in an application window: ```rust use kurogane::{App, NewWindowDecision, Origin}; fn main() { let sign_in = Origin::parse("https://accounts.example.com").unwrap(); App::new("content") .on_new_window(move |request, _app| { if request.origin() == &sign_in { NewWindowDecision::Allow } else { NewWindowDecision::Default } }) .run_or_exit(); } ``` [`NewWindowDecision`](https://kurogane-rs.org/docs/api/requests/newwindowdecision.md) has four answers: | Decision | What happens | |---|---| | `Allow` | opens the page in an application window whatever its origin | | `Deny` | opens no window | | `OpenExternal` | opens the URL in the system browser; only a clicked `http` or `https` link goes there | | `Default` | Kurogane's policy decides | An allowed page reaches only the commands and events that [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) grants its origin. ## Let a provider into the window A page may send the user to a sign-in provider in the same window. [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation) lets its origin in: ```rust use kurogane::{App, NavigationDecision, Origin}; fn main() { let sign_in = Origin::parse("https://accounts.example.com").unwrap(); App::url("https://app.example.com") .on_navigation(move |navigation, _app| { if navigation.origin() == &sign_in { NavigationDecision::Allow } else { NavigationDecision::Default } }) .run_or_exit(); } ``` `Allow` loads the page and lets its origin into that window from then on. The provider sends the user back to `app.example.com`. The window may always show it. `Deny`, `OpenExternal` and `Default` answer as they do for new windows. Your app's own loads, back and forward navigation and frames inside a page never reach the hook. Frames aren't guarded. `App::permit` decides what a frame of another origin reaches. ## Refuse popups a script opens [`NewWindowRequest::kind`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.kind) says how the page asked. [`NewWindowRequest::user_gesture`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.user_gesture) says whether the user clicked or a script asked on its own: ```rust use kurogane::{App, NewWindowDecision, NewWindowKind}; fn main() { App::new("content") .on_new_window(|request, _app| { if request.kind() == NewWindowKind::Popup && !request.user_gesture() { NewWindowDecision::Deny } else { NewWindowDecision::Default } }) .run_or_exit(); } ``` | [`NewWindowKind`](https://kurogane-rs.org/docs/api/requests/newwindowkind.md) | The page asked with | |---|---| | `Tab` | a `target="_blank"` link, `window.open` without features or Ctrl or Cmd | | `BackgroundTab` | the middle button or Ctrl and Shift | | `Popup` | `window.open` with a size or position | | `Window` | Shift | | `PictureInPicture` | `documentPictureInPicture` | Kurogane opens every kind as an application window. The kind lets a policy treat each differently. ## Compare origins, not URLs Compare [`Origin`](https://kurogane-rs.org/docs/api/ipc/origin.md) values and never URL strings. `https://accounts.example.com.evil.net` starts with `https://accounts.example.com`. A request gives every origin it involves: | Request | Methods | |---|---| | [`NewWindowRequest`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md) | `url`, `origin`, `opener_origin`, `kind`, `user_gesture` | | [`NavigationRequest`](https://kurogane-rs.org/docs/api/requests/navigationrequest.md) | `url`, `origin`, `from_origin`, `user_gesture`, `is_redirect` | A window the page fills in itself has the page's origin. A `blob:` URL has the origin of the page that made it. ## Test a policy Write the policy as a function and make requests the way a page sends them: ```rust use kurogane::{NewWindowDecision, NewWindowKind, NewWindowRequest}; fn policy(request: &NewWindowRequest) -> NewWindowDecision { if request.kind() == NewWindowKind::Popup && !request.user_gesture() { NewWindowDecision::Deny } else { NewWindowDecision::Default } } #[test] fn scripted_popups_are_refused() { let scripted = NewWindowRequest::new("https://ads.example/", "app://app/index.html") .with_kind(NewWindowKind::Popup); assert_eq!(policy(&scripted), NewWindowDecision::Deny); } ``` Hand the function to the hook with `.on_new_window(|request, _app| policy(request))`. ## Rules for the hooks * Both hooks run on the UI thread before the window or the navigation starts. They must not block. * A hook that panics refuses the window or the navigation. * A later call replaces an earlier hook. * Chromium's own tabbed browser window never opens. Its new window and new tab shortcuts do nothing. --- # Keyboard shortcuts and Chromium commands > Decide which keys your app takes, which the page gets and which of Chromium's commands run. A Kurogane window runs only Chromium's page-local commands. Those are reload, find, print, zoom, editing, fullscreen, closing the window and DevTools. Kurogane refuses the rest, such as new windows, tabs, history and bookmarks. Two hooks narrow that further. ## The shortcuts Kurogane's shortcuts are the same on every OS. macOS takes Cmd for Ctrl. | Command | Keys | macOS | Order | |---|---|---|---| | Close the window | Ctrl+W, Ctrl+Shift+W | Cmd+W, Cmd+Shift+W | before the page | | Quit | | Cmd+Q | before the page | | Reload | Ctrl+R, F5 | Cmd+R | page first | | Find | Ctrl+F, Ctrl+G, F3 | Cmd+F, Cmd+G | page first | | Print | Ctrl+P | Cmd+P | page first | | Zoom | Ctrl+=, Ctrl+-, Ctrl+0 | Cmd+=, Cmd+-, Cmd+0 | page first | | Back, forward | Alt+Left, Alt+Right | Cmd+[, Cmd+] | page first | | Fullscreen | F11 | Cmd+Ctrl+F | page first | | DevTools | Ctrl+Shift+I, F12 | Cmd+Option+I | page first | Closing and quitting run before the page sees the key. No page keeps them. Every other shortcut reaches the page first. It runs only when the page doesn't call `preventDefault()`. Chromium's keys for what Kurogane refuses (Ctrl+T, Ctrl+N, Ctrl+Shift+T and Ctrl+Tab) are ordinary keys the page gets. > [!NOTE] > On macOS Chromium still takes its own next-tab keys (Cmd+Option+Left and Right, Cmd+Shift+[ and ], Ctrl+Page Up and Page Down) before your app and the page see them. A fullscreen window is the exception. ## Add a shortcut of your own [`App::on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key) sees each key press before a shortcut and the page do. `KeyDecision::Consume` takes the key for your app: ```rust use kurogane::{App, Key, KeyDecision}; fn main() { App::new("content") .on_key(|key, app| { // Ctrl+K (Cmd+K on macOS) opens the page's command palette if key.modifiers().primary() && key.key() == Key::Char('K') { app.broadcast_json("palette", &true); KeyDecision::Consume } else { KeyDecision::Default } }) .run_or_exit(); } ``` The page listens for the event with `kurogane.on("palette", ...)`. A consumed key goes nowhere else. No shortcut runs and the page sees none of the key, its character or its release. [`KeyPress`](https://kurogane-rs.org/docs/api/requests/keypress.md) describes the press: * `key()` names a key by its place. Shift+W is still `Key::Char('W')`. * `modifiers().primary()` is Ctrl on Windows and Linux and Cmd on macOS. * `command()` names the command the key runs as one of Kurogane's shortcuts on any OS. * `in_editable_field()` says whether the user is typing into a field. Check it before taking keys the user may be typing. * `repeat()` says whether the key is held down and repeating. * `browser()` names the browser the key went to. The hook sees presses and their repeats. It never sees releases. ## Turn off a shortcut Consume the key of the command you want gone: ```rust use kurogane::{App, ChromeCommand, KeyDecision}; fn main() { App::new("content") .on_key(|key, _app| { // Ctrl+W (Cmd+W on macOS) doesn't close this window if key.command() == Some(ChromeCommand::Close) { KeyDecision::Consume } else { KeyDecision::Default } }) .run_or_exit(); } ``` The window's close button and closing it from your app still work. ## Let the page handle Ctrl+W `KeyDecision::PageFirst` gives the page closing and quitting first too. The shortcut runs only when the page doesn't call `preventDefault()`: ```rust use kurogane::{App, ChromeCommand, KeyDecision}; fn main() { App::new("content") .on_key(|key, _app| { if key.command() == Some(ChromeCommand::Close) { KeyDecision::PageFirst } else { KeyDecision::Default } }) .run_or_exit(); } ``` `PageFirst` is for shortcuts: * Chromium drops the character of a shortcut the page left alone. A typing key answered `PageFirst` types nothing unless the page handles its keydown. Answer it for chords such as Ctrl+W and not for every key. AltGr arrives as Ctrl+Alt on Windows. * It hands the shortcut to the page. A page that prevents Ctrl+W keeps its window open. A page that hangs holds the key. * Answer it only for windows that show your own pages. `key.browser()` says which window the key went to. * A browser embedded in your own window runs no shortcuts. There `PageFirst` changes nothing but the dropped character. ## Refuse a command [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) is asked about each command a window would run from a shortcut or the context menu. [`CommandDecision::Refuse`](https://kurogane-rs.org/docs/api/requests/commanddecision.md) stops it: ```rust use kurogane::{App, ChromeCommand, CommandDecision}; fn main() { App::new("content") .on_chrome_command(|request, _app| match request.command() { // No DevTools and no reload in release builds ChromeCommand::DevTools | ChromeCommand::Reload if !cfg!(debug_assertions) => { CommandDecision::Refuse } _ => CommandDecision::Default, }) .run_or_exit(); } ``` [`ChromeCommand`](https://kurogane-rs.org/docs/api/requests/chromecommand.md) groups Chromium's commands by what the user asked for. Refusing `DevTools` refuses Ctrl+Shift+I, F12 and the context menu's **Inspect** alike. Refusing `Reload` refuses every kind of reload. The hook can only refuse. It's never asked about a command Kurogane refuses and can't allow one. A key `on_key` consumed never becomes a command. Neither does one the page prevented after `PageFirst`. ## Rules for the hooks * Both hooks run on the UI thread. `on_key` runs for every key press. Keep them quick. * A panicking `on_key` lets the key through. A panicking `on_chrome_command` refuses the command. * DevTools' own windows reach neither hook. * A browser embedded in your own window reaches `on_key`. Chromium runs no commands there and `on_chrome_command` is never asked. * A later call replaces an earlier hook. --- # Downloads > Decide where the files a page downloads are saved. A page downloads a file when a server answers a link with an attachment, a link has a `download` attribute or the page exports a `blob:` or `data:` URL. ## What happens by default Kurogane asks the user where to save each file with the system's **Save As** dialog. The dialog fills in the suggested name. When the user cancels nothing is saved. No page writes to the disk unless the user picked the place. A window shows one dialog at a time. A page that downloads several files asks about each in turn. Chromium's own behavior of saving silently into the Downloads folder is never used. ## Save your app's exports without asking [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download) decides per download. Save your own pages' exports into a folder of your app's and refuse everything else: ```rust use kurogane::{App, DownloadDecision, Origin}; fn main() { let exports = std::env::temp_dir().join("my-app-exports"); let own = Origin::parse("app://app").unwrap(); App::new("content") .on_download(move |download, _app| { if download.origin() == &own { DownloadDecision::SaveTo(exports.join(download.suggested_name())) } else { DownloadDecision::Deny } }) .run_or_exit(); } ``` | [`DownloadDecision`](https://kurogane-rs.org/docs/api/requests/downloaddecision.md) | What happens | |---|---| | `SaveTo(path)` | saves at that absolute path without asking and replaces a file already there | | `Prompt` | asks the user with the Save As dialog | | `Deny` | saves nothing | | `Default` | Kurogane's policy, which asks the user | `SaveTo` creates the folder when it's missing. Nothing is saved when that fails or the path is relative. ## Know where a download comes from [`DownloadRequest`](https://kurogane-rs.org/docs/api/requests/downloadrequest.md) describes the download: * `origin()` is the origin of the page the download comes from, not of the file. A page of your own may export a `blob:` or link to a file anywhere. * `url()` is the URL the file comes from. * `mime_type()` is the file's MIME type. It's empty when unknown. * `suggested_name()` is a file name only. Chromium has already removed any folder a page tried to put in it. Joining it onto a folder of your own stays in that folder. * `browser()` names the browser the download comes from. ## Download one of your own files A `download` link to one of your app's own files (`<a href="report.pdf" download>`) does nothing. Chromium doesn't download from `app://` that way. Fetch the file and download it as a `blob:`. That reaches the hook like any other download: ```javascript const response = await fetch("report.pdf"); const link = document.createElement("a"); link.href = URL.createObjectURL(await response.blob()); link.download = "report.pdf"; link.click(); ``` ## Save from Rust instead A command can write the file itself. Grants and download rules bind pages only. Send the data from the page and write it where your app decides: ```rust use kurogane::{App, AppHandle, IpcError}; fn main() { App::new("content") .binary_command("export", |data: &[u8], _: &AppHandle| { let path = std::env::temp_dir().join("export.bin"); std::fs::write(&path, data).map_err(|e| IpcError::from(e.to_string()))?; Ok(Vec::new()) }) .run_or_exit(); } ``` ```javascript await window.kurogane.invoke("export", new TextEncoder().encode("report")); ``` ## Several files at once A page may download several files without a click for each. Every one of them still reaches `on_download` or the Save As dialog. Chromium's own prompt for multiple downloads never shows. ## Rules for the hook * It runs on the UI thread before the download starts and must not block. * A hook that panics refuses the download. * Downloads from DevTools never reach it and always ask the user. * A later call replaces an earlier hook. --- # Permissions > Allow a camera, a microphone, the location and Chromium's other permissions, or ask the user first. A page asks before it uses a camera, a microphone, the screen, the location, notifications or another [`Permission`](https://kurogane-rs.org/docs/api/requests/permission.md). Without a hook every request is denied. See [Capabilities and permissions](https://kurogane-rs.org/docs/concepts/capabilities-and-permissions.md#chromiums-permissions) for the rules behind each answer. ## Allow a camera and a microphone for your own pages [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission) answers each request: ```rust use kurogane::{App, Origin, Permission, PermissionDecision}; fn main() { let own = Origin::parse("app://app").unwrap(); App::new("content") .on_permission(move |request, _app| { let calls = request .permissions() .iter() .all(|kind| matches!(kind, Permission::Camera | Permission::Microphone)); if request.origin() == &own && calls { PermissionDecision::Allow } else { PermissionDecision::Deny } }) .run_or_exit(); } ``` A request is granted or refused whole. Check every permission it asks for, as `all` does here. A page asking for a camera and a microphone together gets both or neither. `request.origin()` is the origin that asks. It's the page's, or a frame's inside the page when the frame asks. ## Ask the user first Return `PermissionDecision::Later` and keep the request's [`PermissionResponder`](https://kurogane-rs.org/docs/api/requests/permissionresponder.md). The page waits until the responder answers from any thread: ```rust use kurogane::{App, PermissionDecision}; fn ask_the_user(question: &str) -> bool { // Show your own dialog here println!("{question}"); true } fn main() { App::new("content") .on_permission(|request, _app| { let question = format!("Allow {:?} for {}?", request.permissions(), request.origin()); let responder = request.responder(); std::thread::spawn(move || { if ask_the_user(&question) { responder.allow(); } else { responder.deny(); } }); PermissionDecision::Later }) .run_or_exit(); } ``` * A request is answered once. The first answer counts. * Dropping the responder without an answer denies the request. * An answer that comes after the page went away grants nothing. * `Later` without a responder kept denies at once. The hook itself runs on the UI thread and must not wait for the user. Ask from another thread as here. ## Take a permission back Chromium remembers its answers to `http` and `https` sites in the profile. A site's later requests get the remembered answer without reaching the hook. [`AppHandle::forget_permissions`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.forget_permissions) forgets them for one origin: ```rust use kurogane::{App, AppHandle, IpcError, Origin}; fn main() { App::new("content") .command("revoke", |origin: String, app: &AppHandle| { let origin = Origin::parse(&origin).map_err(|e| IpcError::from(e.to_string()))?; app.forget_permissions(&origin); Ok(()) }) .run_or_exit(); } ``` The site's next request reaches `on_permission` again. Forgetting also takes back a grant the site holds now. Its notifications stop. A camera, a microphone and the screen are never remembered. Nothing is remembered for your app's own pages either. ## Rules for the hook * `Default` gives Kurogane's answer. That's `Deny`. * The hook runs on the UI thread and must not block. A hook that panics denies. * Requests from DevTools never reach it and are denied. * Your own pages are told yes for notifications and the location but can't show a notification or read the location. Those grants have to outlast the request. They don't for your app's own origin. > [!WARNING] > Allowing `Permission::ScreenVideo` lets the page record the whole screen with no picker. --- # The context menu > Edit the menu a right-click opens, add items of your own or let the page draw its own. A right-click opens Kurogane's menu and never Chromium's. That holds in a window and in an embedded browser alike. ## What the menu shows * In a text field the editing items: Undo, Redo, Cut, Copy, Paste, Paste as plain text and Select all. Chromium's spelling suggestions come first on a misspelled word. * Copy on a selection. * Nothing elsewhere. An empty menu doesn't show. * **Inspect** last in a debug build. ## Add items of your own [`App::on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu) edits the menu as it opens. [`App::on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command) runs when the user chooses one of your items: ```rust use kurogane::{App, MenuItem}; fn main() { App::new("content") .on_context_menu(|menu, _app| { if menu.target().link_url().is_some() { menu.push(MenuItem::separator()); menu.push(MenuItem::new("copy-link", "Copy link address")); } }) .on_context_menu_command(|command, app| { if command.id() == "copy-link" && let Some(url) = command.target().link_url() { app.broadcast_json("copy-link", &url); } }) .run_or_exit(); } ``` The page copies the address when the event arrives: ```javascript window.kurogane.on("copy-link", (json) => navigator.clipboard.writeText(JSON.parse(json))); ``` `on_context_menu_command` runs only for your items. It gets the same target the menu opened on. An item chosen after its page went away runs nothing. That happens when the page navigated while the menu stayed open. ## Remove an item [`ContextMenu::remove`](https://kurogane-rs.org/docs/api/requests/contextmenu.md#method.remove) takes one of Kurogane's items out, from submenus too: ```rust use kurogane::{App, StandardItem}; fn main() { App::new("content") .on_context_menu(|menu, _app| { if menu.target().is_editable() { // No pasting formatted text into this app's fields menu.remove(StandardItem::Paste); } }) .run_or_exit(); } ``` `menu.clear()` takes every item out. `menu.items_mut()` gives the items as a `Vec` to reorder or filter. A standard item whose command [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) refuses is left out of the menu. It's asked about again when chosen. Refusing `DevTools` there removes **Inspect**. ## Disabled items, check marks and submenus [`AppItem`](https://kurogane-rs.org/docs/api/requests/appitem.md) adds an enabled state and a check mark. [`MenuItem::submenu`](https://kurogane-rs.org/docs/api/requests/menuitem.md#method.submenu) groups items under a label: ```rust use std::sync::atomic::{AtomicBool, Ordering}; use kurogane::{App, AppItem, MenuItem}; static WRAP: AtomicBool = AtomicBool::new(true); fn main() { App::new("content") .on_context_menu(|menu, _app| { menu.push(MenuItem::submenu( "View", [ MenuItem::App(AppItem::new("wrap", "Word wrap").checked(WRAP.load(Ordering::Relaxed))), MenuItem::App(AppItem::new("zoom", "Zoom").enabled(false)), ], )); }) .on_context_menu_command(|command, _app| { if command.id() == "wrap" { WRAP.fetch_xor(true, Ordering::Relaxed); } }) .run_or_exit(); } ``` Choosing a check item doesn't change its mark. Your app sets the mark each time the menu opens. Separators at an edge or next to another aren't shown. Neither are submenus left empty. In a window's menu an `&` in a label marks the letter that chooses the item from the keyboard. `&&` shows an `&`. An embedded browser's menu takes every `&` out. There a typed letter chooses the item whose label begins with it. ## Know what was right-clicked [`ContextMenuTarget`](https://kurogane-rs.org/docs/api/requests/contextmenutarget.md) describes it: | Method | Gives | |---|---| | `origin()` | the origin of the document right-clicked; opaque for a sandboxed document | | `page_url()` | the URL of the page the browser shows | | `frame_url()` | the URL of the document right-clicked, the page's or a frame's | | `link_url()` | the link's URL | | `media()`, `media_url()` | the kind of media ([`MediaKind`](https://kurogane-rs.org/docs/api/requests/mediakind.md)) and its URL | | `selection()` | the selected text | | `is_editable()` | whether it was in a text field or other editable content | | `misspelled_word()` | the misspelled word | | `position()` | where the right-click was in the browser's view | | `browser()` | the browser right-clicked | ## Let the page draw its own menu A page that draws its own menu calls `preventDefault()` on its `contextmenu` event. Kurogane's menu doesn't open then: ```javascript document.addEventListener("contextmenu", (event) => { event.preventDefault(); showMyMenu(event.clientX, event.clientY); }); ``` ## Rules for the hooks * Both hooks run on the UI thread and must not block. * A panicking `on_context_menu` leaves Kurogane's menu as it was. A panicking `on_context_menu_command` is logged. * DevTools' menus are never asked about. * A later call replaces an earlier hook. --- # File choosers > Answer the file choosers a page opens with the system's dialog, files of your choosing or a picker of your own. A page opens a file chooser with `<input type="file">` or the File System Access pickers (`showOpenFilePicker`, `showSaveFilePicker` and `showDirectoryPicker`). Without a hook the system's chooser shows. [`App::on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog) can answer instead. ## Give the page files of your choosing ```rust use kurogane::{App, FileDialogDecision, FileDialogKind}; fn main() { let inbox = std::env::temp_dir().join("inbox.txt"); App::new("content") .on_file_dialog(move |request, _app| match request.kind() { // The page's import always reads the inbox FileDialogKind::Open => FileDialogDecision::Files(vec![inbox.clone()]), _ => FileDialogDecision::Default, }) .run_or_exit(); } ``` The page reads the files as if the user chose them. An `Open` or `Save` dialog takes the first file. An `OpenFolder` dialog takes a folder. An empty list cancels. | [`FileDialogDecision`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md) | What happens | |---|---| | `Default` | the system's file chooser shows | | `Files(paths)` | the page gets these files without a dialog | | `Cancel` | no dialog; the page is told the user cancelled | | `Later` | the request's responder answers later | ## Allow choosers on your own pages only A page of another origin in your app may open a chooser too. Cancel those: ```rust use kurogane::{App, FileDialogDecision, Origin}; fn main() { let own = Origin::parse("app://app").unwrap(); App::new("content") .on_file_dialog(move |request, _app| { if request.origin() == &own { FileDialogDecision::Default } else { FileDialogDecision::Cancel } }) .run_or_exit(); } ``` `request.origin()` is the origin of the frame that has the focus, the one whose control the user activated. ## Show a picker of your own Return `FileDialogDecision::Later` and keep the request's [`FileDialogResponder`](https://kurogane-rs.org/docs/api/requests/filedialogresponder.md). The page waits until the responder selects or cancels from any thread: ```rust use std::path::PathBuf; use kurogane::{App, FileDialogDecision}; fn pick_files() -> Option<Vec<PathBuf>> { // Show your own picker here Some(vec![std::env::temp_dir().join("notes.txt")]) } fn main() { App::new("content") .on_file_dialog(|request, _app| { let responder = request.responder(); std::thread::spawn(move || match pick_files() { Some(files) => responder.select(files), None => responder.cancel(), }); FileDialogDecision::Later }) .run_or_exit(); } ``` * A request is answered once. The first answer counts. * Dropping the responder without an answer cancels the request. * An answer that comes after the page went away gives it nothing. * `Later` without a responder kept cancels at once. ## Know what the page asked for [`FileDialogRequest`](https://kurogane-rs.org/docs/api/requests/filedialogrequest.md) describes the chooser: | Method | Gives | |---|---| | `kind()` | `Open`, `OpenMultiple`, `OpenFolder` or `Save` ([`FileDialogKind`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md)) | | `title()` | the dialog's title as the page gives it; empty for the system's own | | `default_path()` | the file name or path the dialog would start at; the suggested name for a save picker | | `accept()` | what the page accepts as it wrote it, such as `image/*` or `.png`; empty for any file | | `origin()` | the origin of the page that opens the dialog | | `browser()` | the browser of the page | ## Read files without a chooser A page that needs files your app already knows doesn't need a chooser at all. The [filesystem capability](https://kurogane-rs.org/docs/concepts/capabilities-and-permissions.md#the-filesystem-capability) grants it a scope to read and write through `window.kurogane.fs`. ## Rules for the hook * It runs on the UI thread and must not block. * A hook that panics cancels the dialog. * Kurogane's own Save As for a download isn't asked about. [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download) decides where downloads go. * DevTools' dialogs aren't asked about. * A later call replaces an earlier hook. --- # Drags into embedded browsers > Decide what another application may drag into a browser embedded in your own window. [`App::on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter) decides a drag from another application as it enters a browser embedded in your own window. The drag may carry files from a file manager, a link or selected text. Chromium asks only about embedded browsers, the ones [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser) makes. A drag into one of Kurogane's own windows isn't asked about. Its page gets the drop as a browser's would. ## Accept only some files The hook runs before the page sees the drag. `DragDecision::Refuse` keeps the drag from the page: ```rust use kurogane::{App, DragDecision, RuntimeError}; fn main() -> Result<(), RuntimeError> { let runtime = App::new("content") .on_drag_enter(|drag, _app| { let images = !drag.files().is_empty() && drag.files().iter().all(|file| file.extension().is_some_and(|ext| ext == "png")); if images { DragDecision::Allow } else { DragDecision::Refuse } }) .start_embedded()?; // Create child browsers in your window and pump from your loop runtime.shutdown(); Ok(()) } ``` | [`DragDecision`](https://kurogane-rs.org/docs/api/requests/dragdecision.md) | What happens | |---|---| | `Allow` | the drag goes on; the page sees it and may take its drop | | `Refuse` | the drag stops at the window; the page sees nothing and the pointer shows no drop | | `Default` | Kurogane's policy, which allows the drag | ## What the hook sees and the page doesn't The hook sees the paths of the files dragged. The page never does. It gets a dropped file's name and contents only. The hook runs as the drag enters, not when it drops. The user may still move away. Decide there and leave acting on the files to the drop. ## Know what is dragged [`DragEnter`](https://kurogane-rs.org/docs/api/requests/dragenter.md) describes the drag: | Method | Gives | |---|---| | `files()` | the paths of the files dragged; empty for a drag of no file | | `link_url()` | the link dragged | | `text()` | the text dragged | | `origin()` | the origin of the page the drag enters | | `browser()` | the browser the drag enters | ## Rules for the hook * It runs on the UI thread and must not block. * A hook that panics refuses the drag. * Drags of DevTools and of a page's own content within the window aren't asked about. * A later call replaces an earlier hook. --- # Follow the page's title and fullscreen > Keep a window's title and fullscreen state in step with its page and hear when they change. A window takes its page's title and goes fullscreen with its page by itself. Two hooks tell your app when that happens so it can update its own controls. ## Fix a window's title A window follows its page's `<title>` unless its options fix one with [`WindowOptions::title`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.title): ```rust use kurogane::{App, WindowOptions}; fn main() { App::new("content") .window(WindowOptions::new().title("Notes")) .run_or_exit(); } ``` A popup always follows its page. The taskbar and the window switcher show the window's title, a remote page's included. ## Hear title changes [`App::on_title_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_title_change) hears every title a page gives itself. That's its `<title>` as it loads or `document.title` set by a script: ```rust use kurogane::App; fn main() { App::new("content") .on_title_change(|change, _app| { println!("{:?} is now {:?}", change.window(), change.title()); }) .run_or_exit(); } ``` The hook hears every change whether the window follows the title or not. Popups and embedded browsers are reported too. ## Title your own window A browser embedded in your own window doesn't title that window. Your app does. Send the title to your loop and set it there: ```rust use std::sync::mpsc; use kurogane::{App, RuntimeError}; fn main() -> Result<(), RuntimeError> { let (titles, new_titles) = mpsc::channel::<String>(); let runtime = App::new("content") .on_title_change(move |change, _app| { let _ = titles.send(change.title().to_owned()); }) .start_embedded()?; // In your loop, after each pump while let Ok(title) = new_titles.try_recv() { println!("set the host window's title to {title}"); } runtime.shutdown(); Ok(()) } ``` [`TitleChange::window`](https://kurogane-rs.org/docs/api/windows/titlechange.md#method.window) is `None` for an embedded browser. [`TitleChange::browser`](https://kurogane-rs.org/docs/api/windows/titlechange.md#method.browser) says which browser changed. ## Hear fullscreen changes A page enters fullscreen with `requestFullscreen()` and leaves it with `exitFullscreen()` or the user's Escape. [`App::on_fullscreen_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_fullscreen_change) hears both: ```rust use kurogane::App; fn main() { App::new("content") .on_fullscreen_change(|change, _app| { println!("fullscreen: {}", change.is_fullscreen()); }) .run_or_exit(); } ``` Hide your app's own controls there. A window of Kurogane's goes fullscreen with its page by itself. Kurogane doesn't resize a browser embedded in your own window. Your app sizes it, for example to fill a window it made fullscreen. ## Open or keep a window fullscreen [`WindowState::Fullscreen`](https://kurogane-rs.org/docs/api/windows/windowstate.md) opens a window fullscreen: ```rust use kurogane::{App, WindowOptions, WindowState}; fn main() { App::new("content") .window(WindowOptions::new().state(WindowState::Fullscreen)) .run_or_exit(); } ``` The user toggles fullscreen with F11 (Cmd+Ctrl+F on macOS). Refuse `ChromeCommand::Fullscreen` in [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) to turn that shortcut off. See [Keyboard shortcuts](https://kurogane-rs.org/docs/guides/keyboard-shortcuts.md#refuse-a-command). ## Rules for the hooks * Both hooks run on the UI thread and must not block. * A hook that panics is logged. * DevTools isn't reported. * A later call replaces an earlier hook. --- # One instance per profile > Handle a second launch in the running app, run separate copies and choose where the profile lives. Chromium runs one instance of your app per profile. Starting the app again while it runs brings its windows to the front instead of opening another copy. The new launch hands its arguments to the running app and exits with status 0. ## Open what a second launch names A launch often carries something to open. The user double-clicks a file, chooses your app from **Open With**, clicks a `myapp://` link or runs: ```text myapp notes.txt ``` [`App::on_second_instance`](https://kurogane-rs.org/docs/api/app/app.md#method.on_second_instance) receives that launch in the running app. Open the file in the existing window: ```rust use kurogane::App; fn main() { App::new("content") .on_second_instance(|launch, app| { for arg in launch.args() { // Relative to where the new launch started let path = match launch.working_dir() { Some(dir) => dir.join(arg), None => arg.into(), }; app.broadcast_json("open-file", &path); } }) .run_or_exit(); } ``` ```javascript window.kurogane.on("open-file", (json) => openFile(JSON.parse(json))); ``` [`SecondInstance`](https://kurogane-rs.org/docs/api/app/secondinstance.md) describes the launch: * `args()` lists its arguments that aren't switches, in order and without the program name. * `working_dir()` is the directory it started in. Relative paths among its arguments are relative to it. * `switch("new-window")` gives the value of `--new-window`. It's an empty string for a switch without a value and `None` when the switch is absent. Without a hook a second launch only brings the windows to the front. The first launch reads its own arguments with `std::env::args` as any Rust program does. ## Open a window for a second launch The page can open an application window of your own origin with `window.open`. Ask it to from the hook: ```rust use kurogane::App; fn main() { App::new("content") .on_second_instance(|launch, app| { if launch.switch("new-window").is_some() { app.broadcast_json("new-window", &true); } }) .run_or_exit(); } ``` ```javascript window.kurogane.on("new-window", () => window.open("/index.html")); ``` ## Second launches on macOS Opening the app's bundle while it runs activates it without starting another process. The hook runs only for launches that start a process, such as running the executable from a terminal. ## Run separate copies Two copies that must run at the same time need different profiles. [`App::profile_id`](https://kurogane-rs.org/docs/api/app/app.md#method.profile_id) names one: ```rust use kurogane::App; fn main() { let profile = std::env::var("APP_PROFILE").unwrap_or_else(|_| "default".into()); App::new("content").profile_id(profile).run_or_exit(); } ``` Debug builds use a profile of their own. A development run doesn't hand its launch to an installed copy that runs at the same time. ## Where the profile lives The profile holds your app's cookies, storage, permissions and caches. Kurogane keeps it in `kurogane/profiles/<id>` in the local data directory. Cache cleaners leave it alone there: | Platform | Profile | |---|---| | Linux | `~/.local/share/kurogane/profiles/<id>` | | macOS | `~/Library/Application Support/kurogane/profiles/<id>` | | Windows | `%LOCALAPPDATA%\kurogane\profiles\<id>` | `<id>` is the `profile_id` or the executable's name. A debug build adds `-dev`. `kurogane list profiles` lists them. `kurogane clean all` removes them. ### Keep the profile next to the app [`App::profile_dir`](https://kurogane-rs.org/docs/api/app/app.md#method.profile_dir) puts the profile in a directory of your choosing. A portable app keeps it next to its executable: ```rust use kurogane::App; fn main() { let exe = std::env::current_exe().expect("the executable's path"); let profile = exe.parent().expect("a folder").join("profile"); App::new("content").profile_dir(profile).run_or_exit(); } ``` * The directory is created when missing. * It takes an absolute path. A relative one fails at startup. * It's used as given in debug builds too. A development run then shares it with an installed copy and hands its launch over when that copy runs. * It can't be combined with `profile_id`. ## What lasts from one run to the next Cookies with an expiry, local storage and everything else the profile holds last between runs. Session cookies end with each run as in a browser. They're the cookies a server sets without `Expires` or `Max-Age`. Every run starts with your app's windows alone, not the last session's. A login meant to outlast a run uses a cookie with an expiry: ```http Set-Cookie: session=...; Max-Age=2592000; Path=/; Secure; HttpOnly; SameSite=Lax ``` A page can keep its token in local storage instead. ## Rules for the hook * It runs on the UI thread in the running app. * A later call replaces an earlier hook. --- # Commands in depth > Synchronous, async and binary commands, their errors and how much data they carry. A command is a named Rust handler the page calls with `window.kurogane.invoke`. See [IPC](https://kurogane-rs.org/docs/concepts/ipc.md) for how commands sit next to events and streams. ## Take and return your own types The request is any type serde can read. The reply is any type serde can write: ```rust use kurogane::{App, AppHandle, IpcError}; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] struct Search { query: String, limit: usize, } #[derive(Serialize)] struct Hit { title: String, } fn search(request: Search, _: &AppHandle) -> Result<Vec<Hit>, IpcError> { let hits = (0..request.limit) .map(|n| Hit { title: format!("{} #{n}", request.query) }) .collect(); Ok(hits) } fn main() { App::new("content").command("search", search).run_or_exit(); } ``` ```javascript const hits = await window.kurogane.invoke("search", { query: "notes", limit: 3 }); ``` A call without a payload sends JSON `null`. A handler that takes `()` or an `Option` accepts it: ```rust App::new("content") .command("version", |_: (), _: &AppHandle| Ok(env!("CARGO_PKG_VERSION"))) .run_or_exit(); ``` ```javascript const version = await window.kurogane.invoke("version"); ``` A request the handler's type can't read rejects with code `-2` before the handler runs. ## Answer later [`App::command`](https://kurogane-rs.org/docs/api/app/app.md#method.command) runs on the UI thread. That thread also runs every window and receives every message from every page. For slow work use [`App::async_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_command). Its handler gets a [`Responder`](https://kurogane-rs.org/docs/api/ipc/responder.md) and resolves it from any thread: ```rust use kurogane::{App, AppHandle, Responder}; fn main() { App::new("content") .async_command("sum", |numbers: Vec<i64>, responder: Responder<i64>, _: &AppHandle| { std::thread::spawn(move || responder.resolve(Ok(numbers.iter().sum()))); }) .run_or_exit(); } ``` The handler itself still runs on the UI thread. Return from it promptly and do the work elsewhere. * A request is answered once. `resolve` takes the responder. * A responder dropped unanswered rejects the call with code `-3`. Every call settles. * A responder of a cancelled call sends nothing. ## Cancel a call The promise `invoke` returns has a `cancel()`. It rejects the promise with code `0` and marks an async handler's responder cancelled: ```javascript const call = window.kurogane.invoke("sum", numbers); cancelButton.onclick = () => call.cancel(); ``` A page that navigates away or closes cancels its open calls too. Check [`Responder::is_cancelled`](https://kurogane-rs.org/docs/api/ipc/responder.md#method.is_cancelled) to stop work nobody waits for: ```rust use kurogane::{App, AppHandle, Responder}; fn main() { App::new("content") .async_command("count", |to: u64, responder: Responder<u64>, _: &AppHandle| { std::thread::spawn(move || { let mut total = 0; for n in 0..to { if responder.is_cancelled() { return; } total += n; } responder.resolve(Ok(total)); }); }) .run_or_exit(); } ``` A page back from the back-forward cache finds the calls it left open rejected with code `-9`. ## Send bytes [`App::binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.binary_command) takes and returns raw bytes without JSON: ```rust use kurogane::{App, AppHandle}; fn main() { App::new("content") .binary_command("checksum", |data: &[u8], _: &AppHandle| { let sum: u32 = data.iter().map(|&byte| u32::from(byte)).sum(); Ok(sum.to_le_bytes().to_vec()) }) .run_or_exit(); } ``` The page sends an `ArrayBuffer` or a typed array and gets an `ArrayBuffer` back: ```javascript const reply = await window.kurogane.invoke("checksum", new TextEncoder().encode("hello")); const sum = new DataView(reply).getUint32(0, true); ``` [`App::async_binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command) is its async form. Its handler owns the bytes and gets a [`BinaryResponder`](https://kurogane-rs.org/docs/api/ipc/binaryresponder.md). ## Report errors A handler fails with an [`IpcError`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md). A string converts into one. The page's promise rejects with an `Error` whose `code` says what failed and whose `message` is yours: ```rust use kurogane::{App, AppHandle, IpcError}; fn main() { App::new("content") .command("open", |path: String, _: &AppHandle| -> Result<String, IpcError> { std::fs::read_to_string(&path).map_err(|e| format!("can't open {path}: {e}").into()) }) .run_or_exit(); } ``` ```javascript try { const text = await window.kurogane.invoke("open", "notes.txt"); } catch (error) { console.log(error.code, error.message); } ``` Send a code of your own with [`IpcError::with_code`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md#method.with_code) and [`ErrorCode::App`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.App). Your codes are positive: ```rust use std::num::NonZeroU16; use kurogane::{ErrorCode, IpcError}; const NOT_FOUND: NonZeroU16 = NonZeroU16::new(404).unwrap(); fn not_found(what: &str) -> IpcError { IpcError::with_code(format!("{what} not found"), ErrorCode::App(NOT_FOUND)) } ``` Kurogane's own codes are zero or negative: | Code | Meaning | |---|---| | `0` | the handler reported a failure, or the page cancelled | | `-1` | the handler panicked | | `-2` | the request or reply couldn't be decoded or encoded | | `-3` | an async handler dropped its responder unanswered | | `-4` | the page's origin may not call the command | | `-5` | no filesystem grant of the origin covers the operation | | `-6` | the path is outside the granted roots, denied or a link | | `-7` | the path is malformed | | `-8` | a file or message exceeds its transfer limit | | `-9` | the page left with the call open and came back from the back-forward cache | A handler that panics rejects the call with `-1`. Your app keeps running. ## Large data One message from a page has a size cap. A call over it rejects with `-8` before anything is sent. Send larger data as a [stream](https://kurogane-rs.org/docs/concepts/ipc.md#streams) in chunks. The page stays responsive between chunks. ## Test a handler A handler is a function. Call it directly in a test. An async handler's logic can take its `Responder` and leave the `AppHandle` out. [`Responder::new`](https://kurogane-rs.org/docs/api/ipc/responder.md#method.new) makes one that hands its result to a closure: ```rust use std::sync::mpsc; use kurogane::Responder; fn sum(numbers: Vec<i64>, responder: Responder<i64>) { responder.resolve(Ok(numbers.iter().sum())); } #[test] fn sums_the_numbers() { let (tx, rx) = mpsc::channel(); sum(vec![1, 2, 3], Responder::new(Box::new(move |result| tx.send(result).unwrap()))); assert_eq!(rx.recv().unwrap(), Ok(6)); } ``` Register it with `.async_command("sum", |numbers, responder, _| sum(numbers, responder))`. ## Rules for commands * A name registered twice is a configuration error. [`App::build`](https://kurogane-rs.org/docs/api/app/app.md#method.build) reports it before anything starts. * Only your app's own origin calls a command by default. [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) opens one to other origins. See [Who may call](https://kurogane-rs.org/docs/concepts/ipc.md#who-may-call). * Every handler runs on the UI thread. Async responders and binary responders work from any thread. --- # 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. --- # Streams > Move chunks both ways between a page and a Rust handler until one side ends. A stream carries chunks in both directions between one page and one [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md). Use one for data larger than a command carries, for progress as data arrives or for a long exchange that a single reply can't hold. ## Receive an upload Register a factory with [`App::stream`](https://kurogane-rs.org/docs/api/app/app.md#method.stream). It makes a handler for each stream a page opens: ```rust use kurogane::{App, IpcError, StreamHandler, StreamResponder}; struct Upload { received: usize, } impl StreamHandler for Upload { // Accept or refuse before the page holds the stream fn on_open(&mut self, metadata: &str) -> Result<(), IpcError> { if metadata.is_empty() { return Err("name the upload".into()); } Ok(()) } fn on_chunk(&mut self, data: &[u8], _: &StreamResponder) -> Result<(), IpcError> { self.received += data.len(); Ok(()) } fn on_end(&mut self, _: &str, responder: StreamResponder) -> Result<(), IpcError> { responder.end(&self.received.to_string()) } } fn main() { App::new("content") .stream("upload", || Upload { received: 0 }) .run_or_exit(); } ``` The page opens the stream, writes chunks and ends it: ```javascript const stream = await window.kurogane.openStream("upload", "notes.txt"); stream.onEnd((result) => console.log(`${result} bytes received`)); stream.onError((message) => console.error(message)); const bytes = new Uint8Array(await file.arrayBuffer()); const chunk = 1 << 20; for (let offset = 0; offset < bytes.length; offset += chunk) { stream.write(bytes.subarray(offset, offset + chunk)); } stream.end(); ``` ## Send data to the page from a thread [`StreamHandler::on_opened`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened) runs once the page holds the stream. Hand a clone of the [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md) to a thread that produces the data: ```rust use std::io::Read; use kurogane::{App, IpcError, StreamHandler, StreamResponder}; struct Download; impl StreamHandler for Download { fn on_opened(&mut self, responder: &StreamResponder) -> Result<(), IpcError> { let responder = responder.clone(); std::thread::spawn(move || { let path = std::env::temp_dir().join("export.bin"); let Ok(mut file) = std::fs::File::open(path) else { let _ = responder.error("no export yet"); return; }; let mut buffer = vec![0; 1 << 20]; loop { match file.read(&mut buffer) { Ok(0) => break, Ok(n) => { if responder.send_data(&buffer[..n]).is_err() { // The page left or the stream closed return; } } Err(e) => { let _ = responder.error(e.to_string()); return; } } } let _ = responder.end("done"); }); Ok(()) } fn on_chunk(&mut self, _: &[u8], _: &StreamResponder) -> Result<(), IpcError> { Err("this stream only sends".into()) } } fn main() { App::new("content").stream("download", || Download).run_or_exit(); } ``` ```javascript const stream = await window.kurogane.openStream("download"); const parts = []; stream.onData((buffer) => parts.push(buffer)); stream.onEnd(() => save(new Blob(parts))); stream.onError((message) => console.error(message)); ``` Chunks that arrive before `onData` is registered are kept and handed over when it is. ## A stream's life 1. [`on_open`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_open) accepts or refuses the stream. Nothing can be sent yet since the page doesn't hold the stream. An `Err` rejects the page's `openStream` with its message and code. 2. The page's `openStream` resolves. Then [`on_opened`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened) runs. 3. [`on_chunk`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#tymethod.on_chunk) runs for each chunk the page writes. 4. [`on_end`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_end) runs when the page ends the stream with its result. When it sends neither an end nor an error the runtime ends the stream with an empty result. The page always hears back. [`on_error`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_error) runs when the page's side reports a failure. `on_chunk` is the one callback without a default. The first `end` or `error` sent closes the stream, whichever clone of the responder sends it. Later sends fail with `stream closed`. An `Err` from `on_opened`, `on_chunk` or `on_end` fails the stream unless it's already closed. A panic in any callback counts as an `Err` with the message `handler panicked`. The runtime drops the handler once the stream is closed. ## The page's side `openStream(name, metadata)` resolves with a stream once the handler accepts it: | Method | What it does | |---|---| | `onData(callback)` | receives each chunk as an `ArrayBuffer` | | `onEnd(callback)` | receives the result the stream ended with, once | | `onError(callback)` | receives the failure's message, once | | `write(data)` | sends an `ArrayBuffer` or typed array to `on_chunk` | | `end(result)` | ends the stream; `on_end` receives `result` | A refused open rejects with an `Error` whose `code` is `0` when the handler refused it and `-4` when the page's origin may not open it. A chunk over the size cap makes `write` throw. It sends nothing and the stream stays open. ## Reach the app from a handler [`App::stream_h`](https://kurogane-rs.org/docs/api/app/app.md#method.stream_h) gives the factory the [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md) too. Keep a clone in the handler to send events or query what is open: ```rust use kurogane::{App, AppHandle, IpcError, StreamHandler, StreamResponder}; struct Logged { app: AppHandle, } impl StreamHandler for Logged { fn on_chunk(&mut self, data: &[u8], _: &StreamResponder) -> Result<(), IpcError> { self.app.broadcast_json("received", &data.len()); Ok(()) } fn on_end(&mut self, _: &str, _: StreamResponder) -> Result<(), IpcError> { Ok(()) } } fn main() { App::new("content") .stream_h("logged", |app| Logged { app: app.clone() }) .run_or_exit(); } ``` ## Rules for streams * The factory and every callback run on the UI thread. Return promptly. A `StreamResponder` works from any thread. * Streams follow the same access rule as commands. [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) opens one to other origins. * A responder's sends fail once its page's document goes, when the frame navigates or closes. * A page back from the back-forward cache finds the streams it left open failed with `The page left`. * A name registered twice is a configuration error. --- # WebAssembly > Build a WebAssembly module and load it in your page. Kurogane serves `.wasm` files like any other asset of your frontend. The page loads them with the standard WebAssembly API. No runtime tooling is involved. ## Build a module Add the WebAssembly target once: ```bash rustup target add wasm32-unknown-unknown ``` Write the module in plain Rust. This one exports a single function: ```rust // add.rs #![no_std] #[panic_handler] fn panic(_: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b } ``` Compile it: ```bash rustc --target wasm32-unknown-unknown -O --crate-type=cdylib add.rs -o add.wasm ``` ## Put it with your frontend The module must end up in the built frontend next to `index.html`. With Vite put it in `frontend/public/`. Vite serves it during development and copies it into `frontend/dist/` when it builds: ```text frontend/ ├── index.html ├── main.ts └── public/ └── add.wasm ``` `kurogane bundle` then carries it into the bundle's `content` with the rest of the frontend. ## Load it in the page Fetch it by a relative URL. The same code then works from the dev server and from `app://app` in a release build: ```javascript const { instance } = await WebAssembly.instantiateStreaming(fetch("add.wasm")); console.log(instance.exports.add(2, 3)); // 5 ``` `app://` serves `.wasm` files as `application/wasm`. `instantiateStreaming` needs that type and compiles the module while it downloads. ## Call JavaScript from the module A module imports what the page hands it. Declare the imports in Rust: ```rust // counter.rs #![no_std] #[panic_handler] fn panic(_: &core::panic::PanicInfo) -> ! { loop {} } #[link(wasm_import_module = "env")] extern "C" { fn report(value: i32); } static mut COUNT: i32 = 0; #[no_mangle] pub extern "C" fn tick() { unsafe { COUNT += 1; report(COUNT); } } ``` Hand the page's functions over as the second argument: ```javascript const imports = { env: { report: (value) => console.log("count", value) } }; const { instance } = await WebAssembly.instantiateStreaming(fetch("counter.wasm"), imports); instance.exports.tick(); ``` ## Higher-level tooling `wasm-bindgen`, `wasm-pack` and Vite's WebAssembly plugins work as they do in a browser. Kurogane serves whatever files their build output holds. ## WebAssembly or a command WebAssembly runs inside the renderer next to your page. It suits work the page does on its own data, such as parsing, image processing or simulation. That work needs no round trip to Rust. A [command](https://kurogane-rs.org/docs/guides/commands.md) runs in the browser process with your app's full rights. Use one for files, the network and anything else outside the page. --- # GPU mode > Choose how Chromium renders your page and check what the GPU does on a machine. [`App::gpu_mode`](https://kurogane-rs.org/docs/api/app/app.md#method.gpu_mode) sets how Chromium renders. [`GpuMode::Auto`](https://kurogane-rs.org/docs/api/app/gpumode.md) is the default: ```rust use kurogane::{App, GpuMode}; fn main() { App::new("content") .gpu_mode(GpuMode::Software) .run_or_exit(); } ``` ## The modes | [`GpuMode`](https://kurogane-rs.org/docs/api/app/gpumode.md) | What Chromium does | |---|---| | `Auto` | picks `Hardware` or `Software` for the machine | | `Hardware` | renders on the GPU | | `Software` | renders on the CPU with SwiftShader | | `Disabled` | turns the GPU off; no WebGL and no canvas acceleration | ### Auto On Linux `Auto` picks `Software` inside a virtual machine whose display is a virtual GPU (VirtualBox, VMware or QEMU and virtio). Everywhere else it picks `Hardware`. ### Hardware on each platform * **Windows.** Without the sandbox GPU work runs inside the browser process. It waits there for a lost device to recover. Under [`SandboxMode::Chromium`](https://kurogane-rs.org/docs/concepts/sandbox.md) it runs in a GPU process of its own instead. * **macOS.** Chromium renders through Metal and Core Animation with no overrides. * **Linux.** Chromium chooses between X11 and Wayland. With an NVIDIA GPU in a Wayland session Kurogane runs Chromium on X11 under XWayland. ## When to choose a mode yourself * **`Software`** for virtual machines `Auto` doesn't recognize, CI and remote desktop sessions. Rendering is slower but doesn't depend on a GPU driver. * **`Hardware`** to keep the GPU inside a virtual machine whose GPU is passed through. * **`Disabled`** for apps that draw nothing that needs a GPU, or to rule the GPU out while you debug a rendering problem. Pick the mode at runtime when it depends on the machine: ```rust use kurogane::{App, GpuMode}; fn main() { let mode = match std::env::var("APP_GPU").as_deref() { Ok("software") => GpuMode::Software, Ok("off") => GpuMode::Disabled, _ => GpuMode::Auto, }; App::new("content").gpu_mode(mode).run_or_exit(); } ``` ## Check the GPU on a machine `kurogane doctor` reports the machine's graphics: ```bash kurogane doctor ``` On Linux it reads OpenGL through `glxinfo` with the libraries your apps load. Install `mesa-utils` for that report on Debian and Ubuntu. The Nix flake brings its own `glxinfo`. On NixOS an app built on an older nixpkgs can't load the system's drivers and renders without the GPU. See [GPU drivers on NixOS](https://kurogane-rs.org/docs/start/install.md#gpu-drivers-on-nixos). ## Override Chromium's switches [`App::chromium_flag`](https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag) and [`App::chromium_flag_with_value`](https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag_with_value) override a switch the GPU mode sets. Keep Chromium on Wayland with an NVIDIA GPU, for example: ```rust use kurogane::App; fn main() { App::new("content") .chromium_flag_with_value("ozone-platform", "wayland") .run_or_exit(); } ``` --- # Credential storage > Choose how Chromium protects cookies and saved passwords at rest and stop Keychain prompts. Chromium encrypts the cookies and saved passwords in your app's profile. [`App::credential_storage`](https://kurogane-rs.org/docs/api/app/app.md#method.credential_storage) chooses where the key comes from: ```rust use kurogane::{App, CredentialStorage}; fn main() { App::new("content") .credential_storage(CredentialStorage::Basic) .run_or_exit(); } ``` ## The two stores | [`CredentialStorage`](https://kurogane-rs.org/docs/api/app/credentialstorage.md) | Key | Protects | |---|---|---| | `System` (default) | the platform's credential store | the profile against anyone without the user's login | | `Basic` | a fixed key built into Chromium | nothing; it obfuscates | `System` keeps the key in the Keychain on macOS, kwallet or gnome-keyring on Linux and DPAPI on Windows. `Basic` is obfuscation and not encryption. Anyone who can read the profile directory can read what it holds. ## When the system store gets in the way The platform stores grant access to a code identity: * **macOS.** An unsigned binary has no identity that survives a rebuild. Every run of an unsigned build raises a Keychain prompt. * **Linux.** A host without a keyring daemon has no store to reach. Chromium then stores the data unencrypted on its own. Denying the macOS prompt is harmless. Chromium logs `Encryption is not available` and stores the data unencrypted. Signing your macOS app ends the prompts. See the signing section of `kurogane bundle`. Until then use `Basic` for development builds. ## Use Basic for development only Keep `System` for release builds and use `Basic` while you develop: ```rust use kurogane::{App, CredentialStorage}; fn main() { let storage = if cfg!(debug_assertions) { CredentialStorage::Basic } else { CredentialStorage::System }; App::new("content").credential_storage(storage).run_or_exit(); } ``` `Basic` suits: * Unsigned development builds * Containers and CI * Headless hosts without a keyring daemon It doesn't suit a profile holding data worth protecting. > [!NOTE] > Debug and release builds use different profiles. A debug build's `Basic` data never mixes with a release build's encrypted data. --- # Chromium flags and preferences > Pass Chromium switches, set its preferences and turn back on what Kurogane turns off. Kurogane starts Chromium with its own switches and preferences. Your app adds to them, overrides them or removes them. ## Add a switch [`App::chromium_flag`](https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag) adds a switch without a value. [`App::chromium_flag_with_value`](https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag_with_value) adds one with a value: ```rust use kurogane::App; fn main() { App::new("content") .chromium_flag("disable-popup-blocking") .chromium_flag_with_value("enable-blink-features", "CanvasDrawElement") .run_or_exit(); } ``` * A name may be written with or without its leading `--`. On Windows it's case-insensitive as Chromium treats it. * A name holding `=` is logged and skipped. Its value goes in `chromium_flag_with_value`. * Your switches apply after Kurogane's own, in the order given. The last value given for a switch wins over Kurogane's own value too. ## Add features `enable-features` and `disable-features` are lists. A value adds its features to them instead of replacing them: ```rust use kurogane::App; fn main() { App::new("content") .chromium_flag_with_value("disable-features", "Translate") .run_or_exit(); } ``` The features CEF disables itself stay disabled. An `enable-features` entry turns back on a feature Kurogane turns off, in any form Chromium reads (`Name`, `Name:param/value`, `Name<Study` or `*Name`). ## Remove a switch Kurogane passes [`App::without_chromium_flag`](https://kurogane-rs.org/docs/api/app/app.md#method.without_chromium_flag) drops a switch Kurogane would pass. That's one of its defaults, one a setting such as `gpu_mode` sets or one your app gave before: ```rust use kurogane::App; fn main() { App::new("content") .without_chromium_flag("disable-stack-profiler") .run_or_exit(); } ``` A switch given after it sets the switch again. For `enable-features` and `disable-features` it drops Kurogane's entries and your earlier ones. CEF's own stay. A switch CEF passes itself or your app was launched with stays. Kurogane logs it. ## Set a preference [`App::chromium_pref`](https://kurogane-rs.org/docs/api/app/app.md#method.chromium_pref) sets any Chromium preference by its name. The value takes the place of Kurogane's own: ```rust use kurogane::App; fn main() { App::new("content") .chromium_pref("component_updates.component_updates_enabled", true) .run_or_exit(); } ``` A null value returns a preference to Chromium's default: ```rust use kurogane::App; use serde_json::Value; fn main() { App::new("content") .chromium_pref("network_time.network_time_queries_enabled", Value::Null) .run_or_exit(); } ``` * The name is the profile's preference when the profile has one of that name and else Chromium's global one. * A preference applies once the runtime has started. Chromium reads some only as the profile starts. Those take effect at the next start. * Preferences are declarative. One set at an earlier start and given no more returns to Chromium's default. * A name Chromium doesn't have, or a value it refuses, is logged and skipped. ## What Kurogane turns off Kurogane turns off what Chromium would run for every app and an app rarely needs. One line turns each back on: | What | Turned off by | Turned back on with | |---|---|---| | Extensions other programs register for Google Chrome | preference `extensions.block_external_extensions` | `.chromium_pref("extensions.block_external_extensions", false)` | | Component updates, Widevine among them | preference `component_updates.component_updates_enabled` | `.chromium_pref("component_updates.component_updates_enabled", true)` | | Queries to Google's time server | preference `network_time.network_time_queries_enabled` | `.chromium_pref("network_time.network_time_queries_enabled", true)` | | The bubble of finished downloads | preference `download_bubble.partial_view_enabled` | `.chromium_pref("download_bubble.partial_view_enabled", true)` | | The omnibox's AI Mode check | feature `AimEnabled` | `.chromium_flag_with_value("enable-features", "AimEnabled")` | | Cast | feature `MediaRouter` | `.chromium_flag_with_value("enable-features", "MediaRouter")` | | A renderer kept ready for the next site | feature `SpareRendererForSitePerProcess` | `.chromium_flag_with_value("enable-features", "SpareRendererForSitePerProcess")` | | A copy of the whole bundle at every macOS start | feature `MacAppCodeSignClone` | `.chromium_flag_with_value("enable-features", "MacAppCodeSignClone")` | | Chrome's stack-sampling profiler | switch `disable-stack-profiler` | `.without_chromium_flag("disable-stack-profiler")` | On macOS Chromium can copy the app bundle into the user's temporary folder at every start. The running app's code signature then stays valid when an updater replaces the bundle in place. A killed app leaves its copy behind. An app whose updater replaces the bundle while it runs turns `MacAppCodeSignClone` back on. ## See what Chromium got * Chromium ignores a switch or feature name it doesn't know and says nothing. Kurogane reads every switch back once Chromium holds it and logs one held otherwise than passed. * The final command line is logged at debug level. See [Logging](https://kurogane-rs.org/docs/guides/logging.md). --- # Logging > See what Kurogane and Chromium do and read the errors your app reports when it can't start. Kurogane reports what it does through [`tracing`](https://docs.rs/tracing) events. Lifecycle and IPC detail go to `debug`. Problems go to `warn` and `error`. Kurogane never writes to stdout or stderr itself. The one exception is the error `run_or_exit` prints when your app can't start. Nothing appears until your app installs a subscriber. ## Print Kurogane's log Add `tracing-subscriber`: ```toml [dependencies] tracing-subscriber = { version = "0.3", features = ["env-filter"] } ``` Install it before the app starts: ```rust use tracing_subscriber::EnvFilter; use tracing_subscriber::filter::LevelFilter; fn main() { tracing_subscriber::fmt() .with_env_filter( EnvFilter::builder() .with_default_directive(LevelFilter::WARN.into()) .from_env_lossy(), ) .log_internal_errors(false) .init(); kurogane::App::new("content").run_or_exit(); } ``` Warnings and errors then print by default. Add the detail with `RUST_LOG`: ```bash RUST_LOG=kurogane=debug kurogane dev ``` Any other `tracing` subscriber works the same way. > [!IMPORTANT] > Keep `log_internal_errors(false)`. Without it the subscriber reports a line it can't write on stderr instead. That happens when your app's output goes into a program that has exited, such as `| tee` ended by Ctrl+C. When stderr is that same closed pipe the report panics. A panic inside a Chromium callback aborts your app. ## What the debug log shows * Each step of startup and shutdown * Each browser and window as it opens and closes * IPC traffic between pages and your handlers * The final command line Chromium starts with * Every switch Chromium holds otherwise than Kurogane passed it Chromium ignores a switch or feature name it doesn't know without a word. The last two lines are how you spot one. See [Chromium flags and preferences](https://kurogane-rs.org/docs/guides/chromium-flags.md). ## Chromium's own log Chromium keeps a log of its own apart from Kurogane's. Kurogane leaves its settings at CEF's defaults. CEF reads the `log-file` and `log-severity` switches for them: ```rust use kurogane::App; fn main() { App::new("content") .chromium_flag_with_value("log-severity", "verbose") .chromium_flag_with_value("log-file", "chromium.log") .run_or_exit(); } ``` ## When the app can't start [`App::run_or_exit`](https://kurogane-rs.org/docs/api/app/app.md#method.run_or_exit) prints the error with each of its causes and exits with code 1. [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) returns it as a [`RuntimeError`](https://kurogane-rs.org/docs/api/app/runtimeerror.md) for your app to handle. A configuration problem is [`RuntimeError::InvalidConfiguration`](https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.InvalidConfiguration). It lists every problem the builder found before anything started. When the Chromium runtime can't be used the error says which runtime failed and how to fix it: | Error | When | |---|---| | `CefNotInstalled` | no runtime of your app's CEF version is installed | | `CefPathMissing` | `CEF_PATH` names no directory | | `CefVersionMismatch` | the runtime is another CEF build than the one your app was built against | | `InvalidCefRuntime` | the runtime is incomplete | `CefVersionMismatch` and `InvalidCefRuntime` carry a [`CefLocation`](https://kurogane-rs.org/docs/api/app/ceflocation.md). Each message gives the fix for its location: | Location | Fix | |---|---| | `Bundle` | reinstall the app | | `BesideExecutable` | remove the runtime beside the executable or replace it with the right CEF | | `CefPath` | point `CEF_PATH` at the right CEF or unset it | | `Installed` | remove it and reinstall it with `kurogane install` | `kurogane doctor` checks the runtime, the build tools and the project before you run anything. --- # Browser and renderer delegates > Take part in Chromium's browser and renderer process lifecycles without replacing Kurogane's own. Delegates are the lower-level way into Chromium. A browser delegate runs in the browser process. A renderer delegate runs inside each renderer, next to your page. Kurogane's own handling runs either way. Delegates add to it. Reach for a delegate when no `App` setting or hook covers what you need. Their callbacks take CEF types which Kurogane re-exports as [`kurogane::tanso`](https://kurogane-rs.org/docs/api.md#re-exports). ## Run work once Chromium is ready [`ClientAppBrowserDelegate`](https://kurogane-rs.org/docs/api/app/clientappbrowserdelegate.md) gets the browser process's lifecycle. [`App::delegate`](https://kurogane-rs.org/docs/api/app/app.md#method.delegate) registers one: ```rust use kurogane::{App, ClientAppBrowserDelegate}; struct Startup; impl ClientAppBrowserDelegate for Startup { fn on_context_initialized(&self) { // Runs once, in the browser process only println!("Chromium is ready"); } } fn main() { App::new("content").delegate(Startup).run_or_exit(); } ``` | Method | When it runs | |---|---| | `on_before_command_line_processing` | before Chromium reads its command line | | `on_context_initialized` | once the browser process has started; windows may open from here on | `on_context_initialized` runs only in the browser process. It's the place for one-time work that needs Chromium running. See [Process model](https://kurogane-rs.org/docs/concepts/process-model.md#one-binary). `on_before_command_line_processing` is an escape hatch. [`App::chromium_flag`](https://kurogane-rs.org/docs/guides/chromium-flags.md) covers switches in almost every case. ## Watch the page from inside the renderer [`ClientAppRendererDelegate`](https://kurogane-rs.org/docs/api/app/clientapprendererdelegate.md) gets each renderer's lifecycle. [`App::renderer_delegate`](https://kurogane-rs.org/docs/api/app/app.md#method.renderer_delegate) registers one: ```rust use kurogane::tanso::{Browser, Frame, V8Context, V8Exception, V8StackTrace}; use kurogane::{App, ClientAppRendererDelegate}; struct Watch; impl ClientAppRendererDelegate for Watch { fn on_context_created(&self, _: Option<&Browser>, _: Option<&Frame>, _: Option<&V8Context>) { println!("a page's JavaScript context is ready"); } fn on_uncaught_exception( &self, _: Option<&Browser>, _: Option<&Frame>, _: Option<&V8Context>, _: Option<&V8Exception>, _: Option<&V8StackTrace>, ) { println!("a page threw an exception it didn't catch"); } } fn main() { App::new("content").renderer_delegate(Watch).run_or_exit(); } ``` | Method | When it runs | |---|---| | `on_web_kit_initialized` | once per renderer; register V8 extensions and renderer-wide state | | `on_browser_created`, `on_browser_destroyed` | as a browser appears in and leaves the renderer | | `on_context_created`, `on_context_released` | as a page's JavaScript context starts and ends; `window.kurogane` is already there | | `on_uncaught_exception` | when a page throws an exception it doesn't catch | | `on_focused_node_changed` | when the focused element changes | | `on_process_message_received` | for a process message from another process; Kurogane's own IPC never reaches it | | `load_handler` | supplies a load handler for the renderer | Every method has a default that does nothing. Implement the ones you need. ## Where delegates run * Register delegates on the `App` as usual. Chromium runs your binary again for each helper and builds the same `App` there. That's how a renderer gets your renderer delegates. * A renderer delegate's output and log come from the renderer process. Install your `tracing` subscriber before the app starts so helpers log too. See [Logging](https://kurogane-rs.org/docs/guides/logging.md). * Under [`SandboxMode::Chromium`](https://kurogane-rs.org/docs/concepts/sandbox.md) renderers run sandboxed. A renderer delegate then can't reach files, the network or other processes on its own. * For your page to reach Rust use [commands](https://kurogane-rs.org/docs/guides/commands.md). Delegates don't replace IPC. ## Rules for delegates * Several delegates of a kind run in registration order. * For `load_handler` the first delegate that returns a handler wins. * A non-zero return from `on_process_message_received` marks the message handled and keeps it from later delegates. * Kurogane may do its own work before or after a delegate's callback. Don't rely on an order unless a method's docs promise one. * A panic in a delegate aborts the process it runs in. In the browser process that ends your app. In a renderer it ends that renderer. --- # Drive Chromium from winit > Run Kurogane's windows from a winit event loop and pump Chromium when it asks. Your app can keep its own [winit](https://docs.rs/winit) event loop and drive Chromium from it. Kurogane still owns the windows here. To put a browser inside a winit window of your own see [Embed a browser in your window](https://kurogane-rs.org/docs/embedding/child-browsers.md). See [Runtime and event loop](https://kurogane-rs.org/docs/concepts/runtime-and-event-loop.md) for `start`, `pump` and `should_shutdown`. ## Choose how often to pump Chromium's UI thread does its work when your loop calls [`AppInstance::pump`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.pump). The strategies differ only in when they call it: | Strategy | Pumps | Idle cost | Use it for | |---|---|---|---| | Scheduler | at the deadlines Chromium asks for | low | production apps | | Fixed interval | on a timer | a steady wake-up | simple tools | | Every turn | each time the loop turns | a busy core | quick experiments | The scheduler is what CEF recommends for an app that pumps from its own loop. ## Pump when Chromium asks [`App::scheduler`](https://kurogane-rs.org/docs/api/app/app.md#method.scheduler) hands your closure a [`PumpRequest`](https://kurogane-rs.org/docs/api/app/pumprequest.md) whenever Chromium needs a pump. Chromium may call it from any thread. An `EventLoopProxy` carries the deadline to the event loop: ```rust use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use kurogane::{App, AppInstance, PumpRequest}; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy}; use winit::window::WindowId; // The longest the loop waits between pumps, as CEF's cefclient does const MAX_PUMP_DELAY: Duration = Duration::from_millis(1000 / 30); struct Driver { runtime: AppInstance, next_pump: Instant, } impl ApplicationHandler<Instant> for Driver { fn resumed(&mut self, _: &ActiveEventLoop) {} fn user_event(&mut self, _: &ActiveEventLoop, deadline: Instant) { // Keep the earliest; pumping early is harmless self.next_pump = self.next_pump.min(deadline); } fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, _: WindowEvent) {} fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { let now = Instant::now(); if now >= self.next_pump { self.next_pump = now + MAX_PUMP_DELAY; self.runtime.pump(); } if self.runtime.should_shutdown() { self.runtime.shutdown(); event_loop.exit(); return; } event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_pump)); } } fn main() { // Kurogane starts first; the scheduler reaches the loop once it exists let wake: Arc<OnceLock<EventLoopProxy<Instant>>> = Arc::default(); let runtime = App::new("content") .scheduler({ let wake = wake.clone(); move |request: PumpRequest| { if let Some(proxy) = wake.get() { let _ = proxy.send_event(request.deadline(Instant::now())); } } }) .start() .expect("Kurogane failed to start"); #[cfg(target_os = "macos")] let event_loop = { use winit::platform::macos::EventLoopBuilderExtMacOS; EventLoop::<Instant>::with_user_event().with_default_menu(false).build().unwrap() }; #[cfg(not(target_os = "macos"))] let event_loop = EventLoop::<Instant>::with_user_event().build().unwrap(); let _ = wake.set(event_loop.create_proxy()); // The first pump comes at once; requests made before the proxy existed went nowhere let mut driver = Driver { runtime, next_pump: Instant::now() }; event_loop.run_app(&mut driver).unwrap(); } ``` * **The earliest deadline wins.** A later request can't push back one the loop hasn't served yet. * **At least every 33 ms.** CEF doesn't promise to ask again after every pump. Its sample app cefclient never waits longer than 1000/30 ms. This loop does the same. * **Shutdown.** The loop ends on `should_shutdown` and then shuts Chromium down. Kurogane's windows close themselves as usual. ## Start Kurogane before winit Build the `App` and start it before winit's event loop exists. On macOS Kurogane installs the `NSApplication` subclass Chromium needs. That must happen before winit creates the application. The scheduler reads the proxy through a `OnceLock` for that reason. The first pump covers the requests made before the loop existed. ## Keep the Edit menu on macOS Kurogane installs the standard App, Edit and Window menus when it starts. winit replaces them at launch with an App menu alone. Without an Edit menu Cmd+C, Cmd+V and Cmd+A reach no page. Build the loop with `with_default_menu(false)` as the example does, or install a menu of your own. Quit (Cmd+Q or the Dock's) closes Kurogane's browsers. The loop ends once `should_shutdown` turns true. ## On Linux Under an external pump `pump` also runs glib's default main context. Chromium reads its X11 and Wayland events there, such as input, a window's close and resizes. Your loop needs no glib of its own. ## Pump on a timer or every turn Without `App::scheduler` Chromium doesn't say when it needs a pump. Pump on your own schedule instead: ```rust use std::time::{Duration, Instant}; use kurogane::AppInstance; use winit::event_loop::{ActiveEventLoop, ControlFlow}; const PUMP_INTERVAL: Duration = Duration::from_millis(16); fn about_to_wait(runtime: &AppInstance, next_pump: &mut Instant, event_loop: &ActiveEventLoop) { if Instant::now() >= *next_pump { runtime.pump(); *next_pump = Instant::now() + PUMP_INTERVAL; } if runtime.should_shutdown() { event_loop.exit(); return; } event_loop.set_control_flow(ControlFlow::WaitUntil(*next_pump)); } ``` A timer wakes your app while Chromium is idle. A longer interval wakes it less and makes animations stutter. `ControlFlow::Poll` with a pump on every turn works too and keeps a core busy. ## Run the examples The Kurogane repository has each strategy as a runnable example in `kurogane-suite/winit`. From `kurogane-suite`: ```bash kurogane run --example winit_views_scheduler ``` The others are `winit_views_poll`, `winit_views_timer` and `winit_native_embedding`. --- # Embed a browser in your window > Place Chromium browsers inside windows your app owns, keep them laid out and close them cleanly. An app started with [`App::start_embedded`](https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded) owns its windows. Kurogane opens none. [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser) places a browser inside a window of yours as a native child window. Your app decides where it sits, when it moves and when it closes. Use it for a web view inside an existing app, such as a settings panel in a game or a tool window. ## A complete example This winit app embeds one browser that fills its window. It pumps Chromium as [Drive Chromium from winit](https://kurogane-rs.org/docs/embedding/winit.md) does: ```rust use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use kurogane::{App, AppInstance, BrowserBounds, BrowserHandle, PumpRequest}; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy}; use winit::window::{Window, WindowId}; const MAX_PUMP_DELAY: Duration = Duration::from_millis(1000 / 30); struct Host { runtime: AppInstance, window: Option<Window>, browser: Option<BrowserHandle>, next_pump: Instant, } impl ApplicationHandler<Instant> for Host { fn resumed(&mut self, event_loop: &ActiveEventLoop) { if self.window.is_some() { return; } let window = event_loop.create_window(Window::default_attributes().with_title("Host")).unwrap(); match self.runtime.create_child_browser(&window, client_bounds(&window), "app://app/index.html") { Ok(browser) => self.browser = Some(browser), Err(e) => eprintln!("the browser could not be created:\n{e}"), } self.window = Some(window); } fn user_event(&mut self, _: &ActiveEventLoop, deadline: Instant) { self.next_pump = self.next_pump.min(deadline); } fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, event: WindowEvent) { match event { WindowEvent::CloseRequested => { // Start closing the browsers; the window stays until they're gone self.runtime.handle().close_all_browsers(true); } WindowEvent::Resized(_) => { // Chromium placed the browser once; keep it filling the window if let (Some(browser), Some(window)) = (&self.browser, &self.window) { browser.set_bounds(client_bounds(window)); } } _ => {} } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { let now = Instant::now(); if now >= self.next_pump { self.next_pump = now + MAX_PUMP_DELAY; self.runtime.pump(); } if self.runtime.should_shutdown() { self.window = None; self.runtime.shutdown(); event_loop.exit(); return; } event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_pump)); } } /// Returns the window's client area in the units a child browser takes. fn client_bounds(window: &Window) -> BrowserBounds { let size = window.inner_size(); #[cfg(target_os = "macos")] let size = size.to_logical::<u32>(window.scale_factor()); BrowserBounds { x: 0, y: 0, width: size.width as i32, height: size.height as i32 } } fn main() { let wake: Arc<OnceLock<EventLoopProxy<Instant>>> = Arc::default(); let runtime = App::new("content") .scheduler({ let wake = wake.clone(); move |request: PumpRequest| { if let Some(proxy) = wake.get() { let _ = proxy.send_event(request.deadline(Instant::now())); } } }) .start_embedded() .expect("Kurogane failed to start"); // Chromium takes an X11 window as a parent on Linux #[cfg(target_os = "linux")] let event_loop = { use winit::platform::x11::EventLoopBuilderExtX11; EventLoop::<Instant>::with_user_event().with_x11().build() }; #[cfg(target_os = "macos")] let event_loop = { use winit::platform::macos::EventLoopBuilderExtMacOS; EventLoop::<Instant>::with_user_event().with_default_menu(false).build() }; #[cfg(not(any(target_os = "linux", target_os = "macos")))] let event_loop = EventLoop::<Instant>::with_user_event().build(); let event_loop = event_loop.unwrap(); let _ = wake.set(event_loop.create_proxy()); let mut host = Host { runtime, window: None, browser: None, next_pump: Instant::now() }; event_loop.run_app(&mut host).unwrap(); } ``` The same works with any window that hands out a [`raw_window_handle`](https://kurogane-rs.org/docs/api.md#re-exports) window handle. ## Keep the browser laid out Chromium places a child browser once, at the [`BrowserBounds`](https://kurogane-rs.org/docs/api/app/browserbounds.md) you give `create_child_browser`: * **Windows and Linux.** The browser doesn't follow your window. Call [`BrowserHandle::set_bounds`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.set_bounds) whenever its place changes. A browser that fills the window needs it on every resize. * **macOS.** The browser stretches with its parent view by itself. `set_bounds` places it anywhere else. Bounds are in your window's own coordinates. They're pixels from the top-left of the client area on Windows and X11. On macOS they're points in the parent view. That's why the example converts winit's `inner_size` with `to_logical`. A width or height below one counts as one. [`BrowserHandle::notify_move_or_resize_started`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.notify_move_or_resize_started) tells the browser your window is about to move or resize. Chromium uses it on Windows and Linux. ## Several browsers in one window Each `create_child_browser` call places another browser. Give each its own bounds and keep each one's `BrowserHandle` to lay it out. A closed browser takes only its own child window. Your window stays open with the others in it. [`AppInstance::create_child_browser_with_request_context`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser_with_request_context) gives a browser its own cookie and cache partition. ## Linux needs an X11 parent Chromium takes an X11 window as the parent. winit's `with_x11()` gives one. In a Wayland session that window runs under XWayland. A Wayland surface can't be a parent. `create_child_browser` refuses it with [`RuntimeError::UnsupportedParentWindow`](https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.UnsupportedParentWindow). For the same reason Kurogane runs Chromium itself on X11 in an embedded app. Under Wayland it would draw the page beside your window instead of inside it. ## Close the browsers before the window Closing is asynchronous. A close request starts it and the pump finishes it: 1. On your window's close request, call `close_all_browsers(true)`. Don't leave the loop yet. 2. Keep pumping. The browsers close inside `pump`. 3. Once `should_shutdown` turns true, release your window, call `AppInstance::shutdown` and leave the loop. > [!WARNING] > Leaving the loop or dropping your window on the close request stops the pump. The browsers never finish closing and `should_shutdown` never turns true. Your window must outlive the browsers in it. End on `should_shutdown`, not on a flag of your own. On macOS Quit closes every browser without a close request to your window. See [Lifecycle and shutdown](https://kurogane-rs.org/docs/concepts/lifecycle-and-shutdown.md#embedded-apps). ## What differs from Kurogane's windows | Behavior | Embedded browser | |---|---| | Start window | none; `App::window` is a configuration error | | Chromium's keyboard shortcuts | none run; `on_key` still sees every key | | Ctrl+C | no handler; your app handles it | | Drags from other apps | reach [`on_drag_enter`](https://kurogane-rs.org/docs/guides/drags.md) | | Title changes | reach `on_title_change` with no window; title your window yourself | | Fullscreen | Kurogane doesn't resize the browser; your app does | | Context menu | Kurogane's menu, drawn by Chromium; `&` in labels is removed | | `on_window_closing` | not asked | --- # Bundle your app > Package your app with its frontend and the Chromium runtime for Linux, Windows and macOS. `kurogane bundle` turns your project into an app you can hand to other people. The bundle carries your binary, your built frontend and the Chromium runtime. ```bash kurogane bundle ``` It builds a directory on Linux and Windows and a `.app` with a `.dmg` on macOS. The result lands in `dist/`. > [!NOTE] > Bundles are platform-specific. Build each platform's bundle on that platform. A Linux AppImage can't come from Windows and a macOS `.app` can't come from Linux. ## Formats | Format | Command | Platform | Output | |---|---|---|---| | Directory | `kurogane bundle --format dir` | Linux, Windows | `dist/` | | AppImage | `kurogane bundle --format appimage` | Linux | `dist/<name>_<version>_<arch>.AppImage` | | NSIS installer | `kurogane bundle --format nsis` | Windows | `dist/<name>_<version>_x64-setup.exe` | | App bundle | `kurogane bundle --format app` | macOS | `dist/<Name>.app` and `dist/<Name>.dmg` | Every format starts from the same verified bundle. AppImage and NSIS wrap the directory bundle as it is. See [Bundle layouts](https://kurogane-rs.org/docs/shipping/bundle-layouts.md) for what each holds. ## Options | Option | What it does | |---|---| | `--format <format>` | picks the format; `app` on macOS and `dir` elsewhere by default | | `--debug` | builds with Cargo's dev profile instead of release | | `--sign` | signs the Windows binaries or the macOS app; see [Code signing](https://kurogane-rs.org/docs/shipping/signing.md) | | `--ci` | never prompts | ## What you need | For | Needs | |---|---| | every bundle | Rust and the Chromium runtime; `kurogane bundle` installs the runtime when it's missing | | `--format nsis` | [NSIS](https://nsis.sourceforge.io), or `NSIS_PATH` set to `makensis.exe` | | `--format app` | `hdiutil` and `sips` (for an icon); both ship with macOS | | `--format appimage` | nothing extra; the first run downloads a pinned, checksummed linuxdeploy into Kurogane's cache | | `--sign` | `osslsigncode` or `signtool.exe` on Windows, `codesign` on macOS | An app needs at least the glibc of the machine that built it. Build Linux bundles on the oldest distribution you support. ## The frontend goes in first `kurogane bundle` runs `frontend-build` from `kurogane.toml`, builds your Rust code in release mode and copies `frontend-dist` into the bundle's `content`: ```toml [app] frontend-dist = "frontend/dist" frontend-build = "npm --prefix frontend run build" ``` Your release build loads it with `App::new("content")`. That resolves inside the bundle wherever the app starts from. See [app:// and your frontend](https://kurogane-rs.org/docs/concepts/app-protocol.md#relative-directories-in-a-bundle). Without `frontend-build` build the frontend yourself before bundling. Without `frontend-dist` the bundle has no frontend. That suits an app that loads a URL or serves its own scheme. ## Name and describe your app `[app]` in `kurogane.toml` names the app in its bundles: ```toml [app] name = "Notes" identifier = "com.example.notes" publisher = "Example Corp" description = "A notes app" copyright = "(c) 2026 Example Corp" icon = "assets/icon.png" ``` | Key | Used for | |---|---| | `name` | the display name; defaults to the Cargo package name | | `identifier` | the macOS bundle identifier (default `com.kurogane.<name>`) and the AppImage's window class (default the executable's name) | | `publisher` | the NSIS installer's publisher in Add/Remove Programs | | `description` | the NSIS installer's file description | | `copyright` | the NSIS installer's copyright and branding text | | `icon` | the AppImage icon and the macOS app icon, from a PNG | Give [`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) the same `identifier`. The AppImage's launcher then attaches to your windows. ### Per platform ```toml [linux] categories = ["Development", "IDE"] terminal = false [macos] minimum-system-version = "13.0" category = "public.app-category.productivity" [macos.privacy] camera = "Calls use your camera." microphone = "Calls use your microphone." [windows] start-menu-shortcut = true desktop-shortcut = true ``` * `[linux]` sets the desktop entry's categories and whether it runs in a terminal. The default category is `Utility`. * `[macos]` sets the oldest macOS the app runs on and its App Store category. The minimum can't go below macOS 12. That's the oldest CEF supports. * `[macos.privacy]` sets what macOS shows when a page asks for the camera or microphone. Every app declares both. Kurogane's generic wording fills any left unset. * `[windows]` sets the NSIS installer's shortcuts. `[macos]`, the `[signing]` tables and each resource entry refuse a key they don't know. The error names it and its line. ## Ship extra files Declare files and directories your app reads at runtime under `[[bundle.resources]]`: ```toml [[bundle.resources]] source = "assets/data" destination = "share/data" ``` `source` is relative to the project root. `destination` is relative to the bundle root and defaults to the source's file name. [`kurogane::resource_dir`](https://kurogane-rs.org/docs/api/app/resource_dir.md) finds them at runtime: ```rust let data = match kurogane::resource_dir() { Some(resources) => resources.join("share/data"), None => std::path::PathBuf::from("assets/data"), }; ``` `resource_dir` is `None` outside a bundle. Fall back to the project's path then. Every link under a resource must lead inside it. A link out of it, a link back to a directory holding it or a link that leads nowhere is refused before anything is packaged. Such a link could otherwise ship a key or a token from elsewhere. ## The Chromium in the bundle Every bundle carries a Chromium runtime traced to an official CEF release: * By default it's tanso's installation of the CEF version your app was built against. `kurogane bundle` installs or repairs it first when it's missing, incomplete or unverified. * `CEF_PATH` names another distribution instead. It must hold a complete runtime, CEF's notices and an `archive.json` naming the exact CEF build for this platform. A `CEF_PATH` that fails a check stops the bundle. It never falls back. A CEF tree you built or extracted by hand has no provenance and is never packaged. That includes `--debug` bundles. Once bundled your app runs the runtime inside its bundle and no other. `kurogane install` downloads from CEF's build server. `CEF_DOWNLOAD_URL` names a mirror instead. ## Checks before a bundle exists Kurogane refuses to write a bundle that wouldn't run: * The executable exists. * The display name and executable name are each one file name on every platform. * The frontend directory has an `index.html`. * Every extra resource exists and its links stay inside it. * The Chromium runtime is complete for the platform. A bundle on disk has passed every check. There is no partial bundle. ## Troubleshooting ### No usable Chromium distribution The CEF version your app loads isn't installed and `kurogane bundle` couldn't install it (for example when offline). Run this once the download can reach CEF's build server: ```bash kurogane install ``` `kurogane doctor` shows the expected version, its path and every installed version. ### CEF_PATH is refused * **No `archive.json`.** The directory has no provenance. Unset `CEF_PATH` or point it at a distribution `export-cef-dir` wrote. * **No `LICENSE.txt` or `CREDITS.html`.** Every bundle carries CEF's notices. Same fix. * **Version or platform mismatch.** The directory holds another CEF build or another platform's. The error names the expected values. ### NSIS not found Install NSIS or point `NSIS_PATH` at it: ```powershell $env:NSIS_PATH = "C:\Program Files\NSIS\makensis.exe" ``` ### linuxdeploy failed Read the tool's output above the error. The desktop entry's `Icon=` must match a file under `usr/share/icons/hicolor/`. Kurogane installs a placeholder when you give no icon. ### The window is blank in a bundle Check that `content/` landed in the bundle. Outside a bundle `App::new("content")` falls back to the working directory. That can hide a frontend the bundle doesn't carry. Use `App::new("content")` rather than an absolute path so the app keeps working when the bundle moves. ### Running an AppImage without FUSE Some CI runners, containers and WSL1 have no FUSE. Extract the image and run its entry point: ```bash ./myapp_1.0.0_x86_64.AppImage --appimage-extract ./squashfs-root/AppRun ``` --- # Bundle layouts > What each bundle format holds, how a bundled app finds its Chromium and how that runtime is verified. This page describes what [`kurogane bundle`](https://kurogane-rs.org/docs/shipping/bundling.md) produces. You don't need it to bundle an app. Read it to debug a bundle, write an installer around one or check what ships. ## What every bundle carries * Your app's binary * The Chromium runtime, laid out as the platform loads it * CEF's notices, `LICENSE.txt` and `CREDITS.html` * Your built frontend in `content/`, when the project has one * The extra files `[[bundle.resources]]` declares The runtime leaves out CEF's development material (`include/`, `cmake/`, `libcef_dll/`, `CMakeLists.txt`, `libcef.lib`), its download records (`archive.json`, the original archive) and CEF's sandbox bootstraps. A sandboxed Windows bundle ships one bootstrap under your app's name. ## Linux directory `--format dir` on Linux: ```text dist/ ├── myapp # launcher script ├── runtime/ │ ├── myapp # your binary │ ├── kurogane-bundle # marker: run only the runtime below │ └── cef/ # the Chromium runtime │ ├── libcef.so │ ├── locales/ │ ├── icudtl.dat │ ├── chrome-sandbox │ └── ... ├── content/ # your frontend │ └── index.html └── assets/ # extra resources ``` Users start the launcher, `./dist/myapp`. It execs the binary in `runtime/` and leaves the working directory alone: ```sh #!/usr/bin/env sh set -eu ROOT="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" # Opt-in library path for libraries the system's loader does not find if [ -n "${KUROGANE_LD_LIBRARY_PATH:-}" ]; then export LD_LIBRARY_PATH="$KUROGANE_LD_LIBRARY_PATH${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" fi exec "$ROOT"/'runtime/myapp' "$@" ``` The binary's path is one single-quoted word. No character of a name expands in the script. ### Library loading The marker tells your app it runs from a bundle. The app loads `libcef.so` by its full path in `runtime/cef`. Nothing is baked in at link time and Kurogane sets no `LD_LIBRARY_PATH`. Some systems, NixOS among them, have a loader that doesn't find libcef's own system libraries. `KUROGANE_LD_LIBRARY_PATH` adds them for one run. It's never set for you: ```bash KUROGANE_LD_LIBRARY_PATH=/nix/store/...-lib ./dist/myapp ``` ### chrome-sandbox `chrome-sandbox` ships without setuid bits. It stays unused unless your app runs under [`SandboxMode::Chromium`](https://kurogane-rs.org/docs/concepts/sandbox.md) on a system without user namespaces. An installer that wants that route makes the bundled `cef/chrome-sandbox` owned by root and setuid (`chown root:root`, `chmod 4755`). ## Windows directory `--format dir` on Windows: ```text dist/ ├── myapp.exe # your binary ├── myapp.exe.manifest # CEF's application manifest ├── kurogane-bundle # marker: run only the runtime here ├── libcef.dll ├── chrome_elf.dll ├── locales/ ├── icudtl.dat ├── v8_context_snapshot.bin ├── content/ # your frontend │ └── index.html └── assets/ # extra resources ``` Chromium sits beside the executable, where CEF's sandbox bootstrap needs it. Your app loads `libcef.dll` by its full path. Chromium's DLLs load from `libcef.dll`'s own directory and never from `PATH`. Keep them together. `myapp.exe.manifest` is the manifest CEF's own executables carry. Windows reads it when the executable embeds none. An app whose `build.rs` calls `kurogane_build::build()` embeds the same one. ### Sandboxed With `sandbox = true` under `[app]` CEF's windowed bootstrap takes your app's name and your app becomes a library beside it: ```text dist/ ├── myapp.exe # CEF's bootstrap, under your app's name ├── myapp.dll # your app ├── myapp.exe.manifest ├── kurogane-bundle ├── libcef.dll └── ... ``` CEF finds the library by the bootstrap's name in the bootstrap's directory. The bundler keeps the two names in step. Sign both binaries or neither. The bootstrap refuses to load a library unless both are unsigned or both carry the same valid certificate. `kurogane bundle --sign` signs every binary in the bundle. ## Linux AppImage `--format appimage` wraps the Linux directory bundle as it is: ```text squashfs-root/ # ./myapp.AppImage --appimage-extract ├── AppRun # execs the bundle's launcher ├── myapp.desktop ├── myapp.png ├── .DirIcon -> myapp.png └── usr/ ├── lib/myapp/ # the directory bundle, unchanged ├── share/applications/myapp.desktop └── share/icons/hicolor/256x256/apps/myapp.png ``` * `usr/lib/<name>/` is exactly what `--format dir` produces and passes the same checks. * linuxdeploy adds the desktop integration and the system libraries Chromium links against, such as nss, glib and atk. Kurogane keeps it from copying, stripping or relinking the bundle and from duplicating the Chromium runtime. * The desktop entry names the window class (`StartupWMClass`) from `[app].identifier`, or the executable's name without one. Give [`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) the same value. * The desktop entry's `Version=` is the specification's version, `1.0`. Your app's version goes in `X-AppImage-Version=`. An AppImage mounts `nosuid`. Under the sandbox it relies on user namespaces. ## Windows installer `--format nsis` installs the verified directory bundle whole: ```text dist/ ├── myapp_1.0.0_x64-setup.exe # the installer ├── bundle/ # the staged bundle └── installer.nsi # the generated script ``` The installer: * installs per user, into `%LOCALAPPDATA%` by default * creates Start Menu and Desktop shortcuts as `[windows]` asks * registers in **Add or remove programs** under the current user * ships an uninstaller that removes the installation, the shortcuts and the registry keys ## macOS app `--format app` keeps the CEF framework whole inside the `.app`: ```text dist/ ├── MyApp.dmg # the app beside a link to /Applications └── MyApp.app/ └── Contents/ ├── Info.plist ├── MacOS/ │ └── myapp # your binary ├── Frameworks/ │ ├── Chromium Embedded Framework.framework/ │ ├── MyApp Helper.app/ │ ├── MyApp Helper (GPU).app/ │ ├── MyApp Helper (Plugin).app/ │ ├── MyApp Helper (Renderer).app/ │ └── MyApp Helper (Alerts).app/ └── Resources/ ├── AppIcon.icns # from [app].icon ├── Chromium Embedded Framework/ # CEF's notices └── content/ # your frontend ``` Both are named after `[app].name`, or the crate's name without one. There is no macOS `--format dir`. A flat directory couldn't be signed or double-clicked. ### What the app declares Every `Info.plist` in the bundle declares: * `LSMinimumSystemVersion`, from `[macos] minimum-system-version` or else `12.0`, the oldest macOS CEF runs on * `NSCameraUsageDescription` and `NSMicrophoneUsageDescription`, from `[macos.privacy]` or Kurogane's generic wording The app's own plist also carries `LSApplicationCategoryType` from `[macos] category`, `public.app-category.utilities` by default. Kurogane checks these values before anything is built on macOS. ### Helpers Each helper is your binary again under its own bundle identifier. See [Process model](https://kurogane-rs.org/docs/concepts/process-model.md#helpers-on-macos). The app finds the `<name> Helper.app` bundle whatever the `.app` is called. A `.app` without exactly one refuses to start and says to reinstall. ### The framework The app links the framework at `@executable_path/../Frameworks`. The helpers reach the same folder from inside their bundles. There is no RPATH. Each executable reaches only the framework of its own bundle wherever the bundle moves. A bundled app uses its own framework even when `CEF_PATH` is set. A binary from `cargo build` or `kurogane run` links no framework and opens the installed one by path. ## How a bundled app finds its runtime The `kurogane-bundle` marker, or the `.app` itself on macOS, makes your app run only the Chromium inside its bundle. It never reads `CEF_PATH` or the installation then. A bundle whose runtime is gone reports itself incomplete. Relative paths such as `App::new("content")` resolve against the bundle's resource root: | Platform | Executable | Resource root | |---|---|---| | Linux | `<root>/runtime/<exe>` | `<root>` | | Windows | `<root>/<exe>.exe` | `<root>` | | macOS | `<name>.app/Contents/MacOS/<exe>` | `<name>.app/Contents/Resources` | An unbundled run, `cargo run` among them, loads the first runtime it finds: 1. A runtime beside its executable 2. The runtime `CEF_PATH` names 3. tanso's installation of the CEF version it was built against A `CEF_PATH` that names no directory is an error and never skipped. Loading refuses a libcef from another CEF build than the app was built against. ## How the runtime is verified `kurogane install` writes an `archive.json` into every installation: ```json { "type": "minimal", "name": "cef_binary_154.0.33+ga03e714+chromium-154.0.8037.94_linux64_minimal.tar.bz2", "sha1": "..." } ``` `export-cef-dir` writes one too. A distribution passes when: * the runtime is complete and carries CEF's notices * the CEF version in the archive's name equals your project's exactly; `154.0.33+ga03e714` matches `154.0.33` and `154.0.34` doesn't * the platform matches the target After copying, every format checks the runtime holds what Chromium needs to run: | Linux | Windows | macOS | |---|---|---| | `libcef.so` | `libcef.dll` | the framework and its binary | | `chrome-sandbox` | `chrome_elf.dll` | | | `icudtl.dat` | `icudtl.dat` | `icudtl.dat` | | `locales/` | `locales/` | a `*.lproj` locale | | a V8 snapshot | a V8 snapshot | a V8 snapshot | A bundle on disk has passed this check. ### Resolution errors | Error | Meaning | Fix | |---|---|---| | `NotInstalled` | the CEF version isn't installed and `CEF_PATH` isn't set | `kurogane install` | | `CefPathMissing` | `CEF_PATH` names no directory | correct it | | `InvalidRuntime` | the runtime `CEF_PATH` names is incomplete | point it at a distribution `export-cef-dir` wrote or unset it | | `MissingNotice` | it has no `LICENSE.txt` or `CREDITS.html` | as above | | `Unverified` | it fails verification: `NoArchiveJson`, `UnknownArchive`, `VersionMismatch` or `PlatformMismatch` | as above | | `NoInstallDir` | the user has no local data directory | run as a user with a home directory | | `UnsupportedHost` | CEF publishes no build for this host | bundle on a supported platform | --- # Code signing > Sign your Windows binaries and installer or your macOS app as part of kurogane bundle. Signing is off by default. `--sign` turns it on: ```bash kurogane bundle --format nsis --sign ``` Each platform that signs reads its own table in `kurogane.toml`. `[signing.windows]` covers a Windows bundle's binaries and installer. `[signing.macos]` covers a macOS app. One file serves a project that ships both. The tables hold references to certificates and never secrets or passwords. Linux bundles aren't signed. `--sign` on Linux checks the tables and stops. ## Sign on Windows Name a certificate file or a certificate in the Windows certificate store: ```toml [signing.windows] certificate = "certs/codesign.pfx" certificate-password-env = "CODESIGN_PASSWORD" timestamp-url = "http://timestamp.digicert.com" digest-algorithm = "sha256" ``` | Key | What it is | |---|---| | `certificate` | a certificate file; `.pfx` or `.p12`, or a PEM or DER chain with `osslsigncode` | | `certificate-thumbprint` | a certificate in the Windows certificate store, for `signtool`; never beside `certificate` | | `certificate-password-env` | the environment variable a certificate file's password is read from | | `timestamp-url` | the RFC 3161 timestamp server | | `digest-algorithm` | the digest; `sha256` by default | Keep the password out of `kurogane.toml`. Set the variable in your shell or your CI's secrets: ```powershell $env:CODESIGN_PASSWORD = "..." kurogane bundle --format nsis --sign ``` Kurogane signs every `.exe` and `.dll` in the bundle. With `--format nsis` it signs them before the installer is built and then signs the installer. ### Tools Kurogane uses `signtool.exe` when it finds one and `osslsigncode` otherwise: | Tool | Found at | |---|---| | `signtool.exe` | `KUROGANE_SIGNTOOL_PATH`, then the Windows SDK | | `osslsigncode` | `KUROGANE_OSSLSIGNCODE_PATH`, then `PATH` | `osslsigncode` has no certificate store. A thumbprint with it is an error. ### A signing program of your own `custom-command` runs a program of yours for each file instead of a certificate. Every `%1` in an argument becomes the file's path: ```toml [signing.windows] custom-command = ["azuresigntool", "sign", "-kvu", "https://my-vault.vault.azure.net", "%1"] ``` * Each item is one argument. A path with spaces needs no quoting. * A command without `%1` is an error. * It can't stand beside `certificate`, `certificate-thumbprint`, `certificate-password-env`, `timestamp-url` or `digest-algorithm`. Those would be ignored. What the command signed is still verified. ### Sandboxed apps A sandboxed Windows bundle holds CEF's bootstrap and your app as a library. Sign both or neither. The bootstrap refuses to load a library signed otherwise than itself. `--sign` signs both. ## Sign on macOS Name the signing identity from your keychain: ```toml [signing.macos] identity = "Developer ID Application: Example (ABC1234DE5)" ``` ```bash kurogane bundle --format app --sign ``` | Identity | Signs | |---|---| | `Developer ID Application: …` | with a timestamp and the hardened runtime, as distribution requires | | `-` | ad hoc, for local testing only; no timestamp and no hardened runtime | The keychain holds the certificate. The table takes no other key. `codesign` comes from the Xcode Command Line Tools, or from `KUROGANE_CODESIGN_PATH`. ### What gets signed Signing runs from the inside out: 1. The five helper bundles 2. The CEF framework 3. The `.app` with its entitlements 4. The `.dmg`, built from the signed app A failure at any step fails the bundle. No unsigned `.app` is written. Nothing changes signed code afterwards. ### Entitlements The app and its helpers get the exceptions Chromium needs and the devices your app declares: ```xml <dict> <key>com.apple.security.cs.allow-jit</key><true/> <key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/> <key>com.apple.security.cs.disable-library-validation</key><true/> <key>com.apple.security.device.camera</key><true/> <key>com.apple.security.device.audio-input</key><true/> </dict> ``` They're a signing input and never ship inside the app. ### Notarization Kurogane doesn't notarize. `kurogane bundle` stops at a signed `.app` and its signed disk image. Submit the `.dmg` to Apple's notary service yourself. ### Keychain prompts An unsigned build raises a Keychain prompt on every run. Signing ends the prompts. See [Credential storage](https://kurogane-rs.org/docs/guides/credential-storage.md). ## Checks * `--sign` checks every signing table wherever it runs. A mistake in `[signing.macos]` fails a Windows build too. * A table refuses a key it doesn't take, the older flat `[signing]` keys included. The error names the key and its line. * `--sign` fails with an actionable error when this platform's table configures no signing. * The platform's tool verifies every signed file afterwards: `signtool verify`, `osslsigncode verify` or `codesign --verify --deep --strict`. --- # Platforms and requirements > What each platform needs and what behaves differently on Linux, Windows, macOS and Nix. Kurogane installs and finds the Chromium runtime itself. Each platform needs a few system tools. [Install](https://kurogane-rs.org/docs/start/install.md#what-else-you-need) lists them. This page collects what is specific to each platform. | Platform | Architectures | Minimum OS | Formats | |---|---|---|---| | Linux (glibc) | x86_64, aarch64 | glibc 2.31 (Ubuntu 20.04, Debian 11) | directory, AppImage | | Windows | x86_64, ARM64 | Windows 10 | directory, NSIS installer | | macOS | Apple Silicon, Intel | macOS 12 | `.app` and `.dmg` | ## Linux Install a C compiler and Chromium's libraries. Nothing else needs setting up. * **glibc.** An app needs at least the glibc of the machine that built it. Build Linux bundles on the oldest distribution you support. musl systems such as Alpine can run the CLI but not apps. * **Window class.** Windows take the executable's name as their class unless [`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) sets one. An AppImage's desktop entry declares the same class. * **Wayland.** Chromium windows run natively in a Wayland session. Embedded browsers run Chromium on X11 through XWayland. With an NVIDIA GPU Chromium runs on X11 too. * **Sandbox.** It needs unprivileged user namespaces or a setuid `chrome-sandbox`. Ubuntu 24.04 restricts namespaces through AppArmor. See [Sandbox](https://kurogane-rs.org/docs/concepts/sandbox.md#linux). * **GPU report.** `kurogane doctor` reads OpenGL details through `glxinfo`. Install `mesa-utils` for that report on Debian and Ubuntu. * **Signing.** Linux bundles aren't signed. ## Windows Install the Visual Studio C++ Build Tools with the **Desktop development with C++** workload. It includes the Windows SDK. Nothing is compiled from C++ and nothing links Chromium. The Build Tools give Rust its linker. `kurogane dev`, `run` and `bundle` work from any terminal. * **Application manifest.** Your app's `build.rs` calls `kurogane_build::build()` to embed the manifest CEF's own executables carry. Without it Windows tells your app and Chromium they run on Windows 8. * **Sandbox.** CEF's bootstrap starts a sandboxed app and loads it as a library. That takes a library target and `sandbox = true`. See [Sandbox](https://kurogane-rs.org/docs/concepts/sandbox.md#windows). * **GPU.** Without the sandbox GPU work runs inside the browser process. See [GPU mode](https://kurogane-rs.org/docs/guides/gpu-mode.md#hardware-on-each-platform). * **Signing.** `--sign` signs every `.exe` and `.dll` and the installer. See [Code signing](https://kurogane-rs.org/docs/shipping/signing.md#sign-on-windows). ## macOS Install the Xcode Command Line Tools: ```bash xcode-select --install ``` `hdiutil` and `sips` ship with macOS. `--sign` needs `codesign` from the Command Line Tools. * **Menus.** Every app gets the standard App, Edit and Window menus. A winit app keeps them with `with_default_menu(false)`. See [Drive Chromium from winit](https://kurogane-rs.org/docs/embedding/winit.md#keep-the-edit-menu-on-macos). * **Privacy declarations.** Every app declares camera and microphone use with a reason macOS shows when a page asks. `[macos.privacy]` sets your own. * **Minimum version.** Apps run on macOS 12 and later, the oldest CEF supports. `[macos] minimum-system-version` raises it. * **Sandbox.** It needs the app to run from a `.app` bundle. An unbundled `kurogane dev` run refuses `SandboxMode::Chromium`. * **Keychain.** An unsigned build raises a Keychain prompt on every run. Signing ends it. See [Credential storage](https://kurogane-rs.org/docs/guides/credential-storage.md). * **Signing.** `--sign` signs the app inside out and its disk image. Kurogane doesn't notarize. See [Code signing](https://kurogane-rs.org/docs/shipping/signing.md#sign-on-macos). * **Formats.** `--format app` is the default. `--format dir` isn't a macOS format and is refused. ## Nix and NixOS Kurogane has a Nix flake for installing the CLI and for developing Kurogane itself. Nix is optional. | Command | Purpose | |---|---| | `inputs.kurogane` in a system flake | installs Kurogane with your NixOS or Home Manager configuration | | `nix profile add github:0x48piraj/kurogane` | installs the CLI into your user profile | | `nix run github:0x48piraj/kurogane` | runs the CLI without installing it | | `nix develop github:0x48piraj/kurogane` | opens a shell to develop Kurogane itself | [Install](https://kurogane-rs.org/docs/start/install.md#nix-and-nixos) covers the first three, which nixpkgs to follow and GPU drivers. The packaged CLI carries the Chromium runtime with its license, credits and `archive.json`. Its `CEF_PATH` names it. `kurogane run` and `kurogane bundle` use it. No separate CEF installation is needed. Your app needn't be Nix-native because you install Kurogane with Nix. It stays a normal Rust and Cargo project. ### Develop Kurogane with Nix `nix develop` opens a shell with Rust, CEF and the native libraries for building Kurogane from source: ```bash nix develop github:0x48piraj/kurogane cargo build cargo test ``` It doesn't put the packaged CLI on your `PATH`. On `nixos-unstable` open it on your system's nixpkgs so apps built in it load your GPU drivers: ```bash nix develop github:0x48piraj/kurogane --override-input nixpkgs nixpkgs ``` > [!NOTE] > `nix develop` fails when the project's path contains spaces, such as `/home/user/My Projects/kurogane`. That's a known Nix issue ([NixOS/nix#12413](https://github.com/NixOS/nix/issues/12413)). Move the project to a path without spaces. --- # Templates > Start projects from the official starters or a template of your own. Write templates others can use. `kurogane new` generates a project from a template. Every Kurogane template is a [cargo-generate](https://github.com/cargo-generate/cargo-generate) template, the official starters included. A template you write works with `kurogane new` and with plain `cargo generate`. ## Official starters | Starter | Frontend | Repository | |---|---|---| | `minimal` | Vite | [`kurogane-rs/kurogane-starter-minimal`](https://github.com/kurogane-rs/kurogane-starter-minimal) | | `react` | React and Vite | [`kurogane-rs/kurogane-starter-react`](https://github.com/kurogane-rs/kurogane-starter-react) | | `svelte` | Svelte 5 and Vite | [`kurogane-rs/kurogane-starter-svelte`](https://github.com/kurogane-rs/kurogane-starter-svelte) | | `vue` | Vue 3 and Vite | [`kurogane-rs/kurogane-starter-vue`](https://github.com/kurogane-rs/kurogane-starter-vue) | Each comes in TypeScript and JavaScript. `kurogane new` without arguments asks for a starter, a language and a name. Name them to skip the questions: ```bash kurogane new react --language javascript --name my-app ``` The CLI fetches each starter from its repository's default branch. The project directory takes the name in kebab-case. Generated projects aren't git repositories and never join a parent Cargo workspace. ## Generate from your own template `--template` takes a local path, a git URL or a cargo-generate shorthand (`gh:`, `gl:`, `bb:`, `sr:` or `user/repo` for GitHub): ```bash kurogane new --template gh:user/repo ``` ```bash kurogane new --template ./my-template ``` A starter name and `--template` can't be combined. Private repositories use your git credentials and SSH agent. Every run fetches a git template again into a snapshot in Kurogane's cache. A run that can't fetch it generates from the last snapshot and says how old it is. `kurogane clean` removes the snapshots. ### Answer placeholders from a file A template's placeholders are asked for interactively. `--values` takes them from a TOML file instead: ```toml [values] language = "javascript" ``` ```bash kurogane new --template gh:user/repo --name my-app --values answers.toml --ci ``` A values file gives the same answers on every run and every machine. `--language` sets the `language` placeholder of any template. ### Hooks A template can run Rhai hooks during generation. cargo-generate asks before a hook runs a command and shows the command. `--yes` lets hooks run commands without asking. A run with `--ci` and without `--yes` refuses any command a hook asks for. > [!CAUTION] > Pass `--yes` only for templates you trust. Hook scripts are never inspected. The official starters have no hooks. ## Add Kurogane to an existing app `kurogane init` adds the Rust side to an existing frontend project in the current directory. It writes `Cargo.toml`, `build.rs`, `kurogane.toml` and `src/main.rs`: ```bash kurogane init --assets dist --dev-url http://localhost:5173 ``` * It never overwrites a file. It refuses to run when `kurogane.toml`, `Cargo.toml` or `src/main.rs` already exists. * It asks for the build output directory and the dev server URL unless `--assets` and `--dev-url` give them. A run with `--ci` needs both. * `--assets` becomes `frontend-dist` in `kurogane.toml`. `--dev-url ""` makes debug builds load the build output instead of a dev server. See [Project layout](https://kurogane-rs.org/docs/start/project-layout.md#projects-from-kurogane-init) for the result. ## Write a template Start from an official starter. Fork it, change it and publish it. ```text Cargo.toml # the app crate, depending on kurogane and kurogane-build build.rs # calls kurogane_build::build() kurogane.toml # the Kurogane manifest src/main.rs # the entry point frontend/ # a self-contained frontend project cargo-generate.toml # placeholders and conditional files ``` `cargo-generate.toml` is read during generation and never copied into the project. The other files become the project. See [Project layout](https://kurogane-rs.org/docs/start/project-layout.md) for what each does. ### Placeholders Every file is rendered with [Liquid](https://shopify.github.io/liquid/). cargo-generate always provides `{{project-name}}` as typed and `{{crate_name}}` in snake case: ```toml [package] name = "{{crate_name}}" ``` Declare your own placeholders in `cargo-generate.toml`. One with a default and choices takes its value from `--language`, `--values`, the prompt or its default under `--ci`: ```toml [placeholders.language] type = "string" prompt = "Language" default = "typescript" choices = ["typescript", "javascript"] ``` Keep placeholders for real choices. Values every project shares belong in the files as they are. ### Language variants Keep both languages in one `frontend/` folder. Leave out the files one language doesn't need by condition: ```toml [conditional.'language == "typescript"'] ignore = ["frontend/main.js"] [conditional.'language == "javascript"'] ignore = ["frontend/main.ts"] ``` Files both languages share differ inline: ```html <script type="module" src="/main.{% if language == "typescript" %}ts{% else %}js{% endif %}"></script> ``` That needs no hook. Generating asks for no consent. ### Frontend syntax that looks like Liquid Wrap your framework's template syntax in `{% raw %}` so Liquid leaves it alone: ```vue <h1>{% raw %}{{ message }}{% endraw %}</h1> ``` ### Pin Kurogane Pin `kurogane` and `kurogane-build` to the same release. Every generated project then builds the same way: ```toml [dependencies] kurogane = "=<version>" [build-dependencies] kurogane-build = "=<version>" ``` ### Test it Generate from your working copy once per variant: ```bash kurogane new --template ./my-template --name check-ts --language typescript --ci ``` ```bash kurogane new --template ./my-template --name check-js --language javascript --ci ``` Then install, build and run each project as a user would. ### Publish it Push the template to a git host. Users generate from it by its shorthand: ```bash kurogane new --template gh:you/kurogane-template ``` Generated projects need no setup of their own. `kurogane dev` installs the Chromium runtime when it's missing. A template needs no `.cargo/config.toml` or linker flags for it. --- # CLI reference > Every command of the `kurogane` CLI 0.0.6-beta.1, generated from its own definitions. ```text kurogane [OPTIONS] <COMMAND> ``` ## Global options - `--ci`: Never prompt; a true `CI` environment variable does the same - `-h, --help`: print a command's help - `-V, --version`: print the CLI's version ## `kurogane install` Install the Chromium runtime the project uses. Outside a project, installs the version this CLI was built with. ```text kurogane install [OPTIONS] ``` ## `kurogane dev` Run the application, installing its Chromium runtime when missing ```text kurogane dev [OPTIONS] ``` ## `kurogane run` Run the application with Cargo, installing its Chromium runtime when missing. Unlike `dev`, this command passes arguments directly to Cargo. ```text kurogane run [OPTIONS] [CARGO_ARGS]... ``` - `[CARGO_ARGS]...`: Arguments for Cargo. Those after `--` reach the application ## `kurogane bundle` Build the application and package it for distribution ```text kurogane bundle [OPTIONS] ``` - `--debug`: Build with Cargo's dev profile instead of release - `--format <FORMAT>`: Package format (dir or appimage on Linux, dir or nsis on Windows, app on macOS). The default is app on macOS and dir elsewhere - `--sign`: Sign the bundle's Windows binaries ([signing.windows]) or macOS app ([signing.macos]). Linux bundles are not signed ## `kurogane new` Create a project from a starter or template ```text kurogane new [OPTIONS] [STARTER] ``` - `[STARTER]`: Official starter (minimal, react, svelte or vue) - `--name <NAME>`: Project name - `--language <LANGUAGE>`: Starter language - `--template <TEMPLATE>`: Use a template from a local path, git URL or cargo-generate shorthand such as gh:owner/repository - `--values <FILE>`: Read placeholder values from this TOML file - `--yes`: Allow the template's hooks to run commands without asking ## `kurogane init` Add Kurogane to an existing frontend project ```text kurogane init [OPTIONS] ``` - `--assets <ASSETS>`: Frontend assets directory - `--dev-url <DEV_URL>`: Dev server URL - `--yes`: Allow the template's hooks to run commands without asking ## `kurogane clean` Remove the project's dist/ and Kurogane's caches ```text kurogane clean [OPTIONS] [TARGET] ``` - `[TARGET]`: `all` also removes tanso's shared Chromium installation, build tools and every application profile One of `all`. - `--yes`: Accept the confirmation without prompting ## `kurogane showcase` Run Kurogane's showcase application ```text kurogane showcase [OPTIONS] ``` - `--yes`: Allow the template's hooks to run commands without asking ## `kurogane doctor` Check the Chromium runtime, toolchain and project ```text kurogane doctor [OPTIONS] ``` - `--json`: Print the full report as JSON ## `kurogane list` List application profiles and versions ```text kurogane list [OPTIONS] [TARGET] ``` - `[TARGET]`: Only profiles or only versions; both by default One of `profiles`, `version`. ## `kurogane info` Show the CLI, environment and project configuration ```text kurogane info [OPTIONS] ``` ## `kurogane self` Manage the kurogane CLI itself ```text kurogane self [OPTIONS] <COMMAND> ``` Subcommands: `self uninstall` ## `kurogane self uninstall` Remove an installer-managed Kurogane installation. Removes the CLI, PATH setup, Kurogane's caches and tanso's shared Chromium runtimes, which other tanso projects use too. Application profiles and unmanaged installations are preserved. ```text kurogane self uninstall [OPTIONS] ``` - `--yes`: Accept the confirmation without prompting - `--keep-data`: Keep the installed Chromium runtimes and caches --- # Manifest reference > Every table and key of `kurogane.toml` for Kurogane 0.0.6-beta.1, generated from the CLI's own definitions. `kurogane.toml` sits at the project root. The file is optional. Without it or one of its keys the defaults apply. Paths are relative to the project root. ## `[app]` Application identity, frontend and sandbox. Keys this table doesn't take are ignored. - `copyright` (string): Copyright and branding text of an NSIS installer. - `description` (string): File description of an NSIS installer. - `frontend` (string): Frontend source directory relative to the project root. - `frontend-build` (string): Command `kurogane bundle` runs to build the frontend before `cargo build`. It runs from the project root through `sh`, or `cmd` on Windows. - `frontend-dist` (string): Frontend build output that `kurogane bundle` packages, relative to the project root. - `frontend-install` (string): Command that installs the frontend's dependencies. `kurogane new` prints it in its next steps. - `frontend-run` (string): Command that starts the frontend's dev server. `kurogane new` prints it in its next steps. - `icon` (string): PNG icon of an AppImage and a macOS `.app`, relative to the project root. - `identifier` (string): Reverse-DNS identifier, such as `com.example.notes`. It is the macOS `CFBundleIdentifier` (`com.kurogane.<name>` without it) and the window class an AppImage's desktop entry names (the executable's name without it). - `name` (string): Display name. Defaults to the Cargo package name. - `publisher` (string): Publisher an NSIS installer names in Add/Remove Programs. - `sandbox` (boolean): Whether the application enters Chromium's sandbox. When enabled, the CLI builds and starts the application with platform-specific setup required by the sandbox. The runtime policy is selected separately with `App::sandbox_mode`. Default `false`. ## `[bundle]` Bundle contents. Keys this table doesn't take are ignored. ## `[[bundle.resources]]` Extra files and directories every bundle carries. A key this table doesn't take is an error naming it. - `destination` (string): Place inside the bundle relative to its root. Defaults to the source's file name. - `source` (string): File or directory to bundle, relative to the project root. ## `[linux]` Linux desktop entry. Keys this table doesn't take are ignored. - `categories` (array of strings): Categories of an AppImage's desktop entry. Defaults to `Utility`. - `terminal` (boolean): Whether an AppImage's desktop entry runs in a terminal. Defaults to false. ## `[macos]` macOS `Info.plist` declarations. A key this table doesn't take is an error naming it. - `category` (string): `LSApplicationCategoryType`, one of Apple's `public.app-category.*` values. - `minimum-system-version` (string): `LSMinimumSystemVersion`, such as `"13.0"`. Unset means CEF's own floor. No value goes below that floor. ## `[macos.privacy]` Why the application uses each device. A key this table doesn't take is an error naming it. - `camera` (string): `NSCameraUsageDescription`. - `microphone` (string): `NSMicrophoneUsageDescription`. ## `[windows]` Windows installer. Keys this table doesn't take are ignored. - `desktop-shortcut` (boolean): Whether an NSIS installer creates a Desktop shortcut. Default `true`. - `start-menu-shortcut` (boolean): Whether an NSIS installer creates a Start Menu shortcut. Default `true`. ## `[signing]` Code signing. A key this table doesn't take is an error naming it. ## `[signing.macos]` Signing for a macOS `.app`. A key this table doesn't take is an error naming it. - `identity` (string): Codesign identity from the keychain. `-` signs ad hoc. ## `[signing.windows]` Signing for the PE files of a Windows bundle and installer. A key this table doesn't take is an error naming it. - `certificate` (string): Certificate file, a `.pfx` or `.p12` or with `osslsigncode` a PEM or DER chain. - `certificate-password-env` (string): Environment variable a certificate file's password is read from. - `certificate-thumbprint` (string): Thumbprint of a certificate in the Windows certificate store, for `signtool`. Never beside `certificate`. - `custom-command` (array of strings): A program and its arguments; `%1` in an argument is the file to sign. - `digest-algorithm` (string): Digest algorithm. Defaults to `sha256`. - `timestamp-url` (string): RFC 3161 timestamp server. --- # API reference > Every public item of the `kurogane` crate 0.0.6-beta.1, grouped by topic. A composable Chromium runtime for Rust. Build high-performance, GPU-accelerated desktop applications on Chromium or embed it directly into existing applications. Guides, concepts and the CLI reference are at <https://kurogane-rs.org/docs>. ## A first app ```rust use kurogane::{App, AppHandle, IpcError}; fn greet(name: String, _: &AppHandle) -> Result<String, IpcError> { Ok(format!("Hello, {name}!")) } fn main() { App::new("content").command("greet", greet).run_or_exit(); } ``` The page calls the command with `window.kurogane.invoke("greet", "Kurogane")` and gets `"Hello, Kurogane!"` back. ## Where to start * [`App`] describes an application and starts it. * [`AppInstance`] is the running application, owned by the thread that started it. [`AppHandle`] reaches it from any thread. * [`BrowserHandle`] drives one browser. * [`WindowOptions`] describes an application window. ## Talking to the page * [`App::command`] registers a command. Its async and binary forms answer later or take bytes. A handler fails with an [`IpcError`]. * [`AppHandle::broadcast_json`] sends an event to every subscribed page. * [`App::stream`] registers a [`StreamHandler`] for chunks in both directions. * [`App::permit`] opens a command or stream to another origin. * [`capability::Filesystem`] grants pages scoped access to files. ## Deciding what a page may do Hooks such as [`App::on_new_window`], [`App::on_navigation`], [`App::on_download`] and [`App::on_permission`] take a typed request. Each answers with a decision whose `Default` leaves the choice to Kurogane. ## Processes Chromium runs your binary again for each of its helper processes. Code before the call that starts the runtime runs in every process. Guard one-time work with [`is_browser_process`]. See [`App`]. ## Your own event loop [`App::start`] and [`App::start_embedded`] start Chromium without its message loop. Your loop calls [`AppInstance::pump`] until [`AppInstance::should_shutdown`] turns true and then [`AppInstance::shutdown`]. [`AppInstance`]: https://kurogane-rs.org/docs/api/app/appinstance.md [`AppHandle`]: https://kurogane-rs.org/docs/api/app/apphandle.md [`App::on_download`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_download [`BrowserHandle`]: https://kurogane-rs.org/docs/api/app/browserhandle.md [`App::on_new_window`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window [`IpcError`]: https://kurogane-rs.org/docs/api/ipc/ipcerror.md [`App::permit`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit [`App::start_embedded`]: https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded [`App`]: https://kurogane-rs.org/docs/api/app/app.md [`AppHandle::broadcast_json`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.broadcast_json [`App::stream`]: https://kurogane-rs.org/docs/api/app/app.md#method.stream [`capability::Filesystem`]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md [`App::on_navigation`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation [`App::start`]: https://kurogane-rs.org/docs/api/app/app.md#method.start [`AppInstance::pump`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.pump [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown [`WindowOptions`]: https://kurogane-rs.org/docs/api/windows/windowoptions.md [`is_browser_process`]: https://kurogane-rs.org/docs/api/app/is_browser_process.md [`StreamHandler`]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md [`App::command`]: https://kurogane-rs.org/docs/api/app/app.md#method.command [`App::on_permission`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_permission [`AppInstance::should_shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.should_shutdown ## Topics - [App and runtime](https://kurogane-rs.org/docs/api/app.md): Configures an application, starts the runtime and reaches it once it runs. - [Windows and browsers](https://kurogane-rs.org/docs/api/windows.md): Opens windows, places them and names the browsers inside them. - [IPC](https://kurogane-rs.org/docs/api/ipc.md): Commands, streams and errors between your Rust code and the page. - [Capabilities](https://kurogane-rs.org/docs/api/capabilities.md): Grants a page scoped access to the filesystem. - [Requests and decisions](https://kurogane-rs.org/docs/api/requests.md): What a page or Chromium asks of your application and the answers it can give. ## Re-exports - [`raw_window_handle`](https://docs.rs/raw_window_handle) - [`tanso`](https://docs.rs/tanso) --- # App and runtime > Configures an application, starts the runtime and reaches it once it runs. - [`App`](https://kurogane-rs.org/docs/api/app/app.md) (struct): Public application builder. - [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md) (struct): Shared lifecycle handle for a running Kurogane application. - [`AppInstance`](https://kurogane-rs.org/docs/api/app/appinstance.md) (struct): The running application, owned by the thread that started it. - [`BrowserBounds`](https://kurogane-rs.org/docs/api/app/browserbounds.md) (struct): A browser's place inside its parent window, for `AppInstance::create_child_browser` and `BrowserHandle::set_bounds`. It is a position and a size in that window's own coordinates, which CEF applies unconverted. Pixels from the top-left of the client area on Windows and X11; on macOS, points in the parent `NSView`, whose origin is its top-left corner when the view is flipped (winit's is) and its bottom-left corner otherwise. - [`BrowserHandle`](https://kurogane-rs.org/docs/api/app/browserhandle.md) (struct): A browser of the running application. - [`SecondInstance`](https://kurogane-rs.org/docs/api/app/secondinstance.md) (struct): A launch of the application while another instance is already running. - [`CefLocation`](https://kurogane-rs.org/docs/api/app/ceflocation.md) (enum): Where the application found its Chromium runtime, in the order it looks. - [`ConfigError`](https://kurogane-rs.org/docs/api/app/configerror.md) (enum): One problem in the [`App`](https://kurogane-rs.org/docs/api/app/app.md) builder configuration, reported by `build()` / `run()` / `start_embedded()` as `RuntimeError::InvalidConfiguration`. - [`CredentialStorage`](https://kurogane-rs.org/docs/api/app/credentialstorage.md) (enum): Backend used to protect cookies and saved passwords at rest. - [`GpuMode`](https://kurogane-rs.org/docs/api/app/gpumode.md) (enum): GPU backend selection strategy. - [`PumpRequest`](https://kurogane-rs.org/docs/api/app/pumprequest.md) (enum): A request from CEF indicating when it next needs to be serviced. - [`RuntimeError`](https://kurogane-rs.org/docs/api/app/runtimeerror.md) (enum): Failure to start the application or to open a window or a browser. - [`SandboxMode`](https://kurogane-rs.org/docs/api/app/sandboxmode.md) (enum): Chromium process sandbox policy. - [`ClientAppBrowserDelegate`](https://kurogane-rs.org/docs/api/app/clientappbrowserdelegate.md) (trait): Customizes browser-process startup behavior. - [`ClientAppRendererDelegate`](https://kurogane-rs.org/docs/api/app/clientapprendererdelegate.md) (trait): Customizes render-process behavior. - [`SchemeHandler`](https://kurogane-rs.org/docs/api/app/schemehandler.md) (trait): Generates a `ResourceHandler` for requests on a custom scheme. - [`is_browser_process`](https://kurogane-rs.org/docs/api/app/is_browser_process.md) (function): Returns whether this process is Chromium's browser process rather than one of its helper processes (renderer, GPU, utility) which run this same binary again with a `--type=` argument. - [`resource_dir`](https://kurogane-rs.org/docs/api/app/resource_dir.md) (function): The directory a packaged application's bundled resources live in. - [`resource_handler_from_bytes`](https://kurogane-rs.org/docs/api/app/resource_handler_from_bytes.md) (function): Builds a `ResourceHandler` serving `data` once with the given MIME type and status code. - [`sandbox_entry`](https://kurogane-rs.org/docs/api/app/sandbox_entry.md) (macro): Declares the entry points CEF's sandbox bootstrap calls. --- # Struct `kurogane::App` ```rust pub struct App { /* private fields */ } ``` Public application builder. Configures how the first browser instance starts. ## Processes Chromium's helper processes (renderer, GPU, utility) run this same binary again, with a `--type=` argument. In a helper the call that starts the runtime ([`App::run`], [`App::run_or_exit`], [`App::start`], [`App::build`] or [`App::start_embedded`]) becomes the helper and never returns. Code before it runs once per process. Keep side effects (files, output, sockets, spawned processes) out of that code. Guard them with [`is_browser_process`](https://kurogane-rs.org/docs/api/app/is_browser_process.md), or move them into [`ClientAppBrowserDelegate::on_context_initialized`] which only the browser process calls. [`App::run_or_exit`]: https://kurogane-rs.org/docs/api/app/app.md#method.run_or_exit [`App::start_embedded`]: https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded [`App::start`]: https://kurogane-rs.org/docs/api/app/app.md#method.start [crate::is_browser_process]: https://kurogane-rs.org/docs/api/app/is_browser_process.md [`ClientAppBrowserDelegate::on_context_initialized`]: https://kurogane-rs.org/docs/api/app/clientappbrowserdelegate.md#method.on_context_initialized [`App::run`]: https://kurogane-rs.org/docs/api/app/app.md#method.run [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ## Methods ### `new` ```rust pub fn new(path: impl Into<PathBuf>) -> Self ``` Create an app from a local directory (default entrypoint) ### `url` ```rust pub fn url(url: impl Into<String>) -> Self ``` Start from an explicit URL (escape hatch for power users) ### `permit` ```rust pub fn permit( self, name: impl Into<String>, origins: impl IntoIterator<Item = Origin>, ) -> Self ``` Restricts the command or stream `name` to the given origins. An origin is `scheme://host[:port]`, as `location.origin` reports it (`app://app` for the bundled frontend, or the development server's origin); parse one with [`Origin::parse`]. Calls for the same name accumulate and the list replaces the default below. Name the application's own origin too if its pages call `name`. A name without a rule is reachable from the application's own origin only (`app://app` for [`App::new`], the start URL's origin for [`App::url`]). A page of any other origin, whether it arrived in a popup, an iframe or a window navigated away, reaches only the names a rule gives it. An opaque document (`about:blank`, `data:`, a sandboxed frame) reaches only names made public with [`App::permit_all`]. A refused invocation is rejected with [`ErrorCode::Acl`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Acl); a refused stream open fails the stream. Naming a capability command such as `fs.read_file` (granted through [`Filesystem`](https://kurogane-rs.org/docs/api/capabilities/filesystem.md)) or the opaque origin is a configuration error, reported by [`App::build`]. [`App::permit_all`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit_all [`Origin::parse`]: https://kurogane-rs.org/docs/api/ipc/origin.md#method.parse [crate::capability::Filesystem]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build [`App::url`]: https://kurogane-rs.org/docs/api/app/app.md#method.url [crate::ErrorCode::Acl]: https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Acl [`App::new`]: https://kurogane-rs.org/docs/api/app/app.md#method.new ### `permit_all` ```rust pub fn permit_all(self, name: impl Into<String>) -> Self ``` Makes the command or stream `name` callable from any origin, the opaque origin included. Naming a capability command is a configuration error, reported by [`App::build`]. [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `permit_event` ```rust pub fn permit_event( self, name: impl Into<String>, origins: impl IntoIterator<Item = Origin>, ) -> Self ``` Restricts subscriptions to the event `name` to the given origins. Calls for the same event accumulate. Without a rule, an event is subscribable from the application's own origin only, as a command is (see [`App::permit`]). A refused subscription is removed and reported to the `onError` of `kurogane.on(name, callback, onError)` with code `-4`. Naming the opaque origin is a configuration error, reported by [`App::build`]. [`App::permit`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `permit_event_all` ```rust pub fn permit_event_all(self, name: impl Into<String>) -> Self ``` Makes the event `name` subscribable from any origin, the opaque origin included. ### `deny_unlisted` ```rust pub fn deny_unlisted(self) -> Self ``` Switches to deny-by-default. A name without a rule is refused to every origin, the application's own included. Only commands, streams and events with a configured rule ([`App::permit`], [`App::permit_all`], [`App::permit_event`], [`App::permit_event_all`]) stay reachable, only from their permitted origins. Capability commands stay authorized by their grants. [`App::permit_all`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit_all [`App::permit`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit [`App::permit_event_all`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit_event_all [`App::permit_event`]: https://kurogane-rs.org/docs/api/app/app.md#method.permit_event ### `filesystem` ```rust pub fn filesystem(self, fs: FilesystemBuilder) -> Self ``` Installs the filesystem capability, the `fs.*` commands. Filesystem grants for the invoking frame's origin authorize each call. Grants are the only authorization for these commands; the ACL never gates them, `permit` cannot name them and an origin without a grant is rejected with [`ErrorCode::Capability`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Capability). Without this call there are no `fs.*` commands at all. A handler or ACL rule already using an `fs.*` name (including a second call to this method) is a configuration error, reported by [`App::build`]. Takes the builder rather than a built [`Filesystem`](https://kurogane-rs.org/docs/api/capabilities/filesystem.md), because the roots are opened here in the browser process only. Helper processes run this same code but never serve `fs.*`. A directory handle a helper opened before entering Chromium's sandbox would stay usable inside it. A configuration the builder rejects is reported by [`App::build`] as [`RuntimeError::InvalidFilesystem`]. [crate::ErrorCode::Capability]: https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Capability [crate::capability::Filesystem]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md [`RuntimeError::InvalidFilesystem`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.InvalidFilesystem [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `delegate` ```rust pub fn delegate<D: ClientAppBrowserDelegate + 'static>( self, delegate: D, ) -> Self ``` Register a browser lifecycle delegate. ### `renderer_delegate` ```rust pub fn renderer_delegate<D: ClientAppRendererDelegate + 'static>( self, delegate: D, ) -> Self ``` Register a render process lifecycle delegate. ### `register_scheme` ```rust pub fn register_scheme<H: SchemeHandler + 'static>( self, name: impl Into<String>, handler: H, ) -> Self ``` Register a handler for a custom URL scheme. The scheme becomes loadable by the frontend (e.g. for a scheme named `data`, URLs `data://...`). The handler is invoked for every request on the scheme regardless of host. The built-in `app` scheme (used to serve bundled assets) is reserved and cannot be overridden. An invalid or reserved name, or one registered twice, is a configuration error, reported by [`App::build`]. [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `scheduler` ```rust pub fn scheduler<F>(self, f: F) -> Self where F: Fn(PumpRequest) + Send + Sync + 'static, ``` Supply a scheduler callback for pump timing. When CEF determines it needs work done, it will call this closure with a PumpRequest indicating how urgently. The integrator is responsible for calling AppInstance::pump accordingly; [`PumpRequest::deadline`] gives the instant to pump at. CEF may call the scheduler from any thread. It enables CEF's external message pump, which returns after each pump. Use it with [`App::start`] and [`App::start_embedded`]; [`App::run`] does not accept one. [`App::start_embedded`]: https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded [`PumpRequest::deadline`]: https://kurogane-rs.org/docs/api/app/pumprequest.md#method.deadline [`App::start`]: https://kurogane-rs.org/docs/api/app/app.md#method.start [`App::run`]: https://kurogane-rs.org/docs/api/app/app.md#method.run ### `command` ```rust pub fn command<Req, Res, F>(self, name: impl Into<String>, f: F) -> Self where Req: DeserializeOwned + Send + 'static, Res: Serialize + Send + 'static, F: Fn(Req, &AppHandle) -> Result<Res, IpcError> + Send + Sync + 'static, ``` Registers a synchronous JSON command handler. The closure receives the deserialized request and a reference to the shared runtime handle. Use the handle to broadcast events, query what is open or end the application. Ignore it with _ when not needed. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads The closure runs on the UI thread, which also runs every window and receives every message from the page. They all wait until it returns. CEF says not to block this thread. For slow work use [`App::async_command`] and resolve its responder from another thread. [`App::async_command`]: https://kurogane-rs.org/docs/api/app/app.md#method.async_command [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `async_command` ```rust pub fn async_command<Req, Res, F>(self, name: impl Into<String>, f: F) -> Self where Req: DeserializeOwned + Send + 'static, Res: Serialize + Send + 'static, F: Fn(Req, Responder<Res>, &AppHandle) + Send + Sync + 'static, ``` Registers an asynchronous JSON command handler. The closure receives the deserialized request, a typed responder to send the response later and the shared runtime handle. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads The closure runs on the UI thread as for [`App::command`] and should return promptly. The [`Responder`] may be resolved from any thread. [`App::command`]: https://kurogane-rs.org/docs/api/app/app.md#method.command [`Responder`]: https://kurogane-rs.org/docs/api/ipc/responder.md [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `binary_command` ```rust pub fn binary_command<F>(self, name: impl Into<String>, f: F) -> Self where F: Fn(&[u8], &AppHandle) -> Result<Vec<u8>, IpcError> + Send + Sync + 'static, ``` Registers a synchronous binary command handler. The closure receives the raw payload bytes and the shared runtime handle. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads As for [`App::command`]; for slow work use [`App::async_binary_command`]. [`App::command`]: https://kurogane-rs.org/docs/api/app/app.md#method.command [`App::async_binary_command`]: https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `async_binary_command` ```rust pub fn async_binary_command<F>(self, name: impl Into<String>, f: F) -> Self where F: Fn(Vec<u8>, BinaryResponder, &AppHandle) + Send + Sync + 'static, ``` Registers an asynchronous binary command handler. The closure receives the payload bytes (owned), a BinaryResponder to send the response later and the shared runtime handle. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads As for [`App::async_command`]. [`App::async_command`]: https://kurogane-rs.org/docs/api/app/app.md#method.async_command [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `stream` ```rust pub fn stream<F, H>(self, name: impl Into<String>, factory: F) -> Self where F: Fn() -> H + Send + Sync + 'static, H: StreamHandler + 'static, ``` Registers a stream handler whose factory does not need AppHandle. The factory is called for each stream a page opens under `name` that the ACL lets through. Each stream has a handler and mutable state of its own. [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md) describes a stream's life; the handler accepts or refuses the open and then sends. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads The factory and every [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md) callback run on the UI thread as for [`App::command`] and should return promptly. A [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md) may be used from any thread. [crate::StreamHandler]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md [crate::StreamResponder]: https://kurogane-rs.org/docs/api/ipc/streamresponder.md [`App::command`]: https://kurogane-rs.org/docs/api/app/app.md#method.command [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `stream_h` ```rust pub fn stream_h<F, H>(self, name: impl Into<String>, factory: F) -> Self where F: Fn(&AppHandle) -> H + Send + Sync + 'static, H: StreamHandler + 'static, ``` Registers a stream handler whose factory receives &AppHandle. Like [`App::stream`], but the factory receives a reference to the shared runtime handle, useful for broadcasting events or querying runtime state from within stream lifecycle callbacks. A name that is already registered is a configuration error, reported by [`App::build`]. #### Threads As for [`App::stream`]. [`App::stream`]: https://kurogane-rs.org/docs/api/app/app.md#method.stream [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `window` ```rust pub fn window(self, options: WindowOptions) -> Self ``` Sets the start window's [`WindowOptions`]. They hold the name the application knows it by, its title, size and place, the size it cannot be made smaller than and its state. Without it the start window takes its page's title and opens 800 by 600 centered on the primary display. An application started with [`App::start_embedded`] has no start window. Options given to it are [`ConfigError::WindowWhenEmbedded`]; options no window can have are [`ConfigError::InvalidWindowOptions`]. A later call replaces an earlier one. ```rust App::new("dist") .window(WindowOptions::new().title("Notes").size(1100, 720).state(WindowState::Maximized)) .run_or_exit(); ``` [`App::start_embedded`]: https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded [`WindowOptions`]: https://kurogane-rs.org/docs/api/windows/windowoptions.md [`ConfigError::WindowWhenEmbedded`]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.WindowWhenEmbedded [`ConfigError::InvalidWindowOptions`]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.InvalidWindowOptions ### `window_class` ```rust pub fn window_class(self, class: impl Into<String>) -> Self ``` Sets the class of every window Kurogane opens on Linux (WM_CLASS under X11, the app_id under Wayland). The desktop and the window manager tell an application's windows by it. A launcher's icon attaches to them when its desktop entry names the class (`StartupWMClass` under X11; under Wayland the entry's file name is the app_id). The compositor's rules for the application match it. `kurogane bundle` writes `[app].identifier` from `kurogane.toml` as the AppImage's `StartupWMClass`, or the executable's name without one. Give this the same identifier. It names the start window, [`AppInstance::create_window`]'s windows, popups and DevTools alike; not a browser embedded in the application's own window, whose window is the application's. Without it the class is the executable's file name. Other platforms have no window class and ignore it. An empty class or one with a control character is [`ConfigError::InvalidWindowClass`]. A later call replaces an earlier one. ```rust App::new("dist").window_class("com.example.notes").run_or_exit(); ``` [`AppInstance::create_window`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [`ConfigError::InvalidWindowClass`]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.InvalidWindowClass ### `window_icon` ```rust pub fn window_icon(self, png: impl Into<Cow<'static, [u8]>>) -> Self ``` Sets the icon of every window Kurogane opens, a PNG. On Windows it is the window's icon in its title bar, the taskbar and the window switcher; under X11 the icon the window manager shows. A square image of 256 by 256 is plenty; the system scales it to each place. Under Wayland the desktop takes a window's icon from the desktop entry its class names ([`App::window_class`]). On macOS windows have none and the Dock shows the application's own icon. It is the icon of the start window, [`AppInstance::create_window`]'s windows, popups and DevTools alike; not of a browser embedded in the application's own window. Without it the windows keep the system's default. Bytes that are not a PNG are [`ConfigError::InvalidWindowIcon`]. A later call replaces an earlier one. ```rust let icon = std::fs::read("icon.png").expect("the icon"); App::new("dist").window_icon(icon).run_or_exit(); ``` [`App::window_class`]: https://kurogane-rs.org/docs/api/app/app.md#method.window_class [`AppInstance::create_window`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [`ConfigError::InvalidWindowIcon`]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.InvalidWindowIcon ### `profile_id` ```rust pub fn profile_id(self, id: impl Into<String>) -> Self ``` Names the application's profile (its cookies, storage and caches). Defaults to the executable's name. CEF runs one instance per profile. Launching the application while it runs brings the running instance to the front (see [`App::on_second_instance`]). Debug builds use a profile of their own, named with a `-dev` suffix. Profiles live in `kurogane/profiles` in the local data directory (`~/.local/share` on Linux, `~/Library/Application Support` on macOS, `%LOCALAPPDATA%` on Windows). [`App::profile_dir`] puts the profile somewhere else. [`App::on_second_instance`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_second_instance [`App::profile_dir`]: https://kurogane-rs.org/docs/api/app/app.md#method.profile_dir ### `profile_dir` ```rust pub fn profile_dir(self, dir: impl Into<PathBuf>) -> Self ``` Keeps the application's profile in `dir`, an absolute path, instead of Kurogane's place for it ([`App::profile_id`]). The directory is created when missing and used as given, in debug builds too. A development run then shares it and hands its launch to the application already running there (CEF runs one instance per profile). A relative path is [`ConfigError::InvalidProfileDir`](https://kurogane-rs.org/docs/api/app/configerror.md#variant.InvalidProfileDir), as is a directory given together with [`App::profile_id`], which would then name nothing. A later call replaces an earlier one. ```rust // A portable application keeps its profile next to its executable let exe = std::env::current_exe().expect("the executable's path"); let profile = exe.parent().expect("a folder").join("profile"); App::new("dist").profile_dir(profile).run_or_exit(); ``` [crate::ConfigError::InvalidProfileDir]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.InvalidProfileDir [`App::profile_id`]: https://kurogane-rs.org/docs/api/app/app.md#method.profile_id ### `on_second_instance` ```rust pub fn on_second_instance<F>(self, f: F) -> Self where F: Fn(&SecondInstance, &AppHandle) + Send + Sync + 'static, ``` Runs `f` in the running application whenever it is launched again. CEF runs one instance per profile ([`App::profile_id`]). A launch that finds the application running hands it its arguments and exits with status 0. The running application's windows come to the front. `f` then receives the launch, for example to open a file or a link it names. Runs on the UI thread. On macOS opening the application's bundle while it runs activates it without a second launch. There `f` runs only for launches that start a process, such as running the executable directly. A later call replaces an earlier one. [`App::profile_id`]: https://kurogane-rs.org/docs/api/app/app.md#method.profile_id ### `on_new_window` ```rust pub fn on_new_window<F>(self, f: F) -> Self where F: Fn(&NewWindowRequest, &AppHandle) -> NewWindowDecision + Send + Sync + 'static, ``` Decides what happens when a page asks for a window of its own. `window.open`, a `target=_blank` link, a form that targets a new window and a link clicked with Ctrl (Cmd on macOS), the middle button or Shift all ask. An allowed modifier click opens in a new application window, never in Chromium's tabbed browser window. Kurogane decides without a hook or when it answers [`NewWindowDecision::Default`]. A page of the application's own origin opens in an application window. An `http` or `https` link the user clicked opens in the system's default browser. Anything else is refused. A website the application never chose stays out of its windows and a script alone never starts another program. The hook can widen that, for example with [`NewWindowDecision::Allow`] for a sign-in page that has to run inside the application. It narrows it with [`NewWindowDecision::Deny`] or [`NewWindowDecision::OpenExternal`]. [`NewWindowDecision::OpenExternal`] opens only an `http` or `https` link the user clicked and refuses anything else. Compare origins, not strings. `https://trusted.example.evil.net` starts with `https://trusted.example`. Runs on the UI thread before the window exists and must not block. A hook that panics refuses the window. A later call replaces an earlier one. ```rust let sign_in = Origin::parse("https://accounts.example.com").unwrap(); App::new("./dist") .on_new_window(move |request, _| { if request.origin() == &sign_in { NewWindowDecision::Allow } else { NewWindowDecision::Default } }) .run_or_exit(); ``` [`NewWindowDecision::OpenExternal`]: https://kurogane-rs.org/docs/api/requests/newwindowdecision.md#variant.OpenExternal [`NewWindowDecision::Default`]: https://kurogane-rs.org/docs/api/requests/newwindowdecision.md#variant.Default [`NewWindowDecision::Allow`]: https://kurogane-rs.org/docs/api/requests/newwindowdecision.md#variant.Allow [`NewWindowDecision::Deny`]: https://kurogane-rs.org/docs/api/requests/newwindowdecision.md#variant.Deny ### `on_navigation` ```rust pub fn on_navigation<F>(self, f: F) -> Self where F: Fn(&NavigationRequest, &AppHandle) -> NavigationDecision + Send + Sync + 'static, ``` Decides where a page may take the window it is in. Links, `location` assignments, forms and every redirect on the way all ask. A window shows only what was let into it: - the application's own origin - the origins the application loaded there itself (the start page, [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window), [`BrowserHandle::navigate`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.navigate) and the redirects they lead to) - the origin [`on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window) opened a popup to - the origins this hook allowed into it before A navigation to one of those proceeds without a hook or when it answers [`NavigationDecision::Default`]. For any other origin an `http` or `https` link the user clicked opens in the system's default browser. Anything else is refused and the window stays on its page. The application's own loads, going back and forward and frames inside a page never reach the hook. [`NavigationDecision::Allow`] loads the page and lets its origin into that window from then on, for example a sign-in provider the page sends the user to. [`NavigationDecision::Deny`] and [`NavigationDecision::OpenExternal`] narrow Kurogane's answer. Compare origins, not strings. Runs on the UI thread before the navigation starts and must not block. A hook that panics refuses the navigation. A later call replaces an earlier one. ```rust let sign_in = Origin::parse("https://accounts.example.com").unwrap(); App::url("https://app.example.com") .on_navigation(move |navigation, _| { if navigation.origin() == &sign_in { NavigationDecision::Allow } else { NavigationDecision::Default } }) .run_or_exit(); ``` [crate::BrowserHandle::navigate]: https://kurogane-rs.org/docs/api/app/browserhandle.md#method.navigate [`NavigationDecision::Allow`]: https://kurogane-rs.org/docs/api/requests/navigationdecision.md#variant.Allow [App::on_new_window]: https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window [`NavigationDecision::Deny`]: https://kurogane-rs.org/docs/api/requests/navigationdecision.md#variant.Deny [crate::AppInstance::create_window]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [`NavigationDecision::Default`]: https://kurogane-rs.org/docs/api/requests/navigationdecision.md#variant.Default [`NavigationDecision::OpenExternal`]: https://kurogane-rs.org/docs/api/requests/navigationdecision.md#variant.OpenExternal ### `on_key` ```rust pub fn on_key<F>(self, f: F) -> Self where F: Fn(&KeyPress, &AppHandle) -> KeyDecision + Send + Sync + 'static, ``` Sees each key the user presses in a window of the application's before the page and any shortcut do. Decides where the key goes. The hook is asked about each key press and its repeats while held. It is never asked about a release or the character a key types. [`KeyDecision::Default`] lets the key go on in Kurogane's order on every OS. The shortcuts that close the window and quit (Ctrl+W, Cmd+Q on macOS) take it before the page sees it. Every other shortcut runs only after the page and only if the page does not prevent the key's default. [`KeyDecision::Consume`] takes the key from everyone else. No shortcut runs (Ctrl+W does not close the window, Ctrl+R does not reload) and the page sees neither the key, its character nor its release. [`KeyDecision::PageFirst`] gives the page the key first even for closing and quitting. Those then run only if the page lets the key through. It is for shortcuts and lets the page keep one from running (see its documentation). [`KeyPress::command`](https://kurogane-rs.org/docs/api/requests/keypress.md#method.command) names the command a shortcut runs by whatever keys the OS gives it. Compare other keys with [`Modifiers::primary`](https://kurogane-rs.org/docs/api/requests/modifiers.md#method.primary) to match Ctrl on Windows and Linux and Cmd on macOS in one test. Mind [`KeyPress::in_editable_field`](https://kurogane-rs.org/docs/api/requests/keypress.md#method.in_editable_field) so as not to take keys the user is typing. Runs on the UI thread for every key press and must be quick. A hook that panics lets the key through. DevTools' windows are not asked about. A later call replaces an earlier one. ```rust App::new("./dist") .on_key(|key, _| { // Ctrl+W, Cmd+W on macOS, does not close the window if key.command() == Some(ChromeCommand::Close) { KeyDecision::Consume } else { KeyDecision::Default } }) .run_or_exit(); ``` [crate::KeyPress::command]: https://kurogane-rs.org/docs/api/requests/keypress.md#method.command [`KeyDecision::Consume`]: https://kurogane-rs.org/docs/api/requests/keydecision.md#variant.Consume [`KeyDecision::Default`]: https://kurogane-rs.org/docs/api/requests/keydecision.md#variant.Default [crate::Modifiers::primary]: https://kurogane-rs.org/docs/api/requests/modifiers.md#method.primary [`KeyDecision::PageFirst`]: https://kurogane-rs.org/docs/api/requests/keydecision.md#variant.PageFirst [crate::KeyPress::in_editable_field]: https://kurogane-rs.org/docs/api/requests/keypress.md#method.in_editable_field ### `on_chrome_command` ```rust pub fn on_chrome_command<F>(self, f: F) -> Self where F: Fn(&ChromeCommandRequest, &AppHandle) -> CommandDecision + Send + Sync + 'static, ``` Decides whether one of Chromium's commands runs. The hook hears the page-local commands Kurogane lets run from a key shortcut or the context menu (reload, find, print, zoom, editing, closing the window, DevTools). Kurogane refuses every other command first (Chromium's browser UI such as new windows, new tabs, history and bookmarks). The hook is never asked about those. It can refuse a command, never allow one. [`ChromeCommand`](https://kurogane-rs.org/docs/api/requests/chromecommand.md) folds Chromium's commands by what the user asked for. Refusing [`ChromeCommand::DevTools`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.DevTools) refuses the shortcuts and the context menu's Inspect alike. A key the [`on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key) hook consumed never becomes a command. Runs on the UI thread. A hook that panics refuses the command. DevTools' own commands are not asked about. A later call replaces an earlier one. ```rust App::new("./dist") .on_chrome_command(|request, _| match request.command() { // No DevTools and no reload in the shipped application ChromeCommand::DevTools | ChromeCommand::Reload => CommandDecision::Refuse, _ => CommandDecision::Default, }) .run_or_exit(); ``` [App::on_key]: https://kurogane-rs.org/docs/api/app/app.md#method.on_key [crate::ChromeCommand::DevTools]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.DevTools [crate::ChromeCommand]: https://kurogane-rs.org/docs/api/requests/chromecommand.md ### `on_download` ```rust pub fn on_download<F>(self, f: F) -> Self where F: Fn(&DownloadRequest, &AppHandle) -> DownloadDecision + Send + Sync + 'static, ``` Decides where a file a page downloads is saved. A link the server answers with an attachment, a link with a `download` attribute and a `blob:` or `data:` export all download. Without a hook the user picks the place in the system's Save As dialog with the suggested name filled in. [`DownloadDecision::Default`] does the same. Nothing is saved if they cancel. No page writes to the disk unless the user picked the place. A window shows one dialog at a time. Chromium's own behavior (saving silently into the Downloads folder with nothing on screen) is never used. [`DownloadDecision::SaveTo`] saves at an absolute path the application chose without asking, for example its own exports into a folder of its own. [`DownloadDecision::Deny`] saves nothing. Every download a page starts reaches the hook, several at once included. Chromium's prompt for multiple downloads never shows. Runs on the UI thread before the download starts and must not block. A hook that panics refuses the download. Downloads from DevTools are not asked about and always ask the user. A later call replaces an earlier one. ```rust let exports = std::env::temp_dir().join("my-app-exports"); let own = Origin::parse("app://app").unwrap(); App::new("./dist") .on_download(move |download, _| { if download.origin() == &own { DownloadDecision::SaveTo(exports.join(download.suggested_name())) } else { DownloadDecision::Deny } }) .run_or_exit(); ``` [`DownloadDecision::Default`]: https://kurogane-rs.org/docs/api/requests/downloaddecision.md#variant.Default [`DownloadDecision::SaveTo`]: https://kurogane-rs.org/docs/api/requests/downloaddecision.md#variant.SaveTo [`DownloadDecision::Deny`]: https://kurogane-rs.org/docs/api/requests/downloaddecision.md#variant.Deny ### `on_permission` ```rust pub fn on_permission<F>(self, f: F) -> Self where F: Fn(&PermissionRequest, &AppHandle) -> PermissionDecision + Send + Sync + 'static, ``` Decides what a page may use only with consent (a camera, a microphone, the screen, the location, notifications, reading the clipboard and the rest of [`Permission`](https://kurogane-rs.org/docs/api/requests/permission.md)). Without a hook the request is denied, as it is when the hook answers [`PermissionDecision::Default`]. No page gets a device or a permission the application did not allow. Chromium's own prompt never shows, in a window or an embedded browser. [`PermissionDecision::Allow`] grants everything the request asks for and [`PermissionDecision::Deny`] none of it. A page asking for a camera and a microphone together gets both or neither. The hook asks the user first by taking a [`PermissionResponder`](https://kurogane-rs.org/docs/api/requests/permissionresponder.md) with [`PermissionRequest::responder`] and answering [`PermissionDecision::Later`]. The page waits until the responder allows or denies from any thread. A responder dropped unanswered denies. Allowing [`Permission::ScreenVideo`](https://kurogane-rs.org/docs/api/requests/permission.md#variant.ScreenVideo) lets the page record the whole screen. There is no picker. Chromium remembers its answer to a web site (http, https), granted or denied, in the profile. The site's later requests get it without reaching the hook; [`AppHandle::forget_permissions`] makes them ask again. A camera, a microphone and the screen are never remembered. For the application's own pages nothing is remembered and a grant that must still hold after the request does not. Such a page is told yes for notifications and the location but cannot show a notification or read the location. Runs on the UI thread and must not block. A hook that panics denies. Requests from DevTools are not asked about and are denied. A later call replaces an earlier one. ```rust let own = Origin::parse("app://app").unwrap(); App::new("./dist") .on_permission(move |request, _| { let devices = request .permissions() .iter() .all(|kind| matches!(kind, Permission::Camera | Permission::Microphone)); if request.origin() == &own && devices { PermissionDecision::Allow } else { PermissionDecision::Deny } }) .run_or_exit(); ``` [`PermissionRequest::responder`]: https://kurogane-rs.org/docs/api/requests/permissionrequest.md#method.responder [crate::Permission]: https://kurogane-rs.org/docs/api/requests/permission.md [`PermissionDecision::Default`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Default [crate::Permission::ScreenVideo]: https://kurogane-rs.org/docs/api/requests/permission.md#variant.ScreenVideo [`AppHandle::forget_permissions`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.forget_permissions [`PermissionDecision::Later`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Later [crate::PermissionResponder]: https://kurogane-rs.org/docs/api/requests/permissionresponder.md [`PermissionDecision::Allow`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Allow [`PermissionDecision::Deny`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Deny ### `on_context_menu` ```rust pub fn on_context_menu<F>(self, f: F) -> Self where F: Fn(&mut ContextMenu, &AppHandle) + Send + Sync + 'static, ``` Edits the menu a right-click opens. Kurogane builds the same menu in a window and in an embedded browser, never Chromium's own: - in a text field the editing items (Undo, Redo, Cut, Copy, Paste, Paste as plain text, Select all), under Chromium's spelling suggestions on a misspelled word - Copy on a selection - nothing elsewhere - Inspect last in a debug build The hook gets that [`ContextMenu`](https://kurogane-rs.org/docs/api/requests/contextmenu.md) with what was right-clicked ([`ContextMenu::target`](https://kurogane-rs.org/docs/api/requests/contextmenu.md#method.target) names a link, an image, a selection or a text field). It may add, remove or reorder the menu's items. Items are Kurogane's own ([`StandardItem`](https://kurogane-rs.org/docs/api/requests/standarditem.md)), the application's ([`MenuItem::new`](https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new), whose choice goes to [`on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command)), separators and submenus. A menu left empty does not show. A standard item whose command [`on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) refuses is left out and asked about again when chosen. Separators at an edge or next to another are not shown, nor are submenus left empty. A page that draws its own menu calls `preventDefault()` on the `contextmenu` event. No menu of Kurogane's opens then. Runs on the UI thread as the menu opens and must not block. A hook that panics leaves Kurogane's menu. DevTools' menus are not asked about. A later call replaces an earlier one. ```rust App::new("./dist") .on_context_menu(|menu, _| { if menu.target().link_url().is_some() { menu.push(MenuItem::new("copy-link", "Copy link")); } }) .on_context_menu_command(|command, _| { if command.id() == "copy-link" { println!("copy {:?}", command.target().link_url()); } }) .run_or_exit(); ``` [crate::MenuItem::new]: https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new [App::on_context_menu_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command [App::on_chrome_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command [crate::ContextMenu]: https://kurogane-rs.org/docs/api/requests/contextmenu.md [crate::ContextMenu::target]: https://kurogane-rs.org/docs/api/requests/contextmenu.md#method.target [crate::StandardItem]: https://kurogane-rs.org/docs/api/requests/standarditem.md ### `on_context_menu_command` ```rust pub fn on_context_menu_command<F>(self, f: F) -> Self where F: Fn(&ContextMenuCommand, &AppHandle) + Send + Sync + 'static, ``` Runs an item of the application's that the user chose from a context menu ([`MenuItem::new`](https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new) in [`on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu)), with what the menu was opened on. An item chosen after the document the menu was opened on went away (a page that navigated while its menu stayed open) runs nothing. Runs on the UI thread and must not block. A hook that panics is logged. A later call replaces an earlier one. [crate::MenuItem::new]: https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new [App::on_context_menu]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu ### `on_window_closing` ```rust pub fn on_window_closing<F>(self, f: F) -> Self where F: Fn(&WindowClosing, &AppHandle) + Send + Sync + 'static, ``` Hears each window of the application's close, with which it is and where it was, to open it there again next time. Asked once each for the start window, every [`AppInstance::create_window`] window and every window a page opened as the application's. It is asked however the window closes (the user, the page, the application, Ctrl+C). Not for popups, DevTools or a browser embedded in the application's own window. [`WindowClosing::name`](https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.name) is the name the window's options gave it, free for a new window from here on. [`WindowClosing::placement`](https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement) is where it was and how it showed. Given back to [`WindowOptions::placement`] it opens the window as it was on a display that is still there. Runs on the UI thread as the window closes, before the application's last window ends it. Saving a small settings file here is fine; anything slow is not. A hook that panics is logged and the window closes as it would. A later call replaces an earlier one. ```rust let mut main = WindowOptions::new().name("main").size(1100, 720); if let Some(placement) = load("main") { main = main.placement(placement); } App::new("dist") .window(main) .on_window_closing(|closing, _| { if let Some(name) = closing.name() { save(name, closing.placement()); } }) .run_or_exit(); ``` [`AppInstance::create_window`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [crate::WindowClosing::placement]: https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement [`WindowOptions::placement`]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement [crate::WindowClosing::name]: https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.name ### `on_file_dialog` ```rust pub fn on_file_dialog<F>(self, f: F) -> Self where F: Fn(&FileDialogRequest, &AppHandle) -> FileDialogDecision + Send + Sync + 'static, ``` Answers the file choosers pages open. They are `<input type=file>` and the File System Access pickers (`showOpenFilePicker`, `showSaveFilePicker`, `showDirectoryPicker`). Chromium shows the system's file chooser without a hook or when it answers [`FileDialogDecision::Default`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Default). The hook can give the page files of its choosing instead ([`FileDialogDecision::Files`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Files)) for the page to read, or cancel the dialog. The hook shows a picker of the application's own by taking a [`FileDialogResponder`](https://kurogane-rs.org/docs/api/requests/filedialogresponder.md) with [`FileDialogRequest::responder`](https://kurogane-rs.org/docs/api/requests/filedialogrequest.md#method.responder) and answering [`FileDialogDecision::Later`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Later). The page waits until the responder selects or cancels from any thread. A responder dropped unanswered cancels. Kurogane's own Save As dialog for a download is not asked about ([`App::on_download`] decides where a download goes), nor are the dialogs of DevTools. Runs on the UI thread and must not block. A hook that panics cancels the dialog. A later call replaces an earlier one. ```rust let inbox = std::env::temp_dir().join("inbox.txt"); App::new("./dist") .on_file_dialog(move |request, _| match request.kind() { // The page imports the inbox, whatever the user would pick FileDialogKind::Open => FileDialogDecision::Files(vec![inbox.clone()]), _ => FileDialogDecision::Default, }) .run_or_exit(); ``` [crate::FileDialogRequest::responder]: https://kurogane-rs.org/docs/api/requests/filedialogrequest.md#method.responder [crate::FileDialogDecision::Default]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Default [`App::on_download`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_download [crate::FileDialogDecision::Later]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Later [crate::FileDialogResponder]: https://kurogane-rs.org/docs/api/requests/filedialogresponder.md [crate::FileDialogDecision::Files]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Files ### `on_drag_enter` ```rust pub fn on_drag_enter<F>(self, f: F) -> Self where F: Fn(&DragEnter, &AppHandle) -> DragDecision + Send + Sync + 'static, ``` Decides the drags that enter a browser embedded in the application's own window from another application (files from a file manager, a link, selected text). CEF asks only such a browser (Alloy style). A drag into one of Kurogane's own windows ([`App::window`], [`AppInstance::create_window`], popups) is not asked about; its page gets the drop as a browser's would. Asked as the drag enters, before the page sees it. The hook sees the paths of the files dragged ([`DragEnter::files`](https://kurogane-rs.org/docs/api/requests/dragenter.md#method.files)), which the page never does. A page gets a dropped file's name and contents only. [`DragDecision::Refuse`](https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Refuse) keeps the drag from the page altogether and the pointer shows it cannot drop there. Without a hook or with [`DragDecision::Default`](https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Default) the drag goes on to the page. Drags of DevTools and of a page's own content within the window are not asked about. Runs on the UI thread and must not block. A hook that panics refuses the drag. A later call replaces an earlier one. ```rust let runtime = App::new("./dist") .on_drag_enter(|drag, _| { let images = !drag.files().is_empty() && drag.files().iter().all(|file| { file.extension().is_some_and(|ext| ext == "png" || ext == "jpg") }); if images { DragDecision::Allow } else { DragDecision::Refuse } }) .start_embedded()?; // Create the browser in the host's window with `create_child_browser` ``` [`AppInstance::create_window`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [`App::window`]: https://kurogane-rs.org/docs/api/app/app.md#method.window [crate::DragDecision::Refuse]: https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Refuse [crate::DragEnter::files]: https://kurogane-rs.org/docs/api/requests/dragenter.md#method.files [crate::DragDecision::Default]: https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Default ### `on_title_change` ```rust pub fn on_title_change<F>(self, f: F) -> Self where F: Fn(&TitleChange, &AppHandle) + Send + Sync + 'static, ``` Hears a page's title change, its `<title>` as it loads or `document.title` set by a script. Kurogane titles a window after its page itself unless the window's options fixed a title ([`WindowOptions::title`]). The hook hears of every change either way, a popup's and an embedded browser's included, DevTools' not. Runs on the UI thread and must not block. A hook that panics is logged. A later call replaces an earlier one. ```rust App::new("./dist") .on_title_change(|change, _| println!("now {:?}", change.title())) .run_or_exit(); ``` [`WindowOptions::title`]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.title ### `on_fullscreen_change` ```rust pub fn on_fullscreen_change<F>(self, f: F) -> Self where F: Fn(&FullscreenChange, &AppHandle) + Send + Sync + 'static, ``` Hears a page enter or leave fullscreen through `requestFullscreen()` and then `exitFullscreen()` or the user's Escape. A window enters and leaves fullscreen with its page by itself. The hook hears of it, to hide the application's own controls for example. Not for DevTools. Kurogane does not resize a browser embedded in the application's own window; the application sizes it. Runs on the UI thread and must not block. A hook that panics is logged. A later call replaces an earlier one. ```rust App::new("./dist") .on_fullscreen_change(|change, _| println!("fullscreen: {}", change.is_fullscreen())) .run_or_exit(); ``` ### `sandbox_mode` ```rust pub fn sandbox_mode(self, mode: SandboxMode) -> Self ``` Sets the Chromium process sandbox policy. Defaults to [`SandboxMode::Disabled`]. [`SandboxMode::Chromium`] is checked before CEF starts and fails with a [`RuntimeError`] when this platform or machine cannot enforce it. See [`SandboxMode::Chromium`] for the per-platform requirements. [`SandboxMode::Disabled`]: https://kurogane-rs.org/docs/api/app/sandboxmode.md#variant.Disabled [`SandboxMode::Chromium`]: https://kurogane-rs.org/docs/api/app/sandboxmode.md#variant.Chromium [`RuntimeError`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md ### `gpu_mode` ```rust pub fn gpu_mode(self, mode: GpuMode) -> Self ``` Override GPU backend selection. ### `credential_storage` ```rust pub fn credential_storage(self, storage: CredentialStorage) -> Self ``` Override how cookies and saved passwords are protected at rest. Defaults to the platform credential store. `CredentialStorage::Basic` trades encryption for a fixed built-in key, which keeps unsigned builds and keyring-less hosts from prompting on every run. ### `chromium_flag` ```rust pub fn chromium_flag(self, name: impl Into<String>) -> Self ``` Add a Chromium flag with no value. The name is a Chromium switch name, with or without its leading `--` or `-` (or `/` on Windows); on Windows it is case-insensitive, as Chromium treats it. The flag overrides the runtime's own setting of the same switch; the feature lists, which only add (see [`App::chromium_flag_with_value`]), are left as they are. A name holding `=` is logged and skipped; a value goes in [`App::chromium_flag_with_value`]. The application's flags apply after Kurogane's own and in the order given. [`App::chromium_flag_with_value`]: https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag_with_value ### `chromium_flag_with_value` ```rust pub fn chromium_flag_with_value( self, name: impl Into<String>, value: impl Into<String>, ) -> Self ``` Adds a Chromium flag with a value. The name is read as [`App::chromium_flag`] reads it. The last value given for a switch wins, over the runtime's own value too. `disable-features` and `enable-features` differ. Their value adds its features to the list after CEF's own, the ones the application was launched with and those given before, each feature once. An `enable-features` entry in any form Chromium reads (`Name`, `Name:param/value`, `Name<Study` or `*Name`) turns back on a feature Kurogane turns off (see [`App::chromium_pref`]). ```rust // CEF's own disabled features stay disabled App::new("dist") .chromium_flag_with_value("disable-features", "Translate,MediaRouter") .run_or_exit(); ``` [`App::chromium_flag`]: https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag [`App::chromium_pref`]: https://kurogane-rs.org/docs/api/app/app.md#method.chromium_pref ### `without_chromium_flag` ```rust pub fn without_chromium_flag(self, name: impl Into<String>) -> Self ``` Remove a Chromium flag Kurogane would pass. The name is read as [`App::chromium_flag`] reads it. Kurogane then passes no such switch, neither one of its defaults nor one a setting such as [`App::gpu_mode`] sets, nor one the application gave before. A flag given after sets it again. For `disable-features` or `enable-features` it drops Kurogane's entries and the application's earlier ones; CEF's own and the launch's stay. A switch the application was launched with stays and is logged. ```rust // Chrome's stack-sampling profiler, which Kurogane turns off App::new("dist") .without_chromium_flag("disable-stack-profiler") .run_or_exit(); ``` [`App::chromium_flag`]: https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag [`App::gpu_mode`]: https://kurogane-rs.org/docs/api/app/app.md#method.gpu_mode ### `chromium_pref` ```rust pub fn chromium_pref( self, name: impl Into<String>, value: impl Into<Value>, ) -> Self ``` Set a Chromium preference. The name is Chromium's, such as `extensions.block_external_extensions`. It is the profile's preference when the profile has one of that name and else Chromium's global one. The value takes the place of Kurogane's own and applies once the runtime has started. Chromium reads some preferences only as the profile starts; those take effect at the next start. A null value returns the preference to Chromium's default. A name Chromium does not have, or a value it refuses, is logged and skipped. Preferences are declarative. One set at an earlier start and given no more returns to Chromium's default. Kurogane turns off what an application rarely needs and Chromium would run anyway: | Preference | Kurogane's value | |---|---| | `download_bubble.partial_view_enabled` | `false` | | `extensions.block_external_extensions` | `true` | | `component_updates.component_updates_enabled` | `false` | | `network_time.network_time_queries_enabled` | `false` | It also turns off the features `AimEnabled`, `MediaRouter`, `SpareRendererForSitePerProcess` and `MacAppCodeSignClone`, which no preference gates. An `enable-features` entry turns one back on (see [`App::chromium_flag_with_value`]). Chrome's stack-sampling profiler, which nothing else gates, is off through `--disable-stack-profiler`; [`App::without_chromium_flag`] turns it back on. ```rust // Widevine arrives as a component App::new("dist") .chromium_pref("component_updates.component_updates_enabled", true) .run_or_exit(); ``` [`App::without_chromium_flag`]: https://kurogane-rs.org/docs/api/app/app.md#method.without_chromium_flag [`App::chromium_flag_with_value`]: https://kurogane-rs.org/docs/api/app/app.md#method.chromium_flag_with_value ### `build` ```rust pub fn build(self) -> Result<AppInstance, RuntimeError> ``` Initialize CEF and return an AppInstance. In a Chromium helper process this never returns; see [Processes](https://kurogane-rs.org/docs/api/app/app.md). #### Errors [`RuntimeError::InvalidConfiguration`] lists every builder problem before anything starts; the other variants report startup failures. [`RuntimeError::InvalidConfiguration`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.InvalidConfiguration [App#processes]: https://kurogane-rs.org/docs/api/app/app.md ### `start_embedded` ```rust pub fn start_embedded(self) -> Result<AppInstance, RuntimeError> ``` Starts the runtime in embedded mode. #### Errors As [`App::build`]. [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build ### `run` ```rust pub fn run(self) -> Result<(), RuntimeError> ``` Start the application and run the message loop. #### Errors As [`App::build`]. Returns [`ConfigError::SchedulerWithRunLoop`] when a [`App::scheduler`] is configured, since [`App::run`] owns the message loop. [`App::build`]: https://kurogane-rs.org/docs/api/app/app.md#method.build [`ConfigError::SchedulerWithRunLoop`]: https://kurogane-rs.org/docs/api/app/configerror.md#variant.SchedulerWithRunLoop [`App::run`]: https://kurogane-rs.org/docs/api/app/app.md#method.run [`App::scheduler`]: https://kurogane-rs.org/docs/api/app/app.md#method.scheduler ### `start` ```rust pub fn start(self) -> Result<AppInstance, RuntimeError> ``` Initialize the application without entering a message loop. ### `run_or_exit` ```rust pub fn run_or_exit(self) ``` Run the application and terminate the process on failure, after printing the error and each of its causes. Intended for binaries. Libraries embedding the runtime should use run() instead. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/app.rs#L265 --- # Struct `kurogane::AppHandle` ```rust pub struct AppHandle { /* private fields */ } ``` Shared lifecycle handle for a running Kurogane application. Obtain one with [`AppInstance::handle`]; clones share the application. ## Threads Usable from any thread. Queries copy what is open under a short lock. A broadcast sends to its subscribers on the calling thread, which CEF allows for frames in the browser process. Closing and ending run on CEF's UI thread. They run at once when called there and are posted there otherwise. Once [`AppInstance::shutdown`] has begun, calls that would reach CEF do nothing, since CEF takes no call after it has shut down. [`AppInstance::handle`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.handle [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ## Methods ### `shutdown` ```rust pub fn shutdown(&self) ``` Ends the application by closing all browsers. The application ends after the last browser closes. Calling this from another thread posts the close to the UI thread. The call does not wait for the browsers to close. Does nothing once [`AppInstance::shutdown`] has begun. This end cannot be cancelled and no browser may open after it begins. Popups are refused, [`AppInstance::create_window`] and [`AppInstance::create_child_browser`] return [`RuntimeError::ShuttingDown`] and any browser CEF is already creating is closed as it appears. No context menu opens either, not even the one whose [`App::on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu) hook began the end. [`AppInstance::create_window`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown [crate::App::on_context_menu]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu [`RuntimeError::ShuttingDown`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.ShuttingDown [`AppInstance::create_child_browser`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser ### `should_shutdown` ```rust pub fn should_shutdown(&self) -> bool ``` Returns whether the application has ended. Becomes true once the last browser has closed, whatever closed it (its window, [`AppHandle::shutdown`], Ctrl+C or macOS asking the application to quit). Any of those three that finds nothing open ends it at once. Also true once [`AppInstance::shutdown`] has begun. An application that pumps CEF itself keeps pumping until then. [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ### `broadcast` ```rust pub fn broadcast(&self, event: &str, data: &[u8]) ``` Broadcast bytes to all renderers subscribed to event. A page's `kurogane.on` callback receives them as an `ArrayBuffer`. The event is delivered asynchronously to every active subscription for the given event name. This method is thread-safe and returns immediately after queuing the event for delivery. Does nothing once [`AppInstance::shutdown`] has begun. [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ### `broadcast_json` ```rust pub fn broadcast_json<T: Serialize>(&self, event: &str, value: &T) ``` Broadcast a JSON-serializable event to all renderers subscribed to event. The value is serialized to JSON. A page's `kurogane.on` callback receives the JSON text as a string. This is the preferred way to emit structured events. ### `browser_count` ```rust pub fn browser_count(&self) -> usize ``` Number of currently live browser instances. ### `window_count` ```rust pub fn window_count(&self) -> usize ``` Number of currently open windows. ### `window_ids` ```rust pub fn window_ids(&self) -> Vec<WindowId> ``` IDs of all open windows. ### `close_all_windows` ```rust pub fn close_all_windows(&self) ``` Closes all open windows. Safe to call from any thread. CEF's windows close only on the UI thread; a call from elsewhere is posted there. Does nothing once [`AppInstance::shutdown`] has begun. [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ### `close_all_browsers` ```rust pub fn close_all_browsers(&self, force: bool) ``` Closes all live browser instances. The call does not wait. A browser counts in [`AppHandle::browser_count`] until CEF has finished closing it. An application that pumps CEF keeps pumping until the count is 0. A browser embedded in the application's own window closes without asking that window to close. A call from another thread is posted to the UI thread. Does nothing once [`AppInstance::shutdown`] has begun. With `force` no page can cancel the close. A call that finds a browser open then ends the application as [`AppHandle::shutdown`] does and nothing opens after it. Without it a page's `beforeunload` may keep its browser and the application running. [`AppHandle::browser_count`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.browser_count [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown ### `find_window_by_browser` ```rust pub fn find_window_by_browser(&self, browser_id: BrowserId) -> Option<WindowId> ``` Looks up the window that hosts a given browser. None once the browser has closed, even while CEF is still closing its window. ### `find_window_by_name` ```rust pub fn find_window_by_name(&self, name: &str) -> Option<WindowId> ``` Looks up the open window named `name` ([`WindowOptions::name`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name)). None once its close has been reported ([`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing)), even while CEF is still closing it. The name is then free for a new window. [crate::App::on_window_closing]: https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing [crate::WindowOptions::name]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name ### `browsers` ```rust pub fn browsers(&self) -> Vec<(BrowserId, BrowserMetadata)> ``` Metadata for all live browsers. ### `windows` ```rust pub fn windows(&self) -> Vec<(WindowId, WindowMetadata)> ``` Metadata for all open windows. ### `browser_parent` ```rust pub fn browser_parent(&self, id: BrowserId) -> Option<BrowserId> ``` Parent of a given browser. ### `browser_opener` ```rust pub fn browser_opener(&self, id: BrowserId) -> Option<BrowserId> ``` Opener of a given browser. ### `children_of` ```rust pub fn children_of(&self, id: BrowserId) -> Vec<BrowserId> ``` All children of the given parent browser. ### `browser_for_window` ```rust pub fn browser_for_window(&self, id: WindowId) -> Option<BrowserId> ``` Browser hosted in the given window. None until the window's browser has been created and once it has closed. ### `forget_permissions` ```rust pub fn forget_permissions(&self, origin: &Origin) ``` Forgets the permission answers Chromium remembers for `origin`. The site's next request then reaches [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission) again. Use it after the application's policy changed or the user took a permission back. Chromium remembers its answers to web sites (http, https), granted or denied, in the profile. It forgets them nowhere else. Forgetting also takes back a grant the site holds now; its notifications stop. Applies to the profile of every open browser, an embedded browser's own profile included. A call from another thread is posted to the UI thread. Does nothing for the opaque origin, or once [`AppInstance::shutdown`] has begun. [crate::App::on_permission]: https://kurogane-rs.org/docs/api/app/app.md#method.on_permission [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ### `get_browser_handle` ```rust pub fn get_browser_handle(&self, id: BrowserId) -> Option<BrowserHandle> ``` Creates a BrowserHandle for a registered browser, if it exists. Returns None if no browser with the given BrowserId is registered, or once [`AppInstance::shutdown`] has begun. [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ## Trait implementations - `impl Clone for AppHandle` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/runtime.rs#L512 --- # Struct `kurogane::AppInstance` ```rust pub struct AppInstance { /* private fields */ } ``` The running application, owned by the thread that started it. Not `Send`; CEF shuts down on the thread that initialized it and dropping an `AppInstance` shuts CEF down. Use [`AppInstance::handle`] from other threads. [`AppInstance::handle`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.handle ## Methods ### `handle` ```rust pub fn handle(&self) -> &AppHandle ``` Returns the shared handle, usable from any thread. ### `pump` ```rust pub fn pump(&self) ``` Advances Chromium by one iteration of its internal message loop. When using external event-loop ownership via App::start, this must be called repeatedly on the thread that initialized CEF. Kurogane assumes pump calls are non-reentrant and originate from a single UI thread. ### `should_shutdown` ```rust pub fn should_shutdown(&self) -> bool ``` Returns true once the application has ended; see [`AppHandle::should_shutdown`]. [`AppHandle::should_shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.should_shutdown ### `create_window` ```rust pub fn create_window( &self, url: &str, options: WindowOptions, ) -> Result<WindowId, RuntimeError> ``` Opens `url` in a new window of the application's, as `options` say (see [`WindowOptions`](https://kurogane-rs.org/docs/api/windows/windowoptions.md)). #### Errors [`RuntimeError::InvalidWindowOptions`] for options no window can have; [`RuntimeError::WindowNameTaken`] when an open window has the name the options give; [`RuntimeError::ShuttingDown`] once [`AppHandle::shutdown`] has begun; [`RuntimeError::BrowserCreationFailed`] or [`RuntimeError::WindowCreationFailed`] when CEF creates neither. [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown [`RuntimeError::BrowserCreationFailed`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.BrowserCreationFailed [`RuntimeError::WindowCreationFailed`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.WindowCreationFailed [crate::WindowOptions]: https://kurogane-rs.org/docs/api/windows/windowoptions.md [`RuntimeError::InvalidWindowOptions`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.InvalidWindowOptions [`RuntimeError::WindowNameTaken`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.WindowNameTaken [`RuntimeError::ShuttingDown`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.ShuttingDown ### `run` ```rust pub fn run(self) -> Result<(), RuntimeError> ``` Takes ownership and blocks on the CEF message loop. The loop runs until the application's last browser has closed, after [`AppHandle::shutdown`] (from any thread), its last window closing or Ctrl+C. tanso::shutdown() then runs on the current (UI) thread. Not for an application given an [`App::scheduler`](https://kurogane-rs.org/docs/api/app/app.md#method.scheduler). The scheduler turns on CEF's external message pump, under which this loop returns at once and tanso::shutdown() would run under a window still opening. Such an application calls [`AppInstance::pump`] from its own loop until [`AppInstance::should_shutdown`], then [`AppInstance::shutdown`]. [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown [`AppInstance::should_shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.should_shutdown [`AppInstance::pump`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.pump [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown [crate::App::scheduler]: https://kurogane-rs.org/docs/api/app/app.md#method.scheduler ### `shutdown` ```rust pub fn shutdown(&self) ``` Perform orderly CEF shutdown. Calls tanso::shutdown() on the UI thread; [`AppHandle::should_shutdown`] is true from here on. Safe to call multiple times. Subsequent calls are no-ops. Unlike [`AppHandle::shutdown`], this shuts down the CEF runtime itself. All browsers must already be closed; [`AppHandle::should_shutdown`] is true at that point. From here on, [`AppHandle`] and [`BrowserHandle`] calls that would reach CEF do nothing. Finish using them on other threads first. A call made there at this moment can still reach CEF. [`AppHandle`]: https://kurogane-rs.org/docs/api/app/apphandle.md [`AppHandle::should_shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.should_shutdown [`BrowserHandle`]: https://kurogane-rs.org/docs/api/app/browserhandle.md [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown ### `create_child_browser` ```rust pub fn create_child_browser( &self, parent: &impl HasWindowHandle, bounds: BrowserBounds, url: &str, ) -> Result<BrowserHandle, RuntimeError> ``` Creates a Chromium browser hosted inside an existing native window. The browser is a native child window of `parent`, placed at `bounds` in the parent's coordinates (see [`BrowserBounds`]). [`BrowserHandle::set_bounds`] moves it later. `parent` is the host's window as it is, anything that hands out a [`raw_window_handle`] window handle (a winit `Window` for one). It must outlive the browser, which the host closes first (docs/winit.md). The runtime must have been started with App::start_embedded, and AppInstance::pump must continue to be called regularly for Chromium to process events. #### Errors [`RuntimeError::UnsupportedParentWindow`] when `parent` is not a Win32 window, an AppKit view or an X11 window (a Wayland surface, for one); [`RuntimeError::ShuttingDown`] once [`AppHandle::shutdown`] has begun; [`RuntimeError::BrowserCreationFailed`] when CEF creates no browser. [`raw_window_handle`]: https://docs.rs/raw_window_handle/latest/raw_window_handle/index.html [`BrowserHandle::set_bounds`]: https://kurogane-rs.org/docs/api/app/browserhandle.md#method.set_bounds [`BrowserBounds`]: https://kurogane-rs.org/docs/api/app/browserbounds.md [`RuntimeError::UnsupportedParentWindow`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.UnsupportedParentWindow [`RuntimeError::ShuttingDown`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.ShuttingDown [`AppHandle::shutdown`]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown [`RuntimeError::BrowserCreationFailed`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.BrowserCreationFailed ### `create_child_browser_with_request_context` ```rust pub fn create_child_browser_with_request_context( &self, parent: &impl HasWindowHandle, bounds: BrowserBounds, url: &str, rc_settings: &RequestContextSettings, ) -> Result<BrowserHandle, RuntimeError> ``` Creates a child browser with a custom request context (separate cookie/cache partition). Same as create_child_browser but accepts RequestContextSettings to control the cache partition, cookie persistence and accept language for this browser. The runtime must have been started with App::start_embedded. #### Errors As [`create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser); also [`RuntimeError::BrowserCreationFailed`] when CEF creates no request context from `rc_settings`. [Self::create_child_browser]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser [`RuntimeError::BrowserCreationFailed`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.BrowserCreationFailed ## Trait implementations - `impl Drop for AppInstance` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/runtime.rs#L1127 --- # Struct `kurogane::BrowserBounds` ```rust pub struct BrowserBounds { pub x: i32, pub y: i32, pub width: i32, pub height: i32, } ``` A browser's place inside its parent window, for [`AppInstance::create_child_browser`] and [`BrowserHandle::set_bounds`]. It is a position and a size in that window's own coordinates, which CEF applies unconverted. Pixels from the top-left of the client area on Windows and X11; on macOS, points in the parent `NSView`, whose origin is its top-left corner when the view is flipped (winit's is) and its bottom-left corner otherwise. A window's place on the screen is a [`WindowPlacement`](https://kurogane-rs.org/docs/api/windows/windowplacement.md). [`AppInstance::create_child_browser`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser [`BrowserHandle::set_bounds`]: https://kurogane-rs.org/docs/api/app/browserhandle.md#method.set_bounds [crate::WindowPlacement]: https://kurogane-rs.org/docs/api/windows/windowplacement.md ## Fields ### `x` ```rust pub x: i32 ``` ### `y` ```rust pub y: i32 ``` ### `width` ```rust pub width: i32 ``` ### `height` ```rust pub height: i32 ``` ## Trait implementations - `impl Clone for BrowserBounds` - `impl Copy for BrowserBounds` - `impl Debug for BrowserBounds` - `impl Default for BrowserBounds` - `impl Eq for BrowserBounds` - `impl PartialEq for BrowserBounds` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/runtime.rs#L490 --- # Struct `kurogane::BrowserHandle` ```rust pub struct BrowserHandle { /* private fields */ } ``` A browser of the running application. The handle names the browser by its [`BrowserId`] and looks it up on each call. Once the browser has closed, or once [`AppInstance::shutdown`] has begun, the calls that would reach it do nothing and its queries answer false, or an empty URL. ## Threads Usable from any thread, as CEF allows for a browser in the browser process. [`set_bounds`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.set_bounds) and [`has_devtools`](https://kurogane-rs.org/docs/api/app/browserhandle.md#method.has_devtools) are the exceptions. They run only on the thread that started the application (CEF's UI thread) and panic elsewhere. [`AppInstance::shutdown`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown [`BrowserId`]: https://kurogane-rs.org/docs/api/windows/browserid.md [Self::set_bounds]: https://kurogane-rs.org/docs/api/app/browserhandle.md#method.set_bounds [Self::has_devtools]: https://kurogane-rs.org/docs/api/app/browserhandle.md#method.has_devtools ## Methods ### `id` ```rust pub fn id(&self) -> BrowserId ``` The id of the browser this handle names. ### `close` ```rust pub fn close(&self, force: bool) ``` Closes the browser. With `force` false the page's unload handlers run first and may cancel the close. The call does not wait. The browser is gone once CEF has finished closing it. A browser embedded in the application's own window closes without asking that window to close. ### `set_bounds` ```rust pub fn set_bounds(&self, bounds: BrowserBounds) ``` Moves and resizes a browser made by [`AppInstance::create_child_browser`] inside its parent window. `bounds` are in the parent's coordinates, as at creation (see [`BrowserBounds`]); a width or height below one counts as one. On Windows and Linux Chromium places such a browser once and does not follow its parent. The application calls this whenever the browser's place changes (on every resize for a browser that fills its window). On macOS the browser stretches with its parent by itself and this places it anywhere. Does nothing for any other browser and nothing once the browser has closed. #### Panics Off the thread that started the application (CEF's UI thread). The browser's native window is moved only there. [`AppInstance::create_child_browser`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser [`BrowserBounds`]: https://kurogane-rs.org/docs/api/app/browserbounds.md ### `notify_move_or_resize_started` ```rust pub fn notify_move_or_resize_started(&self) ``` Tells the browser that the window hosting it is about to move or resize. CEF uses this on Windows and Linux only. ### `navigate` ```rust pub fn navigate(&self, url: &str) ``` Navigate the main frame to the given URL. ### `reload` ```rust pub fn reload(&self) ``` Reload the current page. ### `reload_ignore_cache` ```rust pub fn reload_ignore_cache(&self) ``` Reload the current page, ignoring cached content. ### `go_back` ```rust pub fn go_back(&self) ``` Navigate back in history, if possible. ### `go_forward` ```rust pub fn go_forward(&self) ``` Navigate forward in history, if possible. ### `can_go_back` ```rust pub fn can_go_back(&self) -> bool ``` Returns true if the browser can go back. ### `can_go_forward` ```rust pub fn can_go_forward(&self) -> bool ``` Returns true if the browser can go forward. ### `is_loading` ```rust pub fn is_loading(&self) -> bool ``` Returns true if the browser is currently loading. ### `url` ```rust pub fn url(&self) -> String ``` Returns the current URL of the main frame. ### `execute_javascript` ```rust pub fn execute_javascript(&self, code: &str, script_url: &str, start_line: i32) ``` Execute JavaScript in the main frame. ### `show_devtools` ```rust pub fn show_devtools(&self) ``` Open DevTools for this browser. ### `close_devtools` ```rust pub fn close_devtools(&self) ``` Close DevTools if open. ### `has_devtools` ```rust pub fn has_devtools(&self) -> bool ``` Returns true if DevTools is currently open for this browser. #### Panics Off the thread that started the application (CEF's UI thread). CEF answers this only there. ## Trait implementations - `impl Debug for BrowserHandle` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/runtime.rs#L908 --- # Struct `kurogane::SecondInstance` ```rust pub struct SecondInstance { /* private fields */ } ``` A launch of the application while another instance is already running. Chromium allows one instance per profile. The new launch passes its arguments and working directory to the running instance and exits. Passed to the closure given to [`App::on_second_instance`]. [`App::on_second_instance`]: https://kurogane-rs.org/docs/api/app/app.md#method.on_second_instance ## Methods ### `args` ```rust pub fn args(&self) -> &[String] ``` Returns the launch arguments that are not switches. The arguments contain the files or links named by the launch, in order. The program name is not included. ### `switch` ```rust pub fn switch(&self, name: &str) -> Option<&str> ``` Returns the value of the `--name` switch. Returns an empty string when the switch has no value and `None` when the switch was not present. ### `working_dir` ```rust pub fn working_dir(&self) -> Option<&Path> ``` The directory the launch was started in, which the relative paths among its arguments are relative to. ## Trait implementations - `impl Clone for SecondInstance` - `impl Debug for SecondInstance` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/app.rs#L81 --- # Enum `kurogane::CefLocation` ```rust #[non_exhaustive] pub enum CefLocation { Bundle, BesideExecutable, CefPath, Installed, } ``` Where the application found its Chromium runtime, in the order it looks. ## Variants ### `Bundle` ```rust Bundle ``` The application's bundle, which runs its own runtime and no other. ### `BesideExecutable` ```rust BesideExecutable ``` The executable's directory, looked at before `CEF_PATH` and the installation. ### `CefPath` ```rust CefPath ``` The directory `CEF_PATH` names, looked at before the installation. ### `Installed` ```rust Installed ``` The shared installation of the CEF version the application was built against. ## Trait implementations - `impl Clone for CefLocation` - `impl Copy for CefLocation` - `impl Debug for CefLocation` - `impl Display for CefLocation` - `impl Eq for CefLocation` - `impl PartialEq for CefLocation` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/error.rs#L125 --- # Enum `kurogane::ConfigError` ```rust #[non_exhaustive] pub enum ConfigError { DuplicateHandler(String), InvalidScheme { name: String, reason: &'static str }, DuplicateScheme(String), CapabilityCommand(String), OpaqueOrigin(String), SchedulerWithRunLoop, InvalidWindowOptions(&'static str), WindowWhenEmbedded, InvalidWindowClass(&'static str), InvalidWindowIcon, InvalidProfileDir(&'static str), } ``` One problem in the [`App`](https://kurogane-rs.org/docs/api/app/app.md) builder configuration, reported by `build()` / `run()` / `start_embedded()` as [`RuntimeError::InvalidConfiguration`]. [crate::App]: https://kurogane-rs.org/docs/api/app/app.md [`RuntimeError::InvalidConfiguration`]: https://kurogane-rs.org/docs/api/app/runtimeerror.md#variant.InvalidConfiguration ## Variants ### `DuplicateHandler` ```rust DuplicateHandler(String) ``` Two handlers share a name. Commands, async and binary commands, streams and capability commands share one namespace. ### `InvalidScheme` ```rust InvalidScheme { name: String, reason: &'static str } ``` A custom scheme name is invalid or reserved. ### `DuplicateScheme` ```rust DuplicateScheme(String) ``` Two custom schemes share a name. ### `CapabilityCommand` ```rust CapabilityCommand(String) ``` An ACL rule and a native capability both claim a command. ### `OpaqueOrigin` ```rust OpaqueOrigin(String) ``` An ACL rule names the opaque origin, which would match every frame without a host. ### `SchedulerWithRunLoop` ```rust SchedulerWithRunLoop ``` [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) was given a pump scheduler, which requires the application to drive CEF's message loop itself. [crate::App::run]: https://kurogane-rs.org/docs/api/app/app.md#method.run ### `InvalidWindowOptions` ```rust InvalidWindowOptions(&'static str) ``` [`App::window`](https://kurogane-rs.org/docs/api/app/app.md#method.window) was given options no window can have, named here. [crate::App::window]: https://kurogane-rs.org/docs/api/app/app.md#method.window ### `WindowWhenEmbedded` ```rust WindowWhenEmbedded ``` [`App::window`](https://kurogane-rs.org/docs/api/app/app.md#method.window) was given to an application started with [`App::start_embedded`](https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded), which has no start window. [crate::App::window]: https://kurogane-rs.org/docs/api/app/app.md#method.window [crate::App::start_embedded]: https://kurogane-rs.org/docs/api/app/app.md#method.start_embedded ### `InvalidWindowClass` ```rust InvalidWindowClass(&'static str) ``` [`App::window_class`](https://kurogane-rs.org/docs/api/app/app.md#method.window_class) was given a class no window manager can take, named here. [crate::App::window_class]: https://kurogane-rs.org/docs/api/app/app.md#method.window_class ### `InvalidWindowIcon` ```rust InvalidWindowIcon ``` [`App::window_icon`](https://kurogane-rs.org/docs/api/app/app.md#method.window_icon) was given bytes that are not a PNG. [crate::App::window_icon]: https://kurogane-rs.org/docs/api/app/app.md#method.window_icon ### `InvalidProfileDir` ```rust InvalidProfileDir(&'static str) ``` [`App::profile_dir`](https://kurogane-rs.org/docs/api/app/app.md#method.profile_dir) was given a directory no profile can be in, named here. [crate::App::profile_dir]: https://kurogane-rs.org/docs/api/app/app.md#method.profile_dir ## Trait implementations - `impl Clone for ConfigError` - `impl Debug for ConfigError` - `impl Display for ConfigError` - `impl Eq for ConfigError` - `impl Error for ConfigError` - `impl PartialEq for ConfigError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/error.rs#L444 --- # Enum `kurogane::CredentialStorage` ```rust pub enum CredentialStorage { System, Basic, } ``` Backend used to protect cookies and saved passwords at rest. Pass to App::credential_storage to control whether the runtime reaches for the platform credential store (default = CredentialStorage::System). ## Variants ### `System` ```rust System ``` Use the platform credential store. Cookies and passwords are encrypted with a key held by the Keychain (macOS), kwallet or gnome-keyring (Linux) or DPAPI (Windows). Unsigned macOS builds prompt for Keychain access on every run because they have no stable code identity, and Linux hosts without a keyring daemon fall back to unencrypted storage on their own. ### `Basic` ```rust Basic ``` Bypass the platform credential store. Chromium protects data with a built-in fixed key instead, which is obfuscation rather than encryption: anything readable by the process is readable by anyone with access to the profile directory. Suited to development, containers and CI, where the credential store is either absent or prompts on every run. Not suited to profiles holding data worth protecting. ## Trait implementations - `impl Clone for CredentialStorage` - `impl Copy for CredentialStorage` - `impl Debug for CredentialStorage` - `impl Default for CredentialStorage` - `impl Eq for CredentialStorage` - `impl PartialEq for CredentialStorage` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/credentials/backend.rs#L17 --- # Enum `kurogane::GpuMode` ```rust pub enum GpuMode { Auto, Hardware, Software, Disabled, } ``` GPU backend selection strategy. Pass to App::gpu_mode to control how Chromium selects its rendering backend (default = GpuMode::Auto). ## Variants ### `Auto` ```rust Auto ``` Automatically select a backend ### `Hardware` ```rust Hardware ``` Use hardware acceleration On Windows without [`SandboxMode::Chromium`](https://kurogane-rs.org/docs/api/app/sandboxmode.md#variant.Chromium), GPU work runs inside the browser process rather than a GPU process. [crate::SandboxMode::Chromium]: https://kurogane-rs.org/docs/api/app/sandboxmode.md#variant.Chromium ### `Software` ```rust Software ``` Use SwiftShader software rendering ### `Disabled` ```rust Disabled ``` Disable GPU entirely. No canvas acceleration, no WebGL ## Trait implementations - `impl Clone for GpuMode` - `impl Copy for GpuMode` - `impl Debug for GpuMode` - `impl Default for GpuMode` - `impl Eq for GpuMode` - `impl PartialEq for GpuMode` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/gpu/backend.rs#L18 --- # Enum `kurogane::PumpRequest` ```rust pub enum PumpRequest { Now, After(Duration), } ``` A request from CEF indicating when it next needs to be serviced. Passed to the closure given to [`App::scheduler`]. [`App::scheduler`]: https://kurogane-rs.org/docs/api/app/app.md#method.scheduler ## Variants ### `Now` ```rust Now ``` CEF needs work immediately. ### `After` ```rust After(Duration) ``` CEF needs work after the given delay. ## Methods ### `deadline` ```rust pub fn deadline(self, now: Instant) -> Instant ``` Returns when to call [`AppInstance::pump`] for a request made at `now`. That is `now` itself or `now` plus the delay. A delay too long to add to `now` gives `now`; pumping early is safe. [`AppInstance::pump`]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.pump ## Trait implementations - `impl Clone for PumpRequest` - `impl Copy for PumpRequest` - `impl Debug for PumpRequest` - `impl Eq for PumpRequest` - `impl PartialEq for PumpRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/app.rs#L48 --- # Enum `kurogane::RuntimeError` ```rust #[non_exhaustive] pub enum RuntimeError { InvalidAssetRoot(PathBuf), InvalidFrontendUrl { url: String, source: Box<dyn Error + Send + Sync> }, AssetRootMissing(PathBuf), EntrypointMissing(PathBuf), AssetRootUnavailable { path: PathBuf, source: Error }, CefInitializeFailed { code: i32 }, CefNotInstalled { expected: Option<PathBuf> }, CefPathMissing(PathBuf), CefVersionMismatch { path: PathBuf, location: CefLocation, found: String, expected: String }, InvalidCefRuntime { path: PathBuf, location: CefLocation, source: Box<dyn Error + Send + Sync> }, ExecutableUnavailable(Error), BundleHelperUnavailable { source: Box<dyn Error + Send + Sync> }, CacheUnavailable { path: PathBuf, source: Error }, BrowserCreationFailed, WindowCreationFailed, InvalidWindowOptions(&'static str), WindowNameTaken { name: String, window: WindowId }, ShuttingDown, UnsupportedParentWindow, SandboxUnsupported { reason: String }, SandboxUnavailable { reason: String }, InvalidConfiguration(Vec<ConfigError>), InvalidFilesystem(FsConfigError), } ``` Failure to start the application or to open a window or a browser. ## Variants ### `InvalidAssetRoot` ```rust InvalidAssetRoot(PathBuf) ``` The frontend path given to [`App::new`](https://kurogane-rs.org/docs/api/app/app.md#method.new) exists but is not a directory. [crate::App::new]: https://kurogane-rs.org/docs/api/app/app.md#method.new ### `InvalidFrontendUrl` ```rust InvalidFrontendUrl { url: String, source: Box<dyn Error + Send + Sync> } ``` The frontend URL could not be parsed; `source` says why. ### `AssetRootMissing` ```rust AssetRootMissing(PathBuf) ``` The frontend directory given to [`App::new`](https://kurogane-rs.org/docs/api/app/app.md#method.new) does not exist. [crate::App::new]: https://kurogane-rs.org/docs/api/app/app.md#method.new ### `EntrypointMissing` ```rust EntrypointMissing(PathBuf) ``` The frontend directory exists but has no `index.html` to serve; none, a directory by that name, or a link out of the directory. ### `AssetRootUnavailable` ```rust AssetRootUnavailable { path: PathBuf, source: Error } ``` The frontend directory at `path` cannot be read; `source` says why. ### `CefInitializeFailed` ```rust CefInitializeFailed { code: i32 } ``` Chromium refused to start after Kurogane found its runtime; its log names the cause. ### `CefNotInstalled` ```rust CefNotInstalled { expected: Option<PathBuf> } ``` No Chromium runtime beside the executable, no `CEF_PATH` and nothing installed at `expected`, which is `None` for a user without a local data directory. ### `CefPathMissing` ```rust CefPathMissing(PathBuf) ``` `CEF_PATH` names a directory that does not exist; no other runtime runs in its place. ### `CefVersionMismatch` ```rust CefVersionMismatch { path: PathBuf, location: CefLocation, found: String, expected: String } ``` The Chromium runtime at `path`, from `location`, is another CEF build, commit `found`, than the one the application was built against, `expected`. ### `InvalidCefRuntime` ```rust InvalidCefRuntime { path: PathBuf, location: CefLocation, source: Box<dyn Error + Send + Sync> } ``` The Chromium runtime at `path`, from `location`, cannot be used; `source` says why. ### `ExecutableUnavailable` ```rust ExecutableUnavailable(Error) ``` The path to the running executable could not be determined. ### `BundleHelperUnavailable` ```rust BundleHelperUnavailable { source: Box<dyn Error + Send + Sync> } ``` The macOS application bundle the executable belongs to has no single helper app to start Chromium's processes from; `source` says what it holds. ### `CacheUnavailable` ```rust CacheUnavailable { path: PathBuf, source: Error } ``` The profile directory at `path` cannot be created; `source` says why. ### `BrowserCreationFailed` ```rust BrowserCreationFailed ``` CEF created no browser. ### `WindowCreationFailed` ```rust WindowCreationFailed ``` CEF created no window. ### `InvalidWindowOptions` ```rust InvalidWindowOptions(&'static str) ``` [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) was given options no window can have, named here. [crate::AppInstance::create_window]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window ### `WindowNameTaken` ```rust WindowNameTaken { name: String, window: WindowId } ``` A window was asked for under `name` ([`WindowOptions::name`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name)), which the open window `window` holds. The name is free once that window's close is reported ([`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing)). [crate::App::on_window_closing]: https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing [crate::WindowOptions::name]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name ### `ShuttingDown` ```rust ShuttingDown ``` The application is ending and no browser may open after [`AppHandle::shutdown`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown), a forced [`AppHandle::close_all_browsers`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.close_all_browsers), or [`AppInstance::shutdown`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown) has begun. [crate::AppHandle::shutdown]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.shutdown [crate::AppHandle::close_all_browsers]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.close_all_browsers [crate::AppInstance::shutdown]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.shutdown ### `UnsupportedParentWindow` ```rust UnsupportedParentWindow ``` The window given to [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser) cannot parent a browser. CEF embeds only in a Win32 window, an AppKit view or an X11 window. A Wayland surface is not one of them. [crate::AppInstance::create_child_browser]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser ### `SandboxUnsupported` ```rust SandboxUnsupported { reason: String } ``` The requested sandbox cannot be enforced on this platform or layout. ### `SandboxUnavailable` ```rust SandboxUnavailable { reason: String } ``` The requested sandbox is supported but not usable on this machine. ### `InvalidConfiguration` ```rust InvalidConfiguration(Vec<ConfigError>) ``` The [`App`](https://kurogane-rs.org/docs/api/app/app.md) builder was misconfigured. Every problem is listed; nothing was started. [crate::App]: https://kurogane-rs.org/docs/api/app/app.md ### `InvalidFilesystem` ```rust InvalidFilesystem(FsConfigError) ``` The filesystem configuration passed to [`App::filesystem`](https://kurogane-rs.org/docs/api/app/app.md#method.filesystem) was rejected; nothing was started. [crate::App::filesystem]: https://kurogane-rs.org/docs/api/app/app.md#method.filesystem ## Trait implementations - `impl Debug for RuntimeError` - `impl Display for RuntimeError` - `impl Error for RuntimeError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/error.rs#L9 --- # Enum `kurogane::SandboxMode` ```rust #[non_exhaustive] pub enum SandboxMode { Disabled, Chromium, } ``` Chromium process sandbox policy. Selected with [`App::sandbox_mode`](https://kurogane-rs.org/docs/api/app/app.md#method.sandbox_mode). [crate::App::sandbox_mode]: https://kurogane-rs.org/docs/api/app/app.md#method.sandbox_mode ## Variants ### `Disabled` ```rust Disabled ``` Run Chromium without its helper-process sandbox. CEF is initialized with `no_sandbox=1` and the platform's sandbox-disabling switches are set. ### `Chromium` ```rust Chromium ``` Run renderer, GPU and utility processes inside Chromium's sandbox. Startup fails unless the platform can enforce it: - Linux: unprivileged user namespaces, or a root-owned setuid `chrome-sandbox` helper. - macOS: the app runs from a `.app` bundle, where each helper can enter its seatbelt sandbox before CEF initializes. - Windows: the app is loaded by CEF's bootstrap executable, which brokers the sandbox. See [`sandbox_entry!`](https://kurogane-rs.org/docs/api/app/sandbox_entry.md). [crate::sandbox_entry]: https://kurogane-rs.org/docs/api/app/sandbox_entry.md ## Trait implementations - `impl Clone for SandboxMode` - `impl Copy for SandboxMode` - `impl Debug for SandboxMode` - `impl Default for SandboxMode` - `impl Eq for SandboxMode` - `impl PartialEq for SandboxMode` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/spec.rs#L25 --- # Trait `kurogane::ClientAppBrowserDelegate` ```rust pub trait ClientAppBrowserDelegate: Send + Sync { fn on_before_command_line_processing(&self, _command_line: &mut CommandLine) { ... } fn on_context_initialized(&self) { ... } } ``` Customizes browser-process startup behavior. Register via App::delegate to customize browser-process startup without replacing Kurogane's built-in runtime. Delegates are invoked in registration order. ## Provided methods ### `on_before_command_line_processing` ```rust fn on_before_command_line_processing(&self, _command_line: &mut CommandLine) ``` Invoked before Chromium processes command-line arguments. Prefer App::chromium_flag for simple flag configuration. This hook exists as a lower-level escape hatch. ### `on_context_initialized` ```rust fn on_context_initialized(&self) ``` Invoked after the browser process has initialized its request context. At this point global browser-process initialization has completed and browser creation may begin. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/app.rs#L149 --- # Trait `kurogane::ClientAppRendererDelegate` ```rust pub trait ClientAppRendererDelegate: Send + Sync { fn on_web_kit_initialized(&self) { ... } fn on_browser_created( &self, _browser: Option<&Browser>, _extra_info: Option<&DictionaryValue>, ) { ... } fn on_browser_destroyed(&self, _browser: Option<&Browser>) { ... } fn on_context_created( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, ) { ... } fn on_context_released( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, ) { ... } fn on_uncaught_exception( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, _exception: Option<&V8Exception>, _stack_trace: Option<&V8StackTrace>, ) { ... } fn on_focused_node_changed( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _node: Option<&Domnode>, ) { ... } fn on_process_message_received( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _source_process: ProcessId, _message: Option<&ProcessMessage>, ) -> i32 { ... } fn load_handler(&self) -> Option<LoadHandler> { ... } } ``` Customizes render-process behavior. Register via App::renderer_delegate to observe or extend renderer-side lifecycle events. Delegates are invoked in registration order. Depending on the callback, Kurogane may perform built-in renderer processing before or after delegate dispatch. Delegate implementations should not rely on a specific ordering unless documented for a particular callback. ## Provided methods ### `on_web_kit_initialized` ```rust fn on_web_kit_initialized(&self) ``` Invoked once after WebKit initialization. Typically used to register V8 extensions and renderer-global state. ### `on_browser_created` ```rust fn on_browser_created( &self, _browser: Option<&Browser>, _extra_info: Option<&DictionaryValue>, ) ``` Invoked when a renderer-side browser instance is created. ### `on_browser_destroyed` ```rust fn on_browser_destroyed(&self, _browser: Option<&Browser>) ``` Invoked before a renderer-side browser instance is destroyed. ### `on_context_created` ```rust fn on_context_created( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, ) ``` Invoked when a JavaScript execution context is created. Kurogane's built-in IPC bridge has already been installed when this callback is dispatched. ### `on_context_released` ```rust fn on_context_released( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, ) ``` Invoked when a JavaScript execution context is released. ### `on_uncaught_exception` ```rust fn on_uncaught_exception( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _context: Option<&V8Context>, _exception: Option<&V8Exception>, _stack_trace: Option<&V8StackTrace>, ) ``` Invoked when an uncaught JavaScript exception occurs. ### `on_focused_node_changed` ```rust fn on_focused_node_changed( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _node: Option<&Domnode>, ) ``` Invoked when the focused DOM node changes. ### `on_process_message_received` ```rust fn on_process_message_received( &self, _browser: Option<&Browser>, _frame: Option<&Frame>, _source_process: ProcessId, _message: Option<&ProcessMessage>, ) -> i32 ``` Invoked when a process message is received from another CEF process. Kurogane's own IPC messages never reach it. A non-zero return marks the message as handled and keeps it from later delegates. ### `load_handler` ```rust fn load_handler(&self) -> Option<LoadHandler> ``` Supplies a renderer-side load handler. Delegates are consulted in registration order. The first delegate returning Some(LoadHandler) wins. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/app.rs#L170 --- # Trait `kurogane::SchemeHandler` ```rust pub trait SchemeHandler: Send + Sync { fn create( &self, browser: Option<&mut Browser>, frame: Option<&mut Frame>, request: Option<&mut Request>, ) -> Option<ResourceHandler>; } ``` Generates a [`ResourceHandler`] for requests on a custom scheme. Implement this trait and pass the instance to [`App::register_scheme`](https://kurogane-rs.org/docs/api/app/app.md#method.register_scheme) to expose a custom scheme to the frontend. The trait method mirrors [`SchemeHandlerFactory::create`](https://docs.rs/tanso/latest/tanso/bindings/x86_64_pc_windows_msvc/struct.SchemeHandlerFactory.html) minus the scheme name which is fixed per registration. CEF calls `create` on the browser-process IO thread, which also carries every IPC message and must not block. Decide there what to answer. Slow work, such as reading a file, belongs in the returned handler's `open` and `read`, which CEF calls on a worker thread that may block. A panic in `create` fails the request, as returning `None` does (with Rust's default `panic = "unwind"`). A [`ResourceHandler`] you implement yourself is called by CEF directly. A panic inside it aborts the process. [`resource_handler_from_bytes`] covers the common static-bytes case. [`ResourceHandler`]: https://docs.rs/tanso/latest/tanso/bindings/x86_64_pc_windows_msvc/struct.ResourceHandler.html [tanso::SchemeHandlerFactory]: https://docs.rs/tanso/latest/tanso/bindings/x86_64_pc_windows_msvc/struct.SchemeHandlerFactory.html [crate::App::register_scheme]: https://kurogane-rs.org/docs/api/app/app.md#method.register_scheme [`resource_handler_from_bytes`]: https://kurogane-rs.org/docs/api/app/resource_handler_from_bytes.md ## Required methods ### `create` ```rust fn create( &self, browser: Option<&mut Browser>, frame: Option<&mut Frame>, request: Option<&mut Request>, ) -> Option<ResourceHandler> ``` Create a resource handler for `request`, or `None` to fail the request. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/scheme.rs#L115 --- # Function `kurogane::is_browser_process` ```rust pub fn is_browser_process() -> bool ``` Returns whether this process is Chromium's browser process rather than one of its helper processes (renderer, GPU, utility) which run this same binary again with a `--type=` argument. Code before [`App::run`](https://kurogane-rs.org/docs/api/app/app.md#method.run) runs in every process. Use this to guard one-time side effects: ```rust if kurogane::is_browser_process() { // create files, print, open sockets; once, not once per helper } kurogane::App::new("content").run_or_exit(); ``` [crate::App::run]: https://kurogane-rs.org/docs/api/app/app.md#method.run Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/runtime.rs#L241 --- # Function `kurogane::resource_dir` ```rust pub fn resource_dir() -> Option<PathBuf> ``` The directory a packaged application's bundled resources live in. Returns `None` when the application is not running from a recognised bundle or its executable path cannot be resolved. ```rust let config = match kurogane::resource_dir() { Some(resources) => resources.join("config.toml"), None => std::path::PathBuf::from("config.toml"), }; ``` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/resources.rs#L16 --- # Function `kurogane::resource_handler_from_bytes` ```rust pub fn resource_handler_from_bytes( data: Vec<u8>, mime: &str, status: i32, ) -> ResourceHandler ``` Builds a [`ResourceHandler`] serving `data` once with the given MIME type and status code. For custom scheme handlers that answer with static bytes. The bytes exist before [`SchemeHandler::create`] returns on the IO thread. Producing them must be cheap. [`ResourceHandler`]: https://docs.rs/tanso/latest/tanso/bindings/x86_64_pc_windows_msvc/struct.ResourceHandler.html [`SchemeHandler::create`]: https://kurogane-rs.org/docs/api/app/schemehandler.md#tymethod.create Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/scheme.rs#L530 --- # Macro `kurogane::sandbox_entry` ```rust macro_rules! sandbox_entry { ($entry:path) => { ... }; } ``` Declares the entry points CEF's sandbox bootstrap calls. Chromium's Windows sandbox is brokered by CEF's bootstrap executable, which loads the application as a DLL and calls `RunWinMain` (windowed) or `RunConsoleMain` (console). This macro writes both, handing the broker state to the runtime before running `entry`. Off Windows it expands to nothing but a signature check. The same source builds everywhere. ## Layout The exports have to come from the application's own crate. A `cdylib` does not re-export symbols from its dependencies. The application lives in `src/lib.rs` and `src/main.rs` is a shim. This layout keeps `cargo run` and unsandboxed builds working unchanged: ```toml [lib] name = "myapp_lib" crate-type = ["cdylib", "rlib"] [[bin]] name = "myapp" ``` The library is named apart from the binary because on Windows the two would otherwise write the same `.pdb`, which Cargo warns about. The bootstrap keeps the binary's name. ```rust // src/lib.rs pub fn run() { kurogane::App::new("content") .sandbox_mode(kurogane::SandboxMode::Chromium) .run_or_exit(); } kurogane::sandbox_entry!(run); ``` ```rust // src/main.rs fn main() { myapp_lib::run() } ``` Then set `sandbox = true` under `[app]` in `kurogane.toml`. `kurogane run` and `kurogane dev` then start the application through the bootstrap. `kurogane bundle` ships the bootstrap under the application's name. Invoke the macro once, at the crate root. A second invocation is a duplicate symbol. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/sandbox/entry.rs#L63 --- # Windows and browsers > Opens windows, places them and names the browsers inside them. - [`BrowserId`](https://kurogane-rs.org/docs/api/windows/browserid.md) (struct): Identifier of a browser, never reused while the application runs. - [`BrowserMetadata`](https://kurogane-rs.org/docs/api/windows/browsermetadata.md) (struct): What the runtime knows about an open browser, from [`AppHandle::browsers`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.browsers). - [`FullscreenChange`](https://kurogane-rs.org/docs/api/windows/fullscreenchange.md) (struct): A page entering or leaving fullscreen, passed to [`App::on_fullscreen_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_fullscreen_change). - [`TitleChange`](https://kurogane-rs.org/docs/api/windows/titlechange.md) (struct): A page's new title, passed to [`App::on_title_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_title_change). - [`WindowClosing`](https://kurogane-rs.org/docs/api/windows/windowclosing.md) (struct): A window of the application's closing, passed to [`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing). It says which window it is and where it was, to open it there again with [`WindowOptions::placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement). - [`WindowId`](https://kurogane-rs.org/docs/api/windows/windowid.md) (struct): Identifier of a window, never reused while the application runs. - [`WindowMetadata`](https://kurogane-rs.org/docs/api/windows/windowmetadata.md) (struct): What the runtime knows about an open window, from [`AppHandle::windows`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.windows). - [`WindowOptions`](https://kurogane-rs.org/docs/api/windows/windowoptions.md) (struct): How an application window opens. It holds the name the application knows it by, its title, size and place, the size it cannot be made smaller than and its state. - [`WindowPlacement`](https://kurogane-rs.org/docs/api/windows/windowplacement.md) (struct): Where a window's content is on the screen in density-independent pixels and how the window shows. A window maximized, minimized or fullscreen is placed where it restores to. - [`BrowserType`](https://kurogane-rs.org/docs/api/windows/browsertype.md) (enum): Kind of a browser. - [`WindowState`](https://kurogane-rs.org/docs/api/windows/windowstate.md) (enum): How a window shows when it opens (as its options say) and as it closes. --- # Struct `kurogane::BrowserId` ```rust pub struct BrowserId(/* private field */); ``` Identifier of a browser, never reused while the application runs. ## Methods ### `as_u32` ```rust pub fn as_u32(&self) -> u32 ``` Returns the identifier as a number. ## Trait implementations - `impl Clone for BrowserId` - `impl Copy for BrowserId` - `impl Debug for BrowserId` - `impl Eq for BrowserId` - `impl Hash for BrowserId` - `impl Ord for BrowserId` - `impl PartialEq for BrowserId` - `impl PartialOrd for BrowserId` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/browser_registry.rs#L14 --- # Struct `kurogane::BrowserMetadata` ```rust pub struct BrowserMetadata { pub id: BrowserId, pub browser_type: BrowserType, pub parent_id: Option<BrowserId>, pub opener_id: Option<BrowserId>, pub created_at: Instant, } ``` What the runtime knows about an open browser, from [`AppHandle::browsers`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.browsers). [crate::AppHandle::browsers]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.browsers ## Fields ### `id` ```rust pub id: BrowserId ``` Browser identifier. ### `browser_type` ```rust pub browser_type: BrowserType ``` Kind of browser. ### `parent_id` ```rust pub parent_id: Option<BrowserId> ``` Browser that opened a popup or that DevTools inspects. None for a `Main` or `ChromeUi` browser. ### `opener_id` ```rust pub opener_id: Option<BrowserId> ``` Same browser as `parent_id`. ### `created_at` ```rust pub created_at: Instant ``` When the runtime first saw the browser. ## Trait implementations - `impl Clone for BrowserMetadata` - `impl Debug for BrowserMetadata` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/browser_registry.rs#L52 --- # Struct `kurogane::FullscreenChange` ```rust pub struct FullscreenChange { /* private fields */ } ``` A page entering or leaving fullscreen, passed to [`App::on_fullscreen_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_fullscreen_change). [crate::App::on_fullscreen_change]: https://kurogane-rs.org/docs/api/app/app.md#method.on_fullscreen_change ## Methods ### `is_fullscreen` ```rust pub fn is_fullscreen(&self) -> bool ``` Whether the page is fullscreen now. It asked with `requestFullscreen()` or left with `exitFullscreen()` or Escape. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser of the page. ### `window` ```rust pub fn window(&self) -> Option<WindowId> ``` The window the page is in; none for a browser embedded in the application's own window. ## Trait implementations - `impl Clone for FullscreenChange` - `impl Copy for FullscreenChange` - `impl Debug for FullscreenChange` - `impl Eq for FullscreenChange` - `impl PartialEq for FullscreenChange` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/page_events.rs#L59 --- # Struct `kurogane::TitleChange` ```rust pub struct TitleChange { /* private fields */ } ``` A page's new title, passed to [`App::on_title_change`](https://kurogane-rs.org/docs/api/app/app.md#method.on_title_change). [crate::App::on_title_change]: https://kurogane-rs.org/docs/api/app/app.md#method.on_title_change ## Methods ### `title` ```rust pub fn title(&self) -> &str ``` The title the page gave itself, its `<title>` or what a script set `document.title` to. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser of the page. ### `window` ```rust pub fn window(&self) -> Option<WindowId> ``` The window the page is in; none for a browser embedded in the application's own window. ## Trait implementations - `impl Clone for TitleChange` - `impl Debug for TitleChange` - `impl Eq for TitleChange` - `impl PartialEq for TitleChange` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/page_events.rs#L23 --- # Struct `kurogane::WindowClosing` ```rust pub struct WindowClosing { /* private fields */ } ``` A window of the application's closing, passed to [`App::on_window_closing`](https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing). It says which window it is and where it was, to open it there again with [`WindowOptions::placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement). [crate::App::on_window_closing]: https://kurogane-rs.org/docs/api/app/app.md#method.on_window_closing [crate::WindowOptions::placement]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement ## Methods ### `window` ```rust pub fn window(&self) -> WindowId ``` The window [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) returned or the start window. [crate::AppInstance::create_window]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window ### `name` ```rust pub fn name(&self) -> Option<&str> ``` The name its options gave it ([`WindowOptions::name`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name)); none for a window opened without one, as a page's is. The name is free from this report on. A window opened now may take it. [crate::WindowOptions::name]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.name ### `placement` ```rust pub fn placement(&self) -> WindowPlacement ``` Where the window was and how it showed. A window maximized, minimized or fullscreen gives the place and size it restores to, not the display it fills. The state is `Normal`, `Maximized` or `Fullscreen`. A window minimized or never shown gives the state it shows in once restored. The placement given back opens a window the user sees. Under xfwm4 a window the user maximized can give its maximized place and size as `Normal` because xfwm4 sends a maximize's geometry before its state. ## Trait implementations - `impl Clone for WindowClosing` - `impl Debug for WindowClosing` - `impl Eq for WindowClosing` - `impl PartialEq for WindowClosing` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_closing.rs#L21 --- # Struct `kurogane::WindowId` ```rust pub struct WindowId(/* private field */); ``` Identifier of a window, never reused while the application runs. ## Methods ### `as_u32` ```rust pub fn as_u32(&self) -> u32 ``` Returns the identifier as a number. ## Trait implementations - `impl Clone for WindowId` - `impl Copy for WindowId` - `impl Debug for WindowId` - `impl Eq for WindowId` - `impl Hash for WindowId` - `impl PartialEq for WindowId` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_registry.rs#L10 --- # Struct `kurogane::WindowMetadata` ```rust pub struct WindowMetadata { pub id: WindowId, pub created_at: Instant, } ``` What the runtime knows about an open window, from [`AppHandle::windows`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.windows). [crate::AppHandle::windows]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.windows ## Fields ### `id` ```rust pub id: WindowId ``` Window identifier. ### `created_at` ```rust pub created_at: Instant ``` When the runtime first saw the window. ## Trait implementations - `impl Clone for WindowMetadata` - `impl Debug for WindowMetadata` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_registry.rs#L22 --- # Struct `kurogane::WindowOptions` ```rust pub struct WindowOptions { /* private fields */ } ``` How an application window opens. It holds the name the application knows it by, its title, size and place, the size it cannot be made smaller than and its state. Sizes and places are in density-independent pixels (DIP) which the display's scale turns into pixels. A size of 800 by 600 is 1200 by 900 pixels on a display at 150%. A place is on the screen, from the top-left corner of the primary display. A size and a place are the window's content, the area its page shows in, without the frame the system draws around it. Centring a window and keeping it on a display take the whole window, frame included, on Windows and macOS. Under X11 the window manager adds the frame once the window shows. There the content is centred and kept on the display. ```rust App::new("dist") .window(WindowOptions::new().title("Notes").size(1100, 720).min_size(640, 480)) .run_or_exit(); ``` ## Methods ### `new` ```rust pub fn new() -> Self ``` A window titled after its page, 800 by 600 centred on the primary display, shown normally. ### `name` ```rust pub fn name(self, name: impl Into<String>) -> Self ``` The application's name for the window, never shown. [`WindowClosing::name`](https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.name) gives it back as the window closes to keep its placement under. [`AppHandle::find_window_by_name`](https://kurogane-rs.org/docs/api/app/apphandle.md#method.find_window_by_name) finds the window by it. One open window has a name at a time. [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) is refused a name an open window has until that window's close is reported. [crate::AppInstance::create_window]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [crate::AppHandle::find_window_by_name]: https://kurogane-rs.org/docs/api/app/apphandle.md#method.find_window_by_name [crate::WindowClosing::name]: https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.name ### `title` ```rust pub fn title(self, title: impl Into<String>) -> Self ``` The window's title, kept whatever title the page gives itself. Without one the window takes its page's title as a browser tab does. A page the window shows then names it in the taskbar and the window switcher. ### `size` ```rust pub fn size(self, width: u32, height: u32) -> Self ``` The size of the window's content, the window centred on the primary display and made to fit its work area. [`placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement), when given, decides the size instead. [Self::placement]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement ### `placement` ```rust pub fn placement(self, placement: WindowPlacement) -> Self ``` Opens the window as `placement` says. That is where it was the last time ([`WindowClosing::placement`](https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement)), at its size and in its state. It decides the size over [`size`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.size) and sets the state as [`state`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.state) does. Of the two the later call holds. A place no display shows any more is moved onto the nearest one. A window larger than that display's work area is made to fit it. Wayland lets no application place its windows; there only the size applies. [Self::state]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.state [Self::size]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.size [crate::WindowClosing::placement]: https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement ### `min_size` ```rust pub fn min_size(self, width: u32, height: u32) -> Self ``` The size of content the user cannot make the window smaller than. A side of 0 leaves that side free. ### `state` ```rust pub fn state(self, state: WindowState) -> Self ``` How the window first shows. Opened maximized, minimized or fullscreen, it restores to its size and place. Sets the state [`placement`](https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement) sets. Of the two the later call holds. [Self::placement]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement ## Trait implementations - `impl Clone for WindowOptions` - `impl Debug for WindowOptions` - `impl Default for WindowOptions` - `impl Eq for WindowOptions` - `impl PartialEq for WindowOptions` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_options.rs#L33 --- # Struct `kurogane::WindowPlacement` ```rust pub struct WindowPlacement { pub x: i32, pub y: i32, pub width: u32, pub height: u32, pub state: WindowState, } ``` Where a window's content is on the screen in density-independent pixels and how the window shows. A window maximized, minimized or fullscreen is placed where it restores to. [`WindowClosing::placement`](https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement) gives one as a window closes. [`WindowOptions::placement`] opens a window as one says. Serialized with serde it is `{"x":200,"y":150,"width":900,"height":600,"state":"Maximized"}` in JSON, to keep with the application's settings. [`WindowOptions::placement`]: https://kurogane-rs.org/docs/api/windows/windowoptions.md#method.placement [crate::WindowClosing::placement]: https://kurogane-rs.org/docs/api/windows/windowclosing.md#method.placement ## Fields ### `x` ```rust pub x: i32 ``` The content's left edge, from the primary display's top-left corner. ### `y` ```rust pub y: i32 ``` The content's top edge. ### `width` ```rust pub width: u32 ``` The content's width. ### `height` ```rust pub height: u32 ``` The content's height. ### `state` ```rust pub state: WindowState ``` How it shows. ## Trait implementations - `impl Clone for WindowPlacement` - `impl Copy for WindowPlacement` - `impl Debug for WindowPlacement` - `impl Eq for WindowPlacement` - `impl PartialEq for WindowPlacement` - `impl Serialize for WindowPlacement` - `impl<'de> Deserialize<'de> for WindowPlacement` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_options.rs#L194 --- # Enum `kurogane::BrowserType` ```rust #[non_exhaustive] pub enum BrowserType { Main, Popup, DevTools, Osr, ChromeUi, } ``` Kind of a browser. ## Variants ### `Main` ```rust Main ``` The start window's browser, a browser of [`AppInstance::create_window`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window) or one embedded with [`AppInstance::create_child_browser`](https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser). [crate::AppInstance::create_window]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_window [crate::AppInstance::create_child_browser]: https://kurogane-rs.org/docs/api/app/appinstance.md#method.create_child_browser ### `Popup` ```rust Popup ``` A window a page opened. Its parent is the browser that opened it. ### `DevTools` ```rust DevTools ``` Chromium's developer tools. Its parent is the browser it inspects. ### `Osr` ```rust Osr ``` ### `ChromeUi` ```rust ChromeUi ``` A browser Chromium opened on its own, such as a window restored from an earlier session. It closes with the application rather than keeping it running. ## Trait implementations - `impl Clone for BrowserType` - `impl Copy for BrowserType` - `impl Debug for BrowserType` - `impl Eq for BrowserType` - `impl PartialEq for BrowserType` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/browser_registry.rs#L31 --- # Enum `kurogane::WindowState` ```rust #[non_exhaustive] pub enum WindowState { Normal, Minimized, Maximized, Fullscreen, Hidden, } ``` How a window shows when it opens (as its options say) and as it closes. ## Variants ### `Normal` ```rust Normal ``` Shown normally. ### `Minimized` ```rust Minimized ``` Minimized. ### `Maximized` ```rust Maximized ``` Maximized. ### `Fullscreen` ```rust Fullscreen ``` Filling its display, without a frame. ### `Hidden` ```rust Hidden ``` Not shown. A hidden window's browser keeps the application running as any open browser does. ## Trait implementations - `impl Clone for WindowState` - `impl Copy for WindowState` - `impl Debug for WindowState` - `impl Default for WindowState` - `impl Eq for WindowState` - `impl From<WindowState> for ShowState` - `impl PartialEq for WindowState` - `impl Serialize for WindowState` - `impl<'de> Deserialize<'de> for WindowState` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/window_options.rs#L210 --- # IPC > Commands, streams and errors between your Rust code and the page. - [`IpcError`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md) (struct): A structured error with a numeric `ErrorCode` and human-readable message. - [`Origin`](https://kurogane-rs.org/docs/api/ipc/origin.md) (struct): Security origin of a frame as `scheme://host:port` or opaque. - [`OriginError`](https://kurogane-rs.org/docs/api/ipc/originerror.md) (struct): A configured origin that does not parse. - [`Responder`](https://kurogane-rs.org/docs/api/ipc/responder.md) (struct): The answer to one async request. - [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md) (struct): Responder for sending data from a browser-side stream handler to the renderer. - [`ErrorCode`](https://kurogane-rs.org/docs/api/ipc/errorcode.md) (enum): Classifies an `IpcError` by the numeric code exposed to the renderer. Runtime errors use the fixed codes `0` through `-9`; applications may use positive codes through `ErrorCode::App`. - [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md) (trait): Handles one stream a page opens. - [`BinaryResponder`](https://kurogane-rs.org/docs/api/ipc/binaryresponder.md) (type alias): Responder of an async binary command, resolved with the reply's bytes ([`App::async_binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command)). --- # Struct `kurogane::IpcError` ```rust pub struct IpcError { /* private fields */ } ``` A structured error with a numeric [`ErrorCode`] and human-readable message. Displays as `"{code}: {message}"`, the format the renderer parses into an `Error` with a numeric `.code`. [`ErrorCode`]: https://kurogane-rs.org/docs/api/ipc/errorcode.md ## Methods ### `new` ```rust pub fn new(message: impl Into<String>) -> Self ``` A handler failure ([`ErrorCode::Handler`]). [`ErrorCode::Handler`]: https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.Handler ### `with_code` ```rust pub fn with_code(message: impl Into<String>, code: ErrorCode) -> Self ``` A failure of class `code`. ### `code` ```rust pub fn code(&self) -> ErrorCode ``` ### `message` ```rust pub fn message(&self) -> &str ``` ## Trait implementations - `impl Clone for IpcError` - `impl Debug for IpcError` - `impl Display for IpcError` - `impl Eq for IpcError` - `impl Error for IpcError` - `impl From<&str> for IpcError` - `impl From<Error> for IpcError` - `impl From<FsError> for IpcError` - `impl From<String> for IpcError` - `impl PartialEq for IpcError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/browser_state.rs#L71 --- # Struct `kurogane::Origin` ```rust pub struct Origin(/* private field */); ``` Security origin of a frame as `scheme://host[:port]` or opaque. Serialized like `location.origin` with a lowercase scheme and host and default ports elided. Frames without a host (`file:`, `data:`, `about:`) and unparseable URLs are opaque. An opaque origin matches no rule and no grant. ## Associated constants ### `OPAQUE` ```rust const OPAQUE: Origin = _ ``` The opaque origin. ## Methods ### `from_url` ```rust pub fn from_url(url: &str) -> Origin ``` The origin of the document at `url` (browser side; never fails). ### `parse` ```rust pub fn parse(text: &str) -> Result<Origin, OriginError> ``` Parses a configured origin such as `app://app` or `http://localhost:5173`. #### Errors Returns [`OriginError`] when `text` is not a URL, has no host, is a `file:` URL, or carries a path, query, fragment or credentials. [`OriginError`]: https://kurogane-rs.org/docs/api/ipc/originerror.md ### `is_opaque` ```rust pub fn is_opaque(&self) -> bool ``` Returns true for the opaque origin. ## Trait implementations - `impl Clone for Origin` - `impl Debug for Origin` - `impl Display for Origin` - `impl Eq for Origin` - `impl FromStr for Origin` - `impl Hash for Origin` - `impl PartialEq for Origin` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/acl.rs#L36 --- # Struct `kurogane::OriginError` ```rust pub struct OriginError { /* private fields */ } ``` A configured origin that does not parse. ## Trait implementations - `impl Clone for OriginError` - `impl Debug for OriginError` - `impl Display for OriginError` - `impl Eq for OriginError` - `impl Error for OriginError` - `impl PartialEq for OriginError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/acl.rs#L131 --- # Struct `kurogane::Responder` ```rust pub struct Responder<T> { /* private fields */ } ``` The answer to one async request. Resolving it takes it; a request is answered once. A responder dropped without [`resolve`](https://kurogane-rs.org/docs/api/ipc/responder.md#method.resolve) rejects its promise. Every pending request settles. [Responder::resolve]: https://kurogane-rs.org/docs/api/ipc/responder.md#method.resolve ## Methods ### `new` ```rust pub fn new(callback: Box<dyn FnOnce(Result<T, IpcError>) + Send>) -> Self ``` Creates a responder that hands its result to `callback`. The runtime gives one to an async handler; a test of the handler can do the same. ### `is_cancelled` ```rust pub fn is_cancelled(&self) -> bool ``` Whether this responder has been cancelled. Typically by an incoming RPC_CANCEL from the renderer. ### `resolve` ```rust pub fn resolve(self, result: Result<T, IpcError>) ``` Answers the request, unless it was cancelled meanwhile. ### `map` ```rust pub fn map<U, F>(self, f: F) -> Responder<U> where U: 'static, F: FnOnce(U) -> Result<T, IpcError> + Send + 'static, ``` Transform the resolved value type. The returned responder chains through `f` before calling the original callback. Useful for wrapping a typed `Responder<Res>` into a `Responder<Vec<u8>>` at the serialisation boundary. The mapped responder shares the cancellation flag with the source. Cancelling the source or the mapped responder cancels both. ## Trait implementations - `impl<T> Drop for Responder<T>` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/responder.rs#L14 --- # Struct `kurogane::StreamResponder` ```rust pub struct StreamResponder { /* private fields */ } ``` Responder for sending data from a browser-side stream handler to the renderer. A responder the runtime hands a handler is bound to its stream and its document. Once any clone has sent the stream's end or error, or the stream is closed or its document has ended, every send returns `Err`. ## Methods ### `send_data` ```rust pub fn send_data(&self, data: &[u8]) -> Result<(), IpcError> ``` Sends a data chunk to the page's `onData`. #### Errors Returns `Err` and sends nothing when the stream has ended or failed, or the document that opened it has gone (its frame navigated or closed). ### `end` ```rust pub fn end(&self, result: &str) -> Result<(), IpcError> ``` Ends the stream. The page's `onEnd` receives `result`. The first `end` or `error` sent, from any clone, closes the stream. #### Errors As [`send_data`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.send_data); the error's message is `stream closed` once the stream has ended or failed. [Self::send_data]: https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.send_data ### `error` ```rust pub fn error(&self, error: impl Into<IpcError>) -> Result<(), IpcError> ``` Fails the stream. The page's `onError` receives the error's message. A string is an [`IpcError::new`]. Closes the stream, as [`end`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.end) does. #### Errors As [`end`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.end). [Self::end]: https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.end [`IpcError::new`]: https://kurogane-rs.org/docs/api/ipc/ipcerror.md#method.new ## Trait implementations - `impl Clone for StreamResponder` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/stream/mod.rs#L28 --- # Enum `kurogane::ErrorCode` ```rust #[non_exhaustive] pub enum ErrorCode { Handler, Panic, Buffer, Dropped, Acl, Capability, PathDenied, PathInvalid, TooLarge, Left, App(NonZeroU16), } ``` Classifies an [`IpcError`] by the numeric code exposed to the renderer. Runtime errors use the fixed codes `0` through `-9`; applications may use positive codes through [`ErrorCode::App`]. [`IpcError`]: https://kurogane-rs.org/docs/api/ipc/ipcerror.md [`ErrorCode::App`]: https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.App ## Variants ### `Handler` ```rust Handler ``` A handler reported a failure (`0`, the default). ### `Panic` ```rust Panic ``` The handler panicked (`-1`). ### `Buffer` ```rust Buffer ``` The request or response could not be decoded or encoded (`-2`). ### `Dropped` ```rust Dropped ``` The handler dropped its responder without resolving (`-3`). ### `Acl` ```rust Acl ``` The ACL refused the calling origin (`-4`). ### `Capability` ```rust Capability ``` No capability grant of the origin covers the operation (`-5`). ### `PathDenied` ```rust PathDenied ``` The path is outside the granted roots, denied, or a link (`-6`). ### `PathInvalid` ```rust PathInvalid ``` The path is malformed (`-7`). ### `TooLarge` ```rust TooLarge ``` The file or message exceeds its transfer limit (`-8`). ### `Left` ```rust Left ``` The page left with the request open and came back from the back-forward cache (`-9`). ### `App` ```rust App(NonZeroU16) ``` An application-defined code, sent as is. ## Methods ### `wire` ```rust pub fn wire(self) -> i32 ``` The numeric code the renderer receives. ## Trait implementations - `impl Clone for ErrorCode` - `impl Copy for ErrorCode` - `impl Debug for ErrorCode` - `impl Eq for ErrorCode` - `impl Hash for ErrorCode` - `impl PartialEq for ErrorCode` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/browser_state.rs#L21 --- # Trait `kurogane::StreamHandler` ```rust pub trait StreamHandler: Send + 'static { fn on_open(&mut self, metadata: &str) -> Result<(), IpcError> { ... } fn on_opened(&mut self, responder: &StreamResponder) -> Result<(), IpcError> { ... } fn on_chunk( &mut self, data: &[u8], responder: &StreamResponder, ) -> Result<(), IpcError>; fn on_end( &mut self, result: &str, responder: StreamResponder, ) -> Result<(), IpcError> { ... } fn on_error(&mut self, message: &str) { ... } } ``` Handles one stream a page opens. The factory registered with [`App::stream`](https://kurogane-rs.org/docs/api/app/app.md#method.stream) makes a handler for each stream. In order: 1. [`on_open`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_open) accepts or refuses the stream. Nothing can be sent yet since the page does not hold the stream. 2. The runtime tells the page the stream is open, which resolves its `openStream`, then calls [`on_opened`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened). 3. [`on_chunk`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#tymethod.on_chunk) runs for each chunk the page writes. 4. [`on_end`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_end) runs when the page ends the stream. The first [`end`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.end) or [`error`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.error) sent closes the stream, whichever clone of the responder sends it; later sends fail with `stream closed`. An `Err` from `on_open` rejects the open with the error's message and code, as a command's error does; an `Err` from `on_opened`, `on_chunk` or `on_end` fails the stream, whose `onError` receives the message, unless it is already closed. A panic in any of them counts as an `Err` with the message `handler panicked`. The page's end is always answered. When `on_end` sends neither the runtime ends the stream with an empty result. The runtime drops the handler once the stream is closed. A stream closed from another thread is noticed at the next stream open, or when its document goes. ## Threads Every callback runs on the UI thread. That thread also runs every window and receives every message from the page. Return promptly; CEF says not to block this thread. The responder may be cloned and used from any thread. ## Examples A handler that greets the page, then counts the bytes the page writes: ```rust use kurogane::{App, IpcError, StreamHandler, StreamResponder}; #[derive(Default)] struct Counter { bytes: usize, } impl StreamHandler for Counter { fn on_opened(&mut self, responder: &StreamResponder) -> Result<(), IpcError> { responder.send_data(b"ready") } fn on_chunk(&mut self, data: &[u8], _: &StreamResponder) -> Result<(), IpcError> { self.bytes += data.len(); Ok(()) } fn on_end(&mut self, _: &str, responder: StreamResponder) -> Result<(), IpcError> { responder.end(&self.bytes.to_string()) } } App::new("frontend").stream("count", Counter::default).run_or_exit(); ``` [Self::on_end]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_end [Self::on_opened]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened [crate::App::stream]: https://kurogane-rs.org/docs/api/app/app.md#method.stream [StreamResponder::end]: https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.end [StreamResponder::error]: https://kurogane-rs.org/docs/api/ipc/streamresponder.md#method.error [Self::on_open]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_open [Self::on_chunk]: https://kurogane-rs.org/docs/api/ipc/streamhandler.md#tymethod.on_chunk ## Required methods ### `on_chunk` ```rust fn on_chunk( &mut self, data: &[u8], responder: &StreamResponder, ) -> Result<(), IpcError> ``` Called for each chunk the page writes. An `Err` fails the stream. ## Provided methods ### `on_open` ```rust fn on_open(&mut self, metadata: &str) -> Result<(), IpcError> ``` Accepts or refuses the stream. `metadata` is the second argument of the page's `openStream`. An `Err` rejects the `openStream` with its message and code. ### `on_opened` ```rust fn on_opened(&mut self, responder: &StreamResponder) -> Result<(), IpcError> ``` Called once the page has been told the stream is open. It is the place to send initial data, to end or fail the stream or to hand a clone of `responder` to a thread that produces data. An `Err` fails the stream. ### `on_end` ```rust fn on_end( &mut self, result: &str, responder: StreamResponder, ) -> Result<(), IpcError> ``` Called when the page ends the stream with `result`. Once it returns `Ok`, the runtime ends the stream with an empty result unless the handler has ended or failed it; an `Err` fails the stream instead. ### `on_error` ```rust fn on_error(&mut self, message: &str) ``` Called when the renderer reports that the stream failed; not for a failure the handler or the runtime sends. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/stream/mod.rs#L219 --- # Type alias `kurogane::BinaryResponder` ```rust pub type BinaryResponder = Responder<Vec<u8>>; ``` Responder of an async binary command, resolved with the reply's bytes ([`App::async_binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command)). [crate::App::async_binary_command]: https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/ipc/request_response.rs#L21 --- # Capabilities > Grants a page scoped access to the filesystem. Per-origin, per-operation filesystem capabilities for renderer code. Every `fs.*` call is subject to three independent checks: 1. Command: The command ACL permits the `fs.*` capability surface but neither grants nor revokes filesystem access. 2. Operation: Each command performs one operation and requires the corresponding [`FsAccess`] bit in the origin's grants. 3. Resource: The path must lie beneath an allow root carrying that bit and outside every deny rule held by the origin. The opened object's real location is checked again before use. Nothing is reachable without a grant. Links are never traversed. Denials never disclose request contents. The public surface is [`Filesystem`], which defines scopes and grants and is passed to [`App::filesystem`](https://kurogane-rs.org/docs/api/app/app.md#method.filesystem) to install the `fs.*` commands. [`Filesystem::authorize`] produces the exact authority granted to an origin for tests and headless checks. Modules: - `policy`: capability bits and the `fs.*` command set. - `fold`: how each platform's filesystems compare names and the inverse glob classes match through. - `path`: validated names, request parsing and comparison keys. - `scope`: allow roots and deny rules. - `safe`: platform-specific kernel-confined opening. - `authorized`: filesystem configuration and per-origin authority. - `commands`: IPC handlers. - `audit`: cross-layer invariants (tests only). [crate::App::filesystem]: https://kurogane-rs.org/docs/api/app/app.md#method.filesystem [`Filesystem::authorize`]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md#method.authorize [`Filesystem`]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md [`FsAccess`]: https://kurogane-rs.org/docs/api/capabilities/fsaccess.md - [`AuthorizedFs`](https://kurogane-rs.org/docs/api/capabilities/authorizedfs.md) (struct): The authority of one origin. Every operation runs the decision rules in the module documentation; nothing else reaches the filesystem for a renderer. - [`DirEntry`](https://kurogane-rs.org/docs/api/capabilities/direntry.md) (struct): One entry of a listed directory. Links and reparse points are never listed. - [`Filesystem`](https://kurogane-rs.org/docs/api/capabilities/filesystem.md) (struct): Filesystem capability configuration of named scopes and the grants that bind origins to them. - [`FilesystemBuilder`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md) (struct): Builder for `Filesystem`. - [`FsAccess`](https://kurogane-rs.org/docs/api/capabilities/fsaccess.md) (struct): A set of operational filesystem capabilities. - [`ScopeBuilder`](https://kurogane-rs.org/docs/api/capabilities/scopebuilder.md) (struct): Declares one scope inside [`FilesystemBuilder::scope`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.scope). - [`ScopeId`](https://kurogane-rs.org/docs/api/capabilities/scopeid.md) (struct): Handle to a scope declared on a `FilesystemBuilder`. Grants name scopes by handle. A grant cannot reference a scope that was never declared. - [`Denial`](https://kurogane-rs.org/docs/api/capabilities/denial.md) (enum): Why an in-grant request was refused. Each variant renders one fixed, class-level message. - [`EntryKind`](https://kurogane-rs.org/docs/api/capabilities/entrykind.md) (enum): The kind of a directory entry. - [`FsConfigError`](https://kurogane-rs.org/docs/api/capabilities/fsconfigerror.md) (enum): A `Filesystem` configuration that cannot be built. These are developer-facing and may name paths; they never reach a renderer. - [`FsError`](https://kurogane-rs.org/docs/api/capabilities/fserror.md) (enum): Failure of one filesystem operation performed for an origin. --- # Struct `kurogane::capability::AuthorizedFs` ```rust pub struct AuthorizedFs<'a> { /* private fields */ } ``` The authority of one origin. Every operation runs the decision rules in the module documentation; nothing else reaches the filesystem for a renderer. ## Methods ### `access` ```rust pub fn access(&self) -> FsAccess ``` Every capability the origin holds, across its grants. ### `read_file` ```rust pub fn read_file(&self, path: &Path) -> Result<Vec<u8>, FsError> ``` `fs.read_file`: READ. Regular files only, up to the transfer limit. ### `write_file` ```rust pub fn write_file(&self, path: &Path, contents: &[u8]) -> Result<(), FsError> ``` `fs.write_file`: WRITE to replace an existing file, CREATE to make a new one. The object decides which applies. Contents over the transfer limit are refused before anything is opened. An existing file is replaced whole. The contents go to a new file beside it which then takes its name and its permissions. A write that fails part-way leaves the old contents. The file is a new object afterwards (its owner is the application's user); on Windows another program holding it open without delete sharing makes the write fail. ### `create_dir` ```rust pub fn create_dir(&self, path: &Path) -> Result<(), FsError> ``` `fs.create_dir`: CREATE. One level; the parent must exist. ### `remove_file` ```rust pub fn remove_file(&self, path: &Path) -> Result<(), FsError> ``` `fs.remove_file`: DELETE. ### `remove_dir` ```rust pub fn remove_dir(&self, path: &Path) -> Result<(), FsError> ``` `fs.remove_dir`: DELETE. The directory must be empty. ### `rename_file` ```rust pub fn rename_file(&self, from: &Path, to: &Path) -> Result<(), FsError> ``` `fs.rename_file`: RENAME on source and destination, each authorized independently. An existing destination is replaced. Every rule is a function of where content lives. A move is also judged as a whole. It may not carry content out from under a deny rule (`PATH_DENIED`) nor to a place where the origin holds more access over it than it held at the source (`PATH_DENIED`). ### `copy_file` ```rust pub fn copy_file(&self, from: &Path, to: &Path) -> Result<u64, FsError> ``` `fs.copy_file`: READ on the source, CREATE on the destination. Never overwrites. Returns the number of bytes copied. ### `list_dir` ```rust pub fn list_dir(&self, path: &Path) -> Result<Vec<DirEntry>, FsError> ``` `fs.read_dir`: LIST. Denied entries, links and reparse points are omitted, never flagged. ### `exists` ```rust pub fn exists(&self, path: &Path) -> Result<bool, FsError> ``` `fs.exists`: METADATA. `false` only for genuine absence; a denied path is an error, never `false`. ### `size` ```rust pub fn size(&self, path: &Path) -> Result<u64, FsError> ``` `fs.size`: METADATA. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/authorized.rs#L248 --- # Struct `kurogane::capability::DirEntry` ```rust pub struct DirEntry { /* private fields */ } ``` One entry of a listed directory. Links and reparse points are never listed. ## Methods ### `name` ```rust pub fn name(&self) -> &OsStr ``` ### `kind` ```rust pub fn kind(&self) -> EntryKind ``` ## Trait implementations - `impl Clone for DirEntry` - `impl Debug for DirEntry` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/safe/mod.rs#L81 --- # Struct `kurogane::capability::Filesystem` ```rust pub struct Filesystem { /* private fields */ } ``` Filesystem capability configuration of named scopes and the grants that bind origins to them. ```rust use kurogane::Origin; use kurogane::capability::{Filesystem, FsAccess}; let mut builder = Filesystem::builder(); let notes = builder.scope("notes", |scope| { scope.allow_directory_recursive("/path/to/notes"); scope.deny_path("/path/to/notes/secrets"); scope.deny_glob("**/.git"); }); builder.grant(Origin::parse("app://app")?, notes, FsAccess::READ | FsAccess::LIST); let fs = builder.build()?; ``` ## Associated constants ### `DEFAULT_MAX_FILE_SIZE` ```rust const DEFAULT_MAX_FILE_SIZE: u64 = _ ``` Default of [`FilesystemBuilder::max_file_size`] (64 MiB). [`FilesystemBuilder::max_file_size`]: https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.max_file_size ## Methods ### `builder` ```rust pub fn builder() -> FilesystemBuilder ``` ### `authorize` ```rust pub fn authorize(&self, origin: &Origin) -> Option<AuthorizedFs<'_>> ``` Mints the typed authority for `origin`, or `None` when it holds no grant. This is the only origin-dependent decision in the layer. Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/authorized.rs#L53 --- # Struct `kurogane::capability::FilesystemBuilder` ```rust pub struct FilesystemBuilder { /* private fields */ } ``` Builder for [`Filesystem`]. [`Filesystem`]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md ## Methods ### `allow_hard_links` ```rust pub fn allow_hard_links(&mut self, allow: bool) -> &mut Self ``` Permits regular files that have other names (hard links). By default such a file is refused (`PATH_DENIED`) by every operation that reads, writes, copies or measures its contents. Its other names may lie outside every root or under a deny rule and no platform can tell the location re-check which. Enable only when the roots hold multiply linked files by design (a pnpm store, a local `git clone`) and nobody untrusted can create links in them. Listing, removing and renaming a link's name are unaffected either way. ### `max_file_size` ```rust pub fn max_file_size(&mut self, bytes: u64) -> &mut Self ``` Caps the bytes `read_file` returns and `write_file` accepts ([`FsError::TooLarge`] beyond it). A whole file travels in one IPC message and is held in memory by both processes. The cap bounds what one renderer call can cost until file transfers stream. Defaults to [`Filesystem::DEFAULT_MAX_FILE_SIZE`]. `copy_file` stays in the browser process and is not capped. [`Filesystem::DEFAULT_MAX_FILE_SIZE`]: https://kurogane-rs.org/docs/api/capabilities/filesystem.md#associatedconstant.DEFAULT_MAX_FILE_SIZE [`FsError::TooLarge`]: https://kurogane-rs.org/docs/api/capabilities/fserror.md#variant.TooLarge ### `scope` ```rust pub fn scope( &mut self, name: impl Into<String>, declare: impl FnOnce(&mut ScopeBuilder), ) -> ScopeId ``` Declares a scope and returns its handle. `name` labels configuration errors only. ### `grant` ```rust pub fn grant( &mut self, origin: Origin, scope: ScopeId, access: FsAccess, ) -> &mut Self ``` Grants `access` over `scope` to `origin`, matched exactly. Several grants to one origin combine. ### `build` ```rust pub fn build(self) -> Result<Filesystem, FsConfigError> ``` Opens every allow root and checks every rule. #### Errors Returns [`FsConfigError`] for a scope handle from another builder, a grant to the opaque origin, a malformed deny glob, a deny path outside its scope's roots, or an allow root that cannot be opened as a directory (including every root on platforms without a safe-open backend). [`FsConfigError`]: https://kurogane-rs.org/docs/api/capabilities/fsconfigerror.md ## Trait implementations - `impl Default for FilesystemBuilder` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/authorized.rs#L77 --- # Struct `kurogane::capability::FsAccess` ```rust pub struct FsAccess(/* private field */); ``` A set of operational filesystem capabilities. The default is [`FsAccess::NONE`]. The bits limit what web content may do through `fs.*`; the application's own Rust code is not restricted by them. [`FsAccess::NONE`]: https://kurogane-rs.org/docs/api/capabilities/fsaccess.md#associatedconstant.NONE ## Associated constants ### `NONE` ```rust const NONE: FsAccess = _ ``` No native filesystem capability. ### `READ` ```rust const READ: FsAccess = _ ``` Read a regular file's contents. ### `METADATA` ```rust const METADATA: FsAccess = _ ``` Read metadata (`exists` / `size`), never contents. ### `LIST` ```rust const LIST: FsAccess = _ ``` Enumerate a directory under the strict visibility policy. ### `WRITE` ```rust const WRITE: FsAccess = _ ``` Replace the contents of an existing file. ### `CREATE` ```rust const CREATE: FsAccess = _ ``` Create new files and directories. ### `DELETE` ```rust const DELETE: FsAccess = _ ``` Remove files and empty directories. ### `RENAME` ```rust const RENAME: FsAccess = _ ``` Rename or move entries. ### `ALL` ```rust const ALL: FsAccess = _ ``` Every capability. ## Methods ### `contains` ```rust pub const fn contains(self, other: FsAccess) -> bool ``` Returns true when every bit of `other` is present. ### `union` ```rust pub const fn union(self, other: FsAccess) -> FsAccess ``` Returns the union of both sets; the `const` form of `|`. ## Trait implementations - `impl BitOr for FsAccess` - `impl BitOrAssign for FsAccess` - `impl Clone for FsAccess` - `impl Copy for FsAccess` - `impl Debug for FsAccess` - `impl Default for FsAccess` - `impl Eq for FsAccess` - `impl Hash for FsAccess` - `impl PartialEq for FsAccess` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/policy.rs#L32 --- # Struct `kurogane::capability::ScopeBuilder` ```rust pub struct ScopeBuilder { /* private fields */ } ``` Declares one scope inside [`FilesystemBuilder::scope`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.scope). Methods only record; roots are opened and patterns checked when the `Filesystem` is built. [crate::capability::FilesystemBuilder::scope]: https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.scope ## Methods ### `allow_directory` ```rust pub fn allow_directory(&mut self, path: impl AsRef<Path>) -> &mut Self ``` Allows the directory itself and its immediate children. ### `allow_directory_recursive` ```rust pub fn allow_directory_recursive(&mut self, path: impl AsRef<Path>) -> &mut Self ``` Allows the directory and its whole subtree. ### `deny_path` ```rust pub fn deny_path(&mut self, path: impl AsRef<Path>) -> &mut Self ``` Denies a literal path and everything beneath it. The path is never a pattern, whatever characters it contains. It must lie under one of this scope's allow roots. ### `deny_glob` ```rust pub fn deny_glob(&mut self, pattern: impl Into<String>) -> &mut Self ``` Denies what `pattern` matches beneath every allow root of this scope (`**/.git`, `**/*.key`). Patterns use `/` on every platform and `\` as the escape; a matched directory is denied with its subtree. ## Trait implementations - `impl Debug for ScopeBuilder` - `impl Default for ScopeBuilder` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/scope/mod.rs#L47 --- # Struct `kurogane::capability::ScopeId` ```rust pub struct ScopeId { /* private fields */ } ``` Handle to a scope declared on a [`FilesystemBuilder`]. Grants name scopes by handle. A grant cannot reference a scope that was never declared. [`FilesystemBuilder`]: https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md ## Trait implementations - `impl Clone for ScopeId` - `impl Copy for ScopeId` - `impl Debug for ScopeId` - `impl Eq for ScopeId` - `impl PartialEq for ScopeId` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/authorized.rs#L71 --- # Enum `kurogane::capability::Denial` ```rust #[non_exhaustive] pub enum Denial { OutsideRoots, DenyRule, ObjectLocation, } ``` Why an in-grant request was refused. Each variant renders one fixed, class-level message. ## Variants ### `OutsideRoots` ```rust OutsideRoots ``` The request lies outside every allow root that carries the capability, or `..` pops above its anchor. ### `DenyRule` ```rust DenyRule ``` The request matches a deny rule of one of the origin's scopes. ### `ObjectLocation` ```rust ObjectLocation ``` The opened object (or a mutation's target) is located in a denied subtree, or is a link / reparse point. ## Methods ### `message` ```rust pub const fn message(self) -> &'static str ``` The class-level message surfaced to the renderer. ## Trait implementations - `impl Clone for Denial` - `impl Copy for Denial` - `impl Debug for Denial` - `impl Eq for Denial` - `impl PartialEq for Denial` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/error.rs#L18 --- # Enum `kurogane::capability::EntryKind` ```rust #[non_exhaustive] pub enum EntryKind { File, Dir, Other, } ``` The kind of a directory entry. ## Variants ### `File` ```rust File ``` ### `Dir` ```rust Dir ``` ### `Other` ```rust Other ``` A device, FIFO or socket. ## Trait implementations - `impl Clone for EntryKind` - `impl Copy for EntryKind` - `impl Debug for EntryKind` - `impl Eq for EntryKind` - `impl PartialEq for EntryKind` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/safe/mod.rs#L72 --- # Enum `kurogane::capability::FsConfigError` ```rust #[non_exhaustive] pub enum FsConfigError { ForeignScope, OpaqueOrigin, Root { path: PathBuf, source: Error }, DenyOutsideRoots { scope: String, path: PathBuf }, InvalidGlob { scope: String, pattern: String, reason: &'static str }, } ``` A `Filesystem` configuration that cannot be built. These are developer-facing and may name paths; they never reach a renderer. ## Variants ### `ForeignScope` ```rust ForeignScope ``` A grant uses a [`ScopeId`](https://kurogane-rs.org/docs/api/capabilities/scopeid.md) declared on another builder. [crate::capability::ScopeId]: https://kurogane-rs.org/docs/api/capabilities/scopeid.md ### `OpaqueOrigin` ```rust OpaqueOrigin ``` A grant targets the opaque origin, which would match every frame without a host. ### `Root` ```rust Root { path: PathBuf, source: Error } ``` An allow root cannot be opened as a directory. ### `DenyOutsideRoots` ```rust DenyOutsideRoots { scope: String, path: PathBuf } ``` A `deny_path` lies outside every allow root of its scope. ### `InvalidGlob` ```rust InvalidGlob { scope: String, pattern: String, reason: &'static str } ``` A `deny_glob` pattern is malformed. ## Trait implementations - `impl Debug for FsConfigError` - `impl Display for FsConfigError` - `impl Error for FsConfigError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/error.rs#L107 --- # Enum `kurogane::capability::FsError` ```rust #[non_exhaustive] pub enum FsError { CapabilityDenied, PathDenied(Denial), InvalidPath(&'static str), TooLarge { limit: u64 }, Io(Error), } ``` Failure of one filesystem operation performed for an origin. ## Variants ### `CapabilityDenied` ```rust CapabilityDenied ``` No grant of the origin carries the capability the operation needs. ### `PathDenied` ```rust PathDenied(Denial) ``` A grant carries the capability, but not for this path. ### `InvalidPath` ```rust InvalidPath(&'static str) ``` The request path is malformed. The reason is a category, never the path. ### `TooLarge` ```rust TooLarge { limit: u64 } ``` The file is larger than the transfer limit ([`FilesystemBuilder::max_file_size`](https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.max_file_size)). [crate::capability::FilesystemBuilder::max_file_size]: https://kurogane-rs.org/docs/api/capabilities/filesystembuilder.md#method.max_file_size ### `Io` ```rust Io(Error) ``` The authorized operation failed in the OS. The caller is inside the grant for this object. The OS detail may be shown. ## Trait implementations - `impl Debug for FsError` - `impl Display for FsError` - `impl Error for FsError` - `impl From<Error> for FsError` - `impl From<FsError> for IpcError` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/capability/error.rs#L43 --- # Requests and decisions > What a page or Chromium asks of your application and the answers it can give. - [`AppItem`](https://kurogane-rs.org/docs/api/requests/appitem.md) (struct): An item of the application's in a `ContextMenu`. - [`ChromeCommandRequest`](https://kurogane-rs.org/docs/api/requests/chromecommandrequest.md) (struct): A command about to run, passed to [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command). - [`ContextMenu`](https://kurogane-rs.org/docs/api/requests/contextmenu.md) (struct): The menu a right-click opens, passed to [`App::on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu) to edit. - [`ContextMenuCommand`](https://kurogane-rs.org/docs/api/requests/contextmenucommand.md) (struct): An item of the application's chosen, passed to [`App::on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command). - [`ContextMenuTarget`](https://kurogane-rs.org/docs/api/requests/contextmenutarget.md) (struct): What a right-click was on. - [`DownloadRequest`](https://kurogane-rs.org/docs/api/requests/downloadrequest.md) (struct): A download about to start, passed to [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download). - [`DragEnter`](https://kurogane-rs.org/docs/api/requests/dragenter.md) (struct): A drag entering a window, passed to [`App::on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter). - [`FileDialogRequest`](https://kurogane-rs.org/docs/api/requests/filedialogrequest.md) (struct): A page opening a file chooser, passed to [`App::on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog). - [`FileDialogResponder`](https://kurogane-rs.org/docs/api/requests/filedialogresponder.md) (struct): Answers a `FileDialogRequest` the hook left for later (`FileDialogDecision::Later`), from any thread. - [`KeyPress`](https://kurogane-rs.org/docs/api/requests/keypress.md) (struct): A key the user pressed, passed to [`App::on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key). - [`Modifiers`](https://kurogane-rs.org/docs/api/requests/modifiers.md) (struct): The modifier keys held with a key. - [`NavigationRequest`](https://kurogane-rs.org/docs/api/requests/navigationrequest.md) (struct): A page's navigation of the window it is in, passed to [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation). - [`NewWindowRequest`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md) (struct): A page's request for a new window, passed to [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window). - [`PermissionRequest`](https://kurogane-rs.org/docs/api/requests/permissionrequest.md) (struct): A page asking for a device or a permission, passed to [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission). - [`PermissionResponder`](https://kurogane-rs.org/docs/api/requests/permissionresponder.md) (struct): Answers a `PermissionRequest` the hook left for later (`PermissionDecision::Later`), from any thread. - [`Submenu`](https://kurogane-rs.org/docs/api/requests/submenu.md) (struct): A submenu of a `ContextMenu`. Shown only when an item of it is. - [`ChromeCommand`](https://kurogane-rs.org/docs/api/requests/chromecommand.md) (enum): A command Chromium runs in a window of the application's, from a key shortcut or the context menu, as [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) is asked about it. Chromium's own commands are folded by what the user asked for. Every kind of reload is [`Reload`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Reload); the context menu's Copy and Ctrl+C are both [`Copy`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Copy). - [`CommandDecision`](https://kurogane-rs.org/docs/api/requests/commanddecision.md) (enum): The answer of [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command). - [`DownloadDecision`](https://kurogane-rs.org/docs/api/requests/downloaddecision.md) (enum): The answer of [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download). - [`DragDecision`](https://kurogane-rs.org/docs/api/requests/dragdecision.md) (enum): The answer of [`App::on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter). - [`FileDialogDecision`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md) (enum): The answer of [`App::on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog). - [`FileDialogKind`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md) (enum): What kind of file chooser a page opens (`FileDialogRequest::kind`). - [`Key`](https://kurogane-rs.org/docs/api/requests/key.md) (enum): A key by its place on the keyboard rather than what it types. Shift+W and W are both `Key::Char('W')`. - [`KeyDecision`](https://kurogane-rs.org/docs/api/requests/keydecision.md) (enum): The answer of [`App::on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key). - [`MediaKind`](https://kurogane-rs.org/docs/api/requests/mediakind.md) (enum): What kind of media was right-clicked. - [`MenuItem`](https://kurogane-rs.org/docs/api/requests/menuitem.md) (enum): An item of a `ContextMenu`. - [`NavigationDecision`](https://kurogane-rs.org/docs/api/requests/navigationdecision.md) (enum): The answer of [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation). - [`NewWindowDecision`](https://kurogane-rs.org/docs/api/requests/newwindowdecision.md) (enum): The answer of [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window). - [`NewWindowKind`](https://kurogane-rs.org/docs/api/requests/newwindowkind.md) (enum): How a page asked for a window of its own (`NewWindowRequest::kind`). - [`Permission`](https://kurogane-rs.org/docs/api/requests/permission.md) (enum): What a page asks for, in a `PermissionRequest`. - [`PermissionDecision`](https://kurogane-rs.org/docs/api/requests/permissiondecision.md) (enum): The answer of [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission). - [`StandardItem`](https://kurogane-rs.org/docs/api/requests/standarditem.md) (enum): One of Kurogane's items, which runs a command of Chromium's. --- # Struct `kurogane::AppItem` ```rust pub struct AppItem { /* private fields */ } ``` An item of the application's in a [`ContextMenu`]. [`ContextMenu`]: https://kurogane-rs.org/docs/api/requests/contextmenu.md ## Methods ### `new` ```rust pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self ``` An item that reports `id` when chosen, shown as `label` (see [`MenuItem::new`]). [`MenuItem::new`]: https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new ### `enabled` ```rust pub fn enabled(self, enabled: bool) -> Self ``` Shown greyed out and not chosen, when `enabled` is false. ### `checked` ```rust pub fn checked(self, checked: bool) -> Self ``` A check item, shown checked when `checked` is true. Choosing it does not change the mark; the application shows it as it decides. ### `id` ```rust pub fn id(&self) -> &str ``` The id it reports when chosen. ### `label` ```rust pub fn label(&self) -> &str ``` ### `is_enabled` ```rust pub fn is_enabled(&self) -> bool ``` ### `is_checked` ```rust pub fn is_checked(&self) -> Option<bool> ``` Whether it is checked, for a check item. ## Trait implementations - `impl Clone for AppItem` - `impl Debug for AppItem` - `impl Eq for AppItem` - `impl From<AppItem> for MenuItem` - `impl PartialEq for AppItem` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L152 --- # Struct `kurogane::ChromeCommandRequest` ```rust pub struct ChromeCommandRequest { /* private fields */ } ``` A command about to run, passed to [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command). [crate::App::on_chrome_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command ## Methods ### `command` ```rust pub fn command(&self) -> ChromeCommand ``` The command. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser it runs in. ## Trait implementations - `impl Clone for ChromeCommandRequest` - `impl Debug for ChromeCommandRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/chrome_commands.rs#L71 --- # Struct `kurogane::ContextMenu` ```rust pub struct ContextMenu { /* private fields */ } ``` The menu a right-click opens, passed to [`App::on_context_menu`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu) to edit. [crate::App::on_context_menu]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu ## Methods ### `target` ```rust pub fn target(&self) -> &ContextMenuTarget ``` What the right-click was on. ### `items` ```rust pub fn items(&self) -> &[MenuItem] ``` ### `items_mut` ```rust pub fn items_mut(&mut self) -> &mut Vec<MenuItem> ``` ### `push` ```rust pub fn push(&mut self, item: impl Into<MenuItem>) ``` Adds `item` at the end. ### `remove` ```rust pub fn remove(&mut self, item: StandardItem) ``` Takes `item` out, from its submenus too. ### `clear` ```rust pub fn clear(&mut self) ``` Takes every item out. An empty menu does not show. ## Trait implementations - `impl Clone for ContextMenu` - `impl Debug for ContextMenu` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L356 --- # Struct `kurogane::ContextMenuCommand` ```rust pub struct ContextMenuCommand { /* private fields */ } ``` An item of the application's chosen, passed to [`App::on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command). [crate::App::on_context_menu_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command ## Methods ### `id` ```rust pub fn id(&self) -> &str ``` The item's id, as [`MenuItem::new`] gave it. [`MenuItem::new`]: https://kurogane-rs.org/docs/api/requests/menuitem.md#method.new ### `target` ```rust pub fn target(&self) -> &ContextMenuTarget ``` What the right-click that opened the menu was on. ## Trait implementations - `impl Clone for ContextMenuCommand` - `impl Debug for ContextMenuCommand` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L403 --- # Struct `kurogane::ContextMenuTarget` ```rust pub struct ContextMenuTarget { /* private fields */ } ``` What a right-click was on. ## Methods ### `origin` ```rust pub fn origin(&self) -> &Origin ``` Returns the origin of the document right-clicked (the page's or a frame's inside it). A sandboxed document's origin is opaque here whatever its URL. ### `page_url` ```rust pub fn page_url(&self) -> &str ``` The URL of the page the browser shows. ### `frame_url` ```rust pub fn frame_url(&self) -> &str ``` The URL of the document right-clicked, the page's or a frame's. ### `link_url` ```rust pub fn link_url(&self) -> Option<&str> ``` The URL of the link right-clicked. ### `media` ```rust pub fn media(&self) -> Option<MediaKind> ``` Returns the kind of media right-clicked (for example an image or a video). ### `media_url` ```rust pub fn media_url(&self) -> Option<&str> ``` The URL of the media right-clicked, when it has one. ### `selection` ```rust pub fn selection(&self) -> Option<&str> ``` The text selected where the right-click was. ### `is_editable` ```rust pub fn is_editable(&self) -> bool ``` Whether the right-click was in a text field or other editable content. ### `misspelled_word` ```rust pub fn misspelled_word(&self) -> Option<&str> ``` The misspelled word right-clicked. ### `position` ```rust pub fn position(&self) -> (i32, i32) ``` Where the right-click was, in the browser's view. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser right-clicked. ## Trait implementations - `impl Clone for ContextMenuTarget` - `impl Debug for ContextMenuTarget` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L245 --- # Struct `kurogane::DownloadRequest` ```rust pub struct DownloadRequest { /* private fields */ } ``` A download about to start, passed to [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download). [crate::App::on_download]: https://kurogane-rs.org/docs/api/app/app.md#method.on_download ## Methods ### `url` ```rust pub fn url(&self) -> &str ``` The URL the file comes from. ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin of the page the download comes from. That is the document the window shows, which a frame inside it counts as. ### `suggested_name` ```rust pub fn suggested_name(&self) -> &str ``` The file name the server or the page suggests, a name only, without a directory. Chromium has already made it safe for the platform. ### `mime_type` ```rust pub fn mime_type(&self) -> &str ``` The file's MIME type, empty when it is unknown. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser the download comes from. ## Trait implementations - `impl Clone for DownloadRequest` - `impl Debug for DownloadRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/downloads.rs#L34 --- # Struct `kurogane::DragEnter` ```rust pub struct DragEnter { /* private fields */ } ``` A drag entering a window, passed to [`App::on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter). [crate::App::on_drag_enter]: https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter ## Methods ### `files` ```rust pub fn files(&self) -> &[PathBuf] ``` The paths of the files dragged, as the system gives them; empty for a drag of no file. ### `link_url` ```rust pub fn link_url(&self) -> Option<&str> ``` The link dragged, if it is one. ### `text` ```rust pub fn text(&self) -> Option<&str> ``` The text dragged, if it is some. ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin of the page the drag enters. It is the window's own page. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser the drag enters. ## Trait implementations - `impl Clone for DragEnter` - `impl Debug for DragEnter` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/drag.rs#L25 --- # Struct `kurogane::FileDialogRequest` ```rust pub struct FileDialogRequest { /* private fields */ } ``` A page opening a file chooser, passed to [`App::on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog). [crate::App::on_file_dialog]: https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog ## Methods ### `kind` ```rust pub fn kind(&self) -> FileDialogKind ``` What the page asks to choose. ### `title` ```rust pub fn title(&self) -> &str ``` The dialog's title as the page gives it; empty for the system's own. ### `default_path` ```rust pub fn default_path(&self) -> Option<&Path> ``` The file name or path the dialog would start at, if any. For a picker it is the suggested name for saving. ### `accept` ```rust pub fn accept(&self) -> &[String] ``` What the page accepts as it wrote it, in MIME types (`image/*`, `text/plain`) and extensions (`.png`). Empty when it accepts any file. ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin of the page that opens the dialog. That page is the frame that has the focus, the one whose control the user activated. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser of the page. ### `responder` ```rust pub fn responder(&self) -> FileDialogResponder ``` A responder that answers this request later from any thread once the hook returns [`FileDialogDecision::Later`] (after the application's own picker closed, for example). With any other answer from the hook the responder does nothing. [`FileDialogDecision::Later`]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Later ## Trait implementations - `impl Debug for FileDialogRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/file_dialog.rs#L63 --- # Struct `kurogane::FileDialogResponder` ```rust pub struct FileDialogResponder { /* private fields */ } ``` Answers a [`FileDialogRequest`] the hook left for later ([`FileDialogDecision::Later`]), from any thread. A request is answered once and the first answer counts. Dropping every responder of a request without answering cancels it. An answer that comes after the page went away gives it nothing. ```rust App::new("./dist") .on_file_dialog(|request, _| { let responder = request.responder(); std::thread::spawn(move || match pick_files() { Some(files) => responder.select(files), None => responder.cancel(), }); FileDialogDecision::Later }) .run_or_exit(); ``` [`FileDialogRequest`]: https://kurogane-rs.org/docs/api/requests/filedialogrequest.md [`FileDialogDecision::Later`]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Later ## Methods ### `select` ```rust pub fn select(self, files: Vec<PathBuf>) ``` Gives the page `files`, as [`FileDialogDecision::Files`] does. [`FileDialogDecision::Files`]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Files ### `cancel` ```rust pub fn cancel(self) ``` Tells the page the user cancelled. ## Trait implementations - `impl Debug for FileDialogResponder` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/file_dialog.rs#L194 --- # Struct `kurogane::KeyPress` ```rust pub struct KeyPress { /* private fields */ } ``` A key the user pressed, passed to [`App::on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key). [crate::App::on_key]: https://kurogane-rs.org/docs/api/app/app.md#method.on_key ## Methods ### `key` ```rust pub fn key(&self) -> Key ``` The key. ### `modifiers` ```rust pub fn modifiers(&self) -> Modifiers ``` The modifier keys held with it. ### `character` ```rust pub fn character(&self) -> Option<char> ``` Returns the character the press types. There is none with a modifier that turns it into a control character (Ctrl+W) and none for keys that type nothing (F5, the arrows). ### `in_editable_field` ```rust pub fn in_editable_field(&self) -> bool ``` Whether the focus is in a field the user types into (an input, a text area, an editable element). ### `repeat` ```rust pub fn repeat(&self) -> bool ``` Whether the key is held down and this press is its repeat. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser the key went to. ### `command` ```rust pub fn command(&self) -> Option<ChromeCommand> ``` Returns the command the key runs as one of Kurogane's shortcuts on any OS. Ctrl+W (Cmd+W on macOS) is [`Close`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Close). Ctrl+R and F5 are [`Reload`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Reload). Ctrl+Shift+I (Cmd+Option+I) and F12 are [`DevTools`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.DevTools). macOS's Cmd+Q quits and names no command. A browser embedded in the application's own window runs no shortcut and names none. [ChromeCommand::Close]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Close [ChromeCommand::Reload]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Reload [ChromeCommand::DevTools]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.DevTools ## Trait implementations - `impl Clone for KeyPress` - `impl Debug for KeyPress` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/keys.rs#L21 --- # Struct `kurogane::Modifiers` ```rust pub struct Modifiers(/* private field */); ``` The modifier keys held with a key. ## Methods ### `shift` ```rust pub fn shift(self) -> bool ``` ### `ctrl` ```rust pub fn ctrl(self) -> bool ``` ### `alt` ```rust pub fn alt(self) -> bool ``` Alt, Option on macOS. ### `meta` ```rust pub fn meta(self) -> bool ``` Cmd on macOS, the Windows key elsewhere. ### `primary` ```rust pub fn primary(self) -> bool ``` Returns whether the modifier of the platform's shortcuts is held (Cmd on macOS, Ctrl elsewhere). Ctrl+W on Windows and Linux and Cmd+W on macOS both have it. ### `none` ```rust pub fn none(self) -> bool ``` Whether no modifier is held (Shift included). ## Trait implementations - `impl Clone for Modifiers` - `impl Copy for Modifiers` - `impl Debug for Modifiers` - `impl Default for Modifiers` - `impl Eq for Modifiers` - `impl PartialEq for Modifiers` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/keys.rs#L173 --- # Struct `kurogane::NavigationRequest` ```rust pub struct NavigationRequest { /* private fields */ } ``` A page's navigation of the window it is in, passed to [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation). [crate::App::on_navigation]: https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation ## Methods ### `url` ```rust pub fn url(&self) -> &str ``` The URL the window would load. ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin of the document the window would show. ### `from_origin` ```rust pub fn from_origin(&self) -> &Origin ``` The origin of the document the window shows now. ### `user_gesture` ```rust pub fn user_gesture(&self) -> bool ``` Whether the user asked, by clicking a link or a button, rather than a script on its own. ### `is_redirect` ```rust pub fn is_redirect(&self) -> bool ``` Whether the server sent the navigation here from the URL it asked for first. ## Trait implementations - `impl Clone for NavigationRequest` - `impl Debug for NavigationRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/navigation.rs#L27 --- # Struct `kurogane::NewWindowRequest` ```rust pub struct NewWindowRequest { /* private fields */ } ``` A page's request for a new window, passed to [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window). An application can make one to test its own hook: ```rust use kurogane::{NewWindowKind, NewWindowRequest}; let request = NewWindowRequest::new("https://docs.rs/", "app://app/index.html") .with_user_gesture(true) .with_kind(NewWindowKind::Popup); assert_eq!(request.origin().to_string(), "https://docs.rs"); assert_eq!(request.opener_origin().to_string(), "app://app"); ``` [crate::App::on_new_window]: https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window ## Methods ### `new` ```rust pub fn new(url: impl Into<String>, opener_url: &str) -> Self ``` Creates the request of a page at `opener_url` for a window showing `url`. It is a tab a script asked for until [`with_kind`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.with_kind) and [`with_user_gesture`](https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.with_user_gesture) say otherwise. The origins are worked out as Kurogane works them out for a page's request. [Self::with_kind]: https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.with_kind [Self::with_user_gesture]: https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.with_user_gesture ### `with_user_gesture` ```rust pub fn with_user_gesture(self, user_gesture: bool) -> Self ``` This request, asked for by the user (`true`) or by a script. ### `with_kind` ```rust pub fn with_kind(self, kind: NewWindowKind) -> Self ``` This request, for a window of `kind`. ### `url` ```rust pub fn url(&self) -> &str ``` The URL the window would load, as Chromium resolved it. Empty or `about:blank` when the page fills the window in itself. ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin of the document the window would show. A window the page fills in itself has the page's origin. A `blob:` URL has the origin of the page that made it. ### `opener_origin` ```rust pub fn opener_origin(&self) -> &Origin ``` The origin of the page that asked. ### `user_gesture` ```rust pub fn user_gesture(&self) -> bool ``` Whether the user asked, by clicking a link or a button, rather than a script on its own. ### `kind` ```rust pub fn kind(&self) -> NewWindowKind ``` What the page asked for (a tab, a popup or a window). Kurogane opens each as an application window alike; the kind says how the page asked. ## Trait implementations - `impl Clone for NewWindowRequest` - `impl Debug for NewWindowRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/new_window.rs#L37 --- # Struct `kurogane::PermissionRequest` ```rust pub struct PermissionRequest { /* private fields */ } ``` A page asking for a device or a permission, passed to [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission). [crate::App::on_permission]: https://kurogane-rs.org/docs/api/app/app.md#method.on_permission ## Methods ### `origin` ```rust pub fn origin(&self) -> &Origin ``` The origin that asks. It is the page's, or a frame's inside it when the frame asks. ### `permissions` ```rust pub fn permissions(&self) -> &[Permission] ``` What the request asks for, all of it together. A page asking for a camera and a microphone at once is granted both or neither. ### `browser` ```rust pub fn browser(&self) -> Option<BrowserId> ``` The browser of the page that asks. ### `responder` ```rust pub fn responder(&self) -> PermissionResponder ``` A responder that answers this request later, from any thread, once the hook returns [`PermissionDecision::Later`] (after asking the user, for example). The responder does nothing after any other answer from the hook. [`PermissionDecision::Later`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Later ## Trait implementations - `impl Debug for PermissionRequest` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/permissions.rs#L372 --- # Struct `kurogane::PermissionResponder` ```rust pub struct PermissionResponder { /* private fields */ } ``` Answers a [`PermissionRequest`] the hook left for later ([`PermissionDecision::Later`]), from any thread. A request is answered once; the first answer counts. Dropping every responder of a request without answering denies it. An answer that comes after the page went away grants nothing. ```rust App::new("./dist") .on_permission(|request, _| { let question = format!("Allow {:?} for {}?", request.permissions(), request.origin()); let responder = request.responder(); std::thread::spawn(move || { if ask_the_user(&question) { responder.allow(); } else { responder.deny(); } }); PermissionDecision::Later }) .run_or_exit(); ``` [`PermissionDecision::Later`]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Later [`PermissionRequest`]: https://kurogane-rs.org/docs/api/requests/permissionrequest.md ## Methods ### `allow` ```rust pub fn allow(self) ``` Grants everything the request asks for. ### `deny` ```rust pub fn deny(self) ``` Grants nothing. ## Trait implementations - `impl Debug for PermissionResponder` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/permissions.rs#L490 --- # Struct `kurogane::Submenu` ```rust pub struct Submenu { /* private fields */ } ``` A submenu of a [`ContextMenu`]. Shown only when an item of it is. [`ContextMenu`]: https://kurogane-rs.org/docs/api/requests/contextmenu.md ## Methods ### `new` ```rust pub fn new( label: impl Into<String>, items: impl IntoIterator<Item = MenuItem>, ) -> Self ``` ### `label` ```rust pub fn label(&self) -> &str ``` ### `items` ```rust pub fn items(&self) -> &[MenuItem] ``` ### `items_mut` ```rust pub fn items_mut(&mut self) -> &mut Vec<MenuItem> ``` ## Trait implementations - `impl Clone for Submenu` - `impl Debug for Submenu` - `impl Eq for Submenu` - `impl From<Submenu> for MenuItem` - `impl PartialEq for Submenu` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L205 --- # Enum `kurogane::ChromeCommand` ```rust #[non_exhaustive] pub enum ChromeCommand { Back, Forward, Reload, Stop, ZoomIn, ZoomOut, ZoomReset, Fullscreen, Find, Print, Cut, Copy, Paste, Delete, SelectAll, Undo, Redo, Close, DevTools, } ``` A command Chromium runs in a window of the application's, from a key shortcut or the context menu, as [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command) is asked about it. Chromium's own commands are folded by what the user asked for. Every kind of reload is [`Reload`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Reload); the context menu's Copy and Ctrl+C are both [`Copy`](https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Copy). [Self::Reload]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Reload [Self::Copy]: https://kurogane-rs.org/docs/api/requests/chromecommand.md#variant.Copy [crate::App::on_chrome_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command ## Variants ### `Back` ```rust Back ``` ### `Forward` ```rust Forward ``` ### `Reload` ```rust Reload ``` Reload, also bypassing or clearing the cache. ### `Stop` ```rust Stop ``` ### `ZoomIn` ```rust ZoomIn ``` ### `ZoomOut` ```rust ZoomOut ``` ### `ZoomReset` ```rust ZoomReset ``` ### `Fullscreen` ```rust Fullscreen ``` ### `Find` ```rust Find ``` Find, find next and find previous. ### `Print` ```rust Print ``` ### `Cut` ```rust Cut ``` ### `Copy` ```rust Copy ``` ### `Paste` ```rust Paste ``` Paste, also matching the style around it. ### `Delete` ```rust Delete ``` ### `SelectAll` ```rust SelectAll ``` ### `Undo` ```rust Undo ``` ### `Redo` ```rust Redo ``` ### `Close` ```rust Close ``` Closing the window (Ctrl+W and Ctrl+Shift+W). ### `DevTools` ```rust DevTools ``` DevTools, its console, inspect and the context menu's Inspect. ## Trait implementations - `impl Clone for ChromeCommand` - `impl Copy for ChromeCommand` - `impl Debug for ChromeCommand` - `impl Eq for ChromeCommand` - `impl Hash for ChromeCommand` - `impl PartialEq for ChromeCommand` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/chrome_commands.rs#L41 --- # Enum `kurogane::CommandDecision` ```rust #[non_exhaustive] pub enum CommandDecision { Default, Refuse, } ``` The answer of [`App::on_chrome_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command). [crate::App::on_chrome_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_chrome_command ## Variants ### `Default` ```rust Default ``` The command runs. ### `Refuse` ```rust Refuse ``` The command does not run. ## Trait implementations - `impl Clone for CommandDecision` - `impl Copy for CommandDecision` - `impl Debug for CommandDecision` - `impl Default for CommandDecision` - `impl Eq for CommandDecision` - `impl PartialEq for CommandDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/chrome_commands.rs#L95 --- # Enum `kurogane::DownloadDecision` ```rust #[non_exhaustive] pub enum DownloadDecision { Default, Prompt, SaveTo(PathBuf), Deny, } ``` The answer of [`App::on_download`](https://kurogane-rs.org/docs/api/app/app.md#method.on_download). [crate::App::on_download]: https://kurogane-rs.org/docs/api/app/app.md#method.on_download ## Variants ### `Default` ```rust Default ``` Kurogane's policy, which is [`Prompt`](https://kurogane-rs.org/docs/api/requests/downloaddecision.md#variant.Prompt). [Self::Prompt]: https://kurogane-rs.org/docs/api/requests/downloaddecision.md#variant.Prompt ### `Prompt` ```rust Prompt ``` Asks the user with the system's Save As dialog, the suggested name filled in; cancelling it saves nothing. A window shows one dialog at a time. A download may wait for the one before it. ### `SaveTo` ```rust SaveTo(PathBuf) ``` Saves the file at this absolute path, which names the file itself, without asking, replacing a file already there. The folder is created when missing. A place whose folder cannot be made saves nothing and neither does a relative path. ### `Deny` ```rust Deny ``` Saves nothing. ## Trait implementations - `impl Clone for DownloadDecision` - `impl Debug for DownloadDecision` - `impl Default for DownloadDecision` - `impl Eq for DownloadDecision` - `impl PartialEq for DownloadDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/downloads.rs#L90 --- # Enum `kurogane::DragDecision` ```rust #[non_exhaustive] pub enum DragDecision { Default, Allow, Refuse, } ``` The answer of [`App::on_drag_enter`](https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter). [crate::App::on_drag_enter]: https://kurogane-rs.org/docs/api/app/app.md#method.on_drag_enter ## Variants ### `Default` ```rust Default ``` Kurogane's policy. The drag goes on as with [`Allow`](https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Allow). [Self::Allow]: https://kurogane-rs.org/docs/api/requests/dragdecision.md#variant.Allow ### `Allow` ```rust Allow ``` The drag goes on. The page sees it and may take its drop. ### `Refuse` ```rust Refuse ``` The drag stops at the window. The page sees nothing of it and the pointer shows it cannot drop there. ## Trait implementations - `impl Clone for DragDecision` - `impl Copy for DragDecision` - `impl Debug for DragDecision` - `impl Default for DragDecision` - `impl Eq for DragDecision` - `impl PartialEq for DragDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/drag.rs#L80 --- # Enum `kurogane::FileDialogDecision` ```rust #[non_exhaustive] pub enum FileDialogDecision { Default, Cancel, Files(Vec<PathBuf>), Later, } ``` The answer of [`App::on_file_dialog`](https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog). [crate::App::on_file_dialog]: https://kurogane-rs.org/docs/api/app/app.md#method.on_file_dialog ## Variants ### `Default` ```rust Default ``` Chromium's own dialog, the system's file chooser. ### `Cancel` ```rust Cancel ``` No dialog. The page is told the user cancelled. ### `Files` ```rust Files(Vec<PathBuf>) ``` These files, as if the user chose them. The page reads them. An [`Open`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.Open) or [`Save`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.Save) dialog takes the first, an [`OpenFolder`](https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.OpenFolder) one a folder. No file is [`Cancel`](https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Cancel). [Self::Cancel]: https://kurogane-rs.org/docs/api/requests/filedialogdecision.md#variant.Cancel [FileDialogKind::Save]: https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.Save [FileDialogKind::OpenFolder]: https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.OpenFolder [FileDialogKind::Open]: https://kurogane-rs.org/docs/api/requests/filedialogkind.md#variant.Open ### `Later` ```rust Later ``` The [`FileDialogResponder`] the hook took with [`FileDialogRequest::responder`] answers later; the page waits until then. Without a responder kept, the dialog is cancelled at once. [`FileDialogRequest::responder`]: https://kurogane-rs.org/docs/api/requests/filedialogrequest.md#method.responder [`FileDialogResponder`]: https://kurogane-rs.org/docs/api/requests/filedialogresponder.md ## Trait implementations - `impl Clone for FileDialogDecision` - `impl Debug for FileDialogDecision` - `impl Default for FileDialogDecision` - `impl Eq for FileDialogDecision` - `impl PartialEq for FileDialogDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/file_dialog.rs#L151 --- # Enum `kurogane::FileDialogKind` ```rust #[non_exhaustive] pub enum FileDialogKind { Open, OpenMultiple, OpenFolder, Save, } ``` What kind of file chooser a page opens ([`FileDialogRequest::kind`]). [`FileDialogRequest::kind`]: https://kurogane-rs.org/docs/api/requests/filedialogrequest.md#method.kind ## Variants ### `Open` ```rust Open ``` One existing file. ### `OpenMultiple` ```rust OpenMultiple ``` One or more existing files (`<input type=file multiple>`). ### `OpenFolder` ```rust OpenFolder ``` A folder (`<input type=file webkitdirectory>`, `showDirectoryPicker`). ### `Save` ```rust Save ``` A file to save to, which may not exist yet (`showSaveFilePicker`). ## Trait implementations - `impl Clone for FileDialogKind` - `impl Copy for FileDialogKind` - `impl Debug for FileDialogKind` - `impl Eq for FileDialogKind` - `impl Hash for FileDialogKind` - `impl PartialEq for FileDialogKind` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/file_dialog.rs#L29 --- # Enum `kurogane::Key` ```rust #[non_exhaustive] pub enum Key { Char(char), Digit(u8), F(u8), Escape, Enter, Tab, Space, Backspace, Delete, Insert, Home, End, PageUp, PageDown, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Other(u32), } ``` A key by its place on the keyboard rather than what it types. Shift+W and W are both `Key::Char('W')`. ## Variants ### `Char` ```rust Char(char) ``` A letter key, as its uppercase ASCII letter. ### `Digit` ```rust Digit(u8) ``` A digit key of the top row, 0 to 9. ### `F` ```rust F(u8) ``` A function key, F1 to F24. ### `Escape` ```rust Escape ``` ### `Enter` ```rust Enter ``` ### `Tab` ```rust Tab ``` ### `Space` ```rust Space ``` ### `Backspace` ```rust Backspace ``` ### `Delete` ```rust Delete ``` ### `Insert` ```rust Insert ``` ### `Home` ```rust Home ``` ### `End` ```rust End ``` ### `PageUp` ```rust PageUp ``` ### `PageDown` ```rust PageDown ``` ### `ArrowUp` ```rust ArrowUp ``` ### `ArrowDown` ```rust ArrowDown ``` ### `ArrowLeft` ```rust ArrowLeft ``` ### `ArrowRight` ```rust ArrowRight ``` ### `Other` ```rust Other(u32) ``` Any other key by its Windows virtual-key code, which CEF uses on every platform. Such keys are punctuation (whose code depends on the keyboard layout), the keypad and the modifier keys themselves. ## Trait implementations - `impl Clone for Key` - `impl Copy for Key` - `impl Debug for Key` - `impl Eq for Key` - `impl Hash for Key` - `impl PartialEq for Key` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/keys.rs#L104 --- # Enum `kurogane::KeyDecision` ```rust #[non_exhaustive] pub enum KeyDecision { Default, Consume, PageFirst, } ``` The answer of [`App::on_key`](https://kurogane-rs.org/docs/api/app/app.md#method.on_key). [crate::App::on_key]: https://kurogane-rs.org/docs/api/app/app.md#method.on_key ## Variants ### `Default` ```rust Default ``` The key goes on in Kurogane's order on every OS. A shortcut that closes the window or quits (Ctrl+W, Cmd+Q on macOS) runs before the page sees the key. The page never gets it. Every other shortcut (Ctrl+F, Ctrl+P, Ctrl+R, F5) reaches the page first and runs only if the page does not prevent the key's default. Kurogane refuses the commands of Chromium's keys for new tabs and windows (Ctrl+T, Ctrl+N). Those keys reach the page as any key. ### `Consume` ```rust Consume ``` The key goes nowhere. Neither a shortcut nor the page sees it, its character or its release. ### `PageFirst` ```rust PageFirst ``` The key goes to the page first. Its shortcut runs only if the page does not prevent the key's default. Under [`Default`](https://kurogane-rs.org/docs/api/requests/keydecision.md#variant.Default) every shortcut but closing and quitting has this order. A page binds Ctrl+W for itself this way. For shortcuts only. A key that types a character and is answered `PageFirst` types nothing unless the page handles its keydown. Chromium drops the character of a shortcut the page left alone. AltGr arrives as Ctrl+Alt on Windows. The page then decides whether the shortcut runs. One that prevents Ctrl+W keeps its window open and one that hangs holds the key. Closing and quitting run before the page so that no page can keep them. Answer `PageFirst` only for windows that show the application's own pages ([`KeyPress::browser`]). [Self::Default]: https://kurogane-rs.org/docs/api/requests/keydecision.md#variant.Default [`KeyPress::browser`]: https://kurogane-rs.org/docs/api/requests/keypress.md#method.browser ## Trait implementations - `impl Clone for KeyDecision` - `impl Copy for KeyDecision` - `impl Debug for KeyDecision` - `impl Default for KeyDecision` - `impl Eq for KeyDecision` - `impl PartialEq for KeyDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/keys.rs#L223 --- # Enum `kurogane::MediaKind` ```rust #[non_exhaustive] pub enum MediaKind { Image, Video, Audio, Canvas, File, Plugin, } ``` What kind of media was right-clicked. ## Variants ### `Image` ```rust Image ``` ### `Video` ```rust Video ``` ### `Audio` ```rust Audio ``` ### `Canvas` ```rust Canvas ``` ### `File` ```rust File ``` ### `Plugin` ```rust Plugin ``` ## Trait implementations - `impl Clone for MediaKind` - `impl Copy for MediaKind` - `impl Debug for MediaKind` - `impl Eq for MediaKind` - `impl Hash for MediaKind` - `impl PartialEq for MediaKind` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L234 --- # Enum `kurogane::MenuItem` ```rust #[non_exhaustive] pub enum MenuItem { Standard(StandardItem), App(AppItem), Submenu(Submenu), Separator, } ``` An item of a [`ContextMenu`]. [`ContextMenu`]: https://kurogane-rs.org/docs/api/requests/contextmenu.md ## Variants ### `Standard` ```rust Standard(StandardItem) ``` One of Kurogane's items. ### `App` ```rust App(AppItem) ``` An item of the application's, which reports its choice to [`App::on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command). [crate::App::on_context_menu_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command ### `Submenu` ```rust Submenu(Submenu) ``` A submenu. ### `Separator` ```rust Separator ``` A line between groups of items. One at an edge of a menu, or next to another, is not shown. ## Methods ### `new` ```rust pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self ``` An item of the application's. Choosing it calls [`App::on_context_menu_command`](https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command) with `id`. In a window's menu an `&` in `label` marks the letter that chooses it from the keyboard and `&&` shows an `&`. An embedded browser's menu, which CEF draws, takes every `&` out of a label. There a typed letter chooses the item whose label begins with it. A label cannot show an `&`. [crate::App::on_context_menu_command]: https://kurogane-rs.org/docs/api/app/app.md#method.on_context_menu_command ### `separator` ```rust pub fn separator() -> Self ``` A line between groups of items. ### `submenu` ```rust pub fn submenu( label: impl Into<String>, items: impl IntoIterator<Item = MenuItem>, ) -> Self ``` A submenu of `items`, under `label`. ## Trait implementations - `impl Clone for MenuItem` - `impl Debug for MenuItem` - `impl Eq for MenuItem` - `impl From<AppItem> for MenuItem` - `impl From<StandardItem> for MenuItem` - `impl From<Submenu> for MenuItem` - `impl PartialEq for MenuItem` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L94 --- # Enum `kurogane::NavigationDecision` ```rust #[non_exhaustive] pub enum NavigationDecision { Default, Allow, Deny, OpenExternal, } ``` The answer of [`App::on_navigation`](https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation). [crate::App::on_navigation]: https://kurogane-rs.org/docs/api/app/app.md#method.on_navigation ## Variants ### `Default` ```rust Default ``` Kurogane's policy decides. An origin the window may show is loaded. An `http` or `https` link the user clicked to any other origin goes to the system browser. Anything else is refused. ### `Allow` ```rust Allow ``` Loads the page and lets its origin into this window from now on. The page reaches only the commands and events that [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) and its kin grant its origin. [crate::App::permit]: https://kurogane-rs.org/docs/api/app/app.md#method.permit ### `Deny` ```rust Deny ``` Refuses the navigation; the window stays on its page. ### `OpenExternal` ```rust OpenExternal ``` Opens the URL in the system's default browser instead. The window stays on its page. Only an `http` or `https` link the user clicked goes there; any other navigation is refused. ## Trait implementations - `impl Clone for NavigationDecision` - `impl Copy for NavigationDecision` - `impl Debug for NavigationDecision` - `impl Default for NavigationDecision` - `impl Eq for NavigationDecision` - `impl PartialEq for NavigationDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/navigation.rs#L80 --- # Enum `kurogane::NewWindowDecision` ```rust #[non_exhaustive] pub enum NewWindowDecision { Default, Allow, Deny, OpenExternal, } ``` The answer of [`App::on_new_window`](https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window). [crate::App::on_new_window]: https://kurogane-rs.org/docs/api/app/app.md#method.on_new_window ## Variants ### `Default` ```rust Default ``` Kurogane's policy decides. A page of the application's own origin gets a window, an `http` or `https` link the user clicked goes to the system browser and anything else is refused. ### `Allow` ```rust Allow ``` Opens the page in an application window, whatever its origin. The page reaches only the commands and events that [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) and its kin grant its origin. [crate::App::permit]: https://kurogane-rs.org/docs/api/app/app.md#method.permit ### `Deny` ```rust Deny ``` Opens no window. ### `OpenExternal` ```rust OpenExternal ``` Opens the URL in the system's default browser instead. Only an `http` or `https` link the user clicked goes there; any other request is refused. ## Trait implementations - `impl Clone for NewWindowDecision` - `impl Copy for NewWindowDecision` - `impl Debug for NewWindowDecision` - `impl Default for NewWindowDecision` - `impl Eq for NewWindowDecision` - `impl PartialEq for NewWindowDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/new_window.rs#L131 --- # Enum `kurogane::NewWindowKind` ```rust #[non_exhaustive] pub enum NewWindowKind { Tab, BackgroundTab, Popup, Window, PictureInPicture, } ``` How a page asked for a window of its own ([`NewWindowRequest::kind`]). [`NewWindowRequest::kind`]: https://kurogane-rs.org/docs/api/requests/newwindowrequest.md#method.kind ## Variants ### `Tab` ```rust Tab ``` A tab in front. A `target=_blank` link, `window.open` without features and a link clicked with Ctrl (Cmd on macOS) ask for one. ### `BackgroundTab` ```rust BackgroundTab ``` A tab behind the current one. A link clicked with the middle button or with Ctrl and Shift asks for one. ### `Popup` ```rust Popup ``` A popup. `window.open` with features such as a size or position asks for one. ### `Window` ```rust Window ``` A window. A link clicked with Shift asks for one. ### `PictureInPicture` ```rust PictureInPicture ``` A picture-in-picture window (`documentPictureInPicture`). ## Trait implementations - `impl Clone for NewWindowKind` - `impl Copy for NewWindowKind` - `impl Debug for NewWindowKind` - `impl Eq for NewWindowKind` - `impl Hash for NewWindowKind` - `impl PartialEq for NewWindowKind` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/new_window.rs#L112 --- # Enum `kurogane::Permission` ```rust #[non_exhaustive] pub enum Permission { Camera, Microphone, ScreenVideo, ScreenAudio, Geolocation, Notifications, ClipboardRead, MidiSysex, CameraPanTiltZoom, ArSession, VrSession, HandTracking, CapturedSurfaceControl, StorageAccess, TopLevelStorageAccess, DiskQuota, LocalFonts, IdentityProvider, IdleDetection, KeyboardLock, PointerLock, ProtectedMediaIdentifier, RegisterProtocolHandler, WebAppInstallation, WindowManagement, FileSystemAccess, LocalNetwork, LoopbackNetwork, Sensors, } ``` What a page asks for, in a [`PermissionRequest`]. [`PermissionRequest`]: https://kurogane-rs.org/docs/api/requests/permissionrequest.md ## Variants ### `Camera` ```rust Camera ``` A camera (`getUserMedia` with video). ### `Microphone` ```rust Microphone ``` A microphone (`getUserMedia` with audio). ### `ScreenVideo` ```rust ScreenVideo ``` A picture of the screen (`getDisplayMedia`). There is no picker; once allowed the page records the whole screen. ### `ScreenAudio` ```rust ScreenAudio ``` The sound the system plays, with a picture of the screen. ### `Geolocation` ```rust Geolocation ``` The device's location (`navigator.geolocation`). ### `Notifications` ```rust Notifications ``` Showing notifications (`Notification.requestPermission`). ### `ClipboardRead` ```rust ClipboardRead ``` Reading the clipboard (`navigator.clipboard.readText` and `read`). ### `MidiSysex` ```rust MidiSysex ``` MIDI devices with system-exclusive messages (`requestMIDIAccess({ sysex: true })`). ### `CameraPanTiltZoom` ```rust CameraPanTiltZoom ``` Turning a camera (pan, tilt and zoom). ### `ArSession` ```rust ArSession ``` An augmented-reality session (WebXR). ### `VrSession` ```rust VrSession ``` A virtual-reality session (WebXR). ### `HandTracking` ```rust HandTracking ``` Tracking the user's hands in a WebXR session. ### `CapturedSurfaceControl` ```rust CapturedSurfaceControl ``` Scrolling and zooming a captured tab or window. ### `StorageAccess` ```rust StorageAccess ``` An embedded site's own cookies and storage inside another site's page (`document.requestStorageAccess`). ### `TopLevelStorageAccess` ```rust TopLevelStorageAccess ``` A site's own cookies and storage inside the pages of other sites, asked for by the site itself (`requestStorageAccessFor`). ### `DiskQuota` ```rust DiskQuota ``` More disk space for the site's storage. ### `LocalFonts` ```rust LocalFonts ``` The fonts installed on the system (`queryLocalFonts`). ### `IdentityProvider` ```rust IdentityProvider ``` Signing in with the site as an identity provider (FedCM). ### `IdleDetection` ```rust IdleDetection ``` Whether the user is idle (`IdleDetector`). ### `KeyboardLock` ```rust KeyboardLock ``` Keys the system would otherwise take, such as Alt+Tab (`navigator.keyboard.lock`). ### `PointerLock` ```rust PointerLock ``` Holding the pointer inside the page (`requestPointerLock`). ### `ProtectedMediaIdentifier` ```rust ProtectedMediaIdentifier ``` An identifier for playing protected media. ### `RegisterProtocolHandler` ```rust RegisterProtocolHandler ``` Handling links of a URL scheme (`registerProtocolHandler`). ### `WebAppInstallation` ```rust WebAppInstallation ``` Installing the site as an app. ### `WindowManagement` ```rust WindowManagement ``` The screens' layout and placing windows on them (`getScreenDetails`). ### `FileSystemAccess` ```rust FileSystemAccess ``` Writing to files and folders the user picked (File System Access). ### `LocalNetwork` ```rust LocalNetwork ``` Reaching devices on the local network. ### `LoopbackNetwork` ```rust LoopbackNetwork ``` Reaching services on this computer. ### `Sensors` ```rust Sensors ``` Motion and orientation sensors. ## Trait implementations - `impl Clone for Permission` - `impl Copy for Permission` - `impl Debug for Permission` - `impl Display for Permission` - `impl Eq for Permission` - `impl Hash for Permission` - `impl PartialEq for Permission` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/permissions.rs#L42 --- # Enum `kurogane::PermissionDecision` ```rust #[non_exhaustive] pub enum PermissionDecision { Default, Allow, Deny, Later, } ``` The answer of [`App::on_permission`](https://kurogane-rs.org/docs/api/app/app.md#method.on_permission). [crate::App::on_permission]: https://kurogane-rs.org/docs/api/app/app.md#method.on_permission ## Variants ### `Default` ```rust Default ``` Kurogane's policy ([`Deny`](https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Deny)). [Self::Deny]: https://kurogane-rs.org/docs/api/requests/permissiondecision.md#variant.Deny ### `Allow` ```rust Allow ``` Grants everything the request asks for. ### `Deny` ```rust Deny ``` Grants nothing. ### `Later` ```rust Later ``` The [`PermissionResponder`] the hook took with [`PermissionRequest::responder`] answers later; the page waits until then. Without a responder kept, the request is denied at once. [`PermissionRequest::responder`]: https://kurogane-rs.org/docs/api/requests/permissionrequest.md#method.responder [`PermissionResponder`]: https://kurogane-rs.org/docs/api/requests/permissionresponder.md ## Trait implementations - `impl Clone for PermissionDecision` - `impl Copy for PermissionDecision` - `impl Debug for PermissionDecision` - `impl Default for PermissionDecision` - `impl Eq for PermissionDecision` - `impl PartialEq for PermissionDecision` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/permissions.rs#L571 --- # Enum `kurogane::StandardItem` ```rust #[non_exhaustive] pub enum StandardItem { Undo, Redo, Cut, Copy, Paste, PasteAsPlainText, Delete, SelectAll, SpellingSuggestions, AddToDictionary, Back, Forward, Reload, Print, Inspect, } ``` One of Kurogane's items, which runs a command of Chromium's. ## Variants ### `Undo` ```rust Undo ``` ### `Redo` ```rust Redo ``` ### `Cut` ```rust Cut ``` ### `Copy` ```rust Copy ``` ### `Paste` ```rust Paste ``` ### `PasteAsPlainText` ```rust PasteAsPlainText ``` Paste without the formatting of the text pasted. ### `Delete` ```rust Delete ``` ### `SelectAll` ```rust SelectAll ``` ### `SpellingSuggestions` ```rust SpellingSuggestions ``` Chromium's suggestions for the misspelled word right-clicked; nothing elsewhere. ### `AddToDictionary` ```rust AddToDictionary ``` Adds the misspelled word right-clicked to the dictionary; nothing elsewhere. ### `Back` ```rust Back ``` ### `Forward` ```rust Forward ``` ### `Reload` ```rust Reload ``` ### `Print` ```rust Print ``` ### `Inspect` ```rust Inspect ``` DevTools, inspecting the element right-clicked. ## Trait implementations - `impl Clone for StandardItem` - `impl Copy for StandardItem` - `impl Debug for StandardItem` - `impl Eq for StandardItem` - `impl From<StandardItem> for MenuItem` - `impl Hash for StandardItem` - `impl PartialEq for StandardItem` Source: https://github.com/0x48piraj/kurogane/blob/584c586118ee53cc04604007ee038557bd859092/kurogane/src/context_menu.rs#L44