Add the desktop client

A per-user client service in Rust with a C++ Dear ImGui tray GUI built
on the vendored UHDK, in the pixel-art style the web UI now shares.
The explorer draft shows FILES, GRAPH and TREE over a hard-coded
sample repository until the service reads real workspaces.

Builds with Zig 0.17.1 and Cargo; see desktop/README.md.
This commit is contained in:
Peterino 2026-11-25 19:09:43 -07:00
parent ab8555c65f
commit 6ebe985668
218 changed files with 153053 additions and 0 deletions

View File

@ -0,0 +1,230 @@
# Desktop client
Status: milestone 1 (GUI and tray shell over a stub service) done on macOS. Last updated
2026-11-25.
lore-forge's desktop side: a tray application and a terminal UI for people working in Lore
repositories, both driven by one per-user **client service** that does the Lore work and runs
policies such as autosync.
## Decisions
| Decision | Choice | Source |
| --- | --- | --- |
| Shape | One per-user client service; the GUI and the TUI are frontends that connect to it | Owner, 2026-11-25 |
| How the service drives Lore | liblore, Lore's C API, pinned in `lore.lock` like the binaries | Owner, 2026-11-25 |
| Service and TUI language | Rust (tokio; ratatui for the TUI) | Owner, 2026-11-25 |
| GUI | C++ with a stylized Dear ImGui, on vendored UHDK (windows, OpenGL, tray) | Owner, 2026-11-25 |
| GUI look | Pixel art: a bitmap font, square bevelled widgets, hard shadows; terse, functional copy | Owner, 2026-11-25 |
| GUI layout | A file explorer with FILES, GRAPH (revision DAG) and TREE (branch > revision > changes) tabs | Owner, 2026-11-25 |
| Explorer data until liblore | A sample repository hard-coded in the GUI; the protocol methods come with liblore | Owner, 2026-11-25 |
| Location | `desktop/` in this repository, with its own Cargo workspace and `zig build` | Owner, 2026-11-25 |
| First milestone | GUI and tray shell, talking to a stub service | Owner, 2026-11-25 |
| Frontend protocol | JSON-RPC 2.0, one message per line, over a per-user local socket | Implementation choice |
## Why a service
- Policies run with no window open. Autosync, lock reminders and notification watching belong
to something that outlives the GUI. The tray app then only reflects and steers it.
- One owner per working copy. The GUI and the TUI never run Lore operations themselves, so
two frontends cannot race on the same repository.
- Separate toolchains. The service links liblore, built with MSVC on Windows; the GUI links
UHDK, which targets `x86_64-windows-gnu`. As separate processes they never share a link.
Lore has its own `lore service`, verified in `docs/tutorials/run-commands-through-the-service.md`
at `6b12f00`:
- It is a per-user process that carries out CLI commands over a local socket.
- It has no policies or frontend protocol.
Our service is a liblore client like the CLI, so Lore's service settings apply to it too.
## Components
| Component | Language | Built by | Contents |
| --- | --- | --- | --- |
| `forge-service` | Rust | Cargo (`desktop/Cargo.toml`) | Local socket server, workspaces, policies, liblore calls |
| `forge-protocol` | Rust | Cargo | Message types, socket location; the protocol's reference |
| `forge-tui` | Rust | Cargo | ratatui frontend. Not started |
| `forge-desktop` | C++17 | `zig build` (`desktop/build.zig`) | UHDK window and tray, Dear ImGui UI, protocol client |
`zig build` in `desktop/` also runs Cargo for the service and installs both programs side by
side in `desktop/zig-out/bin/`, so the GUI can start the service it was built with.
## Frontend protocol
- **Transport:** a local socket private to the user.
- **macOS:** `~/Library/Application Support/lore-forge/service.sock`.
- **Linux:** `$XDG_RUNTIME_DIR/lore-forge/service.sock`, falling back to
`~/.local/state/lore-forge/service.sock`.
- **Windows:** the named pipe `\\.\pipe\lore-forge-service-<user name>`.
- On Unix the directory is mode 700.
- **Framing:** one JSON-RPC 2.0 message per line, UTF-8, no embedded newlines.
- **Handshake:** a client's first request is `hello` with the protocol version it speaks. The
service answers with its own version and refuses versions it does not speak.
- **Events:** the service sends JSON-RPC notifications (no `id`) to every connected client
after its `hello`: workspace changes, activity progress, policy decisions.
- **Single instance:** a service that finds the socket live exits. It removes a stale socket
left by a crashed service.
- **Starting the service:** a frontend that cannot connect starts `forge-service` from its own
directory, then retries.
- **Lifetime:** quitting a frontend leaves the service running. `shutdown` stops it.
`forge-protocol` is the reference. Milestone 1 methods:
| Method | Result |
| --- | --- |
| `hello {protocol, client}` | `{protocol, service, pid}` |
| `status` | `{workspaces: [{id, name, path, remote, state, autosync}], uptime_s}` |
| `sync_now {workspace}` | `{}`; progress follows as `activity` events |
| `shutdown` | `{}`, then the service exits |
| Event | Data |
| --- | --- |
| `activity` | `{workspace, kind, phase, progress, message}` |
| `workspaces` | The `status` workspaces list, after any change |
In milestone 1 the service **simulates** sync, and its workspaces come from
`desktop.toml` in the service's config directory. liblore replaces both in milestone 2.
## liblore
Verified against the v0.14.0 release and `lore-capi/lore.h` at `6b12f00`:
- Each release publishes `liblore-<version>-<target>` for `aarch64-apple-darwin`,
`x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu` (tar.gz) and
`x86_64-pc-windows-msvc` (zip).
- The API has about 180 operations, all `_async`, covering auth, repositories, branches,
revisions, files, locks, links, notifications, storage and Lore's own service.
- Each operation takes `lore_global_args_t`, its own arguments and a
`lore_event_callback_config_t`. Progress and results arrive as events, ending with an END
event, on Lore's worker threads.
- Structures must be zeroed before use. Strings in events are valid only during the callback.
Assumed, to check in milestone 2:
- liblore shares the CLI's stored logins (`LORE_AUTH_PATH`, the keychain-held key), so a
`lore auth login` also signs the service in.
- Generating Rust bindings from `lore.h` at the pinned version is enough; we need no
hand-written ABI.
## UHDK
Vendored from `~/git/uhdk-internal` (the owner's library, MIT) into `desktop/vendor/uhdk/`; its
`VENDOR.md` records the revision and checksums. Verified in its README and headers:
- Zig 0.17.1 with a C99 API. It provides windows, input and IME, clipboard, menus, tray
icons and an OpenGL context.
- `uhdk_open`, then a `uhdk_next_frame` / `uhdk_end_frame` loop on the main thread.
`uhdk_wake` is the one call that is safe from other threads, which is how the protocol
thread wakes the UI.
- The tray works on macOS (`NSStatusItem`), Windows (`Shell_NotifyIconW`) and Linux
(StatusNotifierItem plus D-BusMenu). It needs a StatusNotifier host on Linux, and reports
`UHDK_CAP_TRAY` false without one.
- **Linux is Wayland only.** X11 is unsupported.
- **Windows builds target `x86_64-windows-gnu`.**
- Dear ImGui runs on UHDK through the UHDK example backend, which `desktop/gui/` carries a
copy of. It supports one native window, docking inside it and asynchronous clipboard
reads; no OS multi-viewports.
## Look
The owner asked for a "crunchier", pixel-art look with little copy. `gui/src/theme.*` holds it:
- **Font:** IBM VGA 8x16 from VileR's Oldschool PC Font Pack, at its native 16 px (32 px for the
title), compiled in with `#embed`. It is CC BY-SA 4.0, which asks for attribution;
`forge-desktop --licenses` prints it.
- **Palette:** Sweetie 16, by GrafxKid. Orange is the accent and primary buttons.
- **Shapes:** no rounding or anti-aliasing. Buttons are bevelled blocks with a 2 px hard shadow
that press in when held; cards have a 3 px shadow; progress is a row of cells.
- **Icons:** one 16x16 anvil, scaled by whole numbers: a black template for the macOS menu bar,
outlined in colour elsewhere, and on a tile for the app icon.
- **Copy:** labels are short and uppercase (ONLINE, SYNC, STOP SERVICE); status lines are
short and lowercase (fetching, no service at ...). No sentences where a word does.
## Explorer
A draft, drawn over a sample repository (`gui/src/sample_repo.cpp`) and labelled SAMPLE DATA.
Workspaces in the sidebar are real (from the service); everything about their contents is not.
- **Sidebar:** workspaces with their sync state, then the branches. Picking a branch selects
its head in the history tabs.
- **Workspace bar:** name, current branch and head revision, sync progress, SYNC.
- **FILES:** breadcrumbs with UP, a folder tree, and a list with size, last revision and state
(MOD and NEW for working-copy changes, LOCK for locks: blue when yours). Below, the
selected file's details and the revisions that changed it.
- **GRAPH:** revisions newest first with lanes. Each lane holds the revision it leads to; a
revision takes the first lane leading to it, and a parent already waited for is joined
rather than given a new lane. Lines take the branch's colour, merges are hollow nodes, and
branch heads carry a tag. Below, the selected revision's parents and changes.
- **TREE:** branches, each opening to its revisions, each opening to its changes.
- A change or history row jumps to the file or the revision.
For milestone 2 the protocol needs, roughly: a workspace's branches and current revision, a
directory listing with working-copy state and locks, and a page of revisions with parents and
changes. `ThinClientService` (`RevisionTree`, `RevisionInfo`) and liblore's revision and file
operations are the likely sources. The web browser now reads the same views from
`ThinClientService` and `RevisionService` (see "Reading repositories" in
[lore-integration.md](lore-integration.md)); liblore's side is still unchecked. The web GRAPH
uses the same lane layout, ported to Rust in `crates/forge-web/src/pages/graph.rs`.
## Verified so far
On macOS (Apple silicon), 2026-11-25:
- `zig build test` passes. It runs:
- the Rust tests (protocol, config, and the service's protocol handling over in-memory
streams);
- `forge-desktop --test`, which starts a private service in a fresh temporary directory,
completes `hello` and `status`, draws, and stops that service.
- With two sample workspaces (`--config-from`), the self-test starts a sync from the GUI,
sees the `activity` and `workspaces` events, and captures the window mid-sync with
`--screenshot`. `--tab` captures each explorer tab. Clicking through the explorer has not
been automated.
- The tray item registers: the window offers HIDE, which it does only when UHDK reports the
tray available.
- **A sleeping display.** On macOS the window cannot open while the display sleeps, most
likely because UHDK's display link needs an active display. `--test` then fails with "open
session: Operating system error"; waking the display (`caffeinate -u`) is enough.
Compiled and linked only, not run:
- **GUI:** `zig build -Dtarget=x86_64-windows-gnu` (a GUI-subsystem PE) and `x86_64-linux-gnu`.
- **Service on Windows:** the named-pipe code path has not been compiled; the Rust Windows
target is not installed here.
- **GUI pipe client:** the Windows code path compiles, but no Windows run has exercised it.
Found while building:
- **Unix socket path length.** A socket path must fit `sun_path`: 103 bytes on macOS, 107 on
Linux. The default locations fit. A long `LORE_FORGE_DESKTOP_DIR` does not, and both sides
then say so rather than failing vaguely.
## Milestones
1. **GUI and tray shell.** Done.
- A UHDK window with a stylized ImGui UI.
- A tray icon whose menu offers Open, Sync all and Quit. Closing the window hides it to the
tray when one is available.
- The protocol client: connects to the service, starting it when needed, and shows its
workspaces and live activity.
- A stub service in Rust that speaks the protocol.
2. **liblore in the service.**
- Bindings and the fetch of liblore from `lore.lock`.
- Protocol methods for the explorer, replacing the sample repository.
- Real status and sync now, and login state.
- Workspaces added from the GUI.
3. **Policies.** Autosync (on an interval, on file change, never), with conflict handling to
design. Then notifications from `NotificationService`.
4. **TUI.** ratatui over the same protocol.
5. **lore-forge integration.** Repository lists and permissions from the forge; sign-in
through the forge's device flow.
## Open
- What autosync does on a conflict or with unstaged local changes.
- Whether the service should start at login (launch agent, systemd user unit, Run key), and
who installs that.
- Packaging and signing per platform.
- Whether to adopt Epic's desktop client once it is open source. Lore's roadmap promises it
for 2027; today it is a closed binary.

668
desktop/Cargo.lock generated Normal file
View File

@ -0,0 +1,668 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bytes"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "clap"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "forge-protocol"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "forge-service"
version = "0.1.0"
dependencies = [
"clap",
"forge-protocol",
"serde",
"serde_json",
"tempfile",
"tokio",
"toml",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "matchers"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
"regex-automata",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mio"
version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "pin-project-lite"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thread_local"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
dependencies = [
"cfg-if",
]
[[package]]
name = "tokio"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow 0.7.15",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow 1.0.5",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
"valuable",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
dependencies = [
"matchers",
"nu-ansi-term",
"once_cell",
"regex-automata",
"sharded-slab",
"smallvec",
"thread_local",
"tracing",
"tracing-core",
"tracing-log",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

23
desktop/Cargo.toml Normal file
View File

@ -0,0 +1,23 @@
# The desktop client's Rust side: the client service and (later) the TUI. Kept apart from the
# server workspace so building lore-forge never needs Zig or the GUI's toolchain.
[workspace]
members = ["protocol", "service"]
resolver = "3"
[workspace.package]
version = "0.1.0"
edition = "2024"
rust-version = "1.85"
license = "MIT"
publish = false
[workspace.dependencies]
forge-protocol = { path = "protocol" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "signal", "fs"] }
toml = "0.9"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
clap = { version = "4", features = ["derive"] }
tempfile = "3"

91
desktop/README.md Normal file
View File

@ -0,0 +1,91 @@
# lore-forge desktop client
A tray application for people working in Lore repositories, and the per-user service it talks
to. The design is in [.ai/designs/desktop-client.md](../.ai/designs/desktop-client.md).
| Program | What it is |
| --- | --- |
| `forge-desktop` | The GUI: a UHDK window and tray icon, drawn with Dear ImGui (C++) in a pixel-art style |
| `forge-service` | The client service: does the Lore work and runs policies (Rust) |
| `forge-tui` | A terminal frontend. Not written yet |
**Milestone 1:** the service syncs nothing yet. It simulates sync for the workspaces listed in
its `desktop.toml`. liblore comes in milestone 2.
The window is a repository explorer: workspaces and branches on the left, and three tabs:
FILES (folder tree, file list, details and history of the selected file), GRAPH (the revision
graph) and TREE (branches, their revisions and each revision's changes). Until the service can
report repositories, all three show a built-in **sample repository**, labelled SAMPLE DATA.
## Build and run
You need Zig 0.17.1 and Rust. On macOS you also need the Xcode Command Line Tools. From this
directory:
```sh
zig build # both programs, installed in zig-out/bin/
zig build run # open the GUI; it starts the service if none is running
zig build test # the GUI's self-test against a private service, then cargo test
```
Closing the window hides it to the tray when there is one. The tray's Quit ends the GUI and
leaves the service running; STOP SERVICE in the window stops it.
`forge-desktop --licenses` prints the licences of what is compiled in: the IBM VGA 8x16 font
(CC BY-SA 4.0, by VileR), Dear ImGui, UHDK and glad.
The service keeps its socket, `desktop.toml` and `service.log` in:
| Platform | Directory |
| --- | --- |
| macOS | `~/Library/Application Support/lore-forge/` |
| Linux | `~/.config/lore-forge/`; the socket is in `$XDG_RUNTIME_DIR/lore-forge/` |
| Windows | `%APPDATA%\lore-forge\`; the socket is a named pipe |
Set `LORE_FORGE_DESKTOP_DIR` to use one directory instead. A Unix socket path must stay under
about 100 bytes, so keep that directory's path short.
Workspaces, until the GUI can add them:
```toml
# desktop.toml
[[workspace]]
name = "my-game"
path = "/Users/me/lore/my-game"
remote = "lore://localhost:41337/me/my-game"
autosync = "off" # off, interval or on_change; not acted on yet
```
## Self-test
`forge-desktop --test` runs against a private service in a new temporary directory and exits 0
once the service has answered and a frame has been drawn.
- **`--config-from desktop.toml`** gives that service workspaces. The test then syncs the
first one and waits for its progress.
- **`--tab files|graph|tree`** opens on that tab.
- **`--screenshot out.png`** saves the final frame. Use it to check UI changes; it needs a
display that is awake (on macOS a sleeping display makes the window fail to open).
- **`--service PATH`** picks the service binary to start.
## Other platforms
`zig build check -Dtarget=x86_64-windows-gnu` (or `x86_64-linux-gnu`) cross-compiles the GUI.
Cargo builds the service for the host only. For another platform, build it with Cargo for that
target and put `forge-service` beside `forge-desktop`.
Platform limits come from UHDK:
- **Linux:** Wayland only. The tray needs a StatusNotifier host.
- **Windows:** builds target `x86_64-windows-gnu`.
## Layout
| Path | Contents |
| --- | --- |
| `gui/src/` | The GUI: frame loop, sidebar and service handling (`main.cpp`), the explorer tabs (`explorer.cpp`), the sample repository (`sample_repo.cpp`), protocol client, platform glue, the pixel-art theme and icons (`theme.cpp`), the compiled-in font and licences (`embedded.cpp`) |
| `gui/uhdk_imgui/` | UHDK's ImGui platform backend, copied from UHDK's examples |
| `protocol/` | Message types and socket location; the reference the C++ client follows |
| `service/` | The client service |
| `vendor/` | UHDK, Dear ImGui and the font, unmodified; see [vendor/README.md](vendor/README.md) |

116
desktop/build.zig Normal file
View File

@ -0,0 +1,116 @@
// Builds the desktop client: forge-desktop (C++, Dear ImGui on vendored UHDK) with Zig, and
// forge-service (Rust) with Cargo, installing both into zig-out/bin/ so the GUI can start the
// service beside it.
//
// zig build build and install both
// zig build run run the GUI (it starts the service when none is running)
// zig build test the GUI's --test smoke run (private service), then cargo test
// zig build check compile the GUI only (any -Dtarget)
//
// Cargo builds only for the host. For another -Dtarget, build the GUI here and the service
// with Cargo for that target, then put forge-service beside forge-desktop.
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const native = target.query.isNative();
const with_service = b.option(bool, "service", "Build forge-service with Cargo (default: when building for the host)") orelse native;
const uhdk = b.dependency("uhdk", .{ .target = target, .optimize = optimize });
const gui = b.addExecutable(.{
.name = "forge-desktop",
.root_module = b.createModule(.{
.target = target,
.optimize = optimize,
.link_libc = true,
.link_libcpp = true,
}),
});
if (target.result.os.tag == .windows) gui.subsystem = .windows;
gui.root_module.addIncludePath(uhdk.path("include"));
gui.root_module.addIncludePath(b.path("vendor/imgui"));
gui.root_module.addIncludePath(b.path("gui/uhdk_imgui"));
gui.root_module.addCSourceFiles(.{
.files = &.{
"gui/src/main.cpp",
"gui/src/explorer.cpp",
"gui/src/sample_repo.cpp",
"gui/src/json.cpp",
"gui/src/platform.cpp",
"gui/src/png.cpp",
"gui/src/service_client.cpp",
"gui/src/theme.cpp",
},
.flags = &.{ "-std=c++17", "-Wall", "-Wextra", "-Werror" },
});
// The font and licence texts, through #embed: a C23 feature Clang allows in C++ as an
// extension, hence no -Werror here.
gui.root_module.addCSourceFile(.{
.file = b.path("gui/src/embedded.cpp"),
.flags = &.{ "-std=c++17", "-Wno-c23-extensions" },
});
gui.root_module.addCSourceFiles(.{
.files = &.{
"gui/uhdk_imgui/imgui_impl_uhdk.cpp",
"vendor/imgui/imgui.cpp",
"vendor/imgui/imgui_draw.cpp",
"vendor/imgui/imgui_tables.cpp",
"vendor/imgui/imgui_widgets.cpp",
"vendor/imgui/backends/imgui_impl_opengl3.cpp",
},
.flags = &.{"-std=c++17"},
});
gui.root_module.linkLibrary(uhdk.artifact("uhdk"));
const check = b.step("check", "Compile forge-desktop without installing or running it");
check.dependOn(&gui.step);
const install_gui = b.addInstallArtifact(gui, .{});
b.getInstallStep().dependOn(&install_gui.step);
// Cargo keeps its own incremental state in target/, so it runs every time.
const service_exe = if (target.result.os.tag == .windows) "forge-service.exe" else "forge-service";
var service_built: ?std.Build.LazyPath = null;
var cargo_step: ?*std.Build.Step = null;
if (with_service) {
const release = optimize != .debug;
const cargo = b.addSystemCommand(&.{ "cargo", "build", "--quiet", "--package", "forge-service", "--manifest-path" });
cargo.addFileArg(b.path("Cargo.toml"));
if (release) cargo.addArg("--release");
cargo.has_side_effects = true;
const built = b.path(b.fmt("target/{s}/{s}", .{ if (release) "release" else "debug", service_exe }));
const install = b.addInstallBinFile(built, service_exe);
install.step.dependOn(&cargo.step);
b.getInstallStep().dependOn(&install.step);
service_built = built;
cargo_step = &cargo.step;
}
// `run` and `test` run the GUI from Zig's cache, so they name the service explicitly.
const run = b.addRunArtifact(gui);
if (service_built) |built| {
run.addArg("--service");
run.addFileArg(built);
run.step.dependOn(cargo_step.?);
}
run.addPassthruArgs();
b.step("run", "Run forge-desktop").dependOn(&run.step);
const test_step = b.step("test", "Run forge-desktop --test against a private service, then the Cargo tests");
if (service_built) |built| {
const smoke = b.addRunArtifact(gui);
smoke.addArg("--service");
smoke.addFileArg(built);
smoke.addArg("--test");
smoke.has_side_effects = true;
smoke.step.dependOn(cargo_step.?);
test_step.dependOn(&smoke.step);
const cargo_test = b.addSystemCommand(&.{ "cargo", "test", "--quiet", "--manifest-path" });
cargo_test.addFileArg(b.path("Cargo.toml"));
cargo_test.has_side_effects = true;
test_step.dependOn(&cargo_test.step);
}
}

8
desktop/build.zig.zon Normal file
View File

@ -0,0 +1,8 @@
.{
.name = .lore_forge_desktop,
.fingerprint = 0x1ef4f52f01e208fb,
.version = "0.1.0",
.minimum_zig_version = "0.17.1",
.dependencies = .{ .uhdk = .{ .path = "vendor/uhdk" } },
.paths = .{ "build.zig", "build.zig.zon", "gui", "vendor", "protocol", "service", "Cargo.toml", "Cargo.lock" },
}

View File

@ -0,0 +1,22 @@
// Data compiled into forge-desktop: the UI font and the licences `--licenses` prints.
// Built without -Werror: #embed is a Clang extension in C++.
#include <cstddef>
// IBM VGA 8x16 from The Ultimate Oldschool PC Font Pack by VileR, CC BY-SA 4.0.
extern const unsigned char kVgaFont[] = {
#embed "../../vendor/fonts/AcPlus_IBM_VGA_8x16.ttf"
};
extern const size_t kVgaFontSize = sizeof kVgaFont;
extern const char kFontLicense[] = {
#embed "../../vendor/fonts/oldschool-pc-fonts-LICENSE.txt"
, 0};
extern const char kImguiLicense[] = {
#embed "../../vendor/imgui/LICENSE.txt"
, 0};
extern const char kUhdkLicense[] = {
#embed "../../vendor/uhdk/LICENSE"
, 0};
extern const char kGladLicense[] = {
#embed "../../vendor/uhdk/include/glad/LICENSE"
, 0};

View File

@ -0,0 +1,590 @@
#include "explorer.hpp"
#include "theme.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
namespace {
constexpr float kRowH = 20; // list rows: one text line and 2 px above and below
constexpr float kLaneW = 14; // graph lane spacing
constexpr float kRevW = 72; // the revision id column
void Box(ImVec2 a, ImVec2 b, ImU32 colour) {
ImGui::GetWindowDrawList()->AddRectFilled({std::floor(a.x), std::floor(a.y)}, {std::floor(b.x), std::floor(b.y)},
colour);
}
// An inset list: ink background, no padding, rows touching.
void BeginList(const char *id, ImVec2 size, ImVec2 padding = {1, 1}) {
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kInk);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, padding);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
ImGui::BeginChild(id, size, ImGuiChildFlags_Borders);
}
void EndList() {
ImGui::EndChild();
ImGui::PopStyleVar(2);
ImGui::PopStyleColor();
}
void Gap(float height) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + height);
}
// A non-interactive header row of column labels.
void HeaderRow(std::initializer_list<std::pair<float, const char *>> columns) {
ImVec2 p = ImGui::GetCursorScreenPos();
float width = ImGui::GetContentRegionAvail().x;
ImGui::Dummy({width, kRowH});
Box(p, {p.x + width, p.y + kRowH}, theme::kPanel);
for (const auto &[x, label] : columns)
theme::TextAt({p.x + x, p.y + 2}, theme::kMuted, label);
}
std::string Size(uint64_t bytes) {
char out[32];
if (bytes < 1024)
std::snprintf(out, sizeof out, "%llu B", (unsigned long long)bytes);
else if (bytes < 1024 * 1024)
std::snprintf(out, sizeof out, "%.1f KB", bytes / 1024.0);
else
std::snprintf(out, sizeof out, "%.1f MB", bytes / (1024.0 * 1024.0));
return out;
}
ImU32 FileTint(const std::string &name) {
auto ends = [&name](const char *suffix) {
size_t n = std::char_traits<char>::length(suffix);
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
};
if (ends(".cpp") || ends(".h"))
return theme::kGreen;
if (ends(".png") || ends(".fbx"))
return theme::kBlue;
if (ends(".umap"))
return theme::kForge;
if (ends(".ogg") || ends(".wav"))
return theme::kSpark;
return theme::kMuted;
}
std::string Parent(const std::string &path) {
size_t slash = path.rfind('/');
return slash == std::string::npos ? std::string() : path.substr(0, slash);
}
const char *ChangeLabel(char kind, ImU32 &colour) {
switch (kind) {
case 'A': colour = theme::kGreen; return "A";
case 'D': colour = theme::kRed; return "D";
default: colour = theme::kSpark; return "M";
}
}
} // namespace
Explorer::Explorer() : repo_(sample::Get()) {
// Lane layout, newest first: each lane holds the revision it is waiting to reach.
std::vector<std::string> lanes;
auto free_lane = [&lanes] {
for (size_t i = 0; i < lanes.size(); ++i)
if (lanes[i].empty())
return int(i);
lanes.emplace_back();
return int(lanes.size() - 1);
};
for (const auto &rev : repo_.revisions) {
GraphRow row;
row.before = lanes;
row.node = -1;
for (size_t i = 0; i < lanes.size(); ++i)
if (lanes[i] == rev.id) {
row.incoming.push_back(int(i));
if (row.node < 0)
row.node = int(i);
}
if (row.node < 0)
row.node = free_lane(); // a branch head: nothing above leads here
for (int i : row.incoming)
lanes[i].clear();
for (size_t k = 0; k < rev.parents.size(); ++k) {
const std::string &parent = rev.parents[k];
int lane = -1;
for (size_t i = 0; i < lanes.size() && lane < 0; ++i)
if (lanes[i] == parent)
lane = int(i); // another child already leads there: join it
if (lane < 0) {
lane = k == 0 && lanes[row.node].empty() ? row.node : free_lane();
lanes[lane] = parent;
}
row.parents.push_back({lane, k == 0});
}
while (!lanes.empty() && lanes.back().empty())
lanes.pop_back();
row.after = lanes;
lanes_ = std::max({lanes_, int(row.before.size()), int(row.after.size()), row.node + 1});
graph_.push_back(std::move(row));
}
selected_rev_ = repo_.FindBranch(repo_.current_branch)->head;
open_branches_.insert(repo_.current_branch);
open_dirs_ = {"Content", "Source", "Source/Game"};
dir_ = "Source/Game";
selected_path_ = "Source/Game/player.cpp";
}
void Explorer::SetTab(const std::string &name) {
if (name == "graph")
tab_ = Tab::Graph;
else if (name == "tree")
tab_ = Tab::Tree;
else
tab_ = Tab::Files;
}
ImU32 Explorer::BranchColour(const std::string &branch) const {
const sample::Branch *b = repo_.FindBranch(branch);
return b ? b->colour : theme::kMuted;
}
void Explorer::GoToFile(const std::string &path) {
if (!repo_.FindEntry(path))
return;
dir_ = Parent(path);
for (std::string d = dir_; !d.empty(); d = Parent(d))
open_dirs_.insert(d);
selected_path_ = path;
tab_ = Tab::Files;
}
void Explorer::SelectRevision(const std::string &id) {
selected_rev_ = id;
scroll_to_rev_ = true;
}
void Explorer::DrawBranches() {
theme::TextColoured(theme::kMuted, "BRANCHES");
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &b : repo_.branches) {
ImGui::PushID(b.name.c_str());
if (theme::Row("branch", tab_ != Tab::Files && selected_rev_ == b.head, kRowH)) {
SelectRevision(b.head);
open_branches_.insert(b.name);
if (tab_ == Tab::Files)
tab_ = Tab::Graph;
}
ImVec2 p = ImGui::GetItemRectMin();
Box({p.x + 8, p.y + 6}, {p.x + 16, p.y + 14}, b.colour);
theme::TextAt({p.x + 24, p.y + 2}, theme::kPaper, b.name.c_str(), ImGui::GetItemRectMax().x - 20);
if (b.name == repo_.current_branch)
theme::TextAt({ImGui::GetItemRectMax().x - 16, p.y + 2}, theme::kForge, "*");
ImGui::PopID();
}
ImGui::PopStyleVar();
}
bool Explorer::Draw(const WorkspaceView &ws) {
// The workspace bar: name, branch and head on the left, sync on the right.
ImVec2 p = ImGui::GetCursorScreenPos();
float right = p.x + ImGui::GetContentRegionAvail().x;
float x = p.x, y = p.y + 4;
theme::TextAt({x, y}, theme::kPaper, ws.name.c_str());
x += ImGui::CalcTextSize(ws.name.c_str()).x + 12;
const sample::Branch *current = repo_.FindBranch(repo_.current_branch);
theme::TagAt({x, y}, current->name.c_str(), current->colour);
x += theme::TagWidth(current->name.c_str()) + 8;
theme::TextAt({x, y}, theme::kMuted, current->head.c_str());
float sync_x = std::floor(right - theme::ButtonWidth("SYNC"));
if (ws.syncing) {
const float bar = 160;
ImGui::SetCursorScreenPos({sync_x - 12 - bar, p.y + 5});
theme::Progress(ws.progress < 0 ? 0 : ws.progress, bar);
float mw = ImGui::CalcTextSize(ws.message.c_str()).x;
theme::TextAt({sync_x - 24 - bar - mw, y}, theme::kMuted, ws.message.c_str());
}
ImGui::SetCursorScreenPos({sync_x, p.y});
bool sync = theme::Button("SYNC", ws.can_sync && !ws.syncing, true);
ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 10});
// Tabs, touching the panel below.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {4, 0});
if (theme::Tab("FILES", tab_ == Tab::Files))
tab_ = Tab::Files;
ImGui::SameLine();
if (theme::Tab("GRAPH", tab_ == Tab::Graph))
tab_ = Tab::Graph;
ImGui::SameLine();
if (theme::Tab("TREE", tab_ == Tab::Tree))
tab_ = Tab::Tree;
ImVec2 tabs = ImGui::GetItemRectMin();
theme::TagAt({right - theme::TagWidth("SAMPLE DATA"), tabs.y + 4}, "SAMPLE DATA", theme::kSpark);
ImGui::PopStyleVar();
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});
ImGui::BeginChild("panel", {0, 0}, ImGuiChildFlags_Borders);
switch (tab_) {
case Tab::Files: DrawFiles(); break;
case Tab::Graph: DrawGraph(); break;
case Tab::Tree: DrawTree(); break;
}
ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::PopStyleColor();
return sync;
}
// ---- Files
void Explorer::DrawFiles() {
DrawBreadcrumbs();
const float details_h = 156;
float list_h = std::floor(ImGui::GetContentRegionAvail().y - details_h - 8);
BeginList("dirs", {220, list_h});
DrawDirTree(repo_.root, 0);
EndList();
ImGui::SameLine(0, 8);
BeginList("files", {0, list_h});
DrawFileList();
EndList();
Gap(8);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 4});
BeginList("details", {0, 0}, {10, 8});
DrawFileDetails();
EndList();
ImGui::PopStyleVar();
}
void Explorer::DrawBreadcrumbs() {
if (theme::Button("UP", !dir_.empty()))
dir_ = Parent(dir_);
float y = ImGui::GetItemRectMin().y + 4;
std::vector<std::pair<std::string, std::string>> crumbs = {{repo_.name, ""}};
for (std::string d = dir_; !d.empty(); d = Parent(d))
crumbs.insert(crumbs.begin() + 1, {d.substr(d.rfind('/') + 1), d});
for (size_t i = 0; i < crumbs.size(); ++i) {
ImGui::SameLine(0, i ? 6 : 14);
ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y});
if (i) {
theme::TextColoured(theme::kRaised, "/");
ImGui::SameLine(0, 6);
ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y});
}
ImVec2 at = ImGui::GetCursorScreenPos();
const std::string &label = crumbs[i].first;
ImGui::PushID(int(i));
if (ImGui::InvisibleButton("crumb", ImGui::CalcTextSize(label.c_str())))
dir_ = crumbs[i].second;
bool last = i + 1 == crumbs.size();
theme::TextAt(at, ImGui::IsItemHovered() ? theme::kSpark : last ? theme::kPaper : theme::kMuted, label.c_str());
ImGui::PopID();
}
Gap(6);
}
void Explorer::DrawDirTree(const sample::Entry &dir, int depth) {
bool has_sub = std::any_of(dir.children.begin(), dir.children.end(), [](const auto &c) { return c.dir; });
bool open = depth == 0 || open_dirs_.count(dir.path);
ImGui::PushID(("/" + dir.path).c_str());
if (theme::Row("dir", dir_ == dir.path, kRowH)) {
if (dir_ == dir.path && has_sub && depth > 0) {
if (open)
open_dirs_.erase(dir.path);
else
open_dirs_.insert(dir.path);
} else {
dir_ = dir.path;
if (has_sub)
open_dirs_.insert(dir.path);
}
}
ImVec2 p = ImGui::GetItemRectMin();
float x = p.x + 6 + depth * 12;
if (has_sub && depth > 0)
theme::TextAt({x, p.y + 2}, theme::kMuted, open ? "-" : "+");
theme::FolderIcon({x + 12, p.y + 4}, dir_ == dir.path);
theme::TextAt({x + 32, p.y + 2}, theme::kPaper, dir.name.c_str(), ImGui::GetItemRectMax().x);
ImGui::PopID();
if (open)
for (const auto &child : dir.children)
if (child.dir)
DrawDirTree(child, depth + 1);
}
void Explorer::DrawFileList() {
const sample::Entry *dir = repo_.FindEntry(dir_);
if (!dir)
return;
float width = ImGui::GetContentRegionAvail().x;
const float state_x = width - 120, rev_x = state_x - 80, size_right = rev_x - 20;
HeaderRow({{30, "NAME"}, {size_right - 32, "SIZE"}, {rev_x, "REV"}, {state_x, "STATE"}});
if (!dir_.empty()) {
if (theme::Row("..", false, kRowH))
dir_ = Parent(dir_);
ImVec2 p = ImGui::GetItemRectMin();
theme::FolderIcon({p.x + 8, p.y + 4}, false);
theme::TextAt({p.x + 30, p.y + 2}, theme::kMuted, "..");
}
for (const auto &e : dir->children) {
ImGui::PushID(e.name.c_str());
if (theme::Row("entry", selected_path_ == e.path, kRowH))
selected_path_ = e.path;
bool hovered = ImGui::IsItemHovered();
if (hovered && e.dir && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
dir_ = e.path;
open_dirs_.insert(e.path);
}
if (hovered && !e.lock_owner.empty())
ImGui::SetTooltip("locked by %s", e.lock_owner.c_str());
ImVec2 p = ImGui::GetItemRectMin();
float y = p.y + 2;
if (e.dir)
theme::FolderIcon({p.x + 8, p.y + 4}, false);
else
theme::FileIcon({p.x + 8, p.y + 4}, FileTint(e.name));
theme::TextAt({p.x + 30, y}, theme::kPaper, e.name.c_str(), p.x + size_right - 80);
if (!e.dir) {
std::string size = Size(e.size);
theme::TextAt({p.x + size_right - ImGui::CalcTextSize(size.c_str()).x, y}, theme::kMuted, size.c_str());
}
theme::TextAt({p.x + rev_x, y}, theme::kMuted, e.revision.empty() ? "" : e.revision.c_str());
float tx = p.x + state_x;
if (e.local == 'M' || e.local == 'A') {
const char *label = e.local == 'M' ? "MOD" : "NEW";
theme::TagAt({tx, y}, label, e.local == 'M' ? theme::kSpark : theme::kGreen);
tx += theme::TagWidth(label) + 4;
}
if (!e.lock_owner.empty())
theme::TagAt({tx, y}, "LOCK", e.lock_owner == "you" ? theme::kBlue : theme::kRed);
ImGui::PopID();
}
}
void Explorer::DrawFileDetails() {
const sample::Entry *e = repo_.FindEntry(selected_path_.empty() ? dir_ : selected_path_);
if (!e)
e = &repo_.root;
ImVec2 p = ImGui::GetCursorScreenPos();
if (e->dir)
theme::FolderIcon({p.x, p.y + 2}, false);
else
theme::FileIcon({p.x, p.y + 2}, FileTint(e->name));
ImGui::Indent(22);
ImGui::TextUnformatted(e->name.c_str());
ImGui::Unindent(22);
std::string path = repo_.name + (e->path.empty() ? "" : "/" + e->path);
theme::TextColoured(theme::kMuted, path.c_str());
std::string facts;
if (e->dir) {
facts = std::to_string(e->children.size()) + " items";
} else {
facts = Size(e->size) + " rev " + (e->revision.empty() ? "-" : e->revision);
if (e->local == 'M')
facts += " modified";
if (e->local == 'A')
facts += " added";
if (!e->lock_owner.empty())
facts += " locked by " + e->lock_owner;
}
theme::TextColoured(theme::kMuted, facts.c_str());
if (e->dir)
return;
Gap(4);
theme::TextColoured(theme::kMuted, "HISTORY");
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &rev : repo_.revisions) {
bool touches = std::any_of(rev.changes.begin(), rev.changes.end(),
[&](const sample::Change &c) { return c.path == e->path; });
if (!touches)
continue;
ImGui::PushID(rev.id.c_str());
if (theme::Row("rev", false, kRowH)) {
SelectRevision(rev.id);
tab_ = Tab::Graph;
}
ImVec2 r = ImGui::GetItemRectMin();
Box({r.x + 4, r.y + 6}, {r.x + 12, r.y + 14}, BranchColour(rev.branch));
DrawRevisionLine(rev, r.x + 20, r.y + 2, ImGui::GetItemRectMax().x);
ImGui::PopID();
}
ImGui::PopStyleVar();
}
// ---- History
void Explorer::DrawRevisionLine(const sample::Revision &rev, float x, float y, float right) {
const float author_x = right - 168, date_x = right - 100;
theme::TextAt({x, y}, theme::kSpark, rev.id.c_str());
float mx = x + kRevW;
for (const auto &b : repo_.branches)
if (b.head == rev.id) {
theme::TagAt({mx, y}, b.name.c_str(), b.colour);
mx += theme::TagWidth(b.name.c_str()) + 6;
}
theme::TextAt({mx, y}, theme::kPaper, rev.message.c_str(), author_x - 12);
theme::TextAt({author_x, y}, theme::kMuted, rev.author.c_str(), date_x - 8);
theme::TextAt({date_x, y}, theme::kMuted, rev.date.c_str(), right);
}
void Explorer::DrawGraph() {
const float details_h = 176;
float list_h = std::floor(ImGui::GetContentRegionAvail().y - details_h - 8);
BeginList("graph", {0, list_h});
const float graph_w = 10 + lanes_ * kLaneW;
float width = ImGui::GetContentRegionAvail().x;
HeaderRow({{graph_w, "REV"}, {graph_w + kRevW, "MESSAGE"}, {width - 168, "AUTHOR"}, {width - 100, "DATE"}});
auto lane_x = [](ImVec2 p, int lane) { return std::floor(p.x + 10 + lane * kLaneW); };
auto vline = [](float x, float y0, float y1, ImU32 c) { Box({x - 1, y0}, {x + 1, y1}, c); };
auto hline = [](float x0, float x1, float y, ImU32 c) {
Box({std::min(x0, x1) - 1, y - 1}, {std::max(x0, x1) + 1, y + 1}, c);
};
auto colour_of = [this](const std::string &id) {
const sample::Revision *r = repo_.FindRevision(id);
return r ? BranchColour(r->branch) : theme::kMuted;
};
for (size_t i = 0; i < repo_.revisions.size(); ++i) {
const sample::Revision &rev = repo_.revisions[i];
const GraphRow &row = graph_[i];
ImGui::PushID(rev.id.c_str());
bool selected = selected_rev_ == rev.id;
if (theme::Row("rev", selected, kRowH))
SelectRevision(rev.id);
if (selected && scroll_to_rev_) {
ImGui::SetScrollHereY(0.5f);
scroll_to_rev_ = false;
}
ImVec2 p = ImGui::GetItemRectMin();
float y0 = p.y, y1 = p.y + kRowH, yc = std::floor(p.y + kRowH / 2);
float nx = lane_x(p, row.node);
// Lanes passing straight through.
for (size_t l = 0; l < row.before.size(); ++l)
if (!row.before[l].empty() && row.before[l] != rev.id && l < row.after.size() &&
row.after[l] == row.before[l])
vline(lane_x(p, int(l)), y0, y1, colour_of(row.before[l]));
// Lines into this revision from its children, then out to its parents.
ImU32 own = BranchColour(rev.branch);
for (int l : row.incoming) {
vline(lane_x(p, l), y0, yc, own);
hline(lane_x(p, l), nx, yc, own);
}
for (size_t k = 0; k < row.parents.size(); ++k) {
auto [lane, first] = row.parents[k];
ImU32 c = first ? own : colour_of(rev.parents[k]);
hline(nx, lane_x(p, lane), yc, c);
vline(lane_x(p, lane), yc, y1, c);
}
Box({nx - 5, yc - 5}, {nx + 5, yc + 5}, theme::kInk);
Box({nx - 4, yc - 4}, {nx + 4, yc + 4}, own);
if (rev.parents.size() > 1)
Box({nx - 2, yc - 2}, {nx + 2, yc + 2}, theme::kInk); // merges are hollow
DrawRevisionLine(rev, p.x + graph_w, p.y + 2, ImGui::GetItemRectMax().x);
ImGui::PopID();
}
EndList();
Gap(8);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 4});
BeginList("details", {0, 0}, {10, 8});
DrawRevisionDetails();
EndList();
ImGui::PopStyleVar();
}
void Explorer::DrawChangeRow(const sample::Change &change, float indent) {
ImGui::PushID(change.path.c_str());
if (theme::Row("change", false, kRowH))
GoToFile(change.path);
ImVec2 p = ImGui::GetItemRectMin();
ImU32 colour;
const char *label = ChangeLabel(change.kind, colour);
theme::TagAt({p.x + indent, p.y + 2}, label, colour);
theme::FileIcon({p.x + indent + 20, p.y + 4}, FileTint(change.path));
theme::TextAt({p.x + indent + 40, p.y + 2}, change.kind == 'D' ? theme::kMuted : theme::kPaper,
change.path.c_str(), ImGui::GetItemRectMax().x);
ImGui::PopID();
}
void Explorer::DrawRevisionDetails() {
const sample::Revision *rev = repo_.FindRevision(selected_rev_);
if (!rev)
return;
theme::TextColoured(theme::kSpark, rev->id.c_str());
ImGui::SameLine(0, 12);
theme::Tag(rev->branch.c_str(), BranchColour(rev->branch));
ImGui::SameLine(0, 12);
ImGui::TextUnformatted(rev->message.c_str());
std::string facts = rev->author + " " + rev->date + " parents";
for (const auto &parent : rev->parents)
facts += " " + parent;
if (rev->parents.empty())
facts += " -";
theme::TextColoured(theme::kMuted, facts.c_str());
Gap(4);
theme::TextColoured(theme::kMuted, "CHANGES");
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &change : rev->changes)
DrawChangeRow(change, 4);
ImGui::PopStyleVar();
}
void Explorer::DrawTree() {
BeginList("tree", {0, 0});
float width = ImGui::GetContentRegionAvail().x;
HeaderRow({{24, "BRANCH / REV"}, {width - 168, "AUTHOR"}, {width - 100, "DATE"}});
for (const auto &b : repo_.branches) {
ImGui::PushID(b.name.c_str());
bool open = open_branches_.count(b.name);
if (theme::Row("branch", false, kRowH)) {
if (open)
open_branches_.erase(b.name);
else
open_branches_.insert(b.name);
}
ImVec2 p = ImGui::GetItemRectMin();
int count = 0;
for (const auto &rev : repo_.revisions)
count += rev.branch == b.name;
theme::TextAt({p.x + 8, p.y + 2}, theme::kMuted, open ? "-" : "+");
theme::TagAt({p.x + 24, p.y + 2}, b.name.c_str(), b.colour);
std::string facts = std::to_string(count) + " revisions head " + b.head;
if (b.name == repo_.current_branch)
facts += " current";
theme::TextAt({p.x + 36 + theme::TagWidth(b.name.c_str()), p.y + 2}, theme::kMuted, facts.c_str());
if (open)
for (const auto &rev : repo_.revisions) {
if (rev.branch != b.name)
continue;
ImGui::PushID(rev.id.c_str());
bool rev_open = open_revisions_.count(rev.id);
if (theme::Row("rev", selected_rev_ == rev.id, kRowH)) {
SelectRevision(rev.id);
if (rev_open)
open_revisions_.erase(rev.id);
else
open_revisions_.insert(rev.id);
}
ImVec2 r = ImGui::GetItemRectMin();
theme::TextAt({r.x + 28, r.y + 2}, theme::kMuted, rev_open ? "-" : "+");
Box({r.x + 42, r.y + 6}, {r.x + 50, r.y + 14}, b.colour);
if (rev.parents.size() > 1)
Box({r.x + 44, r.y + 8}, {r.x + 48, r.y + 12}, theme::kInk);
DrawRevisionLine(rev, r.x + 58, r.y + 2, ImGui::GetItemRectMax().x);
if (rev_open)
for (const auto &change : rev.changes)
DrawChangeRow(change, 58);
ImGui::PopID();
}
ImGui::PopID();
}
EndList();
}

View File

@ -0,0 +1,65 @@
// The repository explorer: a files tab, the revision graph and a branch tree, over the sample
// repository until the service can report real ones.
#pragma once
#include "sample_repo.hpp"
#include <set>
#include <string>
#include <vector>
// What the explorer shows about the workspace selected in the sidebar.
struct WorkspaceView {
std::string name;
bool syncing = false;
float progress = -1;
std::string message;
bool can_sync = false;
};
class Explorer {
public:
Explorer();
// "files", "graph" or "tree".
void SetTab(const std::string &name);
// The sidebar's branch list.
void DrawBranches();
// The main area. Returns true when the user asked to sync the workspace.
bool Draw(const WorkspaceView &workspace);
private:
enum class Tab { Files, Graph, Tree };
// One row of the revision graph: which lanes carry lines in and out, where the node sits.
struct GraphRow {
std::vector<std::string> before, after; // the revision each lane waits for
int node = 0;
std::vector<int> incoming; // lanes that end in this node
std::vector<std::pair<int, bool>> parents; // lane of each parent; true for the first
};
void DrawFiles();
void DrawBreadcrumbs();
void DrawDirTree(const sample::Entry &dir, int depth);
void DrawFileList();
void DrawFileDetails();
void DrawGraph();
void DrawRevisionDetails();
void DrawTree();
void DrawRevisionLine(const sample::Revision &rev, float x, float y, float right);
void DrawChangeRow(const sample::Change &change, float indent);
void GoToFile(const std::string &path);
void SelectRevision(const std::string &id);
ImU32 BranchColour(const std::string &branch) const;
const sample::Repository &repo_;
std::vector<GraphRow> graph_;
int lanes_ = 1;
Tab tab_ = Tab::Files;
std::string dir_; // the directory the file list shows; "" is the root
std::string selected_path_; // the file or directory selected in the list
std::string selected_rev_;
bool scroll_to_rev_ = false;
std::set<std::string> open_dirs_, open_branches_, open_revisions_;
};

294
desktop/gui/src/json.cpp Normal file
View File

@ -0,0 +1,294 @@
#include "json.hpp"
#include <cstdio>
#include <cstdlib>
namespace json {
static const Value kNull;
static const std::string kEmpty;
const std::string &Value::str() const {
return type_ == Type::String ? string_ : kEmpty;
}
const Value &Value::operator[](std::string_view key) const {
if (type_ == Type::Object)
for (const auto &member : object_)
if (member.first == key)
return member.second;
return kNull;
}
const Value &Value::operator[](size_t index) const {
return type_ == Type::Array && index < array_.size() ? array_[index] : kNull;
}
bool Value::has(std::string_view key) const {
if (type_ == Type::Object)
for (const auto &member : object_)
if (member.first == key)
return true;
return false;
}
class Parser {
public:
explicit Parser(std::string_view text) : text_(text) {}
bool Document(Value &out, std::string *error) {
bool ok = Parse(out, 0);
if (ok) {
Space();
if (pos_ != text_.size())
ok = Fail("trailing characters");
}
if (!ok && error)
*error = error_ + " at byte " + std::to_string(pos_);
return ok;
}
private:
static constexpr int kMaxDepth = 64;
std::string_view text_;
size_t pos_ = 0;
std::string error_;
bool Fail(const char *why) {
if (error_.empty())
error_ = why;
return false;
}
void Space() {
while (pos_ < text_.size() &&
(text_[pos_] == ' ' || text_[pos_] == '\t' || text_[pos_] == '\n' || text_[pos_] == '\r'))
++pos_;
}
bool Literal(std::string_view word) {
if (text_.substr(pos_, word.size()) != word)
return Fail("invalid literal");
pos_ += word.size();
return true;
}
bool Parse(Value &out, int depth) {
if (depth > kMaxDepth)
return Fail("nested too deeply");
Space();
if (pos_ >= text_.size())
return Fail("unexpected end");
switch (text_[pos_]) {
case 'n':
out.type_ = Value::Type::Null;
return Literal("null");
case 't':
out.type_ = Value::Type::Bool;
out.bool_ = true;
return Literal("true");
case 'f':
out.type_ = Value::Type::Bool;
out.bool_ = false;
return Literal("false");
case '"':
out.type_ = Value::Type::String;
return String(out.string_);
case '[':
return Array(out, depth);
case '{':
return Object(out, depth);
default:
return Number(out);
}
}
bool Number(Value &out) {
size_t start = pos_;
if (pos_ < text_.size() && text_[pos_] == '-')
++pos_;
while (pos_ < text_.size() && ((text_[pos_] >= '0' && text_[pos_] <= '9') || text_[pos_] == '.' ||
text_[pos_] == 'e' || text_[pos_] == 'E' || text_[pos_] == '+' ||
text_[pos_] == '-'))
++pos_;
if (pos_ == start)
return Fail("unexpected character");
std::string digits(text_.substr(start, pos_ - start));
char *end = nullptr;
out.number_ = std::strtod(digits.c_str(), &end);
if (!end || *end != '\0')
return Fail("invalid number");
out.type_ = Value::Type::Number;
return true;
}
static void Utf8(std::string &out, unsigned code) {
if (code < 0x80) {
out += char(code);
} else if (code < 0x800) {
out += char(0xC0 | (code >> 6));
out += char(0x80 | (code & 0x3F));
} else if (code < 0x10000) {
out += char(0xE0 | (code >> 12));
out += char(0x80 | ((code >> 6) & 0x3F));
out += char(0x80 | (code & 0x3F));
} else {
out += char(0xF0 | (code >> 18));
out += char(0x80 | ((code >> 12) & 0x3F));
out += char(0x80 | ((code >> 6) & 0x3F));
out += char(0x80 | (code & 0x3F));
}
}
bool Hex4(unsigned &out) {
if (pos_ + 4 > text_.size())
return Fail("short \\u escape");
out = 0;
for (int i = 0; i < 4; ++i) {
char c = text_[pos_++];
out <<= 4;
if (c >= '0' && c <= '9')
out |= unsigned(c - '0');
else if (c >= 'a' && c <= 'f')
out |= unsigned(c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
out |= unsigned(c - 'A' + 10);
else
return Fail("invalid \\u escape");
}
return true;
}
bool String(std::string &out) {
++pos_; // opening quote
while (pos_ < text_.size()) {
char c = text_[pos_++];
if (c == '"')
return true;
if (static_cast<unsigned char>(c) < 0x20)
return Fail("control character in string");
if (c != '\\') {
out += c;
continue;
}
if (pos_ >= text_.size())
break;
switch (text_[pos_++]) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'u': {
unsigned code;
if (!Hex4(code))
return false;
if (code >= 0xD800 && code < 0xDC00) {
unsigned low;
if (text_.substr(pos_, 2) != "\\u")
return Fail("lone surrogate");
pos_ += 2;
if (!Hex4(low) || low < 0xDC00 || low >= 0xE000)
return Fail("invalid surrogate pair");
code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
} else if (code >= 0xDC00 && code < 0xE000) {
return Fail("lone surrogate");
}
Utf8(out, code);
break;
}
default:
return Fail("invalid escape");
}
}
return Fail("unterminated string");
}
bool Array(Value &out, int depth) {
out.type_ = Value::Type::Array;
++pos_;
Space();
if (pos_ < text_.size() && text_[pos_] == ']') {
++pos_;
return true;
}
for (;;) {
out.array_.emplace_back();
if (!Parse(out.array_.back(), depth + 1))
return false;
Space();
if (pos_ >= text_.size())
return Fail("unterminated array");
char c = text_[pos_++];
if (c == ']')
return true;
if (c != ',')
return Fail("expected , or ]");
}
}
bool Object(Value &out, int depth) {
out.type_ = Value::Type::Object;
++pos_;
Space();
if (pos_ < text_.size() && text_[pos_] == '}') {
++pos_;
return true;
}
for (;;) {
Space();
if (pos_ >= text_.size() || text_[pos_] != '"')
return Fail("expected a member name");
std::string key;
if (!String(key))
return false;
Space();
if (pos_ >= text_.size() || text_[pos_++] != ':')
return Fail("expected :");
out.object_.emplace_back(std::move(key), Value());
if (!Parse(out.object_.back().second, depth + 1))
return false;
Space();
if (pos_ >= text_.size())
return Fail("unterminated object");
char c = text_[pos_++];
if (c == '}')
return true;
if (c != ',')
return Fail("expected , or }");
}
}
};
bool Parse(std::string_view text, Value &out, std::string *error) {
out = Value();
return Parser(text).Document(out, error);
}
std::string Quote(std::string_view text) {
std::string out = "\"";
for (char c : text) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
char escape[8];
std::snprintf(escape, sizeof escape, "\\u%04x", unsigned(static_cast<unsigned char>(c)));
out += escape;
} else {
out += c;
}
}
}
out += '"';
return out;
}
} // namespace json

51
desktop/gui/src/json.hpp Normal file
View File

@ -0,0 +1,51 @@
// A small JSON reader and string quoting, enough for the service protocol.
// Numbers are doubles; objects keep their order; nesting is capped.
#pragma once
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace json {
class Value {
public:
enum class Type { Null, Bool, Number, String, Array, Object };
Type type() const { return type_; }
bool is_null() const { return type_ == Type::Null; }
bool is_object() const { return type_ == Type::Object; }
bool is_array() const { return type_ == Type::Array; }
bool is_string() const { return type_ == Type::String; }
bool is_number() const { return type_ == Type::Number; }
// Accessors return a default when the type differs, so lookups chain safely.
const std::string &str() const;
double num(double fallback = 0) const { return type_ == Type::Number ? number_ : fallback; }
bool boolean(bool fallback = false) const { return type_ == Type::Bool ? bool_ : fallback; }
// A member of an object, or null.
const Value &operator[](std::string_view key) const;
// An element of an array, or null.
const Value &operator[](size_t index) const;
size_t size() const { return type_ == Type::Array ? array_.size() : type_ == Type::Object ? object_.size() : 0; }
const std::vector<Value> &items() const { return array_; }
bool has(std::string_view key) const;
private:
friend class Parser;
Type type_ = Type::Null;
bool bool_ = false;
double number_ = 0;
std::string string_;
std::vector<Value> array_;
std::vector<std::pair<std::string, Value>> object_;
};
// Parses one JSON document. On failure returns false and describes why in `error`.
bool Parse(std::string_view text, Value &out, std::string *error = nullptr);
// `text` as a JSON string literal, quotes included.
std::string Quote(std::string_view text);
} // namespace json

714
desktop/gui/src/main.cpp Normal file
View File

@ -0,0 +1,714 @@
// forge-desktop: lore-forge's tray application.
//
// A UHDK window drawn with Dear ImGui, a tray icon, and a connection to forge-service, which
// does the actual work. Closing the window hides it to the tray when there is one; the tray's
// Quit ends the GUI, and the service keeps running.
//
// forge-desktop open the window
// forge-desktop --hidden start in the tray
// forge-desktop --test against a private service in a temporary directory: connect,
// draw, stop that service, and exit 0 once it has answered
// --service PATH the forge-service to start (default: the one beside this program)
// --config-from FILE with --test: the private service's desktop.toml; the test then
// syncs the first workspace and waits for its progress
// --screenshot FILE with --test: write the final frame as a PNG
// --tab files|graph|tree the explorer tab to open on
// forge-desktop --licenses print the licences of what is compiled in
#define UHDK_ENABLE_OPENGL
#include "uhdk.h"
#include "backends/imgui_impl_opengl3.h"
#include "imgui.h"
#include "imgui_impl_uhdk.h"
#include "json.hpp"
#include "png.hpp"
#include "platform.hpp"
#include "service_client.hpp"
#include "explorer.hpp"
#include "theme.hpp"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
extern const char kFontLicense[], kImguiLicense[], kUhdkLicense[], kGladLicense[];
namespace {
uhdk_text Text(const std::string &text) {
return {text.c_str(), text.size()};
}
bool Check(uhdk_status status, const char *operation) {
if (status == UHDK_STATUS_OK)
return true;
const uhdk_text message = uhdk_status_message(status);
std::fprintf(stderr, "forge-desktop: %s: %.*s\n", operation, int(message.len), message.ptr);
return false;
}
enum : uhdk_request_tag { kClipboardTag = 1, kOpenUrlTag = 2 };
enum : uint64_t { kMenuOpen = 1, kMenuSyncAll = 2 };
struct Activity {
std::string phase; // started, running, finished, failed; empty when none
std::string message;
float progress = -1;
};
struct Workspace {
std::string id, name, path, remote, state, autosync;
Activity activity;
};
std::vector<Workspace> ParseWorkspaces(const json::Value &list, const std::vector<Workspace> &previous) {
std::vector<Workspace> out;
for (const auto &item : list.items()) {
Workspace w;
w.id = item["id"].str();
w.name = item["name"].str();
w.path = item["path"].str();
w.remote = item["remote"].str();
w.state = item["state"].str();
w.autosync = item["autosync"].str();
for (const auto &old : previous)
if (old.id == w.id)
w.activity = old.activity;
out.push_back(std::move(w));
}
return out;
}
class App {
public:
App(bool test, std::string screenshot, const std::string &tab) : test_(test), screenshot_(std::move(screenshot)) {
explorer_.SetTab(tab);
}
bool Run(bool start_hidden);
private:
bool Initialize();
void Shutdown();
void CreateTray();
void UpdateTray();
void HandleEvent(const uhdk_event &event);
void HandleIncoming();
void HandleMessage(const json::Value &message);
void Draw(const uhdk_window_metrics &metrics);
void DrawHeader();
void DrawSidebar();
void DrawFooter();
const Workspace *SelectedWorkspace() const;
void SyncAll();
void Show();
bool Connected() const { return client_ && client_->GetState() == ServiceClient::State::Connected && greeted_; }
bool test_;
uhdk_session *session_ = nullptr;
uhdk_window *window_ = nullptr;
GladGLContext gl_ = {};
uhdk_tray *tray_ = nullptr;
uhdk_menu *tray_menu_ = nullptr;
bool tray_available_ = false;
bool hide_when_tray_ready_ = false;
bool platform_ready_ = false, renderer_ready_ = false;
bool quitting_ = false;
int redraw_frames_ = 2;
theme::Fonts fonts_;
platform::ServicePaths paths_;
std::unique_ptr<ServiceClient> client_;
bool greeted_ = false;
std::string service_name_;
std::string error_;
std::vector<Workspace> workspaces_;
bool have_status_ = false;
std::string selected_workspace_;
Explorer explorer_;
std::string tray_tooltip_;
bool tray_sync_enabled_ = false;
bool test_drawn_ = false;
bool test_sync_sent_ = false;
bool test_saw_progress_ = false;
std::string screenshot_;
void Screenshot(const uhdk_window_metrics &metrics);
};
bool App::Initialize() {
window_ = uhdk_get_window(session_);
gl_ = *uhdk_get_gl(session_);
std::vector<uint8_t> icon = theme::AppIcon(128);
uhdk_image image = {sizeof(uhdk_image), 128, 128, 0, {icon.data(), icon.size()}};
if (uhdk_has_capability(session_, UHDK_CAP_APP_ICON))
Check(uhdk_set_icon(session_, &image), "set app icon");
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.IniFilename = nullptr;
theme::Apply();
fonts_ = theme::LoadFonts();
platform_ready_ = ImGui_ImplUHDK_Init(session_, kClipboardTag);
if (!platform_ready_)
return false;
renderer_ready_ = ImGui_ImplOpenGL3_Init("#version 330 core");
if (!renderer_ready_)
return false;
std::string error;
if (!platform::GetServicePaths(paths_, error)) {
error_ = error;
return true;
}
uhdk_session *session = session_;
client_ = std::make_unique<ServiceClient>(paths_, [session] { uhdk_wake(session); });
client_->Start();
return true;
}
void App::Shutdown() {
client_.reset();
if (tray_)
Check(uhdk_tray_destroy(tray_), "destroy tray");
if (tray_menu_)
uhdk_menu_release(tray_menu_);
if (renderer_ready_)
ImGui_ImplOpenGL3_Shutdown();
if (platform_ready_)
ImGui_ImplUHDK_Shutdown();
if (ImGui::GetCurrentContext())
ImGui::DestroyContext();
}
void App::CreateTray() {
if (!uhdk_has_capability(session_, UHDK_CAP_TRAY))
return;
uhdk_menu_item items[] = {
{kMenuOpen, {"Open", 4}, 0, 0, 0, 0, nullptr},
{kMenuSyncAll, {"Sync all", 8}, UHDK_MENU_DISABLED, 0, 0, 0, nullptr},
{0, {nullptr, 0}, UHDK_MENU_SEPARATOR, 0, 0, 0, nullptr},
{0, {"Quit", 4}, 0, UHDK_MENU_ROLE_QUIT, 0, 0, nullptr},
};
if (!Check(uhdk_menu_create(session_, items, 4, &tray_menu_), "create tray menu"))
return;
UpdateTray();
}
// Creates the tray item or refreshes its tooltip and menu. Between frames only.
void App::UpdateTray() {
if (!tray_menu_)
return;
std::string tooltip = "lore-forge: ";
if (!Connected()) {
tooltip += "offline";
} else {
int syncing = 0;
for (const auto &w : workspaces_)
syncing += w.state == "syncing";
tooltip += syncing ? "syncing " + std::to_string(syncing) + "/" + std::to_string(workspaces_.size())
: std::to_string(workspaces_.size()) + " workspaces";
}
bool sync_enabled = Connected() && !workspaces_.empty();
if (tray_ && tooltip == tray_tooltip_ && sync_enabled == tray_sync_enabled_)
return;
if (sync_enabled != tray_sync_enabled_ || !tray_) {
Check(uhdk_menu_set_item_flags(tray_menu_, kMenuSyncAll, sync_enabled ? 0 : UHDK_MENU_DISABLED),
"update tray menu");
tray_sync_enabled_ = sync_enabled;
}
tray_tooltip_ = tooltip;
#if defined(__APPLE__)
const bool template_image = true;
const unsigned size = 36;
#else
const bool template_image = false;
const unsigned size = 32;
#endif
static std::vector<uint8_t> pixels = theme::TrayIcon(size, template_image);
uhdk_tray_desc desc = {};
desc.struct_size = sizeof desc;
desc.template_image = template_image;
desc.id = {"lore-forge", 10};
desc.title = {"lore-forge", 10};
desc.tooltip = Text(tray_tooltip_);
desc.icon = {sizeof(uhdk_image), size, size, 0, {pixels.data(), pixels.size()}};
desc.menu = tray_menu_;
if (tray_) {
Check(uhdk_tray_update(tray_, &desc), "update tray");
} else if (Check(uhdk_tray_create(session_, &desc, &tray_), "create tray")) {
uhdk_tray_state state = {};
state.struct_size = sizeof state;
if (uhdk_tray_get_state(tray_, &state) == UHDK_STATUS_OK)
tray_available_ = state.available;
}
}
void App::Show() {
Check(uhdk_window_set_visible(window_, UHDK_TRUE), "show window");
Check(uhdk_window_request_focus(window_), "focus window");
redraw_frames_ = 2;
}
void App::SyncAll() {
if (!Connected())
return;
for (const auto &w : workspaces_)
if (w.state != "syncing")
client_->Call("sync_now", "{\"workspace\":" + json::Quote(w.id) + "}");
}
void App::HandleEvent(const uhdk_event &event) {
if (platform_ready_)
ImGui_ImplUHDK_ProcessEvent(&event);
switch (event.type) {
case UHDK_EVENT_QUIT_REQUESTED:
quitting_ = true;
uhdk_quit(session_);
break;
case UHDK_EVENT_WINDOW_CLOSE_REQUESTED:
if (tray_available_ && !test_)
Check(uhdk_window_set_visible(window_, UHDK_FALSE), "hide window");
else {
quitting_ = true;
uhdk_quit(session_);
}
break;
case UHDK_EVENT_TRAY_ACTIVATE:
Show();
break;
case UHDK_EVENT_TRAY_STATE: {
const auto *state = static_cast<const uhdk_tray_state_event *>(event.data);
tray_available_ = state->state.available;
if (!tray_available_)
Show(); // Never leave the window hidden with no way back.
break;
}
case UHDK_EVENT_MENU_COMMAND: {
const auto *command = static_cast<const uhdk_menu_event *>(event.data);
if (command->command_id == kMenuOpen)
Show();
else if (command->command_id == kMenuSyncAll)
SyncAll();
break;
}
case UHDK_EVENT_WAKE:
break;
default:
redraw_frames_ = 2;
break;
}
}
void App::HandleIncoming() {
if (!client_)
return;
for (auto &incoming : client_->Drain()) {
redraw_frames_ = 2;
switch (incoming.kind) {
case ServiceClient::Incoming::Kind::Connected:
greeted_ = false;
break;
case ServiceClient::Incoming::Kind::Disconnected:
greeted_ = false;
have_status_ = false;
for (auto &w : workspaces_)
w.state = "unknown";
break;
case ServiceClient::Incoming::Kind::Message:
HandleMessage(incoming.message);
break;
}
}
}
void App::HandleMessage(const json::Value &message) {
const std::string &method = message["method"].str();
if (!method.empty()) {
const json::Value &params = message["params"];
if (method == "workspaces") {
workspaces_ = ParseWorkspaces(params, workspaces_);
} else if (method == "activity") {
for (auto &w : workspaces_)
if (w.id == params["workspace"].str()) {
w.activity.phase = params["phase"].str();
w.activity.message = params["message"].str();
w.activity.progress = float(params["progress"].num(-1));
if (test_ && w.activity.phase == "running" && w.activity.progress >= 0.5f)
test_saw_progress_ = true;
}
}
return;
}
const json::Value &id = message["id"];
const json::Value &error = message["error"];
if (id.is_number() && uint64_t(id.num()) == client_->HelloId()) {
if (error.is_object()) {
error_ = "service refused hello: " + error["message"].str();
} else {
greeted_ = true;
error_.clear();
service_name_ = message["result"]["service"].str() + " pid " +
std::to_string(uint64_t(message["result"]["pid"].num()));
}
return;
}
if (error.is_object()) {
error_ = error["message"].str();
return;
}
const json::Value &result = message["result"];
if (result.has("workspaces")) {
workspaces_ = ParseWorkspaces(result["workspaces"], workspaces_);
have_status_ = true;
}
}
void App::DrawHeader() {
ImGui::PushFont(nullptr, fonts_.size * 2);
theme::TextColoured(theme::kForge, "LORE-FORGE");
ImGui::PopFont();
const char *label = "CONNECTING";
ImU32 colour = theme::kSpark;
if (!client_) {
label = "ERROR";
colour = theme::kRed;
} else {
switch (client_->GetState()) {
case ServiceClient::State::Connected:
if (greeted_) {
label = "ONLINE";
colour = theme::kGreen;
}
break;
case ServiceClient::State::StartingService:
label = "STARTING";
break;
case ServiceClient::State::Unavailable:
label = client_->AutoStart() ? "OFFLINE" : "STOPPED";
colour = client_->AutoStart() ? theme::kRed : theme::kMuted;
break;
case ServiceClient::State::Connecting:
break;
}
}
// LED and state, right-aligned and centred on the title line.
const ImVec2 title_min = ImGui::GetItemRectMin(), title_max = ImGui::GetItemRectMax();
const ImVec2 after = ImGui::GetCursorScreenPos();
const float gap = ImGui::GetStyle().ItemInnerSpacing.x;
float width = 8 + gap + ImGui::CalcTextSize(label).x;
float x = std::floor(ImGui::GetWindowPos().x + ImGui::GetContentRegionMax().x - width);
float y = std::floor((title_min.y + title_max.y - ImGui::GetTextLineHeight()) / 2);
ImGui::SetCursorScreenPos({x, y});
theme::Led(colour);
ImGui::SetCursorScreenPos({x + 8 + gap, y});
theme::TextColoured(colour, label);
ImGui::SetCursorScreenPos(after);
theme::Rule();
}
static ImU32 StateColour(const std::string &state) {
if (state == "syncing")
return theme::kSpark;
if (state == "idle")
return theme::kGreen;
if (state == "error")
return theme::kRed;
return theme::kRaised;
}
const Workspace *App::SelectedWorkspace() const {
for (const auto &w : workspaces_)
if (w.id == selected_workspace_)
return &w;
return workspaces_.empty() ? nullptr : &workspaces_.front();
}
void App::DrawSidebar() {
theme::TextColoured(theme::kMuted, "WORKSPACES");
const Workspace *selected = SelectedWorkspace();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &w : workspaces_) {
ImGui::PushID(w.id.c_str());
if (theme::Row("ws", selected == &w, 38))
selected_workspace_ = w.id;
ImVec2 p = ImGui::GetItemRectMin(), q = ImGui::GetItemRectMax();
ImGui::GetWindowDrawList()->AddRectFilled({p.x + 8, p.y + 6}, {p.x + 16, p.y + 14}, StateColour(w.state));
float right = q.x - 6;
if (w.state == "syncing" && w.activity.progress >= 0) {
char percent[8];
std::snprintf(percent, sizeof percent, "%d%%", int(w.activity.progress * 100 + 0.5f));
right -= ImGui::CalcTextSize(percent).x;
theme::TextAt({right, p.y + 2}, theme::kSpark, percent);
right -= 8;
}
theme::TextAt({p.x + 24, p.y + 2}, theme::kPaper, w.name.c_str(), right);
theme::TextAt({p.x + 24, p.y + 19}, theme::kMuted, w.path.c_str(), q.x - 6);
ImGui::PopID();
}
ImGui::PopStyleVar();
if (Connected() && have_status_ && workspaces_.empty()) {
theme::TextColoured(theme::kPaper, "no workspaces");
ImGui::PushStyleColor(ImGuiCol_Text, theme::kMuted);
ImGui::TextWrapped("add [[workspace]] to %s", paths_.config_file.c_str());
ImGui::PopStyleColor();
}
ImGui::Dummy({0, 8});
explorer_.DrawBranches();
}
void App::DrawFooter() {
theme::Rule();
std::vector<const char *> buttons;
if (client_ && Connected())
buttons.push_back("STOP SERVICE");
else if (client_ && !client_->AutoStart())
buttons.push_back("START SERVICE");
if (tray_available_)
buttons.push_back("HIDE");
float buttons_w = 0;
for (const char *b : buttons)
buttons_w += theme::ButtonWidth(b) + (buttons_w > 0 ? 12 : 0);
ImVec2 p = ImGui::GetCursorScreenPos();
float right = p.x + ImGui::GetContentRegionAvail().x;
std::string status = Connected() ? service_name_
: client_ ? (client_->Detail().empty() ? "looking for service" : client_->Detail())
: error_;
theme::TextAt({p.x, p.y + 4}, theme::kMuted, status.c_str(), right - buttons_w - 12);
ImGui::SetCursorScreenPos({right - buttons_w, p.y});
for (size_t i = 0; i < buttons.size(); ++i) {
if (i)
ImGui::SameLine(0, 12);
if (!theme::Button(buttons[i]))
continue;
if (!std::strcmp(buttons[i], "STOP SERVICE")) {
client_->SetAutoStart(false);
client_->Call("shutdown");
} else if (!std::strcmp(buttons[i], "START SERVICE")) {
client_->SetAutoStart(true);
} else {
Check(uhdk_window_set_visible(window_, UHDK_FALSE), "hide window");
}
}
if (buttons.empty())
ImGui::Dummy({0, ImGui::GetFrameHeight() + 2});
}
void App::Draw(const uhdk_window_metrics &metrics) {
ImGui_ImplUHDK_NewFrame();
ImGui_ImplOpenGL3_NewFrame();
ImGui::NewFrame();
const ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(viewport->WorkSize);
ImGui::Begin("main", nullptr,
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoBringToFrontOnFocus);
DrawHeader();
if (!error_.empty()) {
if (theme::Button("X"))
error_.clear();
ImGui::SameLine(0, 12);
ImGui::AlignTextToFramePadding();
ImGui::PushStyleColor(ImGuiCol_Text, theme::kRed);
ImGui::TextWrapped("%s", error_.c_str());
ImGui::PopStyleColor();
}
// The footer: a rule, then one row of buttons with their shadow.
const ImGuiStyle &style = ImGui::GetStyle();
float footer = 2 + style.ItemSpacing.y + ImGui::GetFrameHeight() + 2 + style.ItemSpacing.y;
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0));
ImGui::BeginChild("sidebar", {240, -footer}, ImGuiChildFlags_None);
DrawSidebar();
ImGui::EndChild();
ImGui::SameLine(0, 16);
ImGui::BeginChild("explorer", {0, -footer}, ImGuiChildFlags_None);
ImGui::PopStyleColor();
WorkspaceView view;
const Workspace *w = SelectedWorkspace();
view.name = w ? w->name : "sample";
view.syncing = w && w->state == "syncing";
view.progress = w ? w->activity.progress : -1;
view.message = w ? w->activity.message : "";
view.can_sync = w && Connected();
if (explorer_.Draw(view) && w)
client_->Call("sync_now", "{\"workspace\":" + json::Quote(w->id) + "}");
ImGui::EndChild();
DrawFooter();
ImGui::End();
ImGui::Render();
gl_.BindFramebuffer(GL_FRAMEBUFFER, 0);
gl_.Viewport(0, 0, GLsizei(metrics.framebuffer_width), GLsizei(metrics.framebuffer_height));
gl_.Disable(GL_SCISSOR_TEST);
const ImVec4 clear = theme::Vec(theme::kInk);
gl_.ClearColor(clear.x, clear.y, clear.z, 1.0f);
gl_.Clear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void App::Screenshot(const uhdk_window_metrics &metrics) {
uint32_t w = metrics.framebuffer_width, h = metrics.framebuffer_height;
std::vector<uint8_t> pixels(size_t(w) * h * 4), flipped(pixels.size());
gl_.PixelStorei(GL_PACK_ALIGNMENT, 1);
gl_.ReadPixels(0, 0, GLsizei(w), GLsizei(h), GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
for (uint32_t y = 0; y < h; ++y)
std::memcpy(&flipped[size_t(y) * w * 4], &pixels[size_t(h - 1 - y) * w * 4], size_t(w) * 4);
for (size_t i = 3; i < flipped.size(); i += 4)
flipped[i] = 255;
if (png::WriteRgba(screenshot_, flipped.data(), w, h))
std::printf("forge-desktop: --test: wrote %s (%ux%u)\n", screenshot_.c_str(), w, h);
else
std::fprintf(stderr, "forge-desktop: --test: cannot write %s\n", screenshot_.c_str());
}
bool App::Run(bool start_hidden) {
uhdk_options options = {};
options.struct_size = sizeof options;
options.render_mode = UHDK_RENDER_ON_DEMAND;
options.application_id = {"org.loreforge.Desktop", 21};
options.title = {"lore-forge", 10};
options.content_size = {1100, 720};
options.min_size = {800, 500};
options.request_focus = !start_hidden && !test_;
if (!Check(uhdk_open(&options, &session_), "open session"))
return false;
bool ok = Initialize();
if (ok)
CreateTray();
hide_when_tray_ready_ = start_hidden;
const uint64_t deadline = uhdk_get_time_ns(session_) + 20'000'000'000ull;
if (test_)
Check(uhdk_set_wake_deadline(session_, deadline), "set test deadline");
uhdk_frame frame = {};
while (ok && uhdk_next_frame(session_, &frame)) {
for (uint64_t i = 0; i < frame.events.len; ++i)
HandleEvent(frame.events.ptr[i]);
HandleIncoming();
if (test_ && !quitting_ && uhdk_get_time_ns(session_) >= deadline) {
std::fprintf(stderr, "forge-desktop: --test: the service did not answer in time (%s)\n",
client_ ? client_->Detail().c_str() : error_.c_str());
ok = false;
uhdk_quit(session_);
}
if (!quitting_ && frame.drawable) {
Draw(frame.metrics);
if (test_ && Connected() && have_status_ && !test_sync_sent_ && !workspaces_.empty()) {
test_sync_sent_ = true;
client_->Call("sync_now", "{\"workspace\":" + json::Quote(workspaces_[0].id) + "}");
}
if (test_ && Connected() && have_status_ && (workspaces_.empty() || test_saw_progress_)) {
if (test_drawn_) {
if (!screenshot_.empty())
Screenshot(frame.metrics);
std::printf("forge-desktop: --test: PASS (%s, %zu workspaces)\n", service_name_.c_str(),
workspaces_.size());
client_->SetAutoStart(false);
client_->Call("shutdown");
quitting_ = true;
uhdk_quit(session_);
}
test_drawn_ = true;
}
}
if (!Check(uhdk_end_frame(session_), "end frame")) {
ok = false;
break;
}
// Native changes belong between frames.
UpdateTray();
if (hide_when_tray_ready_ && tray_available_) {
hide_when_tray_ready_ = false;
Check(uhdk_window_set_visible(window_, UHDK_FALSE), "hide window");
}
if (redraw_frames_ > 0) {
--redraw_frames_;
Check(uhdk_set_wake_deadline(session_, uhdk_get_time_ns(session_) + 16'000'000ull), "schedule redraw");
} else if (test_) {
Check(uhdk_set_wake_deadline(session_, uhdk_get_time_ns(session_) + 100'000'000ull), "schedule test wake");
}
}
if (ok && !Check(uhdk_get_status(session_), "frame loop"))
ok = false;
Shutdown();
uhdk_close(session_);
return ok;
}
} // namespace
int main(int argc, char **argv) {
bool hidden = false, test = false;
std::string config_from, screenshot, tab = "files";
for (int i = 1; i < argc; ++i) {
if (!std::strcmp(argv[i], "--licenses")) {
std::printf("forge-desktop includes the following.\n\n"
"== IBM VGA 8x16 font ==\n%s\n"
"== Dear ImGui ==\n%s\n"
"== UHDK ==\n%s\n"
"== glad (in UHDK) ==\n%s",
kFontLicense, kImguiLicense, kUhdkLicense, kGladLicense);
return 0;
} else if (!std::strcmp(argv[i], "--hidden")) {
hidden = true;
} else if (!std::strcmp(argv[i], "--test")) {
test = true;
} else if (!std::strcmp(argv[i], "--service") && i + 1 < argc) {
platform::SetServiceExecutable(argv[++i]);
} else if (!std::strcmp(argv[i], "--config-from") && i + 1 < argc) {
config_from = argv[++i];
} else if (!std::strcmp(argv[i], "--tab") && i + 1 < argc) {
tab = argv[++i];
} else if (!std::strcmp(argv[i], "--screenshot") && i + 1 < argc) {
screenshot = argv[++i];
} else {
std::fprintf(stderr, "Usage: forge-desktop [--hidden] [--service PATH]\n"
" forge-desktop --licenses\n"
" forge-desktop --test [--service PATH] [--config-from FILE] [--screenshot FILE]\n"
" [--tab files|graph|tree]\n");
return 2;
}
}
if (test) {
// Never touch the user's own service: the spawned one inherits this directory.
std::string dir, error;
if (!platform::MakeTempDir(dir, error)) {
std::fprintf(stderr, "forge-desktop: --test: %s\n", error.c_str());
return 1;
}
platform::SetEnv("LORE_FORGE_DESKTOP_DIR", dir);
std::printf("forge-desktop: --test: private service directory %s\n", dir.c_str());
if (!config_from.empty()) {
std::ifstream in(config_from, std::ios::binary);
std::ofstream out(dir + "/desktop.toml", std::ios::binary);
if (!in || !(out << in.rdbuf())) {
std::fprintf(stderr, "forge-desktop: --test: cannot copy %s\n", config_from.c_str());
return 1;
}
}
} else if (!config_from.empty() || !screenshot.empty()) {
std::fprintf(stderr, "forge-desktop: --config-from and --screenshot need --test\n");
return 2;
}
App app(test, screenshot, tab);
return app.Run(hidden) ? 0 : 1;
}

View File

@ -0,0 +1,301 @@
#include "platform.hpp"
#include <cstdio>
#include <cstdlib>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <climits>
#include <cstdlib>
#include <fcntl.h>
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
extern char **environ;
#endif
namespace platform {
static std::string g_service_override;
void SetServiceExecutable(std::string path) {
g_service_override = std::move(path);
}
unsigned long long Fnv1a(const std::string &bytes) {
unsigned long long hash = 0xcbf29ce484222325ull;
for (unsigned char byte : bytes) {
hash ^= byte;
hash *= 0x100000001b3ull;
}
return hash;
}
#if defined(_WIN32)
static std::string ToUtf8(const wchar_t *text) {
if (!text || !*text)
return {};
int len = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
std::string out(size_t(len > 0 ? len - 1 : 0), '\0');
if (len > 1)
WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), len, nullptr, nullptr);
return out;
}
static std::wstring ToWide(const std::string &text) {
if (text.empty())
return {};
int len = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, nullptr, 0);
std::wstring out(size_t(len > 0 ? len - 1 : 0), L'\0');
if (len > 1)
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, out.data(), len);
return out;
}
static std::string Env(const wchar_t *name) {
return ToUtf8(_wgetenv(name));
}
bool GetServicePaths(ServicePaths &out, std::string &error) {
std::string override_dir = Env(L"LORE_FORGE_DESKTOP_DIR");
std::string dir = override_dir;
if (dir.empty()) {
std::string appdata = Env(L"APPDATA");
if (appdata.empty()) {
error = "APPDATA is not set";
return false;
}
dir = appdata + "\\lore-forge";
}
std::string user = Env(L"USERNAME");
if (user.empty())
user = "user";
for (char &c : user)
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_'))
c = '_';
out.endpoint = "\\\\.\\pipe\\lore-forge-service-" + user;
if (!override_dir.empty()) {
char hash[24];
std::snprintf(hash, sizeof hash, "-%016llx", Fnv1a(override_dir));
out.endpoint += hash;
}
out.config_dir = dir;
out.log_file = dir + "\\service.log";
out.config_file = dir + "\\desktop.toml";
return true;
}
std::string ExecutableDir() {
std::wstring path(MAX_PATH, L'\0');
for (;;) {
DWORD len = GetModuleFileNameW(nullptr, path.data(), DWORD(path.size()));
if (len == 0)
return ".";
if (len < path.size()) {
path.resize(len);
break;
}
path.resize(path.size() * 2);
}
size_t slash = path.find_last_of(L"\\/");
return ToUtf8(slash == std::wstring::npos ? L"." : path.substr(0, slash).c_str());
}
std::string ServiceExecutable() {
if (!g_service_override.empty())
return g_service_override;
std::string bin = Env(L"FORGE_SERVICE_BIN");
return bin.empty() ? ExecutableDir() + "\\forge-service.exe" : bin;
}
bool MakeTempDir(std::string &out, std::string &error) {
wchar_t base[MAX_PATH + 1];
DWORD len = GetTempPathW(MAX_PATH + 1, base);
if (len == 0 || len > MAX_PATH) {
error = "no temporary directory";
return false;
}
for (int attempt = 0; attempt < 16; ++attempt) {
std::wstring dir = std::wstring(base) + L"forge-desktop-" + std::to_wstring(GetCurrentProcessId()) + L"-" +
std::to_wstring(GetTickCount64() + attempt);
if (CreateDirectoryW(dir.c_str(), nullptr)) {
out = ToUtf8(dir.c_str());
return true;
}
}
error = "cannot create a temporary directory";
return false;
}
void SetEnv(const char *name, const std::string &value) {
_wputenv_s(ToWide(name).c_str(), ToWide(value).c_str());
}
static std::wstring QuoteArg(const std::wstring &arg) {
// CommandLineToArgvW rules: backslashes double only before a quote.
std::wstring out = L"\"";
size_t slashes = 0;
for (wchar_t c : arg) {
if (c == L'\\') {
++slashes;
} else if (c == L'"') {
out.append(slashes * 2 + 1, L'\\');
out += c;
slashes = 0;
} else {
out.append(slashes, L'\\');
out += c;
slashes = 0;
}
}
out.append(slashes * 2, L'\\');
out += L'"';
return out;
}
bool SpawnDetached(const std::string &exe, const std::vector<std::string> &args, std::string &error) {
std::wstring wexe = ToWide(exe);
std::wstring command = QuoteArg(wexe);
for (const auto &arg : args)
command += L" " + QuoteArg(ToWide(arg));
STARTUPINFOW startup = {};
startup.cb = sizeof startup;
PROCESS_INFORMATION process = {};
if (!CreateProcessW(wexe.c_str(), command.data(), nullptr, nullptr, FALSE,
DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, nullptr, nullptr, &startup, &process)) {
error = "cannot start " + exe + " (error " + std::to_string(GetLastError()) + ")";
return false;
}
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
return true;
}
void ReapChildren() {}
#else
static std::string Env(const char *name) {
const char *value = std::getenv(name);
return value ? value : "";
}
bool GetServicePaths(ServicePaths &out, std::string &error) {
std::string config, runtime;
std::string override_dir = Env("LORE_FORGE_DESKTOP_DIR");
if (!override_dir.empty()) {
config = runtime = override_dir;
} else {
std::string home = Env("HOME");
if (home.empty()) {
error = "HOME is not set";
return false;
}
#if defined(__APPLE__)
config = runtime = home + "/Library/Application Support/lore-forge";
#else
std::string xdg_config = Env("XDG_CONFIG_HOME");
config = (xdg_config.empty() ? home + "/.config" : xdg_config) + "/lore-forge";
std::string xdg_runtime = Env("XDG_RUNTIME_DIR");
runtime = xdg_runtime.empty() ? home + "/.local/state/lore-forge" : xdg_runtime + "/lore-forge";
#endif
}
out.endpoint = runtime + "/service.sock";
out.config_dir = config;
out.log_file = config + "/service.log";
out.config_file = config + "/desktop.toml";
return true;
}
std::string ExecutableDir() {
std::string path;
#if defined(__APPLE__)
uint32_t size = 0;
_NSGetExecutablePath(nullptr, &size);
std::string raw(size, '\0');
if (_NSGetExecutablePath(raw.data(), &size) != 0)
return ".";
char resolved[PATH_MAX];
path = realpath(raw.c_str(), resolved) ? resolved : raw.c_str();
#else
char buffer[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", buffer, sizeof buffer - 1);
if (len <= 0)
return ".";
path.assign(buffer, size_t(len));
#endif
size_t slash = path.find_last_of('/');
return slash == std::string::npos ? "." : path.substr(0, slash);
}
std::string ServiceExecutable() {
if (!g_service_override.empty())
return g_service_override;
std::string bin = Env("FORGE_SERVICE_BIN");
return bin.empty() ? ExecutableDir() + "/forge-service" : bin;
}
bool MakeTempDir(std::string &out, std::string &error) {
std::string base = Env("TMPDIR");
if (base.empty())
base = "/tmp";
if (base.back() != '/')
base += '/';
std::string pattern = base + "forge-desktop-XXXXXX";
std::vector<char> buffer(pattern.begin(), pattern.end());
buffer.push_back('\0');
if (!mkdtemp(buffer.data())) {
error = "cannot create a temporary directory under " + base;
return false;
}
out = buffer.data();
return true;
}
void SetEnv(const char *name, const std::string &value) {
setenv(name, value.c_str(), 1);
}
bool SpawnDetached(const std::string &exe, const std::vector<std::string> &args, std::string &error) {
std::vector<char *> argv;
argv.push_back(const_cast<char *>(exe.c_str()));
for (const auto &arg : args)
argv.push_back(const_cast<char *>(arg.c_str()));
argv.push_back(nullptr);
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
for (int fd = 0; fd <= 2; ++fd)
posix_spawn_file_actions_addopen(&actions, fd, "/dev/null", fd == 0 ? O_RDONLY : O_WRONLY, 0);
posix_spawnattr_t attr;
posix_spawnattr_init(&attr);
#if defined(POSIX_SPAWN_SETSID)
// Its own session: no controlling terminal, untouched by the GUI's Ctrl-C.
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSID);
#endif
pid_t pid = 0;
int result = posix_spawn(&pid, exe.c_str(), &actions, &attr, argv.data(), environ);
posix_spawn_file_actions_destroy(&actions);
posix_spawnattr_destroy(&attr);
if (result != 0) {
error = "cannot start " + exe + ": " + std::to_string(result);
return false;
}
return true;
}
void ReapChildren() {
int status;
while (waitpid(-1, &status, WNOHANG) > 0) {
}
}
#endif
} // namespace platform

View File

@ -0,0 +1,44 @@
// Platform details the GUI needs outside UHDK: where the service listens, and starting it.
// The locations mirror `forge_protocol::Paths` in desktop/protocol/src/lib.rs; change both.
#pragma once
#include <string>
#include <vector>
namespace platform {
struct ServicePaths {
// Unix: the socket's path. Windows: the named pipe's name, as UTF-8.
std::string endpoint;
std::string config_dir;
std::string log_file;
std::string config_file;
};
// False with `error` set when the environment gives no home directory.
bool GetServicePaths(ServicePaths &out, std::string &error);
// The directory holding this executable, without a trailing separator.
std::string ExecutableDir();
// The service executable to start: the override if set, else $FORGE_SERVICE_BIN, else
// forge-service beside this executable.
std::string ServiceExecutable();
void SetServiceExecutable(std::string path);
// Creates a fresh private directory under the system's temporary directory.
bool MakeTempDir(std::string &out, std::string &error);
// Sets an environment variable for this process and the processes it starts.
void SetEnv(const char *name, const std::string &value);
// Starts `exe` with `args` in its own session, detached from this process's terminal and
// lifetime, with no standard streams. Reaps it if it exits while we run.
bool SpawnDetached(const std::string &exe, const std::vector<std::string> &args, std::string &error);
// Collects exit statuses of detached children that have ended, so none linger as zombies.
void ReapChildren();
// 64-bit FNV-1a, matching `forge_protocol::fnv1a`.
unsigned long long Fnv1a(const std::string &bytes);
} // namespace platform

90
desktop/gui/src/png.cpp Normal file
View File

@ -0,0 +1,90 @@
#include "png.hpp"
#include <cstdio>
#include <vector>
namespace png {
namespace {
uint32_t Crc(const uint8_t *data, size_t len, uint32_t crc = 0xFFFFFFFFu) {
static uint32_t table[256];
static bool ready = false;
if (!ready) {
for (uint32_t n = 0; n < 256; ++n) {
uint32_t c = n;
for (int k = 0; k < 8; ++k)
c = c & 1 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
table[n] = c;
}
ready = true;
}
for (size_t i = 0; i < len; ++i)
crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
return crc;
}
void Be32(std::vector<uint8_t> &out, uint32_t value) {
out.push_back(uint8_t(value >> 24));
out.push_back(uint8_t(value >> 16));
out.push_back(uint8_t(value >> 8));
out.push_back(uint8_t(value));
}
void Chunk(std::vector<uint8_t> &out, const char type[4], const std::vector<uint8_t> &data) {
Be32(out, uint32_t(data.size()));
size_t start = out.size();
out.insert(out.end(), type, type + 4);
out.insert(out.end(), data.begin(), data.end());
Be32(out, Crc(&out[start], out.size() - start) ^ 0xFFFFFFFFu);
}
} // namespace
bool WriteRgba(const std::string &path, const uint8_t *pixels, uint32_t width, uint32_t height) {
// Raw scanlines, each with filter type 0.
std::vector<uint8_t> raw;
raw.reserve(size_t(height) * (size_t(width) * 4 + 1));
for (uint32_t y = 0; y < height; ++y) {
raw.push_back(0);
const uint8_t *row = pixels + size_t(y) * width * 4;
raw.insert(raw.end(), row, row + size_t(width) * 4);
}
// zlib stream of stored deflate blocks, at most 65535 bytes each.
std::vector<uint8_t> z = {0x78, 0x01};
for (size_t offset = 0; offset < raw.size() || raw.empty();) {
size_t len = raw.size() - offset < 65535 ? raw.size() - offset : 65535;
bool last = offset + len >= raw.size();
z.push_back(last ? 1 : 0);
z.push_back(uint8_t(len));
z.push_back(uint8_t(len >> 8));
z.push_back(uint8_t(~len));
z.push_back(uint8_t(~len >> 8));
z.insert(z.end(), raw.begin() + long(offset), raw.begin() + long(offset + len));
offset += len;
if (last)
break;
}
uint32_t a = 1, b = 0;
for (uint8_t byte : raw) {
a = (a + byte) % 65521;
b = (b + a) % 65521;
}
Be32(z, (b << 16) | a);
std::vector<uint8_t> file = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};
std::vector<uint8_t> header;
Be32(header, width);
Be32(header, height);
header.insert(header.end(), {8, 6, 0, 0, 0}); // 8-bit RGBA, no interlace
Chunk(file, "IHDR", header);
Chunk(file, "IDAT", z);
Chunk(file, "IEND", {});
FILE *out = std::fopen(path.c_str(), "wb");
if (!out)
return false;
bool ok = std::fwrite(file.data(), 1, file.size(), out) == file.size();
return std::fclose(out) == 0 && ok;
}
} // namespace png

11
desktop/gui/src/png.hpp Normal file
View File

@ -0,0 +1,11 @@
// Writes an RGBA8 image as an uncompressed PNG. For --test screenshots; no zlib needed.
#pragma once
#include <cstdint>
#include <string>
namespace png {
// `pixels` is top-down, tightly packed RGBA8. Returns false if the file cannot be written.
bool WriteRgba(const std::string &path, const uint8_t *pixels, uint32_t width, uint32_t height);
} // namespace png

View File

@ -0,0 +1,161 @@
#include "sample_repo.hpp"
#include "theme.hpp"
#include <algorithm>
#include <set>
namespace sample {
namespace {
Entry *Child(Entry &parent, const std::string &name, bool dir) {
for (auto &c : parent.children)
if (c.name == name)
return &c;
Entry e;
e.name = name;
e.path = parent.path.empty() ? name : parent.path + "/" + name;
e.dir = dir;
parent.children.push_back(std::move(e));
return &parent.children.back();
}
void AddFile(Entry &root, const std::string &path, uint64_t size, char local = ' ', std::string lock = {}) {
Entry *at = &root;
size_t start = 0;
for (size_t slash; (slash = path.find('/', start)) != std::string::npos; start = slash + 1)
at = Child(*at, path.substr(start, slash - start), true);
Entry *file = Child(*at, path.substr(start), false);
file->size = size;
file->local = local;
file->lock_owner = std::move(lock);
}
void Sort(Entry &e) {
std::sort(e.children.begin(), e.children.end(), [](const Entry &a, const Entry &b) {
return a.dir != b.dir ? a.dir : a.name < b.name;
});
for (auto &c : e.children)
Sort(c);
}
Entry *Find(Entry &e, const std::string &path) {
if (e.path == path)
return &e;
for (auto &c : e.children)
if (path == c.path || (c.dir && path.compare(0, c.path.size() + 1, c.path + "/") == 0))
return Find(c, path);
return nullptr;
}
Repository Build() {
Repository r;
r.name = "my-game";
r.current_branch = "main";
const std::string hero = "Content/Characters/Hero/";
const std::string game = "Source/Game/";
r.revisions = {
{"4be1d07", {"e91c0d2"}, "main", "Tune hero jump height", "bob", "11-25 15:40",
{{'M', game + "player.cpp"}, {'M', "Config/DefaultGame.ini"}}},
{"e91c0d2", {"19d3b7a", "7b2a913"}, "main", "Merge fix/net-crash", "alice", "11-25 14:02",
{{'M', game + "net_session.cpp"}, {'M', game + "net_session.h"}}},
{"7b2a913", {"0a6e5c4"}, "fix/net-crash", "Guard null session on reconnect", "carol", "11-25 11:18",
{{'M', game + "net_session.cpp"}, {'M', game + "net_session.h"}}},
{"c41f8e6", {"8f03ab5"}, "art/hero-v2", "Hero normal map, second pass", "dana", "11-25 10:51",
{{'M', hero + "hero_normal.png"}}},
{"19d3b7a", {"d27c9f1"}, "main", "Rebuild lobby lighting", "alice", "11-24 17:30",
{{'M', "Content/Maps/lobby.umap"}}},
{"0a6e5c4", {"d27c9f1"}, "fix/net-crash", "Repro for reconnect crash", "carol", "11-24 16:12",
{{'M', game + "net_session.cpp"}}},
{"d27c9f1", {"5e8d210", "8f03ab5"}, "main", "Merge art/hero-v2", "alice", "11-24 12:05",
{{'M', hero + "hero.fbx"}, {'A', hero + "hero_normal.png"}, {'M', hero + "hero_diffuse.png"}}},
{"8f03ab5", {"3c9e07b"}, "art/hero-v2", "Hero v2 mesh and textures", "dana", "11-23 18:44",
{{'M', hero + "hero.fbx"}, {'A', hero + "hero_normal.png"}, {'M', hero + "hero_diffuse.png"}}},
{"5e8d210", {"b6a4f3c"}, "main", "Arena spawn points", "bob", "11-23 15:20",
{{'M', "Content/Maps/arena.umap"}}},
{"b6a4f3c", {"f5d1a88"}, "main", "Menu music and hit sounds", "erin", "11-22 13:09",
{{'A', "Content/Audio/music_menu.ogg"}, {'A', "Content/Audio/sfx_hit.wav"}, {'D', "Content/Audio/placeholder.wav"}}},
{"3c9e07b", {"f5d1a88"}, "art/hero-v2", "Block out hero v2", "dana", "11-22 11:37",
{{'M', hero + "hero.fbx"}}},
{"f5d1a88", {"2a7c6e4"}, "main", "Player movement and networking", "bob", "11-21 16:55",
{{'A', game + "player.cpp"}, {'A', game + "player.h"}, {'A', game + "net_session.cpp"},
{'A', game + "net_session.h"}, {'A', "Config/DefaultInput.ini"}}},
{"2a7c6e4", {}, "main", "Initial import", "alice", "11-20 09:00",
{{'A', "README.md"}, {'A', "Config/DefaultGame.ini"}, {'A', "Content/Maps/arena.umap"},
{'A', "Content/Maps/lobby.umap"}, {'A', hero + "hero.fbx"}, {'A', hero + "hero_diffuse.png"},
{'A', "Content/Audio/placeholder.wav"}}},
};
r.branches = {
{"main", "4be1d07", theme::kForge},
{"art/hero-v2", "c41f8e6", theme::kGreen},
{"fix/net-crash", "7b2a913", theme::kBlue},
};
r.root.name = r.name;
r.root.dir = true;
AddFile(r.root, "README.md", 2'418);
AddFile(r.root, "Config/DefaultGame.ini", 3'310, 'M');
AddFile(r.root, "Config/DefaultInput.ini", 7'902);
AddFile(r.root, "Content/Audio/music_menu.ogg", 4'812'077);
AddFile(r.root, "Content/Audio/sfx_hit.wav", 211'540);
AddFile(r.root, hero + "hero.fbx", 48'213'990, ' ', "dana");
AddFile(r.root, hero + "hero_diffuse.png", 16'777'343);
AddFile(r.root, hero + "hero_normal.png", 16'780'002);
AddFile(r.root, "Content/Maps/arena.umap", 92'441'600, ' ', "you");
AddFile(r.root, "Content/Maps/lobby.umap", 61'004'288);
AddFile(r.root, game + "net_debug.cpp", 1'204, 'A');
AddFile(r.root, game + "net_session.cpp", 18'450);
AddFile(r.root, game + "net_session.h", 2'961);
AddFile(r.root, game + "player.cpp", 24'118, 'M');
AddFile(r.root, game + "player.h", 3'377);
Sort(r.root);
// Each file's last revision among those reachable from the current branch's head.
std::set<std::string> reachable;
std::vector<std::string> pending = {r.FindBranch(r.current_branch)->head};
while (!pending.empty()) {
std::string id = pending.back();
pending.pop_back();
if (!reachable.insert(id).second)
continue;
for (const auto &p : r.FindRevision(id)->parents)
pending.push_back(p);
}
for (const auto &rev : r.revisions) {
if (!reachable.count(rev.id))
continue;
for (const auto &change : rev.changes)
if (Entry *e = Find(r.root, change.path); e && e->revision.empty())
e->revision = rev.id;
}
return r;
}
} // namespace
const Revision *Repository::FindRevision(const std::string &id) const {
for (const auto &r : revisions)
if (r.id == id)
return &r;
return nullptr;
}
const Branch *Repository::FindBranch(const std::string &name) const {
for (const auto &b : branches)
if (b.name == name)
return &b;
return nullptr;
}
const Entry *Repository::FindEntry(const std::string &path) const {
return Find(const_cast<Entry &>(root), path);
}
const Repository &Get() {
static const Repository repository = Build();
return repository;
}
} // namespace sample

View File

@ -0,0 +1,52 @@
// A made-up repository for drafting the explorer UI. It stands in for what the service will
// report once it drives Lore through liblore; the GUI marks it as sample data.
#pragma once
#include "imgui.h"
#include <cstdint>
#include <string>
#include <vector>
namespace sample {
struct Entry {
std::string name, path; // path is relative to the repository root; "" for the root
bool dir = false;
uint64_t size = 0;
char local = ' '; // ' ' unchanged, 'M' modified, 'A' added in the working copy
std::string lock_owner; // empty when not locked
std::string revision; // last revision on the current branch that changed it
std::vector<Entry> children; // directories first, then by name
};
struct Change {
char kind; // 'A' added, 'M' modified, 'D' deleted
std::string path;
};
struct Revision {
std::string id;
std::vector<std::string> parents; // first parent first
std::string branch, message, author, date;
std::vector<Change> changes;
};
struct Branch {
std::string name, head;
ImU32 colour;
};
struct Repository {
std::string name, current_branch;
Entry root;
std::vector<Revision> revisions; // newest first; children before parents
std::vector<Branch> branches;
const Revision *FindRevision(const std::string &id) const;
const Branch *FindBranch(const std::string &name) const;
const Entry *FindEntry(const std::string &path) const;
};
const Repository &Get();
} // namespace sample

View File

@ -0,0 +1,413 @@
#include "service_client.hpp"
#include <chrono>
#include <cstring>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <cerrno>
#include <fcntl.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#endif
namespace {
constexpr const char *kClientName = "forge-desktop 0.1.0";
// How long to wait for a service we started before calling it unavailable.
constexpr int kStartWaitMs = 5000;
// How often to retry while unavailable, and to try starting it again.
constexpr int kRetryMs = 2000;
constexpr int kRespawnMs = 15000;
constexpr size_t kMaxLine = 1u << 20;
int64_t NowMs() {
using namespace std::chrono;
return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
} // namespace
ServiceClient::ServiceClient(platform::ServicePaths paths, std::function<void()> wake)
: paths_(std::move(paths)), wake_(std::move(wake)) {
#if defined(_WIN32)
signal_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
#else
int fds[2];
if (pipe(fds) == 0) {
signal_read_ = fds[0];
signal_write_ = fds[1];
fcntl(signal_read_, F_SETFL, O_NONBLOCK);
fcntl(signal_write_, F_SETFL, O_NONBLOCK);
fcntl(signal_read_, F_SETFD, FD_CLOEXEC);
fcntl(signal_write_, F_SETFD, FD_CLOEXEC);
}
#endif
}
ServiceClient::~ServiceClient() {
stop_ = true;
Signal();
if (thread_.joinable())
thread_.join();
Close();
#if defined(_WIN32)
if (signal_)
CloseHandle(signal_);
#else
if (signal_read_ >= 0)
close(signal_read_);
if (signal_write_ >= 0)
close(signal_write_);
#endif
}
void ServiceClient::Start() {
thread_ = std::thread([this] { Run(); });
}
uint64_t ServiceClient::Call(std::string_view method, std::string params_json) {
uint64_t id = NextId();
{
std::lock_guard<std::mutex> lock(mutex_);
outgoing_.push_back(RequestLine(id, method, params_json));
}
Signal();
return id;
}
std::vector<ServiceClient::Incoming> ServiceClient::Drain() {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<Incoming> out;
out.swap(incoming_);
return out;
}
std::string ServiceClient::Detail() const {
std::lock_guard<std::mutex> lock(mutex_);
return detail_;
}
std::string ServiceClient::RequestLine(uint64_t id, std::string_view method, const std::string &params) const {
return "{\"jsonrpc\":\"2.0\",\"id\":" + std::to_string(id) + ",\"method\":" + json::Quote(method) +
",\"params\":" + (params.empty() ? std::string("{}") : params) + "}\n";
}
void ServiceClient::Push(Incoming incoming) {
{
std::lock_guard<std::mutex> lock(mutex_);
incoming_.push_back(std::move(incoming));
}
if (wake_)
wake_();
}
void ServiceClient::SetState(State state, std::string detail) {
{
std::lock_guard<std::mutex> lock(mutex_);
detail_ = std::move(detail);
}
if (state_.exchange(state) != state && wake_)
wake_();
}
bool ServiceClient::SleepUnlessStopped(int milliseconds) {
int64_t until = NowMs() + milliseconds;
while (!stop_) {
int64_t left = until - NowMs();
if (left <= 0)
return true;
std::this_thread::sleep_for(std::chrono::milliseconds(left < 50 ? left : 50));
}
return false;
}
void ServiceClient::Run() {
int64_t last_spawn = -kRespawnMs;
#if !defined(_WIN32)
if (paths_.endpoint.size() >= sizeof(sockaddr_un{}.sun_path)) {
SetState(State::Unavailable, "socket path over " + std::to_string(sizeof(sockaddr_un{}.sun_path) - 1) +
" bytes: " + paths_.endpoint + " (shorten LORE_FORGE_DESKTOP_DIR)");
return;
}
#endif
while (!stop_) {
if (restart_requested_.exchange(false))
last_spawn = -kRespawnMs;
if (Connect()) {
SetState(State::Connected);
Push({Incoming::Kind::Connected, {}, {}});
Serve();
Close();
if (stop_)
break;
{
std::lock_guard<std::mutex> lock(mutex_);
outgoing_.clear();
}
SetState(State::Connecting, "connection closed");
Push({Incoming::Kind::Disconnected, {}, "connection closed"});
if (!SleepUnlessStopped(300))
break;
continue;
}
platform::ReapChildren();
int64_t now = NowMs();
if (!auto_start_) {
SetState(State::Unavailable, "stopped");
if (!SleepUnlessStopped(kRetryMs / 4))
break;
continue;
}
if (now - last_spawn >= kRespawnMs) {
last_spawn = now;
std::string exe = platform::ServiceExecutable(), error;
if (platform::SpawnDetached(exe, {"--log-file", paths_.log_file}, error))
SetState(State::StartingService, "starting " + exe);
else
SetState(State::Unavailable, error);
continue;
}
if (state_ == State::StartingService && now - last_spawn < kStartWaitMs) {
if (!SleepUnlessStopped(150))
break;
continue;
}
if (state_ != State::Unavailable)
SetState(State::Unavailable, "no service at " + paths_.endpoint + "; log " + paths_.log_file);
if (!SleepUnlessStopped(kRetryMs))
break;
}
}
#if defined(_WIN32)
bool ServiceClient::Connect() {
std::wstring name;
{
int len = MultiByteToWideChar(CP_UTF8, 0, paths_.endpoint.c_str(), -1, nullptr, 0);
name.resize(size_t(len > 0 ? len - 1 : 0));
if (len > 1)
MultiByteToWideChar(CP_UTF8, 0, paths_.endpoint.c_str(), -1, name.data(), len);
}
for (int attempt = 0; attempt < 2; ++attempt) {
HANDLE pipe = CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr);
if (pipe != INVALID_HANDLE_VALUE) {
pipe_ = pipe;
return true;
}
if (GetLastError() != ERROR_PIPE_BUSY || !WaitNamedPipeW(name.c_str(), 500))
return false;
}
return false;
}
void ServiceClient::Close() {
if (pipe_) {
CloseHandle(static_cast<HANDLE>(pipe_));
pipe_ = nullptr;
}
}
void ServiceClient::Signal() {
if (signal_)
SetEvent(static_cast<HANDLE>(signal_));
}
bool ServiceClient::WriteAll(const std::string &bytes) {
HANDLE pipe = static_cast<HANDLE>(pipe_);
OVERLAPPED overlapped = {};
overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
bool ok = true;
size_t offset = 0;
while (ok && offset < bytes.size()) {
DWORD written = 0;
ResetEvent(overlapped.hEvent);
if (!WriteFile(pipe, bytes.data() + offset, DWORD(bytes.size() - offset), nullptr, &overlapped) &&
GetLastError() != ERROR_IO_PENDING)
ok = false;
else if (!GetOverlappedResult(pipe, &overlapped, &written, TRUE))
ok = false;
offset += written;
}
CloseHandle(overlapped.hEvent);
return ok;
}
void ServiceClient::Serve() {
HANDLE pipe = static_cast<HANDLE>(pipe_);
uint64_t hello = NextId();
hello_id_ = hello;
std::string greeting = RequestLine(hello, "hello",
"{\"protocol\":" + std::to_string(kProtocolVersion) +
",\"client\":" + json::Quote(kClientName) + "}") +
RequestLine(NextId(), "status", "{}");
if (!WriteAll(greeting))
return;
OVERLAPPED read = {};
read.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
char chunk[16384];
std::string buffer;
bool reading = false, alive = true;
while (alive && !stop_) {
if (!reading) {
ResetEvent(read.hEvent);
if (!ReadFile(pipe, chunk, sizeof chunk, nullptr, &read) && GetLastError() != ERROR_IO_PENDING)
break;
reading = true;
}
HANDLE handles[2] = {read.hEvent, static_cast<HANDLE>(signal_)};
DWORD which = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
if (which == WAIT_OBJECT_0) {
DWORD got = 0;
reading = false;
if (!GetOverlappedResult(pipe, &read, &got, FALSE) || got == 0)
break;
buffer.append(chunk, got);
size_t newline;
while ((newline = buffer.find('\n')) != std::string::npos) {
json::Value message;
if (json::Parse(std::string_view(buffer).substr(0, newline), message))
Push({Incoming::Kind::Message, std::move(message), {}});
buffer.erase(0, newline + 1);
}
if (buffer.size() > kMaxLine)
break;
} else if (which == WAIT_OBJECT_0 + 1) {
std::deque<std::string> lines;
{
std::lock_guard<std::mutex> lock(mutex_);
lines.swap(outgoing_);
}
for (const auto &line : lines)
if (!WriteAll(line)) {
alive = false;
break;
}
} else {
break;
}
}
if (reading) {
DWORD ignored;
CancelIoEx(pipe, &read);
GetOverlappedResult(pipe, &read, &ignored, TRUE);
}
CloseHandle(read.hEvent);
}
#else
bool ServiceClient::Connect() {
sockaddr_un address = {};
address.sun_family = AF_UNIX;
if (paths_.endpoint.size() >= sizeof address.sun_path)
return false;
std::memcpy(address.sun_path, paths_.endpoint.c_str(), paths_.endpoint.size() + 1);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
return false;
fcntl(fd, F_SETFD, FD_CLOEXEC);
#if defined(SO_NOSIGPIPE)
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one);
#endif
if (connect(fd, reinterpret_cast<sockaddr *>(&address), sizeof address) != 0) {
close(fd);
return false;
}
socket_ = fd;
return true;
}
void ServiceClient::Close() {
if (socket_ >= 0) {
close(socket_);
socket_ = -1;
}
}
void ServiceClient::Signal() {
if (signal_write_ >= 0) {
char byte = 1;
// A full pipe already means "look at the queue".
ssize_t ignored = write(signal_write_, &byte, 1);
(void)ignored;
}
}
bool ServiceClient::WriteAll(const std::string &bytes) {
size_t offset = 0;
while (offset < bytes.size()) {
#if defined(MSG_NOSIGNAL)
ssize_t sent = send(socket_, bytes.data() + offset, bytes.size() - offset, MSG_NOSIGNAL);
#else
ssize_t sent = send(socket_, bytes.data() + offset, bytes.size() - offset, 0);
#endif
if (sent < 0 && errno == EINTR)
continue;
if (sent <= 0)
return false;
offset += size_t(sent);
}
return true;
}
void ServiceClient::Serve() {
uint64_t hello = NextId();
hello_id_ = hello;
std::string greeting = RequestLine(hello, "hello",
"{\"protocol\":" + std::to_string(kProtocolVersion) +
",\"client\":" + json::Quote(kClientName) + "}") +
RequestLine(NextId(), "status", "{}");
if (!WriteAll(greeting))
return;
std::string buffer;
char chunk[16384];
while (!stop_) {
pollfd fds[2] = {{socket_, POLLIN, 0}, {signal_read_, POLLIN, 0}};
int ready = poll(fds, 2, -1);
if (ready < 0) {
if (errno == EINTR)
continue;
return;
}
if (fds[1].revents & POLLIN) {
char drain[64];
while (read(signal_read_, drain, sizeof drain) > 0) {
}
std::deque<std::string> lines;
{
std::lock_guard<std::mutex> lock(mutex_);
lines.swap(outgoing_);
}
for (const auto &line : lines)
if (!WriteAll(line))
return;
}
if (fds[0].revents & (POLLIN | POLLHUP | POLLERR)) {
ssize_t got = recv(socket_, chunk, sizeof chunk, 0);
if (got < 0 && errno == EINTR)
continue;
if (got <= 0)
return;
buffer.append(chunk, size_t(got));
size_t newline;
while ((newline = buffer.find('\n')) != std::string::npos) {
json::Value message;
if (json::Parse(std::string_view(buffer).substr(0, newline), message))
Push({Incoming::Kind::Message, std::move(message), {}});
buffer.erase(0, newline + 1);
}
if (buffer.size() > kMaxLine)
return;
}
}
}
#endif

View File

@ -0,0 +1,95 @@
// The GUI's connection to forge-service.
//
// A background thread owns the socket (a Unix socket, or a named pipe on Windows): it
// connects, starts the service when nothing answers, sends `hello` then `status`, reads
// messages and writes queued requests. The UI thread only queues requests and drains what
// arrived; `wake` is called whenever there is something to drain. See
// .ai/designs/desktop-client.md for the protocol.
#pragma once
#include "json.hpp"
#include "platform.hpp"
#include <atomic>
#include <cstdint>
#include <deque>
#include <functional>
#include <mutex>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
class ServiceClient {
public:
static constexpr int kProtocolVersion = 1;
enum class State { Connecting, StartingService, Connected, Unavailable };
struct Incoming {
enum class Kind { Connected, Disconnected, Message } kind;
json::Value message; // Kind::Message: a response or notification
std::string detail; // Kind::Disconnected: why
};
// `wake` must be safe to call from any thread.
ServiceClient(platform::ServicePaths paths, std::function<void()> wake);
~ServiceClient();
ServiceClient(const ServiceClient &) = delete;
ServiceClient &operator=(const ServiceClient &) = delete;
void Start();
// Queues a request; returns its id. Dropped if the connection ends before it is sent.
uint64_t Call(std::string_view method, std::string params_json = "{}");
std::vector<Incoming> Drain();
// Whether to start the service when nothing answers. Turn it off before asking the
// service to shut down, or the client would start it straight back up.
void SetAutoStart(bool enabled) {
auto_start_ = enabled;
if (enabled)
restart_requested_ = true;
}
bool AutoStart() const { return auto_start_.load(); }
State GetState() const { return state_.load(); }
std::string Detail() const;
// Ids of the `hello` and `status` requests sent on the current connection.
uint64_t HelloId() const { return hello_id_.load(); }
private:
void Run();
bool Connect();
void Close();
void Serve();
bool WriteAll(const std::string &bytes);
void Push(Incoming incoming);
void SetState(State state, std::string detail = {});
void Signal();
bool SleepUnlessStopped(int milliseconds);
uint64_t NextId() { return next_id_.fetch_add(1); }
std::string RequestLine(uint64_t id, std::string_view method, const std::string &params) const;
platform::ServicePaths paths_;
std::function<void()> wake_;
std::thread thread_;
std::atomic<bool> stop_{false};
std::atomic<State> state_{State::Connecting};
std::atomic<uint64_t> next_id_{1};
std::atomic<uint64_t> hello_id_{0};
std::atomic<bool> auto_start_{true};
std::atomic<bool> restart_requested_{false};
mutable std::mutex mutex_;
std::string detail_;
std::deque<std::string> outgoing_;
std::vector<Incoming> incoming_;
#if defined(_WIN32)
void *pipe_ = nullptr; // HANDLE
void *signal_ = nullptr; // event: outgoing queued or stop
#else
int socket_ = -1;
int signal_read_ = -1, signal_write_ = -1; // self-pipe: outgoing queued or stop
#endif
};

361
desktop/gui/src/theme.cpp Normal file
View File

@ -0,0 +1,361 @@
#include "theme.hpp"
#include <cmath>
#include <cstring>
extern const unsigned char kVgaFont[];
extern const size_t kVgaFontSize;
namespace theme {
ImVec4 Vec(ImU32 colour) {
return ImGui::ColorConvertU32ToFloat4(colour);
}
void Apply() {
ImGuiStyle &style = ImGui::GetStyle();
style.WindowPadding = {16, 16};
style.FramePadding = {8, 4};
style.ItemSpacing = {8, 8};
style.ItemInnerSpacing = {8, 4};
style.ScrollbarSize = 8;
style.WindowRounding = style.ChildRounding = style.FrameRounding = 0;
style.PopupRounding = style.ScrollbarRounding = style.GrabRounding = style.TabRounding = 0;
style.WindowBorderSize = 0;
style.ChildBorderSize = 1;
style.FrameBorderSize = 1;
style.PopupBorderSize = 1;
style.AntiAliasedLines = false;
style.AntiAliasedLinesUseTex = false;
style.AntiAliasedFill = false;
ImVec4 *c = style.Colors;
c[ImGuiCol_Text] = Vec(kPaper);
c[ImGuiCol_TextDisabled] = Vec(kMuted);
c[ImGuiCol_WindowBg] = Vec(kInk);
c[ImGuiCol_ChildBg] = Vec(kPanel);
c[ImGuiCol_PopupBg] = Vec(kPanel);
c[ImGuiCol_Border] = Vec(kRaised);
c[ImGuiCol_BorderShadow] = {0, 0, 0, 0};
c[ImGuiCol_FrameBg] = Vec(kInk);
c[ImGuiCol_FrameBgHovered] = Vec(kPanel);
c[ImGuiCol_FrameBgActive] = Vec(kPanel);
c[ImGuiCol_Button] = Vec(kRaised);
c[ImGuiCol_ButtonHovered] = Vec(kMuted);
c[ImGuiCol_ButtonActive] = Vec(kForge);
c[ImGuiCol_Header] = Vec(kRaised);
c[ImGuiCol_HeaderHovered] = Vec(kMuted);
c[ImGuiCol_HeaderActive] = Vec(kForge);
c[ImGuiCol_Separator] = Vec(kRaised);
c[ImGuiCol_ScrollbarBg] = Vec(kInk);
c[ImGuiCol_ScrollbarGrab] = Vec(kRaised);
c[ImGuiCol_ScrollbarGrabHovered] = Vec(kMuted);
c[ImGuiCol_ScrollbarGrabActive] = Vec(kForge);
c[ImGuiCol_CheckMark] = Vec(kForge);
c[ImGuiCol_TextSelectedBg] = Vec(kRaised);
c[ImGuiCol_NavCursor] = Vec(kSpark);
}
Fonts LoadFonts() {
Fonts fonts;
ImFontConfig config;
config.FontDataOwnedByAtlas = false; // compiled-in data
config.OversampleH = config.OversampleV = 1;
config.PixelSnapH = true;
std::strncpy(config.Name, "IBM VGA 8x16", sizeof config.Name - 1);
fonts.font = ImGui::GetIO().Fonts->AddFontFromMemoryTTF(const_cast<unsigned char *>(kVgaFont),
int(kVgaFontSize), fonts.size, &config);
if (!fonts.font)
fonts.font = ImGui::GetIO().Fonts->AddFontDefault();
return fonts;
}
static ImVec2 Floor(ImVec2 v) {
return {std::floor(v.x), std::floor(v.y)};
}
static void Box(ImDrawList *d, ImVec2 a, ImVec2 b, ImU32 colour) {
d->AddRectFilled(a, b, colour);
}
// A bevelled block: light top and left edges, dark bottom and right.
static void Bevel(ImDrawList *d, ImVec2 a, ImVec2 b, ImU32 face, ImU32 light, ImU32 dark) {
Box(d, a, b, face);
Box(d, a, {b.x, a.y + 1}, light);
Box(d, a, {a.x + 1, b.y}, light);
Box(d, {a.x, b.y - 1}, b, dark);
Box(d, {b.x - 1, a.y}, b, dark);
}
bool Button(const char *label, bool enabled, bool primary) {
const ImVec2 pad = {10, ImGui::GetStyle().FramePadding.y}; // the face is one frame high
ImVec2 text = ImGui::CalcTextSize(label, nullptr, true);
ImVec2 size = {std::floor(text.x + pad.x * 2), std::floor(text.y + pad.y * 2)};
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
ImGui::BeginDisabled(!enabled);
bool clicked = ImGui::InvisibleButton(label, {size.x + 2, size.y + 2});
bool held = enabled && ImGui::IsItemActive();
bool hovered = enabled && ImGui::IsItemHovered();
ImGui::EndDisabled();
ImDrawList *d = ImGui::GetWindowDrawList();
ImVec2 a = held ? ImVec2{pos.x + 2, pos.y + 2} : pos;
ImVec2 b = {a.x + size.x, a.y + size.y};
if (!held)
Box(d, {pos.x + 2, pos.y + 2}, {pos.x + size.x + 2, pos.y + size.y + 2}, kInk);
ImU32 face = !enabled ? kPanel : primary ? (hovered ? kSpark : kForge) : (hovered ? kMuted : kRaised);
ImU32 light = !enabled ? kRaised : primary ? kSpark : kMuted;
ImU32 dark = !enabled ? kInk : primary ? kRed : kPanel;
Bevel(d, a, b, face, light, dark);
ImU32 ink = !enabled ? kRaised : primary || hovered ? kInk : kPaper;
const char *end = std::strstr(label, "##"); // "##" starts an ID suffix, as in ImGui
d->AddText({a.x + pad.x, a.y + pad.y}, ink, label, end);
return clicked && enabled;
}
float ButtonWidth(const char *label) {
return std::floor(ImGui::CalcTextSize(label, nullptr, true).x) + 20 + 2;
}
bool Tab(const char *label, bool active) {
ImVec2 text = ImGui::CalcTextSize(label, nullptr, true);
ImVec2 size = {std::floor(text.x) + 24, std::floor(text.y) + 8};
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
bool clicked = ImGui::InvisibleButton(label, size);
bool hovered = ImGui::IsItemHovered();
ImDrawList *d = ImGui::GetWindowDrawList();
ImVec2 b = {pos.x + size.x, pos.y + size.y};
if (active) {
Box(d, pos, b, kPanel);
Box(d, pos, {b.x, pos.y + 2}, kForge);
Box(d, {pos.x, pos.y + 2}, {pos.x + 1, b.y}, kMuted);
Box(d, {b.x - 1, pos.y + 2}, b, kInk);
} else {
ImVec2 a = {pos.x, pos.y + 3};
Box(d, a, b, hovered ? kPanel : kInk);
Box(d, a, {b.x, a.y + 1}, kRaised);
Box(d, a, {a.x + 1, b.y}, kRaised);
Box(d, {b.x - 1, a.y}, b, kRaised);
}
const char *end = std::strstr(label, "##");
d->AddText({pos.x + 12, pos.y + (active ? 4 : 5)}, active ? kPaper : hovered ? kPaper : kMuted, label, end);
return clicked;
}
bool Row(const char *id, bool selected, float height) {
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
float width = std::floor(ImGui::GetContentRegionAvail().x);
if (width < 1)
width = 1;
bool clicked = ImGui::InvisibleButton(id, {width, height});
bool hovered = ImGui::IsItemHovered();
ImDrawList *d = ImGui::GetWindowDrawList();
if (selected) {
Box(d, pos, {pos.x + width, pos.y + height}, kRaised);
Box(d, pos, {pos.x + 2, pos.y + height}, kForge);
} else if (hovered) {
Box(d, pos, {pos.x + width, pos.y + height}, kPanel);
}
return clicked;
}
void Progress(float fraction, float width) {
const float cell = 6, gap = 2, height = 10;
int cells = int((width - 4 + gap) / (cell + gap));
if (cells < 1)
cells = 1;
int filled = int(std::lround(fraction * cells));
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
float used = 4 + cells * (cell + gap) - gap;
ImGui::Dummy({used, height + 4});
ImDrawList *d = ImGui::GetWindowDrawList();
Box(d, pos, {pos.x + used, pos.y + height + 4}, kInk);
for (int i = 0; i < cells; ++i) {
ImVec2 a = {pos.x + 2 + i * (cell + gap), pos.y + 2};
Box(d, a, {a.x + cell, a.y + height}, i < filled ? (i == filled - 1 ? kSpark : kForge) : kPanel);
}
}
void Led(ImU32 colour) {
const float size = 8;
float line = ImGui::GetTextLineHeight();
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
pos.y += std::floor((line - size) / 2);
ImGui::Dummy({size, line});
ImDrawList *d = ImGui::GetWindowDrawList();
Box(d, pos, {pos.x + size, pos.y + size}, kInk);
Box(d, {pos.x + 1, pos.y + 1}, {pos.x + size - 1, pos.y + size - 1}, colour);
Box(d, {pos.x + 2, pos.y + 2}, {pos.x + 4, pos.y + 4}, kPaper);
}
void TextColoured(ImU32 colour, const char *text) {
ImGui::PushStyleColor(ImGuiCol_Text, colour);
ImGui::TextUnformatted(text);
ImGui::PopStyleColor();
}
float TagWidth(const char *label) {
return std::floor(ImGui::CalcTextSize(label).x) + 8;
}
void TagAt(ImVec2 pos, const char *label, ImU32 colour) {
pos = Floor(pos);
ImDrawList *d = ImGui::GetWindowDrawList();
Box(d, pos, {pos.x + TagWidth(label), pos.y + ImGui::GetTextLineHeight()}, colour);
d->AddText({pos.x + 4, pos.y}, kInk, label);
}
void Tag(const char *label, ImU32 colour) {
ImVec2 pos = ImGui::GetCursorScreenPos();
ImGui::Dummy({TagWidth(label), ImGui::GetTextLineHeight()});
TagAt(pos, label, colour);
}
void TextAt(ImVec2 pos, ImU32 colour, const char *text, float right) {
pos = Floor(pos);
ImVec4 clip = {pos.x, pos.y, right, pos.y + ImGui::GetTextLineHeight()};
ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize(), pos, colour, text, nullptr, 0,
&clip);
}
void FolderIcon(ImVec2 pos, bool open) {
ImVec2 p = Floor(pos);
ImDrawList *d = ImGui::GetWindowDrawList();
Box(d, {p.x, p.y + 1}, {p.x + 6, p.y + 3}, kForge);
Box(d, {p.x, p.y + 3}, {p.x + 14, p.y + 12}, kForge);
if (open)
Box(d, {p.x + 2, p.y + 6}, {p.x + 14, p.y + 12}, kSpark);
else
Box(d, {p.x, p.y + 4}, {p.x + 14, p.y + 12}, kSpark);
Box(d, {p.x, p.y + 11}, {p.x + 14, p.y + 12}, kForge);
}
void FileIcon(ImVec2 pos, ImU32 tint) {
ImVec2 p = Floor(pos);
ImDrawList *d = ImGui::GetWindowDrawList();
Box(d, {p.x + 2, p.y}, {p.x + 9, p.y + 12}, kPaper);
Box(d, {p.x + 9, p.y + 3}, {p.x + 12, p.y + 12}, kPaper);
Box(d, {p.x + 9, p.y}, {p.x + 10, p.y + 3}, kMuted); // the folded corner
Box(d, {p.x + 10, p.y + 2}, {p.x + 12, p.y + 3}, kMuted);
Box(d, {p.x + 4, p.y + 5}, {p.x + 10, p.y + 6}, tint);
Box(d, {p.x + 4, p.y + 8}, {p.x + 10, p.y + 9}, tint);
}
void Rule() {
ImVec2 pos = Floor(ImGui::GetCursorScreenPos());
float width = std::floor(ImGui::GetContentRegionAvail().x);
ImGui::Dummy({width, 2});
ImDrawList *d = ImGui::GetWindowDrawList();
for (float x = 0; x + 2 <= width; x += 4)
Box(d, {pos.x + x, pos.y}, {pos.x + x + 2, pos.y + 2}, kRaised);
}
void BeginCard(const char *id) {
// ImGui draws a child's background and border into the parent's draw list, so the shadow
// goes on a channel below them.
ImDrawList *d = ImGui::GetWindowDrawList();
d->ChannelsSplit(2);
d->ChannelsSetCurrent(1);
ImGui::BeginChild(id, {-3, 0}, ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY);
}
void EndCard() {
ImGui::EndChild();
ImVec2 a = Floor(ImGui::GetItemRectMin()), b = Floor(ImGui::GetItemRectMax());
ImDrawList *d = ImGui::GetWindowDrawList();
d->ChannelsSetCurrent(0);
Box(d, {a.x + 3, a.y + 3}, {b.x + 3, b.y + 3}, Rgb(0x0c0d14));
d->ChannelsMerge();
}
// 16x16 pixel art. '.' clear, L light, M metal, D dark metal, F forge, S spark.
static const char *const kAnvil[16] = {
"................",
"................",
"...........S....",
".........S...S..",
"...........F....",
"................",
"..LLLLLLLLLLLL..",
"...MMMMMMMMMMM..",
".....MMMMMMMMM..",
".......MMMMM....",
".......DDDDD....",
"......MMMMMMM...",
"....MMMMMMMMMM..",
"....DDDDDDDDDD..",
"................",
"................",
};
static ImU32 ArtColour(char c) {
switch (c) {
case 'L': return kPaper;
case 'M': return kMuted;
case 'D': return kRaised;
case 'F': return kForge;
case 'S': return kSpark;
default: return 0;
}
}
// Scales 16x16 art (with an optional ink outline and background) to `size`, nearest neighbour.
static std::vector<uint8_t> Render(unsigned size, bool template_image, bool tile) {
ImU32 art[16][16];
for (int y = 0; y < 16; ++y)
for (int x = 0; x < 16; ++x)
art[y][x] = template_image ? (kAnvil[y][x] != '.' ? IM_COL32(0, 0, 0, 255) : 0) : ArtColour(kAnvil[y][x]);
if (!template_image) {
// A one-pixel ink outline keeps the icon readable on light and dark trays.
ImU32 outlined[16][16];
std::memcpy(outlined, art, sizeof art);
for (int y = 0; y < 16; ++y)
for (int x = 0; x < 16; ++x) {
if (art[y][x])
continue;
bool edge = false;
for (int dy = -1; dy <= 1; ++dy)
for (int dx = -1; dx <= 1; ++dx) {
int nx = x + dx, ny = y + dy;
if ((dx || dy) && nx >= 0 && ny >= 0 && nx < 16 && ny < 16 && art[ny][nx])
edge = true;
}
if (edge)
outlined[y][x] = kInk;
}
std::memcpy(art, outlined, sizeof art);
}
if (tile)
for (int y = 0; y < 16; ++y)
for (int x = 0; x < 16; ++x) {
bool border = x == 0 || y == 0 || x == 15 || y == 15;
if (border)
art[y][x] = kRaised;
else if (!art[y][x])
art[y][x] = kInk;
}
std::vector<uint8_t> pixels(size_t(size) * size * 4, 0);
unsigned scale = size / 16 ? size / 16 : 1;
unsigned offset = (size - 16 * scale) / 2;
for (unsigned py = 0; py < 16 * scale; ++py)
for (unsigned px = 0; px < 16 * scale; ++px) {
ImU32 colour = art[py / scale][px / scale];
uint8_t *p = &pixels[(size_t(py + offset) * size + px + offset) * 4];
p[0] = uint8_t(colour >> IM_COL32_R_SHIFT);
p[1] = uint8_t(colour >> IM_COL32_G_SHIFT);
p[2] = uint8_t(colour >> IM_COL32_B_SHIFT);
p[3] = uint8_t(colour >> IM_COL32_A_SHIFT);
}
return pixels;
}
std::vector<uint8_t> TrayIcon(unsigned size, bool template_image) {
return Render(size, template_image, false);
}
std::vector<uint8_t> AppIcon(unsigned size) {
return Render(size, false, true);
}
} // namespace theme

66
desktop/gui/src/theme.hpp Normal file
View File

@ -0,0 +1,66 @@
// Pixel-art look: the Sweetie 16 palette, a bitmap font, square bevelled widgets, hard
// shadows. One art pixel is one logical pixel, so keep positions and sizes whole numbers.
#pragma once
#include "imgui.h"
#include <cstdint>
#include <vector>
namespace theme {
// Sweetie 16, by GrafxKid.
constexpr ImU32 Rgb(uint32_t rgb) {
return IM_COL32((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF, 0xFF);
}
inline constexpr ImU32 kInk = Rgb(0x1a1c2c); // background, shadows
inline constexpr ImU32 kPanel = Rgb(0x333c57); // cards
inline constexpr ImU32 kRaised = Rgb(0x566c86); // buttons
inline constexpr ImU32 kMuted = Rgb(0x94b0c2); // secondary text, bevel light
inline constexpr ImU32 kPaper = Rgb(0xf4f4f4); // text
inline constexpr ImU32 kForge = Rgb(0xef7d57); // accent
inline constexpr ImU32 kSpark = Rgb(0xffcd75); // accent highlight, warnings
inline constexpr ImU32 kGreen = Rgb(0x38b764);
inline constexpr ImU32 kRed = Rgb(0xb13e53);
inline constexpr ImU32 kBlue = Rgb(0x41a6f6);
ImVec4 Vec(ImU32 colour);
struct Fonts {
ImFont *font = nullptr;
float size = 16; // the font's native size; titles use 2x
};
void Apply();
Fonts LoadFonts();
// Widgets drawn in the pixel style.
bool Button(const char *label, bool enabled = true, bool primary = false);
float ButtonWidth(const char *label); // including the shadow
// A tab in a row of tabs; the active one takes the panel colour.
bool Tab(const char *label, bool active);
// A full-width selectable row of `height`. Draw its contents at GetItemRectMin() afterwards.
bool Row(const char *id, bool selected, float height);
void Progress(float fraction, float width);
void Led(ImU32 colour);
void TextColoured(ImU32 colour, const char *text);
// A label in a filled box, one text line high: ink text on `colour`.
float TagWidth(const char *label);
void Tag(const char *label, ImU32 colour);
void TagAt(ImVec2 pos, const char *label, ImU32 colour); // at a screen position, no layout
// Text at a screen position, clipped at `right`, with no layout.
void TextAt(ImVec2 pos, ImU32 colour, const char *text, float right = 1e30f);
// 14x12 pixel glyphs for the file views, drawn at a screen position.
void FolderIcon(ImVec2 pos, bool open);
void FileIcon(ImVec2 pos, ImU32 tint);
// A dotted horizontal rule across the content region.
void Rule();
// A bordered child window that sizes to its contents, with a hard shadow. Pair with EndCard.
void BeginCard(const char *id);
void EndCard();
// RGBA8, top-down, scaled from 16x16 pixel art with no smoothing. `template_image` is black
// on transparent for macOS menu bars, which tint it.
std::vector<uint8_t> TrayIcon(unsigned size, bool template_image);
std::vector<uint8_t> AppIcon(unsigned size);
} // namespace theme

View File

@ -0,0 +1,15 @@
#ifndef UHDK_EXAMPLE_PAYLOAD_HPP
#define UHDK_EXAMPLE_PAYLOAD_HPP
#include "uhdk.h"
#include <cassert>
// Call only after checking the event/request discriminator. References are borrowed.
template <typename T> const T &UhdkData(const uhdk_event &event) {
assert(event.data && event.data_size >= sizeof(T));
return *static_cast<const T *>(event.data);
}
template <typename T> const T &UhdkResult(const uhdk_request_result &result) {
assert(result.status == UHDK_STATUS_OK && result.data && result.data_size >= sizeof(T));
return *static_cast<const T *>(result.data);
}
#endif

View File

@ -0,0 +1,568 @@
#include "UhdkPayload.hpp"
// Example-local platform backend. Docking is supported; OS multi-viewports are not.
// Clipboard reads are asynchronous: ImGui's synchronous getter uses a cache,
// refreshed on focus and every 250 ms. No native waits occur inside GL frames.
// IME commits/candidate positioning work; preedit rendering and replacement of
// surrounding text are not implemented (ImGui owns the editable text buffers).
#include "imgui.h"
#include "imgui_impl_uhdk.h"
#include <cfloat>
#include <string>
struct ImGui_ImplUHDK_Data {
uhdk_session *session = nullptr;
uhdk_window *window = nullptr;
uint64_t time = 0;
uint64_t clipboard_time = 0;
uint64_t acknowledged_input = 0;
uhdk_request_tag clipboard_tag = 0;
bool clipboard_pending = false;
bool discard_clipboard = false;
std::string clipboard;
uhdk_modifier_flags modifiers = 0;
unsigned mouse_buttons = 0;
ImGuiMouseCursor cursor = ImGuiMouseCursor_COUNT;
bool focused = false;
bool text_enabled = false;
bool composing = false;
bool macos = false;
uhdk_rect caret = {};
};
static ImGui_ImplUHDK_Data *Data() {
return static_cast<ImGui_ImplUHDK_Data *>(ImGui::GetIO().BackendPlatformUserData);
}
static void Modifiers(uhdk_modifier_flags mods) {
ImGuiIO &io = ImGui::GetIO();
io.AddKeyEvent(ImGuiMod_Ctrl, (mods & UHDK_MOD_CONTROL) != 0);
io.AddKeyEvent(ImGuiMod_Shift, (mods & UHDK_MOD_SHIFT) != 0);
io.AddKeyEvent(ImGuiMod_Alt, (mods & UHDK_MOD_ALT) != 0);
io.AddKeyEvent(ImGuiMod_Super, (mods & UHDK_MOD_SUPER) != 0);
}
static ImGuiKey Key(uint32_t physical, uhdk_key logical) {
// USB HID usages, including modifiers and keypad. Text comes from TEXT_COMMIT.
if (physical >= 0x04 && physical <= 0x1d)
return ImGuiKey(ImGuiKey_A + physical - 0x04);
if (physical >= 0x1e && physical <= 0x26)
return ImGuiKey(ImGuiKey_1 + physical - 0x1e);
if (physical >= 0x3a && physical <= 0x45)
return ImGuiKey(ImGuiKey_F1 + physical - 0x3a);
if (physical >= 0x68 && physical <= 0x73)
return ImGuiKey(ImGuiKey_F13 + physical - 0x68);
if (physical >= 0x59 && physical <= 0x61)
return ImGuiKey(ImGuiKey_Keypad1 + physical - 0x59);
switch (physical) {
case 0x27:
return ImGuiKey_0;
case 0x28:
return ImGuiKey_Enter;
case 0x29:
return ImGuiKey_Escape;
case 0x2a:
return ImGuiKey_Backspace;
case 0x2b:
return ImGuiKey_Tab;
case 0x2c:
return ImGuiKey_Space;
case 0x2d:
return ImGuiKey_Minus;
case 0x2e:
return ImGuiKey_Equal;
case 0x2f:
return ImGuiKey_LeftBracket;
case 0x30:
return ImGuiKey_RightBracket;
case 0x31:
return ImGuiKey_Backslash;
case 0x33:
return ImGuiKey_Semicolon;
case 0x34:
return ImGuiKey_Apostrophe;
case 0x35:
return ImGuiKey_GraveAccent;
case 0x36:
return ImGuiKey_Comma;
case 0x37:
return ImGuiKey_Period;
case 0x38:
return ImGuiKey_Slash;
case 0x39:
return ImGuiKey_CapsLock;
case 0x46:
return ImGuiKey_PrintScreen;
case 0x47:
return ImGuiKey_ScrollLock;
case 0x48:
return ImGuiKey_Pause;
case 0x49:
return ImGuiKey_Insert;
case 0x4a:
return ImGuiKey_Home;
case 0x4b:
return ImGuiKey_PageUp;
case 0x4c:
return ImGuiKey_Delete;
case 0x4d:
return ImGuiKey_End;
case 0x4e:
return ImGuiKey_PageDown;
case 0x4f:
return ImGuiKey_RightArrow;
case 0x50:
return ImGuiKey_LeftArrow;
case 0x51:
return ImGuiKey_DownArrow;
case 0x52:
return ImGuiKey_UpArrow;
case 0x53:
return ImGuiKey_NumLock;
case 0x54:
return ImGuiKey_KeypadDivide;
case 0x55:
return ImGuiKey_KeypadMultiply;
case 0x56:
return ImGuiKey_KeypadSubtract;
case 0x57:
return ImGuiKey_KeypadAdd;
case 0x58:
return ImGuiKey_KeypadEnter;
case 0x62:
return ImGuiKey_Keypad0;
case 0x63:
return ImGuiKey_KeypadDecimal;
case 0x64:
return ImGuiKey_Oem102;
case 0x65:
return ImGuiKey_Menu;
case 0x67:
return ImGuiKey_KeypadEqual;
case 0xe0:
return ImGuiKey_LeftCtrl;
case 0xe1:
return ImGuiKey_LeftShift;
case 0xe2:
return ImGuiKey_LeftAlt;
case 0xe3:
return ImGuiKey_LeftSuper;
case 0xe4:
return ImGuiKey_RightCtrl;
case 0xe5:
return ImGuiKey_RightShift;
case 0xe6:
return ImGuiKey_RightAlt;
case 0xe7:
return ImGuiKey_RightSuper;
default:
break;
}
if (logical >= 'a' && logical <= 'z')
return ImGuiKey(ImGuiKey_A + logical - 'a');
if (logical >= 'A' && logical <= 'Z')
return ImGuiKey(ImGuiKey_A + logical - 'A');
return ImGuiKey_None;
}
static bool NativeEditKey(ImGuiKey key) {
return key == ImGuiKey_Backspace || key == ImGuiKey_Delete || key == ImGuiKey_LeftArrow ||
key == ImGuiKey_RightArrow || key == ImGuiKey_UpArrow || key == ImGuiKey_DownArrow ||
key == ImGuiKey_Home || key == ImGuiKey_End || key == ImGuiKey_Enter ||
key == ImGuiKey_KeypadEnter || key == ImGuiKey_Tab || key == ImGuiKey_PageUp ||
key == ImGuiKey_PageDown || key == ImGuiKey_Escape;
}
static void Edit(const uhdk_event &event) {
auto *bd = Data();
ImGuiKey key = ImGuiKey_None;
uhdk_modifier_flags mods =
UhdkData<uhdk_edit_event>(event).extend_selection ? UHDK_MOD_SHIFT : 0;
const auto shortcut = bd->macos ? UHDK_MOD_SUPER : UHDK_MOD_CONTROL;
switch (UhdkData<uhdk_edit_event>(event).command) {
case UHDK_EDIT_COPY:
key = ImGuiKey_C;
mods |= shortcut;
break;
case UHDK_EDIT_CUT:
key = ImGuiKey_X;
mods |= shortcut;
break;
case UHDK_EDIT_PASTE:
key = ImGuiKey_V;
mods |= shortcut;
break;
case UHDK_EDIT_SELECT_ALL:
key = ImGuiKey_A;
mods |= shortcut;
break;
case UHDK_EDIT_UNDO:
key = ImGuiKey_Z;
mods |= shortcut;
break;
case UHDK_EDIT_REDO:
key = ImGuiKey_Z;
mods |= shortcut | UHDK_MOD_SHIFT;
break;
case UHDK_EDIT_DELETE_WORD_BACKWARD:
key = ImGuiKey_Backspace;
mods |= bd->macos ? UHDK_MOD_ALT : UHDK_MOD_CONTROL;
break;
case UHDK_EDIT_DELETE_WORD_FORWARD:
key = ImGuiKey_Delete;
mods |= bd->macos ? UHDK_MOD_ALT : UHDK_MOD_CONTROL;
break;
case UHDK_EDIT_DELETE_LINE_START:
if (!bd->macos)
return;
key = ImGuiKey_Backspace;
mods |= UHDK_MOD_SUPER;
break;
case UHDK_EDIT_DELETE_BACKWARD:
key = ImGuiKey_Backspace;
break;
case UHDK_EDIT_DELETE_FORWARD:
key = ImGuiKey_Delete;
break;
case UHDK_EDIT_MOVE_LEFT:
case UHDK_EDIT_MOVE_BACKWARD:
key = ImGuiKey_LeftArrow;
break;
case UHDK_EDIT_MOVE_RIGHT:
case UHDK_EDIT_MOVE_FORWARD:
key = ImGuiKey_RightArrow;
break;
case UHDK_EDIT_MOVE_UP:
key = ImGuiKey_UpArrow;
break;
case UHDK_EDIT_MOVE_DOWN:
key = ImGuiKey_DownArrow;
break;
case UHDK_EDIT_LINE_LEFT_END:
case UHDK_EDIT_LINE_START:
key = ImGuiKey_Home;
break;
case UHDK_EDIT_LINE_RIGHT_END:
case UHDK_EDIT_LINE_END:
key = ImGuiKey_End;
break;
case UHDK_EDIT_DOCUMENT_START:
key = ImGuiKey_Home;
mods |= shortcut;
break;
case UHDK_EDIT_DOCUMENT_END:
key = ImGuiKey_End;
mods |= shortcut;
break;
case UHDK_EDIT_WORD_LEFT:
case UHDK_EDIT_WORD_BACKWARD:
key = ImGuiKey_LeftArrow;
mods |= bd->macos ? UHDK_MOD_ALT : UHDK_MOD_CONTROL;
break;
case UHDK_EDIT_WORD_RIGHT:
case UHDK_EDIT_WORD_FORWARD:
key = ImGuiKey_RightArrow;
mods |= bd->macos ? UHDK_MOD_ALT : UHDK_MOD_CONTROL;
break;
case UHDK_EDIT_PAGE_UP:
key = ImGuiKey_PageUp;
break;
case UHDK_EDIT_PAGE_DOWN:
key = ImGuiKey_PageDown;
break;
case UHDK_EDIT_CANCEL:
key = ImGuiKey_Escape;
break;
case UHDK_EDIT_LINE_BREAK:
key = ImGuiKey_Enter;
mods |= UHDK_MOD_SHIFT;
break;
case UHDK_EDIT_BACKTAB:
key = ImGuiKey_Tab;
mods |= UHDK_MOD_SHIFT;
break;
case UHDK_EDIT_NEWLINE:
key = ImGuiKey_Enter;
mods |= bd->modifiers & UHDK_MOD_CONTROL;
break;
case UHDK_EDIT_TAB:
key = ImGuiKey_Tab;
break;
default:
return;
}
Modifiers(mods);
ImGui::GetIO().AddKeyEvent(key, true);
ImGui::GetIO().AddKeyEvent(key, false);
Modifiers(bd->modifiers);
}
static const char *GetClipboard(ImGuiContext *) {
return Data()->clipboard.c_str();
}
static void SetClipboard(ImGuiContext *, const char *text) {
auto *bd = Data();
// Cancel an older read so its eventual completion cannot overwrite this copy.
if (bd->clipboard_pending)
uhdk_request_cancel(bd->session, bd->clipboard_tag);
bd->discard_clipboard = bd->clipboard_pending;
bd->clipboard.assign(text);
bd->clipboard_time = uhdk_get_time_ns(bd->session);
uhdk_clipboard_write_text(bd->session, {text, bd->clipboard.size()});
}
static void SetImeData(ImGuiContext *, ImGuiViewport *, ImGuiPlatformImeData *ime) {
auto *bd = Data();
if (bd->text_enabled != ime->WantTextInput) {
if (uhdk_window_set_text_input(bd->window, ime->WantTextInput) == UHDK_STATUS_OK)
bd->text_enabled = ime->WantTextInput;
}
bd->caret = {ime->InputPos.x, ime->InputPos.y, 1.0f, ime->InputLineHeight};
}
bool ImGui_ImplUHDK_Init(uhdk_session *session, uhdk_request_tag clipboard_tag) {
uhdk_window *window = uhdk_get_window(session);
ImGuiIO &io = ImGui::GetIO();
IM_ASSERT(io.BackendPlatformUserData == nullptr);
uhdk_window_metrics metrics = {};
metrics.struct_size = sizeof(metrics);
if (!session || !clipboard_tag || !window ||
uhdk_window_get_metrics(window, &metrics) != UHDK_STATUS_OK)
return false;
auto *bd = IM_NEW(ImGui_ImplUHDK_Data)();
bd->session = session;
bd->clipboard_tag = clipboard_tag;
bd->window = window;
bd->focused = metrics.focused;
bd->macos = uhdk_get_backend(session) == UHDK_BACKEND_MACOS;
io.BackendPlatformUserData = bd;
io.BackendPlatformName = "imgui_impl_uhdk";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.ConfigMacOSXBehaviors = bd->macos;
io.AddFocusEvent(bd->focused);
auto &platform = ImGui::GetPlatformIO();
platform.Platform_GetClipboardTextFn = GetClipboard;
platform.Platform_SetClipboardTextFn = SetClipboard;
platform.Platform_SetImeDataFn = SetImeData;
ImGui::GetMainViewport()->PlatformHandle = window;
return true;
}
void ImGui_ImplUHDK_Shutdown() {
auto *bd = Data();
IM_ASSERT(bd);
if (bd->clipboard_pending)
uhdk_request_cancel(bd->session, bd->clipboard_tag);
uhdk_window_set_text_input(bd->window, false);
uhdk_window_set_pointer_mode(bd->window, UHDK_POINTER_NORMAL);
uhdk_window_set_cursor_shape(bd->window, UHDK_CURSOR_ARROW);
auto &platform = ImGui::GetPlatformIO();
platform.Platform_GetClipboardTextFn = nullptr;
platform.Platform_SetClipboardTextFn = nullptr;
platform.Platform_SetImeDataFn = nullptr;
ImGui::GetMainViewport()->PlatformHandle = nullptr;
ImGuiIO &io = ImGui::GetIO();
io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors;
io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr;
IM_DELETE(bd);
}
void ImGui_ImplUHDK_ProcessEvent(const uhdk_event *event) {
auto *bd = Data();
ImGuiIO &io = ImGui::GetIO();
if (event->type == UHDK_EVENT_REQUEST_DONE && bd->clipboard_pending &&
UhdkData<uhdk_request_result>(*event).tag == bd->clipboard_tag) {
const auto &result = UhdkData<uhdk_request_result>(*event);
bd->clipboard_pending = false;
if (bd->discard_clipboard) {
bd->discard_clipboard = false;
return;
}
bd->clipboard.clear();
if (result.status == UHDK_STATUS_OK && UhdkResult<uhdk_text>(result).len)
bd->clipboard.assign(
UhdkResult<uhdk_text>(result).ptr, size_t(UhdkResult<uhdk_text>(result).len)
);
return;
}
if (event->window != bd->window)
return;
switch (event->type) {
case UHDK_EVENT_WINDOW_METRICS:
if (bd->focused != bool(UhdkData<uhdk_window_metrics>(*event).focused)) {
bd->focused = UhdkData<uhdk_window_metrics>(*event).focused;
io.AddFocusEvent(bd->focused);
bd->clipboard_time = 0;
if (!bd->focused) {
bd->mouse_buttons = 0;
bd->modifiers = 0;
bd->composing = false;
}
}
break;
case UHDK_EVENT_POINTER_ENTER:
case UHDK_EVENT_POINTER_MOVE:
io.AddMousePosEvent(
UhdkData<uhdk_pointer_event>(*event).position.x,
UhdkData<uhdk_pointer_event>(*event).position.y
);
break;
case UHDK_EVENT_POINTER_LEAVE:
if (!bd->mouse_buttons)
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
break;
case UHDK_EVENT_POINTER_BUTTON: {
const auto &pointer = UhdkData<uhdk_pointer_event>(*event);
int button = int(pointer.button) - 1;
if (button < 0 || button >= 5)
break;
bd->modifiers = pointer.modifiers;
Modifiers(bd->modifiers);
io.AddMousePosEvent(pointer.position.x, pointer.position.y);
io.AddMouseButtonEvent(button, pointer.pressed);
unsigned before = bd->mouse_buttons;
if (pointer.pressed)
bd->mouse_buttons |= 1u << button;
else
bd->mouse_buttons &= ~(1u << button);
if (bool(before) != bool(bd->mouse_buttons)) {
uhdk_window_set_pointer_mode(
bd->window, bd->mouse_buttons ? UHDK_POINTER_CAPTURE : UHDK_POINTER_NORMAL
);
}
break;
}
case UHDK_EVENT_POINTER_MODE_CHANGED:
if (UhdkData<uhdk_pointer_mode_event>(*event).mode == UHDK_POINTER_NORMAL) {
for (int i = 0; i < 5; ++i)
if (bd->mouse_buttons & (1u << i))
io.AddMouseButtonEvent(i, false);
bd->mouse_buttons = 0;
}
break;
case UHDK_EVENT_SCROLL: {
// UHDK uses right/down-positive deltas; ImGui uses left/up-positive.
float unit = UhdkData<uhdk_scroll_event>(*event).unit == UHDK_SCROLL_LOGICAL_PIXELS
? 1.0f / 40.0f
: 1.0f;
io.AddMouseWheelEvent(
-UhdkData<uhdk_scroll_event>(*event).delta.x * unit,
-UhdkData<uhdk_scroll_event>(*event).delta.y * unit
);
break;
}
case UHDK_EVENT_KEY: {
const auto &key = UhdkData<uhdk_key_event>(*event);
bd->modifiers = key.modifiers;
Modifiers(bd->modifiers);
ImGuiKey mapped = Key(key.physical_key, key.logical_key);
// Native EDIT_COMMAND drives editing/repeat while text input is enabled.
bool native_edit = bd->text_enabled && NativeEditKey(mapped);
if (bd->text_enabled && !bd->macos) {
const bool ctrl = (key.modifiers & UHDK_MOD_CONTROL) != 0;
const bool shift = (key.modifiers & UHDK_MOD_SHIFT) != 0;
const bool reserved = (key.modifiers & (UHDK_MOD_ALT | UHDK_MOD_SUPER)) != 0;
const bool clipboard =
ctrl &&
((!shift && (mapped == ImGuiKey_C || mapped == ImGuiKey_X || mapped == ImGuiKey_V ||
mapped == ImGuiKey_A || mapped == ImGuiKey_Y)) ||
mapped == ImGuiKey_Z);
const bool insert_alias = mapped == ImGuiKey_Insert && ctrl != shift;
native_edit = !reserved && (native_edit || clipboard || insert_alias);
if (ctrl && (mapped == ImGuiKey_Tab || mapped == ImGuiKey_Enter ||
mapped == ImGuiKey_KeypadEnter || mapped == ImGuiKey_PageUp ||
mapped == ImGuiKey_PageDown))
native_edit = false;
if ((ctrl || shift) && mapped == ImGuiKey_Escape)
native_edit = false;
}
if (mapped != ImGuiKey_None && !native_edit && !key.repeat &&
(!bd->composing || !key.pressed))
io.AddKeyEvent(mapped, key.pressed);
break;
}
case UHDK_EVENT_TEXT_COMMIT:
bd->acknowledged_input = event->input_id;
if (UhdkData<uhdk_text_event>(*event).text.len) {
std::string text(
UhdkData<uhdk_text_event>(*event).text.ptr,
size_t(UhdkData<uhdk_text_event>(*event).text.len)
);
io.AddInputCharactersUTF8(text.c_str());
}
break;
case UHDK_EVENT_TEXT_PREEDIT:
bd->acknowledged_input = event->input_id;
bd->composing = true;
break;
case UHDK_EVENT_TEXT_COMPOSITION_END:
bd->acknowledged_input = event->input_id;
bd->composing = false;
break;
case UHDK_EVENT_EDIT_COMMAND:
bd->acknowledged_input = event->input_id;
Edit(*event);
break;
default:
break;
}
}
void ImGui_ImplUHDK_NewFrame() {
auto *bd = Data();
ImGuiIO &io = ImGui::GetIO();
IM_ASSERT(!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable));
uhdk_window_metrics metrics = {};
metrics.struct_size = sizeof(metrics);
if (uhdk_window_get_metrics(bd->window, &metrics) == UHDK_STATUS_OK) {
io.DisplaySize = ImVec2(metrics.logical_size.width, metrics.logical_size.height);
if (io.DisplaySize.x > 0 && io.DisplaySize.y > 0)
io.DisplayFramebufferScale = ImVec2(
metrics.framebuffer_width / io.DisplaySize.x,
metrics.framebuffer_height / io.DisplaySize.y
);
}
uint64_t now = uhdk_get_time_ns(bd->session);
io.DeltaTime = bd->time && now > bd->time ? float(double(now - bd->time) / 1e9) : 1.0f / 60.0f;
bd->time = now;
if (bd->focused && !bd->clipboard_pending &&
(!bd->clipboard_time || now - bd->clipboard_time >= 250000000)) {
bd->clipboard_pending =
uhdk_clipboard_read_text_async(bd->session, 8 * 1024 * 1024, bd->clipboard_tag) ==
UHDK_STATUS_OK;
bd->clipboard_time = now;
}
if (!(io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)) {
ImGuiMouseCursor cursor =
io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
if (cursor != bd->cursor) {
static const uhdk_cursor_shape shapes[] = {
UHDK_CURSOR_ARROW,
UHDK_CURSOR_TEXT,
UHDK_CURSOR_MOVE,
UHDK_CURSOR_RESIZE_VERTICAL,
UHDK_CURSOR_RESIZE_HORIZONTAL,
UHDK_CURSOR_RESIZE_NE_SW,
UHDK_CURSOR_RESIZE_NW_SE,
UHDK_CURSOR_HAND,
UHDK_CURSOR_WAIT,
UHDK_CURSOR_WAIT,
UHDK_CURSOR_NOT_ALLOWED,
};
static_assert(IM_ARRAYSIZE(shapes) == ImGuiMouseCursor_COUNT, "Update cursor mapping");
if (uhdk_window_set_cursor_shape(
bd->window,
cursor == ImGuiMouseCursor_None ? UHDK_CURSOR_HIDDEN : shapes[cursor]
) == UHDK_STATUS_OK)
bd->cursor = cursor;
}
}
if (bd->text_enabled) {
uhdk_text_state state = {};
state.struct_size = sizeof(state);
state.acknowledged_input_id = bd->acknowledged_input;
state.caret = bd->caret;
uhdk_window_set_text_state(bd->window, &state);
}
}

View File

@ -0,0 +1,10 @@
// Dear ImGui platform backend for a single UHDK window. Renderer-independent.
// Call on OS main with the owning ImGui context current.
#pragma once
#include "uhdk.h"
// Reserve clipboard_tag for this backend for its entire lifetime.
bool ImGui_ImplUHDK_Init(uhdk_session *session, uhdk_request_tag clipboard_tag);
void ImGui_ImplUHDK_Shutdown();
void ImGui_ImplUHDK_ProcessEvent(const uhdk_event *event);
void ImGui_ImplUHDK_NewFrame();

View File

@ -0,0 +1,12 @@
[package]
name = "forge-protocol"
description = "Messages and socket location shared by the client service and its frontends"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true

295
desktop/protocol/src/lib.rs Normal file
View File

@ -0,0 +1,295 @@
//! The protocol between the client service and its frontends (the desktop GUI and the TUI).
//!
//! JSON-RPC 2.0, one message per line, over a local socket private to the user. A client's
//! first request is [`methods::HELLO`]; after it the service also sends notifications
//! ([`events`]) to that client. The C++ GUI implements the same messages by hand, so this
//! crate is the reference: change both together and bump [`PROTOCOL_VERSION`] when an older
//! peer would misread a message.
//!
//! See `.ai/designs/desktop-client.md`.
use std::path::PathBuf;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
/// The protocol version this build speaks.
pub const PROTOCOL_VERSION: u32 = 1;
/// Overrides the directory holding the socket, configuration and log, for tests and for
/// running more than one service.
pub const DIR_ENV: &str = "LORE_FORGE_DESKTOP_DIR";
pub mod methods {
pub const HELLO: &str = "hello";
pub const STATUS: &str = "status";
pub const SYNC_NOW: &str = "sync_now";
pub const SHUTDOWN: &str = "shutdown";
}
pub mod events {
/// Progress of something the service is doing: [`super::Activity`].
pub const ACTIVITY: &str = "activity";
/// The workspace list changed: [`super::StatusResult`]'s `workspaces`.
pub const WORKSPACES: &str = "workspaces";
}
/// JSON-RPC error codes. The standard ones, then ours from -32000.
pub mod codes {
pub const PARSE_ERROR: i64 = -32700;
pub const INVALID_REQUEST: i64 = -32600;
pub const METHOD_NOT_FOUND: i64 = -32601;
pub const INVALID_PARAMS: i64 = -32602;
pub const INTERNAL_ERROR: i64 = -32603;
/// A request other than `hello` arrived before `hello`.
pub const HELLO_FIRST: i64 = -32000;
/// The client speaks a protocol version the service does not.
pub const UNSUPPORTED_PROTOCOL: i64 = -32001;
/// No workspace has the given id.
pub const NO_SUCH_WORKSPACE: i64 = -32002;
/// The workspace is already doing something that conflicts.
pub const BUSY: i64 = -32003;
}
/// A request from a frontend.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Request {
pub jsonrpc: String,
pub id: Value,
pub method: String,
#[serde(default)]
pub params: Value,
}
/// A reply to one request: `result` or `error`, never both.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Response {
pub jsonrpc: String,
pub id: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<RpcError>,
}
impl Response {
pub fn ok(id: Value, result: Value) -> Self {
Response { jsonrpc: "2.0".into(), id, result: Some(result), error: None }
}
pub fn err(id: Value, code: i64, message: impl Into<String>) -> Self {
Response { jsonrpc: "2.0".into(), id, result: None, error: Some(RpcError { code, message: message.into() }) }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RpcError {
pub code: i64,
pub message: String,
}
/// A message from the service that answers nothing.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Notification {
pub jsonrpc: String,
pub method: String,
pub params: Value,
}
impl Notification {
pub fn new(method: &str, params: impl Serialize) -> Self {
Notification {
jsonrpc: "2.0".into(),
method: method.into(),
params: serde_json::to_value(params).expect("protocol types serialize"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HelloParams {
pub protocol: u32,
/// The frontend's name and version, for the service's log.
pub client: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HelloResult {
pub protocol: u32,
/// The service's name and version.
pub service: String,
pub pid: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StatusResult {
pub workspaces: Vec<Workspace>,
pub uptime_s: u64,
}
/// A working copy the service looks after.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Workspace {
/// Stable for the service's lifetime; frontends address the workspace by it.
pub id: String,
pub name: String,
pub path: String,
pub remote: String,
pub state: WorkspaceState,
pub autosync: Autosync,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceState {
/// Not checked yet.
Unknown,
Idle,
Syncing,
Error,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Autosync {
#[default]
Off,
Interval,
OnChange,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkspaceParams {
pub workspace: String,
}
/// Progress of one piece of work.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Activity {
pub workspace: String,
/// What is being done, such as `sync`.
pub kind: String,
pub phase: Phase,
/// 0 to 1 while running, when known.
#[serde(skip_serializing_if = "Option::is_none")]
pub progress: Option<f32>,
pub message: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
Started,
Running,
Finished,
Failed,
}
/// Where the service keeps its socket, configuration and log.
///
/// - macOS: `~/Library/Application Support/lore-forge`
/// - Linux: `$XDG_RUNTIME_DIR/lore-forge` for the socket, `$XDG_CONFIG_HOME/lore-forge` (or
/// `~/.config/lore-forge`) for the rest
/// - Windows: `%APPDATA%\lore-forge`; the socket is a named pipe
///
/// [`DIR_ENV`] puts everything in one directory instead.
#[derive(Clone, Debug)]
pub struct Paths {
pub config_dir: PathBuf,
/// The socket's directory on Unix. Unused on Windows.
pub runtime_dir: PathBuf,
}
impl Paths {
pub fn from_env() -> Result<Self, String> {
let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty()).map(PathBuf::from);
if let Some(dir) = var(DIR_ENV) {
return Ok(Paths { config_dir: dir.clone(), runtime_dir: dir });
}
let home = || var("HOME").ok_or_else(|| "HOME is not set".to_owned());
if cfg!(target_os = "macos") {
let dir = home()?.join("Library/Application Support/lore-forge");
Ok(Paths { config_dir: dir.clone(), runtime_dir: dir })
} else if cfg!(windows) {
let dir = var("APPDATA").ok_or("APPDATA is not set")?.join("lore-forge");
Ok(Paths { config_dir: dir.clone(), runtime_dir: dir })
} else {
let config = match var("XDG_CONFIG_HOME") {
Some(dir) => dir,
None => home()?.join(".config"),
}
.join("lore-forge");
let runtime = match var("XDG_RUNTIME_DIR") {
Some(dir) => dir.join("lore-forge"),
None => home()?.join(".local/state/lore-forge"),
};
Ok(Paths { config_dir: config, runtime_dir: runtime })
}
}
/// The Unix socket's path.
pub fn socket(&self) -> PathBuf {
self.runtime_dir.join("service.sock")
}
/// The Windows named pipe's name. Per user, and per [`DIR_ENV`] directory when that is
/// set, so test services do not collide with the real one.
pub fn pipe_name(&self) -> String {
let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".into());
let mut name = format!(r"\\.\pipe\lore-forge-service-{}", sanitize(&user));
if std::env::var_os(DIR_ENV).is_some() {
name.push('-');
name.push_str(&format!("{:016x}", fnv1a(self.runtime_dir.to_string_lossy().as_bytes())));
}
name
}
pub fn config_file(&self) -> PathBuf {
self.config_dir.join("desktop.toml")
}
pub fn log_file(&self) -> PathBuf {
self.config_dir.join("service.log")
}
}
fn sanitize(name: &str) -> String {
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect()
}
/// FNV-1a, so the GUI can derive the same pipe name without a hashing library.
pub fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf29ce484222325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn responses_carry_result_or_error() {
let ok = serde_json::to_string(&Response::ok(1.into(), serde_json::json!({}))).unwrap();
assert_eq!(ok, r#"{"jsonrpc":"2.0","id":1,"result":{}}"#);
let err = serde_json::to_string(&Response::err(2.into(), codes::BUSY, "busy")).unwrap();
assert_eq!(err, r#"{"jsonrpc":"2.0","id":2,"error":{"code":-32003,"message":"busy"}}"#);
}
#[test]
fn enums_are_snake_case() {
assert_eq!(serde_json::to_string(&Autosync::OnChange).unwrap(), r#""on_change""#);
assert_eq!(serde_json::to_string(&WorkspaceState::Syncing).unwrap(), r#""syncing""#);
}
#[test]
fn fnv1a_matches_reference() {
// Reference values for FNV-1a 64.
assert_eq!(fnv1a(b""), 0xcbf29ce484222325);
assert_eq!(fnv1a(b"a"), 0xaf63dc4c8601ec8c);
}
}

View File

@ -0,0 +1,21 @@
[package]
name = "forge-service"
description = "The per-user client service the desktop GUI and the TUI connect to"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
forge-protocol.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
toml.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
clap.workspace = true
[dev-dependencies]
tempfile.workspace = true

View File

@ -0,0 +1,81 @@
//! `desktop.toml`: the workspaces the service looks after.
//!
//! ```toml
//! [[workspace]]
//! name = "my-game"
//! path = "/Users/me/lore/my-game"
//! remote = "lore://localhost:41337/me/my-game"
//! autosync = "off" # off, interval or on_change
//! ```
use std::path::Path;
use forge_protocol::Autosync;
use serde::Deserialize;
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(default, rename = "workspace")]
pub workspaces: Vec<WorkspaceConfig>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceConfig {
pub name: String,
pub path: String,
#[serde(default)]
pub remote: String,
#[serde(default)]
pub autosync: Autosync,
}
impl Config {
/// Reads `path`; a missing file is an empty configuration.
pub fn load(path: &Path) -> Result<Config, String> {
match std::fs::read_to_string(path) {
Ok(text) => toml::from_str(&text).map_err(|error| format!("{}: {error}", path.display())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
Err(error) => Err(format!("{}: {error}", path.display())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_workspaces_and_defaults() {
let config: Config = toml::from_str(
r#"
[[workspace]]
name = "game"
path = "/w/game"
remote = "lore://h/me/game"
autosync = "on_change"
[[workspace]]
name = "tools"
path = "/w/tools"
"#,
)
.unwrap();
assert_eq!(config.workspaces.len(), 2);
assert_eq!(config.workspaces[0].autosync, Autosync::OnChange);
assert_eq!(config.workspaces[1].autosync, Autosync::Off);
assert_eq!(config.workspaces[1].remote, "");
}
#[test]
fn missing_file_is_empty() {
let dir = tempfile::tempdir().unwrap();
assert!(Config::load(&dir.path().join("none.toml")).unwrap().workspaces.is_empty());
}
#[test]
fn unknown_keys_are_refused() {
assert!(toml::from_str::<Config>("[[workspace]]\nname='a'\npath='/a'\ncolour='red'").is_err());
}
}

195
desktop/service/src/main.rs Normal file
View File

@ -0,0 +1,195 @@
//! `forge-service`: the per-user client service the desktop GUI and the TUI connect to.
//!
//! It listens on a local socket private to the user (see `forge_protocol::Paths`) and exits
//! quietly when another service already holds it, so frontends may start it whenever they
//! cannot connect.
mod config;
mod server;
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use clap::Parser;
use forge_protocol::Paths;
use crate::config::Config;
use crate::server::Service;
#[derive(Parser)]
#[command(version, about = "The lore-forge client service")]
struct Args {
/// Append the log to this file instead of writing it to stderr.
#[arg(long)]
log_file: Option<PathBuf>,
}
fn main() -> ExitCode {
let args = Args::parse();
init_logging(args.log_file.as_deref());
let paths = match Paths::from_env() {
Ok(paths) => paths,
Err(error) => {
tracing::error!("{error}");
return ExitCode::FAILURE;
}
};
let config = match Config::load(&paths.config_file()) {
Ok(config) => config,
Err(error) => {
tracing::error!("cannot read the configuration: {error}");
return ExitCode::FAILURE;
}
};
let runtime = tokio::runtime::Runtime::new().expect("a tokio runtime");
let service = Service::new(config, Duration::from_millis(600));
match runtime.block_on(listen::run(service, &paths)) {
Ok(()) => ExitCode::SUCCESS,
Err(listen::Error::AlreadyRunning) => {
tracing::info!("another service is already running");
ExitCode::SUCCESS
}
Err(listen::Error::Io(error)) => {
tracing::error!("{error}");
ExitCode::FAILURE
}
}
}
fn init_logging(file: Option<&std::path::Path>) {
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
let builder = tracing_subscriber::fmt().with_env_filter(filter);
let open = |path: &std::path::Path| {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::OpenOptions::new().create(true).append(true).open(path)
};
match file.map(open) {
Some(Ok(file)) => builder.with_ansi(false).with_writer(Arc::new(file)).init(),
Some(Err(error)) => {
builder.with_writer(std::io::stderr).init();
tracing::warn!("cannot open the log file, logging to stderr: {error}");
}
None => builder.with_writer(std::io::stderr).init(),
}
}
mod listen {
use super::*;
pub enum Error {
AlreadyRunning,
Io(std::io::Error),
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Error::Io(error)
}
}
/// Waits for Ctrl-C, or SIGTERM on Unix.
async fn terminated() {
#[cfg(unix)]
{
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("a SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
#[cfg(unix)]
pub async fn run(service: Arc<Service>, paths: &Paths) -> Result<(), Error> {
use std::os::unix::fs::DirBuilderExt;
use std::os::unix::fs::PermissionsExt;
use tokio::net::UnixListener;
use tokio::net::UnixStream;
std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&paths.runtime_dir)?;
std::fs::create_dir_all(&paths.config_dir)?;
let socket = paths.socket();
// sun_path holds 104 bytes on macOS and 108 on Linux, terminator included.
let limit = if cfg!(target_os = "macos") { 103 } else { 107 };
if socket.as_os_str().len() > limit {
return Err(Error::Io(std::io::Error::other(format!(
"the socket path {} is longer than this system allows ({limit} bytes); \
point {} at a shorter directory",
socket.display(),
forge_protocol::DIR_ENV
))));
}
if socket.exists() {
if UnixStream::connect(&socket).await.is_ok() {
return Err(Error::AlreadyRunning);
}
tracing::info!(socket = %socket.display(), "removing a stale socket");
std::fs::remove_file(&socket)?;
}
let listener = UnixListener::bind(&socket)?;
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
tracing::info!(socket = %socket.display(), pid = std::process::id(), "forge-service is listening");
let result = loop {
tokio::select! {
accepted = listener.accept() => match accepted {
Ok((stream, _)) => { tokio::spawn(Arc::clone(&service).serve(stream)); }
Err(error) => break Err(Error::Io(error)),
},
_ = service.stopped() => break Ok(()),
_ = terminated() => break Ok(()),
}
};
let _ = std::fs::remove_file(&socket);
tracing::info!("forge-service stopped");
result
}
#[cfg(windows)]
pub async fn run(service: Arc<Service>, paths: &Paths) -> Result<(), Error> {
use tokio::net::windows::named_pipe::ServerOptions;
std::fs::create_dir_all(&paths.config_dir)?;
let name = paths.pipe_name();
// The first instance fails when another service holds the name. Remote clients are
// refused; the pipe's default security admits only this user and administrators.
let mut server = match ServerOptions::new().first_pipe_instance(true).reject_remote_clients(true).create(&name) {
Ok(server) => server,
Err(error) if error.raw_os_error() == Some(5) || error.raw_os_error() == Some(231) => {
return Err(Error::AlreadyRunning);
}
Err(error) => return Err(Error::Io(error)),
};
tracing::info!(pipe = %name, pid = std::process::id(), "forge-service is listening");
let result = loop {
tokio::select! {
connected = server.connect() => {
if let Err(error) = connected {
break Err(Error::Io(error));
}
let next = match ServerOptions::new().reject_remote_clients(true).create(&name) {
Ok(next) => next,
Err(error) => break Err(Error::Io(error)),
};
let stream = std::mem::replace(&mut server, next);
tokio::spawn(Arc::clone(&service).serve(stream));
}
_ = service.stopped() => break Ok(()),
_ = terminated() => break Ok(()),
}
};
tracing::info!("forge-service stopped");
result
}
}

View File

@ -0,0 +1,417 @@
//! The service's state and the protocol over one connection.
//!
//! Milestone 1: workspaces come from `desktop.toml` and sync is **simulated**. liblore
//! replaces the simulation in milestone 2 (see `.ai/designs/desktop-client.md`).
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use forge_protocol::Activity;
use forge_protocol::HelloParams;
use forge_protocol::HelloResult;
use forge_protocol::Notification;
use forge_protocol::PROTOCOL_VERSION;
use forge_protocol::Phase;
use forge_protocol::Request;
use forge_protocol::Response;
use forge_protocol::StatusResult;
use forge_protocol::Workspace;
use forge_protocol::WorkspaceParams;
use forge_protocol::WorkspaceState;
use forge_protocol::codes;
use forge_protocol::events;
use forge_protocol::methods;
use serde_json::Value;
use serde_json::json;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::sync::Notify;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use crate::config::Config;
/// The longest message accepted from a frontend.
const MAX_LINE: u64 = 1 << 20;
pub struct Service {
started: Instant,
workspaces: Mutex<Vec<Workspace>>,
/// Notifications, already serialized, for every client past `hello`.
events: broadcast::Sender<String>,
shutdown: Notify,
/// How long each step of a simulated sync takes.
step: Duration,
}
impl Service {
pub fn new(config: Config, step: Duration) -> Arc<Service> {
let workspaces = config
.workspaces
.into_iter()
.enumerate()
.map(|(index, workspace)| Workspace {
id: format!("w{}", index + 1),
name: workspace.name,
path: workspace.path,
remote: workspace.remote,
state: WorkspaceState::Unknown,
autosync: workspace.autosync,
})
.collect();
Arc::new(Service {
started: Instant::now(),
workspaces: Mutex::new(workspaces),
events: broadcast::channel(256).0,
shutdown: Notify::new(),
step,
})
}
/// Resolves once a client has asked the service to stop.
pub async fn stopped(&self) {
self.shutdown.notified().await;
}
fn workspaces(&self) -> Vec<Workspace> {
self.workspaces.lock().unwrap().clone()
}
fn notify(&self, method: &str, params: impl serde::Serialize) {
let line = serde_json::to_string(&Notification::new(method, params)).expect("notifications serialize");
// No receivers is fine: nobody is listening.
let _ = self.events.send(line);
}
fn set_state(&self, id: &str, state: WorkspaceState) {
let list = {
let mut workspaces = self.workspaces.lock().unwrap();
if let Some(workspace) = workspaces.iter_mut().find(|w| w.id == id) {
workspace.state = state;
}
workspaces.clone()
};
self.notify(events::WORKSPACES, list);
}
/// Answers one request. `hello` is handled by the connection.
fn handle(self: &Arc<Self>, request: &Request) -> Result<Value, (i64, String)> {
match request.method.as_str() {
methods::STATUS => Ok(json!(StatusResult {
workspaces: self.workspaces(),
uptime_s: self.started.elapsed().as_secs(),
})),
methods::SYNC_NOW => {
let params: WorkspaceParams = serde_json::from_value(request.params.clone())
.map_err(|error| (codes::INVALID_PARAMS, error.to_string()))?;
self.start_sync(&params.workspace)?;
Ok(json!({}))
}
methods::SHUTDOWN => {
tracing::info!("shutdown requested");
self.shutdown.notify_one();
Ok(json!({}))
}
other => Err((codes::METHOD_NOT_FOUND, format!("no method {other}"))),
}
}
fn start_sync(self: &Arc<Self>, id: &str) -> Result<(), (i64, String)> {
{
let mut workspaces = self.workspaces.lock().unwrap();
let workspace = workspaces
.iter_mut()
.find(|w| w.id == id)
.ok_or_else(|| (codes::NO_SUCH_WORKSPACE, format!("no workspace {id}")))?;
if workspace.state == WorkspaceState::Syncing {
return Err((codes::BUSY, format!("{} is already syncing", workspace.name)));
}
workspace.state = WorkspaceState::Syncing;
}
self.notify(events::WORKSPACES, self.workspaces());
let service = Arc::clone(self);
let id = id.to_owned();
tokio::spawn(async move { service.simulate_sync(id).await });
Ok(())
}
async fn simulate_sync(self: Arc<Self>, id: String) {
let activity = |phase, progress, message: &str| Activity {
workspace: id.clone(),
kind: "sync".into(),
phase,
progress,
message: message.into(),
};
self.notify(events::ACTIVITY, activity(Phase::Started, Some(0.0), "connecting"));
for step in 1..=4u8 {
tokio::time::sleep(self.step).await;
let progress = f32::from(step) / 4.0;
self.notify(events::ACTIVITY, activity(Phase::Running, Some(progress), "fetching"));
}
self.notify(events::ACTIVITY, activity(Phase::Finished, Some(1.0), "up to date"));
self.set_state(&id, WorkspaceState::Idle);
}
/// Serves one frontend until it disconnects.
pub async fn serve<S>(self: Arc<Self>, stream: S)
where
S: AsyncRead + AsyncWrite + Send + 'static,
{
let (read, mut write) = tokio::io::split(stream);
let (out, mut outgoing) = mpsc::channel::<String>(64);
let writer = tokio::spawn(async move {
while let Some(mut line) = outgoing.recv().await {
line.push('\n');
if write.write_all(line.as_bytes()).await.is_err() {
break;
}
}
});
let mut reader = BufReader::new(read);
let mut greeted = false;
let mut forwarder = None;
loop {
let mut buffer = Vec::new();
let read = (&mut reader).take(MAX_LINE + 1).read_until(b'\n', &mut buffer).await;
match read {
Ok(0) | Err(_) => break,
Ok(_) if buffer.last() != Some(&b'\n') && buffer.len() as u64 > MAX_LINE => {
let _ = out.send(reply(Response::err(Value::Null, codes::INVALID_REQUEST, "message too long"))).await;
break;
}
Ok(_) => {}
}
let request: Request = match serde_json::from_slice(&buffer) {
Ok(request) => request,
Err(error) => {
let _ = out.send(reply(Response::err(Value::Null, codes::PARSE_ERROR, error.to_string()))).await;
continue;
}
};
let id = request.id.clone();
let response = if request.jsonrpc != "2.0" {
Response::err(id, codes::INVALID_REQUEST, "jsonrpc must be \"2.0\"")
} else if request.method == methods::HELLO {
match self.hello(&request) {
Ok(result) => {
if !greeted {
greeted = true;
forwarder = Some(forward_events(self.events.subscribe(), out.clone()));
}
Response::ok(id, result)
}
Err((code, message)) => Response::err(id, code, message),
}
} else if !greeted {
Response::err(id, codes::HELLO_FIRST, "send hello first")
} else {
match self.handle(&request) {
Ok(result) => Response::ok(id, result),
Err((code, message)) => Response::err(id, code, message),
}
};
if out.send(reply(response)).await.is_err() {
break;
}
}
if let Some(forwarder) = forwarder {
forwarder.abort();
}
drop(out);
let _ = writer.await;
}
fn hello(&self, request: &Request) -> Result<Value, (i64, String)> {
let params: HelloParams =
serde_json::from_value(request.params.clone()).map_err(|error| (codes::INVALID_PARAMS, error.to_string()))?;
if params.protocol != PROTOCOL_VERSION {
return Err((
codes::UNSUPPORTED_PROTOCOL,
format!("this service speaks protocol {PROTOCOL_VERSION}, not {}", params.protocol),
));
}
tracing::info!(client = %params.client, "client connected");
Ok(json!(HelloResult {
protocol: PROTOCOL_VERSION,
service: format!("forge-service {} (stub)", env!("CARGO_PKG_VERSION")),
pid: std::process::id(),
}))
}
}
fn reply(response: Response) -> String {
serde_json::to_string(&response).expect("responses serialize")
}
fn forward_events(mut events: broadcast::Receiver<String>, out: mpsc::Sender<String>) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
match events.recv().await {
Ok(line) => {
if out.send(line).await.is_err() {
break;
}
}
// A client too slow to keep up misses events; the next `workspaces` event
// or a `status` call brings it back in line.
Err(broadcast::error::RecvError::Lagged(skipped)) => {
tracing::warn!(skipped, "a client fell behind on events");
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
})
}
#[cfg(test)]
mod tests {
use tokio::io::DuplexStream;
use tokio::io::Lines;
use super::*;
use crate::config::WorkspaceConfig;
struct Client {
lines: Lines<BufReader<tokio::io::ReadHalf<DuplexStream>>>,
write: tokio::io::WriteHalf<DuplexStream>,
next_id: u64,
}
impl Client {
fn connect(service: &Arc<Service>) -> Client {
let (ours, theirs) = tokio::io::duplex(1 << 16);
tokio::spawn(Arc::clone(service).serve(theirs));
let (read, write) = tokio::io::split(ours);
Client { lines: BufReader::new(read).lines(), write, next_id: 1 }
}
async fn send(&mut self, method: &str, params: Value) -> u64 {
let id = self.next_id;
self.next_id += 1;
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string();
self.write.write_all(format!("{line}\n").as_bytes()).await.unwrap();
id
}
async fn next(&mut self) -> Value {
let line = tokio::time::timeout(Duration::from_secs(5), self.lines.next_line())
.await
.expect("a message within 5 s")
.unwrap()
.expect("the connection stays open");
serde_json::from_str(&line).unwrap()
}
/// The response to `id`, skipping notifications.
async fn response(&mut self, id: u64) -> Value {
loop {
let message = self.next().await;
if message["id"] == json!(id) {
return message;
}
}
}
async fn call(&mut self, method: &str, params: Value) -> Value {
let id = self.send(method, params).await;
self.response(id).await
}
async fn hello(&mut self) -> Value {
self.call(methods::HELLO, json!({"protocol": PROTOCOL_VERSION, "client": "test"})).await
}
}
fn service() -> Arc<Service> {
let config = Config {
workspaces: vec![WorkspaceConfig {
name: "game".into(),
path: "/w/game".into(),
remote: "lore://h/me/game".into(),
autosync: Default::default(),
}],
};
Service::new(config, Duration::from_millis(5))
}
#[tokio::test]
async fn hello_comes_first_and_checks_the_version() {
let service = service();
let mut client = Client::connect(&service);
let early = client.call(methods::STATUS, json!({})).await;
assert_eq!(early["error"]["code"], json!(codes::HELLO_FIRST));
let wrong = client.call(methods::HELLO, json!({"protocol": 999, "client": "test"})).await;
assert_eq!(wrong["error"]["code"], json!(codes::UNSUPPORTED_PROTOCOL));
let hello = client.hello().await;
assert_eq!(hello["result"]["protocol"], json!(PROTOCOL_VERSION));
let status = client.call(methods::STATUS, json!({})).await;
assert_eq!(status["result"]["workspaces"][0]["name"], "game");
assert_eq!(status["result"]["workspaces"][0]["state"], "unknown");
}
#[tokio::test]
async fn bad_lines_get_errors_and_the_connection_survives() {
let service = service();
let mut client = Client::connect(&service);
client.write.write_all(b"not json\n").await.unwrap();
assert_eq!(client.next().await["error"]["code"], json!(codes::PARSE_ERROR));
client.hello().await;
let unknown = client.call("frobnicate", json!({})).await;
assert_eq!(unknown["error"]["code"], json!(codes::METHOD_NOT_FOUND));
}
#[tokio::test]
async fn sync_now_reports_progress_to_every_client() {
let service = service();
let mut first = Client::connect(&service);
let mut second = Client::connect(&service);
first.hello().await;
second.hello().await;
let missing = first.call(methods::SYNC_NOW, json!({"workspace": "nope"})).await;
assert_eq!(missing["error"]["code"], json!(codes::NO_SUCH_WORKSPACE));
let started = first.call(methods::SYNC_NOW, json!({"workspace": "w1"})).await;
assert!(started["result"].is_object(), "{started}");
let busy = first.call(methods::SYNC_NOW, json!({"workspace": "w1"})).await;
assert_eq!(busy["error"]["code"], json!(codes::BUSY));
// The other client sees the whole run, ending idle.
let mut phases = Vec::new();
loop {
let message = second.next().await;
match message["method"].as_str() {
Some(events::ACTIVITY) => phases.push(message["params"]["phase"].as_str().unwrap().to_owned()),
Some(events::WORKSPACES) if message["params"][0]["state"] == "idle" => break,
_ => {}
}
}
assert_eq!(phases.first().map(String::as_str), Some("started"));
assert_eq!(phases.last().map(String::as_str), Some("finished"));
assert_eq!(phases.iter().filter(|phase| *phase == "running").count(), 4);
}
#[tokio::test]
async fn shutdown_wakes_the_service() {
let service = service();
let mut client = Client::connect(&service);
client.hello().await;
let stopped = tokio::spawn({
let service = Arc::clone(&service);
async move { service.stopped().await }
});
tokio::task::yield_now().await;
client.call(methods::SHUTDOWN, json!({})).await;
tokio::time::timeout(Duration::from_secs(5), stopped).await.unwrap().unwrap();
}
}

42
desktop/vendor/README.md vendored Normal file
View File

@ -0,0 +1,42 @@
# Vendored dependencies
All are unmodified copies, exported with `git archive` from the owner's UHDK repository
(`~/git/uhdk-internal`) at commit `19b892fa28e849090400f8b54985e440bc4a10c1` (2026-11-25).
| Path | What | Upstream | License | Checksums |
| --- | --- | --- | --- | --- |
| `uhdk/` | The UHDK package: windows, OpenGL, tray, menus | `uhdk/` in that repository | [MIT](uhdk/LICENSE) | [uhdk.SHA256SUMS](uhdk.SHA256SUMS) |
| `imgui/` | Dear ImGui `v1.92.9b-docking` (`b48d1af`) with its OpenGL 3 backend, as UHDK vendors it | `examples/vendor/imgui/` there; originally <https://github.com/ocornut/imgui> | [MIT](imgui/LICENSE.txt) | [imgui/SHA256SUMS](imgui/SHA256SUMS) (upstream's) |
| `fonts/` | IBM VGA 8x16 (`AcPlus_IBM_VGA_8x16.ttf`), the GUI's font, from The Ultimate Oldschool PC Font Pack v2.2 by VileR | `examples/vendor/` there; originally <https://int10h.org/oldschool-pc-fonts/> | [CC BY-SA 4.0](fonts/oldschool-pc-fonts-LICENSE.txt) | below |
| `fonts/` file | SHA-256 at import |
| --- | --- |
| `AcPlus_IBM_VGA_8x16.ttf` | `57f71fe16b57b5bd24c4f49c3414b99d7f3a2481f77096ef1d491f916ce429a6` |
| `oldschool-pc-fonts-LICENSE.txt` | `f50b4b5c45aa4096cd341b58b9390439fc5c27ea015262d381ad0c9d57a158de` |
The font is compiled into `forge-desktop` (`gui/src/embedded.cpp`), so its licence travels
with the binary: `forge-desktop --licenses` prints it with the MIT notices of Dear ImGui, UHDK
and glad.
`../gui/uhdk_imgui/` holds UHDK's example ImGui platform backend (`examples/imgui_impl_uhdk.*`
and `examples/UhdkPayload.hpp` from the same commit, MIT). It lives with the GUI because it is
example code that we may adapt; record any change there.
| File | SHA-256 at import |
| --- | --- |
| `imgui_impl_uhdk.h` | `d93be8056c2759bcd2242776c20cd19b3a7fe5545aa1e9ebccee55ca73b7445a` |
| `imgui_impl_uhdk.cpp` | `3ba5041fad5189a2422d22318516e0c92fcff7a2e183472dd10894c615d9e001` |
| `UhdkPayload.hpp` | `83864a4c00a338ddc87b9836b523d5032be71c41d65b1fc41c9e2a05fcfdeaf6` |
## Updating
Export the new commit the same way, replacing the directory whole, and regenerate the
checksums:
```sh
git -C ~/git/uhdk-internal archive <commit> uhdk | tar -x --strip-components=1 -C desktop/vendor/uhdk
(cd desktop/vendor/uhdk && find . -type f -print0 | sort -z | xargs -0 shasum -a 256 > ../uhdk.SHA256SUMS)
```
Then update the commit above. UHDK is unreleased, so read its changes to the public header
`include/uhdk.h` before updating.

Binary file not shown.

View File

@ -0,0 +1,14 @@
AcPlus_IBM_VGA_8x16.ttf
AcPlus_IBM_VGA_8x16-2x.ttf
The Ultimate Oldschool PC Font Pack v2.2
Font adaptation by VileR.
Original material: https://int10h.org/oldschool-pc-fonts/
Font file included unmodified.
Licensed under Creative Commons Attribution-ShareAlike 4.0 International:
https://creativecommons.org/licenses/by-sa/4.0/
Full license terms: https://creativecommons.org/licenses/by-sa/4.0/legalcode
Upstream attribution and licensing statement:
https://int10h.org/oldschool-pc-fonts/readme/#legal_stuff

21
desktop/vendor/imgui/LICENSE.txt vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2026 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

15
desktop/vendor/imgui/SHA256SUMS vendored Normal file
View File

@ -0,0 +1,15 @@
ed9911193dcbe641830ad1052e3f69e87182f876b1133484e69b082506da9a9c imgui.h
5755e1b8d6ab0d7811a9d7cac0f509878b51fc5ee77e09bd0f235bcb414971e7 imconfig.h
0e94755a322e1e4c0b09e1f86e29a08ea121c99cbd71e4785ed22173665086b2 imgui_internal.h
889b396795202d1457560a797a7242e96f6f132d4b88ca2d69be58bf05e1771f imstb_rectpack.h
a985f5fa0ed97353d493b497961e9eef52082edcd045cf6954b69990ec9d0741 imstb_textedit.h
c51a0f7e7ea760f2366bd3752635ec58e21fccfec4a832501639990ba6ce0528 imstb_truetype.h
304fe9be60830936a6ca1472b1a09e2af62ebff7c9a80bbcd029ff5982b26a6e imgui.cpp
e8d6cee660dabcd50f94068834bdf87515d42fa7b52767ab5d4d13c1adf36037 imgui_draw.cpp
b5deabe5b569ab712c11b6556562a646bf88327320fc60a451071b2a36498d72 imgui_tables.cpp
1e7107ad89073b4feaf65fff383e7e2a0244a2bf0063782c44640a6080ad63d0 imgui_widgets.cpp
c093be753239c3b9f5a01fbca36dd96dce22f9e62af98f340d431926bdbaad22 imgui_demo.cpp
173506a2d6f7fb67990d257fb2507f188690eca39060c39469ae7bef43aae2a3 LICENSE.txt
0c2c3d0e96343fdc1e209c85698368d0664dcf922e9d61b899f791f21fe14985 backends/imgui_impl_opengl3.cpp
f2d77843bd2d067a20c9915d15cec305d5510e4bfee0df0cd474a51278516a14 backends/imgui_impl_opengl3.h
d3aa3e1f3d23c8c88817832e17d8dd0f2d0b599ae28430067c3fad563b8b7cd5 backends/imgui_impl_opengl3_loader.h

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,82 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
// About WebGL/ES:
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
// - This is done automatically on iOS, Android and Emscripten targets.
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// About GLSL version:
// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually.
IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex);
// Configuration flags to add in your imconfig file:
//#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten)
//#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android)
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#else
// Otherwise imgui_impl_opengl3_loader.h will be used.
#endif
#endif
// [BETA] Selected render state data shared with callbacks.
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplOpenGL3_RenderDrawData() call.
// (Please open an issue if you feel you need access to more data)
struct ImGui_ImplOpenGL3_RenderState
{
bool UseBindSampler;
bool UseTexParameterFilter;
unsigned int CurrentSampler; // (GLuint) Used if UseBindSampler == true, otherwise always 0
unsigned int CurrentTexParameterFilter; // (GLuint) Used if UseTexParameterToSetSampler == true
};
static inline ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState() { return (ImGui_ImplOpenGL3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; }
#endif // #ifndef IMGUI_DISABLE

View File

@ -0,0 +1,958 @@
//-----------------------------------------------------------------------------
// About imgui_impl_opengl3_loader.h:
//
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
// which proved to be endless problems for users.
// Our loader is custom-generated, based on gl3w but automatically filtered to only include
// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
//
// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
//
// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h'
// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp
// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
//
// Regenerate with:
// python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
//
// More info:
// https://github.com/dearimgui/gl3w_stripped
// https://github.com/ocornut/imgui/issues/4445
//-----------------------------------------------------------------------------
/*
* This file was generated with gl3w_gen.py, part of imgl3w
* (hosted at https://github.com/dearimgui/gl3w_stripped)
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __gl3w_h_
#define __gl3w_h_
// Adapted from KHR/khrplatform.h to avoid including entire file.
#ifndef __khrplatform_h_
typedef float khronos_float_t;
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef signed long long int khronos_ssize_t;
#else
typedef signed long int khronos_intptr_t;
typedef signed long int khronos_ssize_t;
#endif
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#else
typedef signed long long khronos_int64_t;
typedef unsigned long long khronos_uint64_t;
#endif
#endif // __khrplatform_h_
#ifndef __gl_glcorearb_h_
#define __gl_glcorearb_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: MIT
**
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** https://github.com/KhronosGroup/OpenGL-Registry
*/
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
/* glcorearb.h is for use with OpenGL core profile implementations.
** It should should be placed in the same directory as gl.h and
** included as <GL/glcorearb.h>.
**
** glcorearb.h includes only APIs in the latest OpenGL core profile
** implementation together with APIs in newer ARB extensions which
** can be supported by the core profile. It does not, and never will
** include functionality removed from the core profile, such as
** fixed-function vertex and fragment processing.
**
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
** <GL/glext.h> in the same source file.
*/
/* Generated C header for:
* API: gl
* Profile: core
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: glcore
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef GL_VERSION_1_0
typedef void GLvoid;
typedef unsigned int GLenum;
typedef khronos_float_t GLfloat;
typedef int GLint;
typedef int GLsizei;
typedef unsigned int GLbitfield;
typedef double GLdouble;
typedef unsigned int GLuint;
typedef unsigned char GLboolean;
typedef khronos_uint8_t GLubyte;
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_FALSE 0
#define GL_TRUE 1
#define GL_TRIANGLES 0x0004
#define GL_ONE 1
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_FRONT_AND_BACK 0x0408
#define GL_POLYGON_MODE 0x0B40
#define GL_CULL_FACE 0x0B44
#define GL_DEPTH_TEST 0x0B71
#define GL_STENCIL_TEST 0x0B90
#define GL_VIEWPORT 0x0BA2
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_BOX 0x0C10
#define GL_SCISSOR_TEST 0x0C11
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_MAX_TEXTURE_SIZE 0x0D33
#define GL_TEXTURE_2D 0x0DE1
#define GL_UNSIGNED_BYTE 0x1401
#define GL_UNSIGNED_SHORT 0x1403
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_RGBA 0x1908
#define GL_FILL 0x1B02
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
#define GL_REPEAT 0x2901
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
GLAPI void APIENTRY glClear (GLbitfield mask);
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLAPI void APIENTRY glDisable (GLenum cap);
GLAPI void APIENTRY glEnable (GLenum cap);
GLAPI void APIENTRY glFlush (void);
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
GLAPI GLenum APIENTRY glGetError (void);
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#endif
#endif /* GL_VERSION_1_0 */
#ifndef GL_VERSION_1_1
typedef khronos_float_t GLclampf;
typedef double GLclampd;
#define GL_TEXTURE_BINDING_2D 0x8069
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
GLAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
#endif
#endif /* GL_VERSION_1_1 */
#ifndef GL_VERSION_1_2
#define GL_CLAMP_TO_EDGE 0x812F
#endif /* GL_VERSION_1_2 */
#ifndef GL_VERSION_1_3
#define GL_TEXTURE0 0x84C0
#define GL_ACTIVE_TEXTURE 0x84E0
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glActiveTexture (GLenum texture);
#endif
#endif /* GL_VERSION_1_3 */
#ifndef GL_VERSION_1_4
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_FUNC_ADD 0x8006
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
GLAPI void APIENTRY glBlendEquation (GLenum mode);
#endif
#endif /* GL_VERSION_1_4 */
#ifndef GL_VERSION_1_5
typedef khronos_ssize_t GLsizeiptr;
typedef khronos_intptr_t GLintptr;
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#endif
#endif /* GL_VERSION_1_5 */
#ifndef GL_VERSION_2_0
typedef char GLchar;
typedef khronos_int16_t GLshort;
typedef khronos_int8_t GLbyte;
typedef khronos_uint16_t GLushort;
#define GL_BLEND_EQUATION_RGB 0x8009
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_BLEND_EQUATION_ALPHA 0x883D
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_CURRENT_PROGRAM 0x8B8D
#define GL_UPPER_LEFT 0x8CA2
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glCompileShader (GLuint shader);
GLAPI GLuint APIENTRY glCreateProgram (void);
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
GLAPI void APIENTRY glDeleteProgram (GLuint program);
GLAPI void APIENTRY glDeleteShader (GLuint shader);
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
GLAPI void APIENTRY glLinkProgram (GLuint program);
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
GLAPI void APIENTRY glUseProgram (GLuint program);
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#endif
#endif /* GL_VERSION_2_0 */
#ifndef GL_VERSION_2_1
#define GL_PIXEL_UNPACK_BUFFER 0x88EC
#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
#endif /* GL_VERSION_2_1 */
#ifndef GL_VERSION_3_0
typedef khronos_uint16_t GLhalf;
#define GL_MAJOR_VERSION 0x821B
#define GL_MINOR_VERSION 0x821C
#define GL_NUM_EXTENSIONS 0x821D
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#define GL_VERTEX_ARRAY_BINDING 0x85B5
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
GLAPI void APIENTRY glBindVertexArray (GLuint array);
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
#endif
#endif /* GL_VERSION_3_0 */
#ifndef GL_VERSION_3_1
#define GL_VERSION_3_1 1
#define GL_PRIMITIVE_RESTART 0x8F9D
#endif /* GL_VERSION_3_1 */
#ifndef GL_VERSION_3_2
#define GL_VERSION_3_2 1
typedef struct __GLsync *GLsync;
typedef khronos_uint64_t GLuint64;
typedef khronos_int64_t GLint64;
#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
#define GL_CONTEXT_PROFILE_MASK 0x9126
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
#endif
#endif /* GL_VERSION_3_2 */
#ifndef GL_VERSION_3_3
#define GL_VERSION_3_3 1
#define GL_SAMPLER_BINDING 0x8919
typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers);
typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers);
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers);
GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers);
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param);
#endif
#endif /* GL_VERSION_3_3 */
#ifndef GL_VERSION_4_1
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
#endif /* GL_VERSION_4_1 */
#ifndef GL_VERSION_4_3
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_VERSION_4_3 */
#ifndef GL_VERSION_4_5
#define GL_CLIP_ORIGIN 0x935C
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
#endif /* GL_VERSION_4_5 */
#ifndef GL_ARB_bindless_texture
typedef khronos_uint64_t GLuint64EXT;
#endif /* GL_ARB_bindless_texture */
#ifndef GL_ARB_cl_event
struct _cl_context;
struct _cl_event;
#endif /* GL_ARB_cl_event */
#ifndef GL_ARB_clip_control
#define GL_ARB_clip_control 1
#endif /* GL_ARB_clip_control */
#ifndef GL_ARB_debug_output
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_ARB_debug_output */
#ifndef GL_EXT_EGL_image_storage
typedef void *GLeglImageOES;
#endif /* GL_EXT_EGL_image_storage */
#ifndef GL_EXT_direct_state_access
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
#endif /* GL_EXT_direct_state_access */
#ifndef GL_NV_draw_vulkan_image
typedef void (APIENTRY *GLVULKANPROCNV)(void);
#endif /* GL_NV_draw_vulkan_image */
#ifndef GL_NV_gpu_shader5
typedef khronos_int64_t GLint64EXT;
#endif /* GL_NV_gpu_shader5 */
#ifndef GL_NV_vertex_buffer_unified_memory
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
#endif /* GL_NV_vertex_buffer_unified_memory */
#ifdef __cplusplus
}
#endif
#endif
#ifndef GL3W_API
#define GL3W_API
#endif
#ifndef __gl_h_
#define __gl_h_
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define GL3W_OK 0
#define GL3W_ERROR_INIT -1
#define GL3W_ERROR_LIBRARY_OPEN -2
#define GL3W_ERROR_OPENGL_VERSION -3
typedef void (*GL3WglProc)(void);
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
/* gl3w api */
GL3W_API int imgl3wInit(void);
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
GL3W_API void imgl3wShutdown(void);
GL3W_API int imgl3wIsSupported(int major, int minor);
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
/* gl3w internal state */
union ImGL3WProcs {
GL3WglProc ptr[63];
struct {
PFNGLACTIVETEXTUREPROC ActiveTexture;
PFNGLATTACHSHADERPROC AttachShader;
PFNGLBINDBUFFERPROC BindBuffer;
PFNGLBINDSAMPLERPROC BindSampler;
PFNGLBINDTEXTUREPROC BindTexture;
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
PFNGLBLENDEQUATIONPROC BlendEquation;
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
PFNGLBUFFERDATAPROC BufferData;
PFNGLBUFFERSUBDATAPROC BufferSubData;
PFNGLCLEARPROC Clear;
PFNGLCLEARCOLORPROC ClearColor;
PFNGLCOMPILESHADERPROC CompileShader;
PFNGLCREATEPROGRAMPROC CreateProgram;
PFNGLCREATESHADERPROC CreateShader;
PFNGLDELETEBUFFERSPROC DeleteBuffers;
PFNGLDELETEPROGRAMPROC DeleteProgram;
PFNGLDELETESAMPLERSPROC DeleteSamplers;
PFNGLDELETESHADERPROC DeleteShader;
PFNGLDELETETEXTURESPROC DeleteTextures;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
PFNGLDETACHSHADERPROC DetachShader;
PFNGLDISABLEPROC Disable;
PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
PFNGLDRAWELEMENTSPROC DrawElements;
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
PFNGLENABLEPROC Enable;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
PFNGLFLUSHPROC Flush;
PFNGLGENBUFFERSPROC GenBuffers;
PFNGLGENSAMPLERSPROC GenSamplers;
PFNGLGENTEXTURESPROC GenTextures;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
PFNGLGETERRORPROC GetError;
PFNGLGETINTEGERVPROC GetIntegerv;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
PFNGLGETPROGRAMIVPROC GetProgramiv;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
PFNGLGETSHADERIVPROC GetShaderiv;
PFNGLGETSTRINGPROC GetString;
PFNGLGETSTRINGIPROC GetStringi;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
PFNGLISENABLEDPROC IsEnabled;
PFNGLISPROGRAMPROC IsProgram;
PFNGLLINKPROGRAMPROC LinkProgram;
PFNGLPIXELSTOREIPROC PixelStorei;
PFNGLPOLYGONMODEPROC PolygonMode;
PFNGLREADPIXELSPROC ReadPixels;
PFNGLSAMPLERPARAMETERIPROC SamplerParameteri;
PFNGLSCISSORPROC Scissor;
PFNGLSHADERSOURCEPROC ShaderSource;
PFNGLTEXIMAGE2DPROC TexImage2D;
PFNGLTEXPARAMETERIPROC TexParameteri;
PFNGLTEXSUBIMAGE2DPROC TexSubImage2D;
PFNGLUNIFORM1IPROC Uniform1i;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
PFNGLUSEPROGRAMPROC UseProgram;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
PFNGLVIEWPORTPROC Viewport;
} gl;
};
GL3W_API extern union ImGL3WProcs imgl3wProcs;
/* OpenGL functions */
#define glActiveTexture imgl3wProcs.gl.ActiveTexture
#define glAttachShader imgl3wProcs.gl.AttachShader
#define glBindBuffer imgl3wProcs.gl.BindBuffer
#define glBindSampler imgl3wProcs.gl.BindSampler
#define glBindTexture imgl3wProcs.gl.BindTexture
#define glBindVertexArray imgl3wProcs.gl.BindVertexArray
#define glBlendEquation imgl3wProcs.gl.BlendEquation
#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
#define glBufferData imgl3wProcs.gl.BufferData
#define glBufferSubData imgl3wProcs.gl.BufferSubData
#define glClear imgl3wProcs.gl.Clear
#define glClearColor imgl3wProcs.gl.ClearColor
#define glCompileShader imgl3wProcs.gl.CompileShader
#define glCreateProgram imgl3wProcs.gl.CreateProgram
#define glCreateShader imgl3wProcs.gl.CreateShader
#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
#define glDeleteProgram imgl3wProcs.gl.DeleteProgram
#define glDeleteSamplers imgl3wProcs.gl.DeleteSamplers
#define glDeleteShader imgl3wProcs.gl.DeleteShader
#define glDeleteTextures imgl3wProcs.gl.DeleteTextures
#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
#define glDetachShader imgl3wProcs.gl.DetachShader
#define glDisable imgl3wProcs.gl.Disable
#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
#define glDrawElements imgl3wProcs.gl.DrawElements
#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
#define glEnable imgl3wProcs.gl.Enable
#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
#define glFlush imgl3wProcs.gl.Flush
#define glGenBuffers imgl3wProcs.gl.GenBuffers
#define glGenSamplers imgl3wProcs.gl.GenSamplers
#define glGenTextures imgl3wProcs.gl.GenTextures
#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
#define glGetError imgl3wProcs.gl.GetError
#define glGetIntegerv imgl3wProcs.gl.GetIntegerv
#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
#define glGetProgramiv imgl3wProcs.gl.GetProgramiv
#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
#define glGetShaderiv imgl3wProcs.gl.GetShaderiv
#define glGetString imgl3wProcs.gl.GetString
#define glGetStringi imgl3wProcs.gl.GetStringi
#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
#define glIsEnabled imgl3wProcs.gl.IsEnabled
#define glIsProgram imgl3wProcs.gl.IsProgram
#define glLinkProgram imgl3wProcs.gl.LinkProgram
#define glPixelStorei imgl3wProcs.gl.PixelStorei
#define glPolygonMode imgl3wProcs.gl.PolygonMode
#define glReadPixels imgl3wProcs.gl.ReadPixels
#define glSamplerParameteri imgl3wProcs.gl.SamplerParameteri
#define glScissor imgl3wProcs.gl.Scissor
#define glShaderSource imgl3wProcs.gl.ShaderSource
#define glTexImage2D imgl3wProcs.gl.TexImage2D
#define glTexParameteri imgl3wProcs.gl.TexParameteri
#define glTexSubImage2D imgl3wProcs.gl.TexSubImage2D
#define glUniform1i imgl3wProcs.gl.Uniform1i
#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
#define glUseProgram imgl3wProcs.gl.UseProgram
#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
#define glViewport imgl3wProcs.gl.Viewport
#ifdef __cplusplus
}
#endif
#endif
#ifdef IMGL3W_IMPL
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
static HMODULE libgl = NULL;
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
static GL3WglGetProcAddr wgl_get_proc_address;
static int open_libgl(void)
{
libgl = LoadLibraryA("opengl32.dll");
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
return GL3W_OK;
}
static void close_libgl(void) { FreeLibrary(libgl); libgl = NULL; }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = (GL3WglProc)wgl_get_proc_address(proc);
if (!res)
res = (GL3WglProc)GetProcAddress(libgl, proc);
return res;
}
#elif defined(__APPLE__)
#include <dlfcn.h>
static void *libgl = NULL;
static int open_libgl(void)
{
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); libgl = NULL; }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#else
#include <dlfcn.h>
static void* libgl; // OpenGL library
static void* libglx; // GLX library
static void* libegl; // EGL library
static GL3WGetProcAddressProc gl_get_proc_address;
static void close_libgl(void)
{
if (libgl) {
dlclose(libgl);
libgl = NULL;
}
if (libegl) {
dlclose(libegl);
libegl = NULL;
}
if (libglx) {
dlclose(libglx);
libglx = NULL;
}
}
static int is_library_loaded(const char* name, void** lib)
{
#if defined(__HAIKU__)
*lib = NULL; // no support for RTLD_NOLOAD on Haiku.
#else
*lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
#endif
return *lib != NULL;
}
static int open_libs(void)
{
// On Linux we have two APIs to get process addresses: EGL and GLX.
// EGL is supported under both X11 and Wayland, whereas GLX is X11-specific.
libgl = NULL;
libegl = NULL;
libglx = NULL;
// First check what's already loaded, the windowing library might have
// already loaded either EGL or GLX and we want to use the same one.
if (is_library_loaded("libEGL.so.1", &libegl) ||
is_library_loaded("libGLX.so.0", &libglx)) {
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
if (libgl)
return GL3W_OK;
else
close_libgl();
}
if (is_library_loaded("libGL.so", &libgl))
return GL3W_OK;
if (is_library_loaded("libGL.so.1", &libgl))
return GL3W_OK;
if (is_library_loaded("libGL.so.3", &libgl))
return GL3W_OK;
// Neither is already loaded, so we have to load one. Try EGL first
// because it is supported under both X11 and Wayland.
// Load OpenGL + EGL
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (libgl && libegl)
return GL3W_OK;
else
close_libgl();
// Fall back to legacy libGL, which includes GLX
// While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983
libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL);
if (libgl)
return GL3W_OK;
return GL3W_ERROR_LIBRARY_OPEN;
}
static int open_libgl(void)
{
int res = open_libs();
if (res)
return res;
if (libegl)
*(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress");
else if (libglx)
*(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB");
else
*(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
if (!gl_get_proc_address) {
close_libgl();
return GL3W_ERROR_LIBRARY_OPEN;
}
return GL3W_OK;
}
static GL3WglProc get_proc(const char* proc)
{
GL3WglProc res = NULL;
// Before EGL version 1.5, eglGetProcAddress doesn't support querying core
// functions and may return a dummy function if we try, so try to load the
// function from the GL library directly first.
if (libegl)
*(void**)(&res) = dlsym(libgl, proc);
if (!res)
res = gl_get_proc_address(proc);
if (!libegl && !res)
*(void**)(&res) = dlsym(libgl, proc);
return res;
}
#endif
static struct { int major, minor; } version;
static int parse_version(void)
{
if (!glGetIntegerv)
return GL3W_ERROR_INIT;
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
if (version.major == 0 && version.minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
if (const char* gl_version = (const char*)glGetString(GL_VERSION))
sscanf(gl_version, "%d.%d", &version.major, &version.minor);
}
if (version.major < 2)
return GL3W_ERROR_OPENGL_VERSION;
return GL3W_OK;
}
static void load_procs(GL3WGetProcAddressProc proc);
static void clear_procs();
int imgl3wInit(void)
{
int res = open_libgl();
if (res)
return res;
atexit(close_libgl);
return imgl3wInit2(get_proc);
}
int imgl3wInit2(GL3WGetProcAddressProc proc)
{
load_procs(proc);
return parse_version();
}
void imgl3wShutdown(void)
{
close_libgl();
clear_procs();
}
int imgl3wIsSupported(int major, int minor)
{
if (major < 2)
return 0;
if (version.major == major)
return version.minor >= minor;
return version.major >= major;
}
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
static const char *proc_names[] = {
"glActiveTexture",
"glAttachShader",
"glBindBuffer",
"glBindSampler",
"glBindTexture",
"glBindVertexArray",
"glBlendEquation",
"glBlendEquationSeparate",
"glBlendFuncSeparate",
"glBufferData",
"glBufferSubData",
"glClear",
"glClearColor",
"glCompileShader",
"glCreateProgram",
"glCreateShader",
"glDeleteBuffers",
"glDeleteProgram",
"glDeleteSamplers",
"glDeleteShader",
"glDeleteTextures",
"glDeleteVertexArrays",
"glDetachShader",
"glDisable",
"glDisableVertexAttribArray",
"glDrawElements",
"glDrawElementsBaseVertex",
"glEnable",
"glEnableVertexAttribArray",
"glFlush",
"glGenBuffers",
"glGenSamplers",
"glGenTextures",
"glGenVertexArrays",
"glGetAttribLocation",
"glGetError",
"glGetIntegerv",
"glGetProgramInfoLog",
"glGetProgramiv",
"glGetShaderInfoLog",
"glGetShaderiv",
"glGetString",
"glGetStringi",
"glGetUniformLocation",
"glGetVertexAttribPointerv",
"glGetVertexAttribiv",
"glIsEnabled",
"glIsProgram",
"glLinkProgram",
"glPixelStorei",
"glPolygonMode",
"glReadPixels",
"glSamplerParameteri",
"glScissor",
"glShaderSource",
"glTexImage2D",
"glTexParameteri",
"glTexSubImage2D",
"glUniform1i",
"glUniformMatrix4fv",
"glUseProgram",
"glVertexAttribPointer",
"glViewport",
};
GL3W_API union ImGL3WProcs imgl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc)
{
size_t i;
for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = proc(proc_names[i]);
}
static void clear_procs()
{
size_t i;
for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = nullptr;
}
#ifdef __cplusplus
}
#endif
#endif

150
desktop/vendor/imgui/imconfig.h vendored Normal file
View File

@ -0,0 +1,150 @@
//-----------------------------------------------------------------------------
// DEAR IMGUI COMPILE-TIME OPTIONS
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// - If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
// - Compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export
//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import
//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_TIME_FUNCTIONS // Don't setup default platform_io.Platform_SessionDate value using time(), localtime_r().
//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded fonts (ProggyClean + ProggyForever). Remove ~9 KB + ~14 KB from output binary. AddFontDefaultXXX() functions will assert.
//#define IMGUI_DISABLE_DEFAULT_FONT_BITMAP // Disable default embedded bitmap font (ProggyClean). Remove ~9 KB from output binary. AddFontDefaultBitmap() will assert.
//#define IMGUI_DISABLE_DEFAULT_FONT_VECTOR // Disable default embedded vector font (ProggyForever), Remove ~14 KB from output binary. AddFontDefaultVector() will assert.
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Enable Test Engine / Automation features.
//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_imconfig.h", see Test Engine for details.
//---- Include imgui_user.h at the end of imgui.h as a convenience
// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included.
//#define IMGUI_INCLUDE_IMGUI_USER_H
//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate.
//#define IMGUI_USE_LEGACY_CRC32_ADLER
//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
//#define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// Note that imgui_freetype.cpp may be used _without_ this define, if you manually call ImFontAtlas::SetFontLoader(). The define is simply a convenience.
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT)
// Only works in combination with IMGUI_ENABLE_FREETYPE.
// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions.
// - Both require headers to be available in the include path + program to be linked with the library code (not provided).
// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG
//#define IMGUI_ENABLE_FREETYPE_LUNASVG
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- ...Or use Dear ImGui's own very basic math operators.
//#define IMGUI_DEFINE_MATH_OPERATORS
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Enable highlight ID conflicts _before_ hovering items. When io.ConfigDebugHighlightIdConflicts is set.
// (THIS WILL SLOW DOWN DEAR IMGUI. Only use occasionally and disable after use)
//#define IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
/*
namespace ImGui
{
void MyFunction(const char* name, MyMatrix44* mtx);
}
*/

24610
desktop/vendor/imgui/imgui.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

4575
desktop/vendor/imgui/imgui.h vendored Normal file

File diff suppressed because it is too large Load Diff

11642
desktop/vendor/imgui/imgui_demo.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

6826
desktop/vendor/imgui/imgui_draw.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

4416
desktop/vendor/imgui/imgui_internal.h vendored Normal file

File diff suppressed because it is too large Load Diff

4905
desktop/vendor/imgui/imgui_tables.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

11166
desktop/vendor/imgui/imgui_widgets.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

627
desktop/vendor/imgui/imstb_rectpack.h vendored Normal file
View File

@ -0,0 +1,627 @@
// [DEAR IMGUI]
// This is a slightly modified version of stb_rect_pack.h 1.01.
// Grep for [DEAR IMGUI] to find the changes.
//
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1<<30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visited
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height <= c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stitched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/

1527
desktop/vendor/imgui/imstb_textedit.h vendored Normal file

File diff suppressed because it is too large Load Diff

5085
desktop/vendor/imgui/imstb_truetype.h vendored Normal file

File diff suppressed because it is too large Load Diff

167
desktop/vendor/uhdk.SHA256SUMS vendored Normal file
View File

@ -0,0 +1,167 @@
12ca407ca0442f927b1091ba91b2e2330a3fb900b1069e12f4ee53bb0b03a5db ./.gitignore
0423ea3ad3fefb5bf24274a2ea022306f210de563240a6a419203b4d15600bda ./LICENSE
10b603958e535977e2b0ea4d51d33870bc891e4f140772e2c5f98c8a34bf741d ./README.md
2bcdce7b3610d300445971eb2f5e3c9593d931ff63ad8f34a7e347d09d63b5b2 ./build.zig
919cc0e66c7c030a9cfaadd99c80c12929bd257fd14881fcbda4aead7c85615e ./build.zig.zon
65fae555a8b3b5709099837001e0c14228b3e45651e2d0fa2ad22649833921e1 ./include/GL/glcorearb.h
7b1e01aaa7ad8f6fc34b5c7bdf79ebf5189bb09e2c4d2e79fc5d350623d11e83 ./include/KHR/khrplatform.h
5e159b13676fd6fd2167cb0f1ee148d865972be731a8dd168020ddce8a784a6c ./include/OPENGL-SOURCES.md
cbb325cd4ac5bd06717ffa34a322b984f9d285e4c67c8ca1b7380d6ef08c2a77 ./include/glad/LICENSE
0dfcb12549b10a4c08372e99dd96c4a3b773ff8d89aec07ef878c8e1ca852456 ./include/glad/gl.h
ba266cab7de269f05f5125f5f1ccc55ae2055bfa72b1fa3585f27bdd89bc4143 ./include/uhdk.h
c86f15db85c8a5c61f42cb6dc10a1da5398fa340c8bbbff3caff38b1341fdad8 ./shell.nix
7e8aa9e45681c0a9e9a39e2fcccfd16b0f3031e7f473235d2664de567ce9f7b3 ./src/Application.zig
a3fef23498e907650d3f7ee841a7f8df8405e9339a95f29cc652af99134d630d ./src/Cycles.zig
a8db9cd4bac95d3cafb94767e37448589233fb82d8df6e04ed8d1c8095412902 ./src/Event.zig
9710fd4f31ef6e97b21339a683477d12f659da080230998d57513fe55c0181ba ./src/EventPayload.zig
c777d4341eb811315e2942ebaa199b303895bc0cc9215778b8beec0dc4207e0e ./src/FileOperation.zig
6303d0d6367adbd822083fe055edaff63f7ee533ef2e3e942a9719ab4c7b2d8b ./src/MinimalIo.zig
6698f12d6f3bb830bc995d39aeeb809c1f185b73e8a9091a49b0abe745d5c5bd ./src/Profile.zig
dbeb5341d50f1d153dd1a2189b99796d78a426d11d1d7195cc19690d34b860f4 ./src/Request.zig
d9a6165a6cc23ad7a2506b4a22fe4a7085de29a13804553d7a081c77010a813f ./src/Resource.zig
f4c2af5c4ff0396242bb1c01ebdc9fb681f2c864a8ed273ac718755d6aca9b7d ./src/abi.zig
2f4aac22b2c2fd7eba2b26e88c360265da130021dc99ca39781a4da7283840f5 ./src/api/app.zig
663d44a2bae081022beb7a11f092b461cf32cd64fe57fdec82379112995e99ca ./src/api/desktop.zig
cee9327419b57080d0285974e5364af3159f5b34d5efd9cd0fc52ab3974157d3 ./src/api/files.zig
eee8439d7837a526be1cc7dd974e9c5a9dbad1eb27c5739922a1ed21663788a6 ./src/api/graphics.zig
ae8b84aae056374c517f3b9b0554912d3a252adb495a77d804fc0e793a1a1e07 ./src/api/input.zig
73dcc77bfa8e782aafbc8d5296efe1b436b6c97623a3ae517d990da8659c2798 ./src/api/menus.zig
75f27a3095c37cb8b8c699d19e8dfb5e86fd32534598d350f741ed5a5325224f ./src/api/session.zig
8cbdb98a760c8e6c66694a5d445a42d1176e81b0820e8ea98696821df4238116 ./src/api/tray.zig
11895bcdbd454319b67706e93a8cbe2fea63984615909229e1f3976cbaaf8fa5 ./src/api/windows.zig
75a0599280479f30d5b42d11f87b9232eb6e0b527c0b3951ed7c63ac657ae4d9 ./src/arenas.zig
093e73bdaf18f1d8bbbed4ecb24c344e2e263245dc58b0561938d934f743cb04 ./src/callbacks.zig
d1b925c677b684b6785327c14083d2b20d8339560c41aa9a280558a4a4c7010b ./src/core_tests.zig
8b1c43437146eeb077b94a507ba778a20938a770f487f3dc26d91b32b2de8eab ./src/edit_keys.h
6ee307a83d30a1dfa1344b263a50b69f5d07a0a1e602f3001a26e25664ac684e ./src/function_keys.h
a6d167fcca30fb926e3883e6a56a74ea65fe7acd043da714dba064c21710f0d7 ./src/gl_loader.c
90b038d9634d18788aa55969bc3280b24cbfe4b2141aae365f57137432bc9a9d ./src/linux/Bitmap.zig
184ffccdde394c37e7d4a8b7494b1d8fd7c0c35f1bc67c7742d78e0dff746989 ./src/linux/Bus.zig
e2148e69a52af48ac4251cfaac10781170e452dc64021c139c780c333585975e ./src/linux/Data.zig
f5af2a0afd025cd861b60742ba8e0d02aa3597c71a9a594ff7788a5a5bac5d24 ./src/linux/Desktop.zig
2fc1fefe9e3ea8a67547d64d9f132ccf15c7e1cdc13698f20f5a52b7515da2e5 ./src/linux/Egl.zig
338ecf62153db40c4bfa31d0044a4217f5783a4347fdf61fac86bd4d1806a083 ./src/linux/Files.zig
82ee131ad3da64f2fa3688de0fea368b00922aebed95beaf2741b6f7b87b703a ./src/linux/Input.zig
80bdf7e80106b428c517ca282c75d6e578f4af709ec882612def651822b6f68d ./src/linux/KdeAppMenu.zig
189bf882d9bf1d36c3e5c8bf13b71654e2255c29b0dda378b1397dd85d1f7928 ./src/linux/Keyboard.zig
3a7dd709a3b36ea85948f381cccf2f27292d8e032f75f00fa13f015649a055a3 ./src/linux/Menu.zig
6437203c2e21d0a505a42c73785f42b7b717e18cf25b2e2f9fc4368b88009113 ./src/linux/Popup.zig
78f96e134beeb3f35d1af09cdc578063a80ca83989706a528d11dc510954638a ./src/linux/Portal.zig
11e975831e492606d19065b75aef9d81aa104b8d66b9bc43efadfe4804daa014 ./src/linux/README.md
1fe07d74fa3e4e6969061bfd7b9edb27c9d1a948c65d7240a8dbdfc1eb758d34 ./src/linux/Text.zig
25bd50577103a1f8862d292e74d8e0ff2156cc69d486616bbcc035bd222e0732 ./src/linux/Tray.zig
f286d83649aa688423a097579458e15dbd34e8c89570e3d39cd4b471fe2d8f62 ./src/linux/Watch.zig
a1b63844cbdb089d6dfde564d3bac632582da42bb90e531b4c8c9d32a148c0e7 ./src/linux/WindowState.zig
c0bb83660a5a3faa4c69c1e4ad0b68ffdcbadda6814b64c305dfcba216015368 ./src/linux/bindings.h
6203e8a7af880b9cb18ffdb0344e616166879b29d138f89a29b201c9b9b473d9 ./src/linux/build.zig
91649b5df2dc3ae489927c51ea9f213c886522a4382cc56b3f3f857366a6d821 ./src/linux/dbus-imports.h
6256fd2283b520506c29aabf5019c978d371c7ec5ad92107a71fba4ddcaae6eb ./src/linux/dbusmenu.xml
bf2042bd6fa09aef4128165bc3f9b22bccc07a7cea57db6d55838200a48c3e31 ./src/linux/exports.map
061402327a96aadb0bfb694a960ed289ecd38d383e396243831ab81feb109c41 ./src/linux/font/OFL.txt
b81923b94e5af9c058023ed9c55ce9374fa0a1120b9db64559376c7377735e26 ./src/linux/font/README.md
02b5ad79c0cdb7879a886020bec56ca65163fca372320a4435ab1fde3f5545c8 ./src/linux/font/manifest.json
6fe87564a24392257fc03e48a7044e18b69d07e9a3461be502c8a1f99fefcab3 ./src/linux/font/roboto-16.fontatlas
13bd60c677e7fe5e04610f4a3f7f5f037e06d82b8bd45d2dd23e66745e7afe43 ./src/linux/function-pointers.h
4e33e1d5b8761526c240635e4b4808914c38f05d982c106a9d20347d9d78f908 ./src/linux/functions.inc
4e7280cddf0d0dd45118cce1a698505c43d1bfcfc633db1ec81ce946766af13d ./src/linux/libraries.c
44d10ed0a4d57424af3babd16a965f03aca6885e5adcc43dd7f3fcce3b3c2fd2 ./src/linux/native.zig
578df3d8bd82d582a36c06df805bb7d3ab5e039f349d5308591a7c0674bbd109 ./src/linux/nix/pkgs.nix
666f8b38bd8c2b904ba2853aefe653bdc64d8050390eeb4a8f91cfe88fb710e1 ./src/linux/protocols/generated/appmenu.c
9627af04a4dd8f057f06e79761401ced0c4f10191a107510764dc8e57371ea0a ./src/linux/protocols/generated/appmenu.h
1d03922d9d51641a6148af2b41d171d9eff85b9ff209977a8da158318ef8d60b ./src/linux/protocols/generated/cursor-shape-v1.c
87edf9719e935db05a0f5545e20d8bdf67f2c2557676f9d1e697b83cc98d6529 ./src/linux/protocols/generated/cursor-shape-v1.h
87a896df22f7b5e6ec5367cc9b3ed7c77c65b54405a50fd3c7133cd4c6fc3281 ./src/linux/protocols/generated/dbus/dbus-arch-deps.h
17ccf68784364bdd29578ea137012e5f4944955d7abba1839d586e1abf96647a ./src/linux/protocols/generated/fractional-scale-v1.c
9243e57b2ce11317f6aaa2cd76c0a9f999fb54ced38b880d81891a6ee5dd27df ./src/linux/protocols/generated/fractional-scale-v1.h
8febb7cca002300dd0ddb4e0f509ba1cc6a30599693879c2c2319c0f11648485 ./src/linux/protocols/generated/pointer-constraints-unstable-v1.c
ccb950e475f81762a0db3d360c3d9745b18e90c55774688f2ee2628a82fae97e ./src/linux/protocols/generated/pointer-constraints-unstable-v1.h
1a660e3638924ae5eff914b489793f4d3a03962b8665282763844e0574fa04fa ./src/linux/protocols/generated/private-symbols.h
223972955bc3ba6dfe06af5a222adfde94287840aa01d944564a98f33c92506e ./src/linux/protocols/generated/tablet-v2.c
eff5398428ff21523ae6c745d57081f3bd5c18509c4bf5b18de75d89d58d18cd ./src/linux/protocols/generated/tablet-v2.h
932e28cf368b78196a92e16418737bbb03f641c0d43e8727b79d6f043d34b511 ./src/linux/protocols/generated/text-input-unstable-v3.c
051057bc8292414f82c46fb854455616fd212cfffb95222aa5af1e2e2cde3067 ./src/linux/protocols/generated/text-input-unstable-v3.h
f19e7c4395ee2254e71455d22c4edd4eefc5c2bfff451c700328f2e4e292a288 ./src/linux/protocols/generated/viewporter.c
dbb68745babf07d3d5587b3f3b83a7cb46848f03885bde4b9cd5e71d19114458 ./src/linux/protocols/generated/viewporter.h
3643fd6aca2f52abcb92a125a0f659c3697268435608a7d3a54e0b614e150f83 ./src/linux/protocols/generated/wayland-client-protocol.h
9ba722d91f4ae3f2820757785f66247868571bc7014f7a679a22f729daaac79f ./src/linux/protocols/generated/wayland-version.h
e1b24bad341ec17a0b1bbbcf37324e5960d9e4bb350a08bebe4d3dca5a364028 ./src/linux/protocols/generated/wayland.c
849c43a721c77cc61f501ea7a41406c27e5b086affe1e0335c654aa4fffb7502 ./src/linux/protocols/generated/xdg-activation-v1.c
c7d669611bcbdd68fea255c102a91f7a686cdb53f58bcbf2b97473edf2221a26 ./src/linux/protocols/generated/xdg-activation-v1.h
ab99cc3a9e7774b69ad24f8e365b4cde1d42d1aa6feccb820b4d451f084795dc ./src/linux/protocols/generated/xdg-decoration-unstable-v1.c
fa1d17dbdfad9e13f35a0d807906926a054edb18cef836cc39063a586d5f6dd4 ./src/linux/protocols/generated/xdg-decoration-unstable-v1.h
89b80bcfdc24f6d4d60f040cde3f0d483f0a932c98d876f17315f3db39aaab1c ./src/linux/protocols/generated/xdg-foreign-unstable-v2.c
f384a4e83ce05ccdc0101cb3bb98b8a36496d6c5a34d921a4b448b14d07e0761 ./src/linux/protocols/generated/xdg-foreign-unstable-v2.h
c39c3fd324a97c921813487f8a0a870b46fec9da6cf3e33c3d5234885d1e74ae ./src/linux/protocols/generated/xdg-shell.c
4b472982e483e37f9e28a1b655aabb5718a6e6a54023dac90fee45bad316ecc9 ./src/linux/protocols/generated/xdg-shell.h
445221aa349c1d15eb80156848a0b348f891fd55c16be568c6ae2bd067e2f0ab ./src/linux/protocols/generated/xdg-toplevel-icon-v1.c
aa7939d3a1b64c280dd73ed5a4d765a838175fbf6e4ef6eada6750c4826e22b6 ./src/linux/protocols/generated/xdg-toplevel-icon-v1.h
7d0251ee00d3d4bc7ee41e3cd1161beaf68a0c18c4f56f48ff1907a475846022 ./src/linux/protocols/xml/appmenu.xml
bb57d91e53a79dadab7c612dab87c233393cee73673feefa7442cfbfdd9aed2f ./src/linux/protocols/xml/cursor-shape-v1.xml
5941de5d28f427ecdadddc8623a6f6af0a30b0ab4726847236ba7a7652b81316 ./src/linux/protocols/xml/fractional-scale-v1.xml
f980fac900ba1dcfbbe97f588fc17b893926bd2b57624563653a1bfe4d035948 ./src/linux/protocols/xml/pointer-constraints-unstable-v1.xml
3ea2783210086dfddef3994fec974f46a00cf175c06efdd8ea47c3007f812a80 ./src/linux/protocols/xml/tablet-v2.xml
2d08f2cddb463e169c23f1c34769de12ae255540e51ee8f515b54667d60b90ba ./src/linux/protocols/xml/text-input-unstable-v3.xml
dcb12279a03746301fe490aaed4b38a403485a925abfce2ccfceb644e104fe71 ./src/linux/protocols/xml/viewporter.xml
60abb5864546288a660f3d8af0c838fc87c85bb386582da23e52cb8476e9adbf ./src/linux/protocols/xml/wayland.xml
d8418be2d5738d50aff788bef1c7574f33f26659aa045447ff2ef9b78c58fe01 ./src/linux/protocols/xml/xdg-activation-v1.xml
73101094eedd2295ac48972a2562d6f99881fee68f3d4d403675837434ab7c70 ./src/linux/protocols/xml/xdg-decoration-unstable-v1.xml
625d83fbb068f48e69e739eafde507f10cdfe7480146f3ac10af9a2ddf551c80 ./src/linux/protocols/xml/xdg-foreign-unstable-v2.xml
9d9e27038ca722f159a361293f8c6cd270dab907ab52de5b8ecfbb8d6b9651c2 ./src/linux/protocols/xml/xdg-shell.xml
791dbfed89280c1b8031689955a03e9b2da55601be3c5854a6198e38cea4978f ./src/linux/protocols/xml/xdg-toplevel-icon-v1.xml
4d37f739e4a895030ab92fb28ebea565de6bf2fada3dc649a9f0de12715e6a51 ./src/linux/redirects.h
ac494003edbee7569bdb767e05a7cc5ad08dfafcc798649125aae02f1da228c3 ./src/linux/tools/audit-elf.py
4f2f131ff071e09da9ef3a10e420aa719e7d903792b8c62fd0d76a19dc1a38a8 ./src/linux/tools/bitmap-font.py
e6f6b2e932c4c987ad8b76dc3f18e4603dc6088917b313a32189c03953701974 ./src/linux/tools/protocols.py
8ffcd037113f0b412388ccbc40ddf370f644d80b4d10db6440b4efbe8ee2f0fa ./src/linux/tray.xml
1e6d3f8695166ec0173f74fa1b618d964052750d3be0e75c69990035c0dd1e7b ./src/linux/vendor/README.md
150e5d08e1cb5e62b65967d7931acad2c42d98ec1bbb584bebb01921cbc853c2 ./src/linux/vendor/dbus/COPYING
5a6834badb73f871acaaea7f03f6497f50e958232a1dbe64f1f098e56c4557ce ./src/linux/vendor/dbus/dbus/dbus-address.h
ecbce7c0446c22e0ce4d4bf2641f2aa6419e721a6c9c1ccbb41b800028334265 ./src/linux/vendor/dbus/dbus/dbus-arch-deps.h.in
c50a3f89fab412a98544d98a1c94dc07ad5b540ebbf63e63105877039ff2f374 ./src/linux/vendor/dbus/dbus/dbus-bus.h
f9496c07830e44fbda1668328b40c78527251c99e62919c80af479631ff794bf ./src/linux/vendor/dbus/dbus/dbus-connection.h
00292ccbbc3d30603c293122155151fd21aa26aa0adbc8333972440544f37ded ./src/linux/vendor/dbus/dbus/dbus-errors.h
78fc922e402466c826145dbfe31d2ae87682ef2df6233d436dc3399552f6362f ./src/linux/vendor/dbus/dbus/dbus-macros.h
7e0487d09e88e705bd166432e3d581aafe2e90c5654224505b73c56ae8d8cf2f ./src/linux/vendor/dbus/dbus/dbus-memory.h
2dd354759e49fad23f25b3b85e73d9e6d4ad0034c08828af1d5f7226971f66d6 ./src/linux/vendor/dbus/dbus/dbus-message.h
6ff2e2f874f55a6b4738aea905ee413d814fec320b48ffd7f30a2df3237894aa ./src/linux/vendor/dbus/dbus/dbus-misc.h
0aee41fe9624a284935fee0d4b572a313f83230ac31bdead59dff96309b7d1e0 ./src/linux/vendor/dbus/dbus/dbus-pending-call.h
533fd55283662d1c013792a29e9993e31babe20d5a5dfedae2c4b8e8bebafc6a ./src/linux/vendor/dbus/dbus/dbus-protocol.h
f63bbd5503d13b1486b66a76cc9f289e19ff46d7b3c5f39df9953af3e6df0323 ./src/linux/vendor/dbus/dbus/dbus-server.h
97ed7edf5baf42bdee4d5777d63158599667078499ca1b0360ccedb013d3531c ./src/linux/vendor/dbus/dbus/dbus-shared.h
13a10246dee6a378899c88a9ac37e0eb618a1f91766fc27de0053309e6aac941 ./src/linux/vendor/dbus/dbus/dbus-signature.h
200170d6ee508b6daa8a17dc9b804a0a35fa555d8d8c8768258edd75dd36cd43 ./src/linux/vendor/dbus/dbus/dbus-syntax.h
16c10fafae90e9aaeaf0506f41432bfa389dfdf333115f8934680d88d83ae12d ./src/linux/vendor/dbus/dbus/dbus-threads.h
0228e51763888e7319f0b8c862f0ee928e3079340408512f7e4a594e1eeae48d ./src/linux/vendor/dbus/dbus/dbus-types.h
56ff456922bf6df191958a291fc5d6d66f39b82b156bc2d715ef87add155cea5 ./src/linux/vendor/dbus/dbus/dbus.h
a7c24c828bf2e1a4dfe6511b4f4812b948a285eb54787074015896976d4da076 ./src/linux/vendor/khronos/EGL/egl.h
a5f574a0074001400c6c50232235ee00e9a67b2168bfd1c364ba0f6f52e5a75c ./src/linux/vendor/khronos/EGL/eglext.h
25b5391655effcf363a38fa00c3154f356a3eab3d35dc067847875513cf1e441 ./src/linux/vendor/khronos/EGL/eglplatform.h
7b1e01aaa7ad8f6fc34b5c7bdf79ebf5189bb09e2c4d2e79fc5d350623d11e83 ./src/linux/vendor/khronos/KHR/khrplatform.h
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./src/linux/vendor/khronos/LICENSE-2.0.txt
fed229b5e556a64ff657068913d597f82da591e1cf216e8738cf869efb40216c ./src/linux/vendor/manifest.json
8f25018489d6fe0dec34a352314c38dc146247b7de65735790f4398a92afa84b ./src/linux/vendor/plasma-wayland-protocols/MIT.txt
f1a2b233e8a9a71c40f4aa885be08a0842ac85bb8588703c1dd7e6e6502e3124 ./src/linux/vendor/wayland-protocols/COPYING
6eefcb023622a463168a5c20add95fd24a38c7482622a9254a23b99b7c153061 ./src/linux/vendor/wayland/COPYING
f744b2c9191bffe7580b7b3894d24f513f52e5dbc586404c4ea8b0f70952dfcd ./src/linux/vendor/wayland/wayland-client-core.h
e9dd1fb014aa6ad848cb7d241cc223b1a70fc0b17fed5997262024e4c05532f7 ./src/linux/vendor/wayland/wayland-client.h
07cd540e327a028066da1dc79dc25126641509857a4478560471540cf1b35c42 ./src/linux/vendor/wayland/wayland-egl-core.h
f336a00a03fcf442a59dc9e5fcce3fc94b2cbfcbcf0befba018be3657b7ea381 ./src/linux/vendor/wayland/wayland-util.h
3d66b4a1c0cc3d04cae23b3c4d4914d8107f9e9ef797ebe9554a846d38920b73 ./src/linux/vendor/wayland/wayland-version.h.in
967e97b28658f0037bbe164a237bdfb0c3ec790e67f6c29372ea5b09306f61f3 ./src/linux/vendor/xkbcommon/LICENSE
fb0384a704897c0dcfcc49f021ad38fadbbedc3307d5390f4f0d1019e3d1a4d9 ./src/linux/vendor/xkbcommon/xkbcommon-compat.h
e6facb4fc280991d15679dd3e5d06af8decdbb6d1eeaaea729642990502c57fe ./src/linux/vendor/xkbcommon/xkbcommon-compose.h
e854c5a8edd8da610e51404f6b09c741027089701c386bdd9bdf5ce851a585a1 ./src/linux/vendor/xkbcommon/xkbcommon-keysyms.h
a5b0ed01c8b1816da8b5ed29cf776eb2ad1f707cf03ff74e62e36a5ca9009f61 ./src/linux/vendor/xkbcommon/xkbcommon-names.h
9f2d729a0a5a0aac5bd2e229c2be8346823ca90342b0f87cc9132ff2816a6b74 ./src/linux/vendor/xkbcommon/xkbcommon.h
4f3a7fb2d4f30a63635dd09fafe684a85d1c701cc47102414f54dec9943ee848 ./src/linux/xkb-imports.h
1e53a239caa339567786b916371295d5905dca0c8ce1813f5266d347605c84c0 ./src/macos/native.m
9b5fa8015079dd2b89b8be36429975428d03a5db5e621f30e46527c5dd533ece ./src/macos/tray.inc
1757b18894c2e2faae8791c4ebb340473f498ce263a3daa8c5f0c9b6a3fa2fc8 ./src/native.h
00af26431b303d3bfbc43059246be8b91d4d37bd7c3a8914d6f320b1f3795e54 ./src/platform_io.c
21246f28640693287939a442b00938f444d7bd38b69e855fb62ab8f1f63d7535 ./src/root.zig
f1748d28a644fa96cee73936a8f5056898c6a072e8422987feef0dfb7ff17b9a ./src/runtime.zig
90dd8b66cd514f84ee1fcdce5db0f466a41356fede4b01995111b32d43371dbd ./src/test_frame.h
f373c0267a5881a0a20ef015a877c038f210764d423a9cbafa71bae2ee70df8d ./src/windows/imports.zig
e5a73120bad391403a58483ad788604b1ae527077a3e998232a3d79ddf05aa7d ./src/windows/native.c
90c4de21f4d25cf87a1807749b3c9ff45932a8ff79b3ed3777924440d4088fd7 ./src/windows/nocrt.h
e7eb8599a629eaeaf787665ebda7171fc2352c2ab5483f5375bc053fc6cb0d93 ./src/windows/tray.inc

4
desktop/vendor/uhdk/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.zig-cache/
zig-out/
.DS_Store
zig-pkg/

22
desktop/vendor/uhdk/LICENSE vendored Normal file
View File

@ -0,0 +1,22 @@
// MIT License
//
// Copyright (c) 2022 Peter Li
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

415
desktop/vendor/uhdk/README.md vendored Normal file
View File

@ -0,0 +1,415 @@
# Uhdk
A small desktop platform library written in Zig 0.17.1 with a C99 ABI.
It provides windows, input and IME, clipboard, file dialogs, incoming file drops, menus, tray icons,
async file operations, file watching, and OpenGL context creation. The macOS
backend uses AppKit, OpenGL, and FSEvents through a private Objective-C bridge.
File dialog filters accept suffixes without a leading dot, including compound
suffixes such as `level.json`.
Internal naming: `z_` means **Zig bridge**, identifying private bridge functions,
types, and helpers connecting the Zig runtime with native platform code. Public
C API symbols use `uhdk_`.
macOS builds require Xcode Command Line Tools. The Windows Win32/WGL backend
targets `x86_64-windows-gnu`. Demo applications have been tested under Wine and
on a Windows 11 host with no issues observed so far. The backend requires
Windows 10 version 1703 or later and an OpenGL 3.3-capable driver for GL sessions.
The Linux Wayland preview implements windows, EGL/OpenGL, keyboard/pointer and
text input, clipboard/file drops, portal dialogs/preferences, activation, icons,
file watches, and Plasma app/window menu export, initially tested on KDE Plasma.
Linux context menus use a small software renderer and a bundled 16px Roboto
bitmap; X11 remains unsupported. Desktop dependencies are limited to vendored
ABI headers/protocol bindings and runtime-loaded system libraries. Normal
builds need Zig alone; the optional `shell.nix` supplies maintainer tools and
NixOS runtime library paths. See [Linux support and limitations](src/linux/README.md).
Window decoration and resizing are selected through `uhdk_window_style` when a
window is created and can be changed later with `uhdk_window_set_style`.
Set `decorated` to false for application-drawn chrome; on Wayland this requests
client-side decoration instead of the compositor's usual title bar and border.
The primary application path is `uhdk_open` followed by one
`uhdk_next_frame`/`uhdk_end_frame` loop. It creates a visible window and current
OpenGL context before returning, reports events and framebuffer metrics together,
and handles presentation at the frame boundary. All services accept that same
session handle. Additional native windows can be created synchronously between
iterations for external rendering; they do not have independent UHDK GL contexts.
On macOS, UHDK disables AppKit's conversion of command-line arguments into
`UHDK_EVENT_OPEN_FILES` by default. Applications handle their own arguments;
document-open requests from Finder and the Dock still arrive as events.
## Tray icons
Create a session-owned `uhdk_tray` with `uhdk_tray_create`, replace its complete
description with `uhdk_tray_update`, and remove it with `uhdk_tray_destroy`.
Create/update belong between frames. The descriptor copies UTF-8 text and a
1–512 pixel RGBA8 image, and retains its optional `uhdk_menu`. Keep its nonempty
`id` stable across updates and unique within the session. Set `hidden` to remove
it temporarily, `menu_on_primary` to open its menu on primary activation, or
`template_image` for a macOS template icon. Other backends ignore that hint.
`UHDK_EVENT_TRAY_ACTIVATE` carries the tray and primary/secondary action.
Menu commands carry their origin in `uhdk_menu_event.tray`, with a NULL window;
ordinary window menu commands have a NULL tray. Tray menus support ordinary
commands, submenus, separators, enabled/checked flags and the QUIT role. Other
window-dependent roles are rejected. Menu shortcuts are not global shortcuts.
Query `uhdk_tray_get_state` and handle `UHDK_EVENT_TRAY_STATE`. `available` means
registered with the host, not guaranteed onscreen: the desktop may hide icons.
`UHDK_CAP_TRAY` reports mechanism/host availability. On Linux, discovery is
asynchronous; creation can succeed before a StatusNotifier host exists, then
register automatically when one appears. Keep processing frames while windows
are hidden. The session still opens with a visible primary window, which the
application may hide once it has an available tray item.
Backends use AppKit `NSStatusItem`, Win32 `Shell_NotifyIconW` (including Explorer
restart recovery), and Linux StatusNotifierItem plus D-BusMenu. Linux needs a
session bus and a compatible tray host; no GTK or Qt dependency is added.
Session close removes all items. Destroy invalidates the handle immediately and
suppresses queued tray events; native removal occurs at the next frame or close.
## Experimental desktop input and window observations
macOS uses AppKit editing selectors. Windows and Wayland share Ctrl-based defaults
for word deletion, paragraph/page movement, clipboard actions, undo/redo, Backtab,
Shift+Enter and cancellation. Shift extends selection only for movement. Alt/Super
combinations are not interpreted as Ctrl editing shortcuts. Clipboard shortcuts
work without a menu, with menu actions taking precedence when available.
Applications own execution, Unicode boundaries, layout and undo history. Commands
without customary shortcuts (such as line-boundary deletion on Windows) have no
invented default binding.
Publish an acknowledged text snapshot after consuming text/edit events. On macOS,
further native text input waits after semantic edits, including ignored commands;
acknowledge asynchronous paste after applying its result. Disabling text input or
losing window focus drops that deferred input. Windows IMM emits ordered text
without surrounding-text replacement ranges. Wayland invalidates old IME snapshot
serials after document/selection-changing commands; new surrounding text is
published after acknowledgment. It does not apply AppKit's input-queue mechanism.
`WINDOW_METRICS` is the resize and state-change hook. Geometry state is independent
of minimization. Observation bits indicate which facts are known:
| Backend | Known observations |
| --- | --- |
| macOS | Minimized, live resize, occluded |
| Windows | Minimized, interactive size/move loop |
| Wayland | Resizing; rendering suspension with xdg-shell v6+ |
A clear observation bit means unknown, not false. Wayland cannot report minimized
state or directly undo minimization, and suspension is not proof of occlusion.
Explicitly unavailable Wayland window-manager actions complete with `UNSUPPORTED`.
Render hints do not replace presentation pacing or event processing.
UHDK is experimental and does not guarantee API or ABI compatibility between
revisions. Rebuild consumers when updating the library and headers. Demo testing
does not qualify every IME, window manager, display configuration or driver.
## Build
```sh
zig build # zig-out/lib/libuhdk.a and zig-out/include/
zig build -Dshared=true # platform shared library and headers
zig build test # run core library tests on the native target
zig build -Dtarget=x86_64-windows-gnu
zig build -Dtarget=x86_64-windows-gnu -Dshared=true
zig build check -Dtarget=x86_64-windows-gnu # compile only
```
## Use from Zig
To use a local checkout at `vendor/uhdk`, add it to `build.zig.zon`:
```zig
.dependencies = .{
.uhdk = .{ .path = "vendor/uhdk" },
},
```
In your build, pass the application's target and optimization options:
```zig
const uhdk = b.dependency("uhdk", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("uhdk", uhdk.module("uhdk"));
```
`@import("uhdk")` provides translated public C declarations, including the bundled
OpenGL and experimental native-handle declarations, and links the library and required system frameworks. The
`uhdk` artifact is also available through `uhdk.artifact("uhdk")` for C consumers
or custom bindings. Set `.shared = true` to build a dynamic library; applications
must arrange its runtime location/rpath.
## C interface
- Guide and API reference: the full repository generates them from `uhdk.h`
with `zig build docs-uhdk` (into `build/docs/uhdk/`).
- [uhdk.h](include/uhdk.h): desktop API, lifecycle, ownership, and threading contracts.
- [OPENGL-SOURCES.md](include/OPENGL-SOURCES.md): GLAD generation recipe and Khronos header provenance and licenses.
All UHDK declarations live in `uhdk.h`. Before its first inclusion, define
`UHDK_ENABLE_OPENGL` to include the bundled GLAD 2 OpenGL 3.3 core declarations
and per-context loader table, and/or `UHDK_ENABLE_NATIVE` for the experimental
native-window handle API:
```c
#define UHDK_ENABLE_OPENGL
#define UHDK_ENABLE_NATIVE
#include "uhdk.h"
```
Presence enables each flag; leave it undefined to disable it. These flags select
header declarations, not library backends. The session API is always declared. The supplied Zig module enables both sections. The vendored GL
headers remain unmodified dependencies rather than being pasted into `uhdk.h`.
The public interface uses pointer-and-length text, `char` booleans, and `float`
coordinates. The native bridge is private; consumers do not need Objective-C.
UHDK loads and owns the GL function table returned by `uhdk_get_gl` and
`frame.gl`. Its members are named `Clear`, `DrawArrays`, etc. Use
`uhdk_get_gl_proc(session, name, &proc)` for extension procedures and
`uhdk_set_vsync(session, enabled)` to change presentation policy. No application
loader implementation or current-context management is needed.
On Windows, the static artifact is `zig-out/lib/uhdk.lib`; shared builds install
`zig-out/bin/uhdk.dll` and its import library under `zig-out/lib/`. Keep the DLL
beside your executable. The DLL links no C runtime and imports only Windows
system DLLs; the static library expects the consumer's MinGW-w64 C runtime. The first lifecycle caller establishes the Windows
platform thread; its message loop also owns COM dialogs, menus, clipboard and
watch completion. Input uses IMM32 composition; TSF reconversion and pen/touch
are not implemented. Native UTF-16 path bytes are kept separately from the WTF-8
paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell
URI, URI export returns `UNSUPPORTED`; native-path export still preserves it.
## Session loop
`uhdk_open` is the default setup path. Pass NULL for defaults, or zero-initialize
`uhdk_options`, set `struct_size`, and override the options you need. Successful
setup returns a visible window, a current OpenGL 3.3-or-newer core context, and a
loaded GL function table. Setup failures unwind all resources.
```c
#define UHDK_ENABLE_OPENGL
#include "uhdk.h"
int main(void) {
uhdk_options options = {0};
options.struct_size = sizeof(options);
options.title = (uhdk_text){"Hello UHDK", 10};
options.content_size = (uhdk_size){800, 600};
uhdk_session *session = 0;
if (uhdk_open(&options, &session) != UHDK_STATUS_OK)
return 1;
/* Create shaders, textures, etc. using uhdk_get_gl(session) here. */
uhdk_frame frame;
uhdk_status status = UHDK_STATUS_OK;
while (uhdk_next_frame(session, &frame)) {
for (uint64_t i = 0; i < frame.events.len; ++i) {
uint32_t type = frame.events.ptr[i].type;
if (type == UHDK_EVENT_WINDOW_CLOSE_REQUESTED ||
type == UHDK_EVENT_QUIT_REQUESTED)
uhdk_quit(session);
}
if (frame.drawable) {
frame.gl->Viewport(0, 0, frame.metrics.framebuffer_width,
frame.metrics.framebuffer_height);
frame.gl->ClearColor(0.1f, 0.15f, 0.2f, 1.0f);
frame.gl->Clear(GL_COLOR_BUFFER_BIT);
}
status = uhdk_end_frame(session);
if (status != UHDK_STATUS_OK)
break;
}
if (status == UHDK_STATUS_OK)
status = uhdk_get_status(session);
/* Delete application GL resources here, while the context is current. */
uhdk_close(session);
return status == UHDK_STATUS_OK ? 0 : 1;
}
```
All session/application/GL work stays on OS main. `next_frame` releases native GL
locks, pumps native work and worker completions, then restores the current context.
`end_frame` presents drawable iterations. Every successful `next_frame` needs an
`end_frame`, including event-only iterations. `close` can discard an unfinished
iteration without presenting it. The primary window belongs to the session and must not be destroyed separately.
Continuous mode is the default and requests vsync. `UHDK_RENDER_ON_DEMAND` waits
for events or wake deadlines after the first iteration. Repaint the complete
framebuffer whenever `drawable` is true. Hidden/minimized windows still receive
events, and `uhdk_wake` or a wake deadline can schedule application work.
The first iteration never waits. Session GL calls are valid before, during and
after iterations until close; drawing to the window is conditional on `drawable`.
A fatal native/driver error may prevent further GL work, including cleanup.
On macOS, vsync waits for a per-window CoreVideo display link before presenting,
with the native OpenGL swap interval disabled. The link follows the window's
display. Present waits only while no refresh has passed since the previous present,
so a frame the driver already held until a refresh is not delayed by another. Each
wait is bounded to 100 ms so a sleeping display cannot indefinitely block the frame
loop; disabling vsync bypasses the wait.
Accept close/quit requests with `uhdk_quit`. Keep iterating to drain request
completions and `STOPPED`; then `next_frame` returns false and `get_status` returns
OK. Failures also end the loop, with a non-OK status. An early `close` abandons
undelivered results and drains internal teardown. File workers stay independent,
although their results reach the application at frame boundaries. Long main-thread
updates delay native event handling.
## Native-only sessions and additional windows
Set `uhdk_options.no_opengl` for an external renderer or native-only integration.
The event/frame lifecycle stays the same; `get_gl` and `frame.gl` return NULL,
`end_frame` does not present, and procedure lookup/vsync return UNSUPPORTED.
`uhdk_window_create` synchronously creates an additional hidden native window.
Call it between iterations; a call during a frame returns BUSY. Creation may pump
native work but preserves the current borrowed batch. No additional GL context is
created. Use native handles to attach an external renderer. The session's primary
window belongs to `close`; `uhdk_window_destroy` rejects attempts to destroy it.
File reads/writes/info and watch preparation execute serially on an internal I/O
worker. Up to 64 such requests can be outstanding; further submissions return
BUSY without accepting an ID. Cancellation is best effort; final close may wait
for an active filesystem call. Native dispatch delivers results at frame boundaries.
## Borrowed event payloads
Events and request results carry `const void *data` plus `data_size` instead of
public unions. Check the event type (or successful request kind), then read the
corresponding named payload struct listed in `uhdk.h`. Check `data_size` before
reading fields; unknown types can be ignored. Payload-free events and unsuccessful
request results have NULL data and zero size. Failure diagnostics remain available
in the request envelope.
```c
if (event->type == UHDK_EVENT_KEY &&
event->data_size >= sizeof(uhdk_key_event)) {
const uhdk_key_event *key = (const uhdk_key_event *)event->data;
/* Read key->logical_key, key->pressed, etc. here. */
}
```
One library-owned scratch arena holds the returned batch, its payload structs,
and nested spans. The next valid next_frame call resets it, even if it returns an empty batch
or an error. Invalid arguments and wrong-thread calls do
not reset it. Session close also invalidates everything. Rendering does not
advance this lifetime. Copy data you need to keep; copying an envelope alone
copies only its pointers. Retain file/menu references when needed beyond an iteration,
but even retained handles cannot outlive the app.
Event envelopes have a fixed array stride within each returned batch.
The scratch arena is maintained as UHDK-owned code in
[src/arenas.zig](src/arenas.zig), including its supporting storage and tests.
It originated in Ribtech p2; the MIT license and attribution are retained in that file.
## Optional profiling
`uhdk.h` provides scope, frame, thread-name and named allocation/
free macros. They compile away without evaluating arguments unless the consumer
defines `UHDK_PROFILE_BACKEND` to a quoted adapter header before including UHDK.
An adapter implements the macros documented in that header. Names require static
lifetime; pair zones on the same thread in nesting order and report frees before
releasing memory. Do not put allocation expressions inside profiling macros.
Internal CPU and memory instrumentation is disabled by default. A static consumer
can pass `.tracy = true` to `b.dependency("uhdk", ...)` (or `-Dtracy=true` when
building the archive) and link its own Tracy 0.14.1 client configured with
`TRACY_ENABLE` and `TRACY_ON_DEMAND`. UHDK never fetches or links Tracy itself.
Shared instrumentation is unsupported. Run unit tests with the default
configuration; enabled instrumentation requires the consumer's linked client.
The `UHDK` memory pool measures requested Zig backing allocations, including
objects and arena blocks. Win32 explicit calloc/free blocks use a separate
`UHDK native` pool. OS/framework allocations and GPU memory are excluded.
On-demand capture omits allocations made before connection, so it is not a full
live-heap snapshot. Failed allocations emit nothing; in-place resizes emit
free + alloc. Moving reallocations use alloc/copy/free to preserve event ordering.
Disabled builds use the original allocator directly.
### Caller-chosen async request tags
Every async operation takes a nonzero `uhdk_request_tag` chosen by the caller.
Completions return it as `uhdk_request_result.tag`; cancellation takes the same tag.
Tags are unique among requests whose completion has not yet been delivered,
including completed requests queued for the next frame. Repeated tags return
`BUSY`. Reuse a tag while handling its completion, or choose distinct tags for
concurrent operations. Failure to start reserves nothing and produces no event.
```c
enum { ReadModel = 1, ReadTexture = 2 };
uhdk_status status = uhdk_file_read_all_async(file, 128 * 1024 * 1024, ReadModel);
/* Later, in REQUEST_DONE handling: switch (result->tag) { ... } */
```
Components sharing a session must coordinate tags; pass a dedicated tag to each
component that starts asynchronous work.
### Function-key policy
Use `uhdk_window_set_function_key_policy(window, UHDK_FUNCTION_KEYS_APPLICATION)`
to suppress Windows native defaults for unmodified F1–F24, including F10 menu
activation. Key events still reach the application. `UHDK_FUNCTION_KEYS_NATIVE`
restores the default behavior. Set the policy before the relevant press; it is
applied at the next frame boundary, and a held key retains the handling selected
at its initial press through repeats and release.
Shift/Control/Alt/Super combinations, including Alt+F4, keep native handling.
Registered UHDK menu shortcuts retain priority over raw key events. This policy
is accepted on macOS and Wayland without an effect; it does not override global
shortcuts, IME interception, or keyboard media-key settings.
### Cursor confinement
Windows and Wayland compositors with pointer-constraints-v1 support keeping the
cursor inside the window's content area. macOS currently reports this capability
as unavailable. Request confinement while the window is visible and focused and
the pointer is inside:
```c
if (uhdk_has_capability(session, UHDK_CAP_POINTER_CONFINEMENT)) {
uhdk_status status = uhdk_window_set_pointer_mode(window, UHDK_POINTER_CONFINED);
/* Handle submission failure. POINTER_MODE_CHANGED confirms activation. */
(void)status;
}
```
Set `UHDK_POINTER_NORMAL` to release active confinement or cancel a pending
request. Confinement follows the content area as the window moves/resizes and
preserves cursor shape and absolute pointer motion. Wayland activation depends
on compositor policy and may never occur. Focus loss, hiding/minimizing, or native
cancellation restores normal mode without automatic reactivation. Destruction
and session close also release it. Capture and confinement are mutually exclusive.
### Errors and input lifecycles
`uhdk_status_message(status)` returns a static UTF-8 text span, usable without a
session and from any thread. It does not allocate or maintain a last-error slot.
Failed async results always contain a nonempty `diagnostic`: native detail when
available, otherwise the status message. Use status codes for decisions and text
for display; successful requests may have an empty diagnostic.
`uhdk_event.cycle_id` associates events within a pointer drag/capture/confinement,
phased scroll gesture, or IME preedit composition. These library-generated IDs are
unique per session and separate from caller request tags and native edit
`input_id` values.
Hover, discrete wheel events, ordinary typing and unrelated events use zero.
Track the ID from the first relevant event; ignore updates from other cycles.
`UHDK_EVENT_CYCLE_END` carries the ID, window, and a `uhdk_cycle_end_event` payload.
Its `reason` distinguishes completion, cancellation, capture/confinement release
or loss, focus loss, hiding, replacement and shutdown. It reports the first observed ending
cause and retires the interaction, without deciding whether
the application should commit or undo its work. Destruction invalidates cycles
immediately; fatal errors or early close may prevent delivery of queued endings.
The C API exposes spans and plain event payloads. `UHDK_EVENT_PAYLOAD` checks an
event's type and payload size before returning a typed pointer; languages that
cannot use C macros perform those checks explicitly.

157
desktop/vendor/uhdk/build.zig vendored Normal file
View File

@ -0,0 +1,157 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const use_llvm = b.option(bool, "use_llvm", "Use LLVM for Zig compilation") orelse null;
const shared = b.option(bool, "shared", "Build libuhdk as a shared library instead of static") orelse false;
const tracy = b.option(bool, "tracy", "Emit Tracy 0.14.1 on-demand hooks; consumer must link the client") orelse false;
if (tracy and shared) @panic("Tracy instrumentation requires static linking");
const lib = createLibraryNamed(b, target, optimize, use_llvm, shared, tracy, "uhdk");
const module = lib.root_module;
const install_lib = b.addInstallArtifact(lib, .{});
const install_headers = b.addInstallDirectory(.{
.source_dir = b.path("include"),
.install_dir = .header,
.install_subdir = "",
});
const lib_step = b.step("lib", "Build and install the Uhdk library and headers");
lib_step.dependOn(&install_lib.step);
lib_step.dependOn(&install_headers.step);
b.getInstallStep().dependOn(&install_lib.step);
b.getInstallStep().dependOn(&install_headers.step);
const unit = b.addTest(.{ .root_module = module });
const check_step = b.step("check", "Compile library and core tests without running them");
check_step.dependOn(&lib.step);
check_step.dependOn(&unit.step);
const unit_run = b.addRunArtifact(unit);
b.step("test", "Run core library tests").dependOn(&unit_run.step);
const public_c = b.addTranslateC(.{
.root_source_file = b.path("include/uhdk.h"),
.target = target,
.optimize = optimize,
});
public_c.defineCMacro("UHDK_ENABLE_OPENGL", "1");
public_c.defineCMacro("UHDK_ENABLE_NATIVE", "1");
public_c.addIncludePath(b.path("include"));
if (shared)
public_c.defineCMacro("UHDK_SHARED", "1");
const public_module = b.addModule("uhdk", .{
.root_source_file = public_c.getOutput(),
.target = target,
.optimize = optimize,
});
public_module.linkLibrary(lib);
}
// Create a library artifact without installing it. Instrumented static builds
// require the consumer to link a matching Tracy client.
pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, use_llvm: ?bool, shared: bool, instrumented: bool) *std.Build.Step.Compile {
return createLibraryNamed(b, target, optimize, use_llvm, shared, instrumented, if (instrumented) "uhdk-instrumented" else "uhdk");
}
fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, use_llvm: ?bool, shared: bool, instrumented: bool, artifact_name: []const u8) *std.Build.Step.Compile {
std.debug.assert(!shared or !instrumented);
// The Windows DLL links no C runtime: MinGW-w64 headers only, and the system
// import libraries come from src/windows/imports.zig. Static libraries keep
// linking libc so consumers inherit the system libraries below.
const no_crt = shared and target.result.os.tag == .windows;
const module = b.createModule(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
.link_libc = !no_crt,
// x64 Windows requires unwind data for SEH and stack walking.
.unwind_tables = if (optimize == .small and target.result.os.tag != .windows) .none else null,
});
const native = b.addTranslateC(.{
.root_source_file = b.path("src/native.h"),
.target = target,
.optimize = optimize,
.link_libc = !no_crt,
});
native.defineCMacro("UHDK_ENABLE_OPENGL", "1");
native.addIncludePath(b.path("include"));
module.addImport("native", native.createModule());
module.addImport("profile", createProfileModule(b, target, optimize, instrumented));
module.addIncludePath(b.path("include"));
module.addIncludePath(b.path("src"));
if (instrumented)
module.addCMacro("UHDK_INTERNAL_TRACY", "1");
if (target.result.os.tag == .macos) {
module.addCSourceFile(.{
.file = b.path("src/macos/native.m"),
.flags = &.{
"-fobjc-arc", "-fblocks", "-Wno-deprecated-declarations",
"-Wall", "-Wextra", "-Werror",
},
});
module.linkFramework("Cocoa", .{});
module.linkFramework("OpenGL", .{});
module.linkFramework("CoreServices", .{});
module.linkFramework("CoreVideo", .{});
} else if (target.result.os.tag == .linux) {
@import("src/linux/build.zig").configure(b, module, target, optimize);
} else {
module.addCSourceFile(.{ .file = b.path("src/windows/native.c"), .flags = cFlags(b, no_crt, &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DUNICODE", "-D_UNICODE" }) });
if (no_crt) {
module.addSystemIncludePath(std.Build.LazyPath.zig_lib.path(b, "libc/include/any-windows-any"));
module.addCMacro("UHDK_NO_CRT", "1");
} else {
for ([_][]const u8{ "user32", "gdi32", "opengl32", "shell32", "ole32", "uuid", "imm32", "comctl32", "shlwapi", "advapi32", "api-ms-win-core-synch-l1-2-0" }) |name| module.linkSystemLibrary(name, .{});
}
}
module.addCSourceFile(.{ .file = b.path("src/gl_loader.c"), .flags = cFlags(b, no_crt, &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" }) });
module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = cFlags(b, no_crt, &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" }) });
const lib = b.addLibrary(.{
.name = artifact_name,
.linkage = if (shared) .dynamic else .static,
.use_llvm = use_llvm,
.root_module = module,
});
if (shared and target.result.os.tag == .linux)
lib.version_script = b.path("src/linux/exports.map");
// temp
// lib.root_module.strip = false;
return lib;
}
// Without a C runtime, keep LLVM from rewriting src/windows/nocrt.h's loops into
// calls to the C runtime functions they replace.
fn cFlags(b: *std.Build, no_crt: bool, flags: []const []const u8) []const []const u8 {
if (!no_crt) return flags;
return std.mem.concat(b.allocator, []const u8, &.{ flags, &.{"-fno-builtin-wcslen"} }) catch @panic("OOM");
}
pub fn createProfileModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, enabled: bool) *std.Build.Module {
const options = b.addOptions();
options.addOption(bool, "enabled", enabled);
const profile = b.createModule(.{
.root_source_file = b.path("src/Profile.zig"),
.target = target,
.optimize = optimize,
});
profile.addOptions("profile_options", options);
return profile;
}

8
desktop/vendor/uhdk/build.zig.zon vendored Normal file
View File

@ -0,0 +1,8 @@
.{
.name = .uhdk,
.fingerprint = 0xe0900359a69bf43d,
.version = "0.1.0",
.minimum_zig_version = "0.17.1",
.dependencies = .{},
.paths = .{ "build.zig", "build.zig.zon", "src", "include", "README.md", "shell.nix" },
}

6132
desktop/vendor/uhdk/include/GL/glcorearb.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,311 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
/*
* To support platform where unsigned long cannot be used interchangeably with
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
* unsigned long long or similar (this results in different C++ name mangling).
* To avoid changes for existing platforms, we restrict usage of intptr_t to
* platforms where the size of a pointer is larger than the size of long.
*/
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
#define KHRONOS_USE_INTPTR_T
#endif
#endif
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef KHRONOS_USE_INTPTR_T
typedef intptr_t khronos_intptr_t;
typedef uintptr_t khronos_uintptr_t;
#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
#endif
#if defined(_WIN64)
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

View File

@ -0,0 +1,36 @@
# Vendored OpenGL headers and loader
## GLAD 2.0.8
`uhdk.h` with `UHDK_ENABLE_OPENGL` includes the generated `glad/gl.h`, no extensions, core 3.3 api
Generated unmodified with the pinned generator and its bundled Khronos snapshot:
```sh
python3 -m venv /tmp/uhdk-glad
/tmp/uhdk-glad/bin/pip install glad2==2.0.8
/tmp/uhdk-glad/bin/python -m glad --api gl:core=3.3 --extensions '' \
--reproducible --out-path /tmp/uhdk-glad-output c --header-only --mx
```
Copy `/tmp/uhdk-glad-output/include/glad/gl.h` to `include/glad/gl.h`.
No generator or Python installation is required to build Uhdk.
- Generator: https://github.com/Dav1dde/glad/tree/v2.0.8
- License: `glad/LICENSE`, from https://raw.githubusercontent.com/Dav1dde/glad/v2.0.8/LICENSE
- Generated header SHA-256: `0dfcb12549b10a4c08372e99dd96c4a3b773ff8d89aec07ef878c8e1ca852456`
- Generated SPDX expression: `(WTFPL OR CC0-1.0) AND Apache-2.0`.
## Original Khronos headers
Retained unmodified for consumers choosing their own loader. Do not combine
`GL/glcorearb.h` with `glad/gl.h` or `UHDK_ENABLE_OPENGL` in a translation unit.
License notices are preserved in each file.
- `include/GL/glcorearb.h`
- Source: https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry/1cdd228e34966dd6b95bd203e9f84faba0f371a1/api/GL/glcorearb.h
- SHA-256: `65fae555a8b3b5709099837001e0c14228b3e45651e2d0fa2ad22649833921e1`
- `include/KHR/khrplatform.h`
- Source: https://raw.githubusercontent.com/KhronosGroup/EGL-Registry/5961a7fe64cf8a126890ced6f13d69e0a1e1b83e/api/KHR/khrplatform.h
- SHA-256: `7b1e01aaa7ad8f6fc34b5c7bdf79ebf5189bb09e2c4d2e79fc5d350623d11e83`

View File

@ -0,0 +1,63 @@
The glad source code:
The MIT License (MIT)
Copyright (c) 2013-2022 David Herberth
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The Khronos Specifications:
Copyright (c) 2013-2020 The Khronos Group Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The EGL Specification and various headers:
Copyright (c) 2007-2016 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Materials.
THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.

2710
desktop/vendor/uhdk/include/glad/gl.h vendored Normal file

File diff suppressed because it is too large Load Diff

1418
desktop/vendor/uhdk/include/uhdk.h vendored Normal file

File diff suppressed because it is too large Load Diff

24
desktop/vendor/uhdk/shell.nix vendored Normal file
View File

@ -0,0 +1,24 @@
{
pkgs ? import ./src/linux/nix/pkgs.nix,
}:
pkgs.mkShell {
packages = [
(pkgs.python3.withPackages (python: [ python.dbus-next python.pillow ]))
pkgs.dbus
pkgs.wayland-scanner
pkgs.clang-tools
pkgs.rustc
pkgs.cargo
pkgs.libpulseaudio
];
# NixOS does not put desktop libraries in the conventional loader search path.
# This affects running an unwrapped development executable, not compilation.
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [
pkgs.wayland
pkgs.libglvnd
pkgs.libxkbcommon
pkgs.dbus.lib
];
UHA_PULSE_LIBRARY = "${pkgs.libpulseaudio}/lib/libpulse.so.0";
}

103
desktop/vendor/uhdk/src/Application.zig vendored Normal file
View File

@ -0,0 +1,103 @@
//! Internal application ownership.
const std = @import("std");
const c = @import("native");
const runtime = @import("runtime.zig");
const abi = @import("abi.zig");
const Event = @import("Event.zig");
const Request = @import("Request.zig");
const Resource = @import("Resource.zig");
const arenas = @import("arenas.zig");
const Application = @This();
gpa: std.mem.Allocator,
io: std.Io,
mutex: std.Io.Mutex = .init,
in_dispatch: bool = false,
next_cycle: u64 = 1,
objects: ?*Resource = null,
queue_head: ?*Request = null,
queue_tail: ?*Request = null,
requests: ?*Request = null,
io_active: ?*Request = null,
io_completed_head: ?*Request = null,
io_completed_tail: ?*Request = null,
io_pending: usize = 0,
io_worker: ?std.Thread = null,
io_available: std.Io.Event = .unset,
io_exit: bool = false,
// Test-only gate permits deterministic blocked-filesystem scheduling tests.
io_test_hook: if (@import("builtin").is_test) ?struct {
context: *anyopaque,
before: *const fn (*anyopaque) void,
} else void = if (@import("builtin").is_test) null else {},
io_head: ?*Request = null,
io_tail: ?*Request = null,
pending_head: ?*Event = null,
pending_tail: ?*Event = null,
published: ?*Event = null,
scratch: arenas.BumpArena,
name: []u8,
application_id: []const u8 = "",
epoch: u64,
deadline: u64 = 0,
next_id: u64 = 1,
running: bool = false,
native_started: bool = false,
native_error: abi.Status = abi.OK,
stopping: bool = false,
stopped_sent: bool = false,
stopped_seen: bool = false,
event_error: abi.Status = abi.OK,
main_thread: ?std.Thread.Id = null,
preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences),
stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats),
last_frame_time: ?u64 = null,
session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions),
session_window: ?*c.uhdk_window = null,
session_has_gl: bool = false,
session_status: abi.Status = abi.OK,
session_active: bool = false,
session_drawable: bool = false,
session_first: bool = true,
session_on_demand: bool = false,
startup_timeout_ns: u64 = 10 * std.time.ns_per_s,
pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application {
const self = try gpa.create(Application);
errdefer gpa.destroy(self);
const owned_name = try gpa.dupe(u8, name);
errdefer gpa.free(owned_name);
const scratch = try arenas.BumpArena.init(gpa, io);
self.* = .{
.gpa = gpa,
.io = io,
.name = owned_name,
.scratch = scratch,
.epoch = runtime.now(io),
};
return self;
}
pub fn lock(self: *Application) void {
self.mutex.lockUncancelable(self.io);
}
pub fn unlock(self: *Application) void {
self.mutex.unlock(self.io);
}
pub fn notify(self: *Application) void {
// Wake native dispatch for events and worker completions.
if (self.native_started) c.z_native_wake();
}

188
desktop/vendor/uhdk/src/Cycles.zig vendored Normal file
View File

@ -0,0 +1,188 @@
//! Shared identities for multi-event input interactions; called under the app lock.
const std = @import("std");
const c = @import("native");
const Cycles = @This();
pointer: u64 = 0,
scroll: u64 = 0,
composition: u64 = 0,
composition_committed: bool = false,
buttons: u32 = 0,
captured: bool = false,
pub const Ended = struct {
ids: [3]u64 = @splat(0),
reasons: [3]c.uhdk_cycle_end_reason = @splat(c.UHDK_CYCLE_COMPLETED),
len: usize = 0,
fn take(self: *Ended, id: *u64, reason: c.uhdk_cycle_end_reason) void {
if (id.* == 0) return;
self.ids[self.len] = id.*;
self.reasons[self.len] = reason;
self.len += 1;
id.* = 0;
}
};
fn begin(id: *u64, next: *u64) !void {
if (id.* != 0) return;
if (next.* == std.math.maxInt(u64)) return error.Exhausted;
id.* = next.*;
next.* += 1;
}
pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended {
var ended: Ended = .{};
ended.take(&self.pointer, reason);
ended.take(&self.scroll, reason);
ended.take(&self.composition, reason);
self.buttons = 0;
self.captured = false;
self.composition_committed = false;
return ended;
}
pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
var ended: Ended = .{};
event.cycle_id = 0;
switch (event.type) {
c.UHDK_EVENT_POINTER_BUTTON => {
const p = event.data.pointer;
if (p.button == 0 or p.button >= 32) return ended;
const bit = @as(u32, 1) << @as(u5, @intCast(p.button));
if (p.pressed != 0) {
try begin(&self.pointer, next);
self.buttons |= bit;
} else self.buttons &= ~bit;
event.cycle_id = self.pointer;
if (self.buttons == 0 and !self.captured) ended.take(&self.pointer, c.UHDK_CYCLE_COMPLETED);
},
c.UHDK_EVENT_POINTER_ENTER, c.UHDK_EVENT_POINTER_LEAVE, c.UHDK_EVENT_POINTER_MOVE => event.cycle_id = self.pointer,
c.UHDK_EVENT_POINTER_MODE_CHANGED => {
self.captured = event.data.pointer_mode != c.UHDK_POINTER_NORMAL;
if (self.captured) try begin(&self.pointer, next);
event.cycle_id = self.pointer;
if (!self.captured) {
self.buttons = 0;
ended.take(&self.pointer, event.cycle_end_reason);
}
},
c.UHDK_EVENT_SCROLL => {
const phase = event.data.scroll.phase;
if (phase != c.UHDK_SCROLL_DISCRETE) {
// A new native BEGIN retires an interrupted previous gesture.
if (phase == c.UHDK_SCROLL_BEGIN) ended.take(&self.scroll, c.UHDK_CYCLE_SUPERSEDED);
if (phase == c.UHDK_SCROLL_BEGIN or phase == c.UHDK_SCROLL_UPDATE) try begin(&self.scroll, next);
event.cycle_id = self.scroll;
if (phase == c.UHDK_SCROLL_END or phase == c.UHDK_SCROLL_CANCEL)
ended.take(&self.scroll, if (phase == c.UHDK_SCROLL_CANCEL) c.UHDK_CYCLE_CANCELLED else c.UHDK_CYCLE_COMPLETED);
}
},
c.UHDK_EVENT_TEXT_PREEDIT => {
if (self.composition == 0) self.composition_committed = false;
try begin(&self.composition, next);
event.cycle_id = self.composition;
},
c.UHDK_EVENT_TEXT_COMMIT => {
event.cycle_id = self.composition;
if (self.composition != 0) self.composition_committed = true;
},
c.UHDK_EVENT_TEXT_COMPOSITION_END => {
event.cycle_id = self.composition;
ended.take(&self.composition, if (self.composition_committed) c.UHDK_CYCLE_COMPLETED else c.UHDK_CYCLE_CANCELLED);
self.composition_committed = false;
},
c.UHDK_EVENT_WINDOW_METRICS => {
if (event.data.metrics.visible == 0) return self.endAll(c.UHDK_CYCLE_HIDDEN);
if (event.data.metrics.focused == 0) return self.endAll(c.UHDK_CYCLE_FOCUS_LOST);
},
else => {},
}
return ended;
}
test "drag and capture share a cycle and late releases cannot revive it" {
var state: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const drag = event.cycle_id;
try std.testing.expect(drag != 0);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_CAPTURE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(drag, ended.ids[0]);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
try std.testing.expect(event.cycle_id != drag);
}
test "independent windows and kinds get distinct cycles and focus loss ends all" {
var state: Cycles = .{};
var other: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const pointer = event.cycle_id;
_ = try other.apply(&next, &event);
try std.testing.expect(event.cycle_id != pointer);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event);
const scroll = event.cycle_id;
event.data.scroll.phase = c.UHDK_SCROLL_UPDATE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
const composition = event.cycle_id;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_COMMIT;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
try std.testing.expect(pointer != scroll and scroll != composition);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics);
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 3), ended.len);
try std.testing.expectEqualSlices(u64, &.{ pointer, scroll, composition }, &ended.ids);
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_DISCRETE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
}

12
desktop/vendor/uhdk/src/Event.zig vendored Normal file
View File

@ -0,0 +1,12 @@
//! Internal event ownership.
const std = @import("std");
const c = @import("native");
const abi = @import("abi.zig");
const Resource = @import("Resource.zig");
const Event = @This();
next: ?*Event = null,
arena: abi.Arena,
gpa: std.mem.Allocator,
event: c.z_event = std.mem.zeroes(c.z_event),
pins: std.ArrayList(*Resource) = .empty,

View File

@ -0,0 +1,88 @@
//! Convert private producer unions to immutable, arena-owned public payloads.
const std = @import("std");
const c = @import("native");
const abi = @import("abi.zig");
const Data = struct {
ptr: ?*const anyopaque = null,
size: u64 = 0,
};
fn store(comptime T: type, allocator: std.mem.Allocator, value: T) !Data {
const ptr = try allocator.create(T);
ptr.* = value;
return .{ .ptr = ptr, .size = @sizeOf(T) };
}
fn files(allocator: std.mem.Allocator, value: c.uhdk_file_list) !c.uhdk_file_list {
if (value.len == 0) return .{ .ptr = null, .len = 0 };
const ptr = try allocator.dupe(?*c.uhdk_file, value.ptr[0..@intCast(value.len)]);
return .{ .ptr = ptr.ptr, .len = ptr.len };
}
fn result(allocator: std.mem.Allocator, source: c.z_request_result) !c.uhdk_request_result {
const data: Data = if (source.status != abi.OK) .{} else switch (source.kind) {
c.UHDK_REQUEST_FILE_DIALOG => try store(c.uhdk_file_list, allocator, try files(allocator, source.value.files)),
c.UHDK_REQUEST_CLIPBOARD_TEXT => try store(c.uhdk_text, allocator, try abi.copyText(allocator, source.value.text)),
c.UHDK_REQUEST_FILE_READ => try store(c.uhdk_bytes, allocator, try abi.copyBytes(allocator, source.value.bytes)),
c.UHDK_REQUEST_FILE_INFO => try store(c.uhdk_file_info, allocator, source.value.info),
c.UHDK_REQUEST_WATCH => try store(c.uhdk_watch_result, allocator, .{ .watch = source.value.watch }),
else => .{},
};
return .{
.tag = source.tag,
.kind = source.kind,
.status = source.status,
.diagnostic = if (source.status != abi.OK and source.diagnostic.len == 0)
abi.statusMessage(source.status)
else
try abi.copyText(allocator, source.diagnostic),
.data = data.ptr,
.data_size = data.size,
};
}
pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event {
const data: Data = switch (source.type) {
c.UHDK_EVENT_APP_ACTIVATION => try store(c.uhdk_app_activation_event, allocator, .{ .active = source.data.active }),
c.UHDK_EVENT_OPEN_FILES => try store(c.uhdk_file_list, allocator, try files(allocator, source.data.files)),
c.UHDK_EVENT_WINDOW_METRICS => try store(c.uhdk_window_metrics, allocator, source.data.metrics),
c.UHDK_EVENT_PREFERENCES_CHANGED => try store(c.uhdk_preferences, allocator, source.data.preferences),
c.UHDK_EVENT_KEY => try store(c.uhdk_key_event, allocator, source.data.key),
c.UHDK_EVENT_POINTER_ENTER,
c.UHDK_EVENT_POINTER_LEAVE,
c.UHDK_EVENT_POINTER_MOVE,
c.UHDK_EVENT_POINTER_BUTTON,
=> try store(c.uhdk_pointer_event, allocator, source.data.pointer),
c.UHDK_EVENT_POINTER_MODE_CHANGED => try store(c.uhdk_pointer_mode_event, allocator, .{ .mode = source.data.pointer_mode }),
c.UHDK_EVENT_SCROLL => try store(c.uhdk_scroll_event, allocator, source.data.scroll),
c.UHDK_EVENT_TEXT_COMMIT, c.UHDK_EVENT_TEXT_PREEDIT => data: {
var text = source.data.text;
text.text = try abi.copyText(allocator, text.text);
break :data try store(c.uhdk_text_event, allocator, text);
},
c.UHDK_EVENT_EDIT_COMMAND => try store(c.uhdk_edit_event, allocator, source.data.edit),
c.UHDK_EVENT_DROP_FILES => data: {
var drop = source.data.drop_files;
drop.files = try files(allocator, drop.files);
break :data try store(c.uhdk_drop_files_event, allocator, drop);
},
c.UHDK_EVENT_MENU_COMMAND => try store(c.uhdk_menu_event, allocator, source.data.menu),
c.UHDK_EVENT_TRAY_ACTIVATE => try store(c.uhdk_tray_event, allocator, source.data.tray),
c.UHDK_EVENT_TRAY_STATE => try store(c.uhdk_tray_state_event, allocator, source.data.tray_state),
c.UHDK_EVENT_WATCH => try store(c.uhdk_watch_event, allocator, source.data.watch),
c.UHDK_EVENT_CYCLE_END => try store(c.uhdk_cycle_end_event, allocator, source.data.cycle_end),
c.UHDK_EVENT_REQUEST_DONE => try store(c.uhdk_request_result, allocator, try result(allocator, source.data.request)),
else => .{},
};
return .{
.struct_size = @sizeOf(c.uhdk_event),
.type = source.type,
.time_ns = source.time_ns,
.input_id = source.input_id,
.cycle_id = source.cycle_id,
.window = source.window,
.data = data.ptr,
.data_size = data.size,
};
}

View File

@ -0,0 +1,194 @@
//! One I/O-worker file operation. Each step transfers at most one chunk. may need more work to do batched chunking
const FileOperation = @This();
const std = @import("std");
const c = @import("native");
const Allocator = std.mem.Allocator;
pub const Kind = enum { read, write, info };
pub const FileKind = enum { file, directory, other };
pub const Info = struct {
size: u64,
modified_ns: i64,
kind: FileKind,
};
pub const Result = union(enum) {
pending,
bytes: []const u8,
info: Info,
written,
};
kind: Kind,
gpa: Allocator,
path: []const u8,
input: []const u8 = &.{},
limit: u64 = 0,
reader: ?*anyopaque = null,
writer: ?*anyopaque = null,
contents: std.ArrayList(u8) = .empty,
offset: u64 = 0,
started: bool = false,
pub fn init(
gpa: Allocator,
kind: Kind,
path: []const u8,
input: []const u8,
limit: u64,
) FileOperation {
return .{ .gpa = gpa, .kind = kind, .path = path, .input = input, .limit = limit };
}
pub fn close(self: *FileOperation) void {
if (self.reader) |reader| c.z_file_reader_close(reader);
self.reader = null;
if (self.writer) |writer| c.z_file_writer_close(writer);
self.writer = null;
}
pub fn deinit(self: *FileOperation) void {
self.close();
self.contents.deinit(self.gpa);
self.* = undefined;
}
/// The caller checks cancellation before each step. A successful replacement is
/// the commit point; subsequent cancellation must not change its successful result.
pub fn step(self: *FileOperation) !Result {
if (self.kind == .info) {
return .{ .info = try metadata(self.path, true) };
}
if (!self.started) {
switch (self.kind) {
.read => {
// Reject nonregular files and do not follow the final symlink.
// Filesystem metadata remains advisory under concurrent changes.
const stat = try metadata(self.path, false);
if (stat.kind != .file) return error.NotRegularFile;
if (stat.size > self.limit) return error.StreamTooLong;
try statusError(c.z_file_reader_open(pathSpan(self.path), &self.reader));
},
.write => {
try statusError(c.z_file_writer_open(pathSpan(self.path), &self.writer));
},
.info => unreachable,
}
self.started = true;
return .pending;
}
const chunk_size = 256 * 1024;
if (self.kind == .read) {
var chunk: [chunk_size]u8 = undefined;
const remaining = self.limit -| self.contents.items.len;
const capacity = @min(chunk.len, remaining +| 1);
var count: usize = 0;
try statusError(c.z_file_reader_read(self.reader.?, self.offset, &chunk, capacity, &count));
if (count == 0) return .{ .bytes = self.contents.items };
if (count > remaining) return error.StreamTooLong;
try self.contents.appendSlice(self.gpa, chunk[0..count]);
self.offset += count;
return .pending;
}
if (self.offset < self.input.len) {
const remaining = self.input[@intCast(self.offset)..];
var count: usize = 0;
const part = remaining[0..@min(chunk_size, remaining.len)];
try statusError(c.z_file_writer_write(self.writer.?, self.offset, part.ptr, part.len, &count));
if (count == 0) return error.WriteFailed;
self.offset += count;
return .pending;
}
try statusError(c.z_file_writer_commit(self.writer.?));
self.writer = null;
return .written;
}
fn pathSpan(path: []const u8) c.uhdk_bytes {
return .{ .ptr = path.ptr, .len = path.len };
}
fn metadata(path: []const u8, follow: bool) !Info {
var value: c.z_file_metadata = undefined;
try statusError(c.z_file_metadata_read(pathSpan(path), @intFromBool(follow), &value));
return .{
.size = value.size,
.modified_ns = value.modified_ns,
.kind = switch (value.type) {
c.Z_FILE_TYPE_REGULAR => .file,
c.Z_FILE_TYPE_DIRECTORY => .directory,
else => .other,
},
};
}
fn statusError(status: u32) !void {
return switch (status) {
c.Z_FILE_OK => {},
c.Z_FILE_NOT_FOUND => error.FileNotFound,
c.Z_FILE_ACCESS_DENIED => error.AccessDenied,
c.Z_FILE_NOT_REGULAR => error.NotRegularFile,
c.Z_FILE_INVALID_PATH => error.InvalidPath,
c.Z_FILE_OUT_OF_MEMORY => error.OutOfMemory,
else => error.Unexpected,
};
}
test "chunked replacement, bounded read, and cancellation before commit" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var temporary = std.testing.tmpDir(.{});
defer temporary.cleanup();
const directory = try temporary.dir.realPathFileAlloc(io, ".", gpa);
defer gpa.free(directory);
const path = try std.fs.path.join(gpa, &.{ directory, "document" });
defer gpa.free(path);
const contents = try gpa.alloc(u8, 600_000);
defer gpa.free(contents);
@memset(contents, 0xab);
var write = FileOperation.init(gpa, .write, path, contents, 0);
defer write.deinit();
var passes: usize = 0;
while (try write.step() == .pending) : (passes += 1) {}
try std.testing.expect(passes >= 4);
var read = FileOperation.init(gpa, .read, path, &.{}, contents.len);
defer read.deinit();
while (true) {
switch (try read.step()) {
.bytes => |result| {
try std.testing.expectEqualSlices(u8, contents, result);
break;
},
.pending => {},
else => unreachable,
}
}
var limited = FileOperation.init(gpa, .read, path, &.{}, 10);
defer limited.deinit();
try std.testing.expectError(error.StreamTooLong, limited.step());
var cancelled = FileOperation.init(gpa, .write, path, "changed", 0);
try std.testing.expect(try cancelled.step() == .pending);
try std.testing.expect(try cancelled.step() == .pending);
cancelled.deinit();
const preserved = try temporary.dir.readFileAlloc(io, "document", gpa, .limited(contents.len + 1));
defer gpa.free(preserved);
try std.testing.expectEqualSlices(u8, contents, preserved);
}

61
desktop/vendor/uhdk/src/MinimalIo.zig vendored Normal file
View File

@ -0,0 +1,61 @@
//! UHDK's small blocking `std.Io` implementation.
//!
//! UHDK schedules file work on its own worker. This interface exists only for
//! clocks and the futex operations used by `std.Io.Mutex` and `std.Io.Event`.
const std = @import("std");
const c = @import("native");
const Io = std.Io;
pub const instance: Io = .{
.userdata = null,
.vtable = &vtable,
};
const vtable: Io.VTable = blk: {
var result = Io.failing.vtable.*;
result.futexWait = futexWait;
result.futexWaitUncancelable = futexWaitUncancelable;
result.futexWake = futexWake;
result.now = now;
break :blk result;
};
fn futexWait(_: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Io.Timeout) Io.Cancelable!void {
const duration = timeout.toDurationFromNow(instance);
const timeout_ns: u64 = if (duration) |value|
std.math.lossyCast(u64, @max(0, value.raw.toNanoseconds()))
else
0;
c.z_io_wait(ptr, expected, timeout_ns, @intFromBool(duration != null));
}
fn futexWaitUncancelable(_: ?*anyopaque, ptr: *const u32, expected: u32) void {
c.z_io_wait(ptr, expected, 0, 0);
}
fn futexWake(_: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
c.z_io_wake(ptr, max_waiters);
}
fn now(_: ?*anyopaque, clock: Io.Clock) Io.Timestamp {
return .{ .nanoseconds = c.z_io_now(@intFromEnum(clock)) };
}
test "clock and event wake" {
var event: Io.Event = .unset;
const worker = try std.Thread.spawn(.{}, struct {
fn run(target: *Io.Event) void {
const start = c.z_io_now(@intFromEnum(Io.Clock.awake));
while (c.z_io_now(@intFromEnum(Io.Clock.awake)) - start < std.time.ns_per_ms)
std.atomic.spinLoopHint();
target.set(instance);
}
}.run, .{&event});
defer worker.join();
try event.waitTimeout(instance, .{ .duration = .{
.raw = .fromSeconds(5),
.clock = .awake,
} });
try std.testing.expect(c.z_io_now(@intFromEnum(Io.Clock.awake)) > 0);
}

146
desktop/vendor/uhdk/src/Profile.zig vendored Normal file
View File

@ -0,0 +1,146 @@
//! Optional compile-time instrumentation, disabled by default.
const std = @import("std");
const builtin = @import("builtin");
pub const enabled = @import("profile_options").enabled;
const verify_stack_order = builtin.mode == .debug or builtin.mode == .safe;
// Tracy 0.14.1 C ABI with TRACY_ON_DEMAND; the consumer supplies the client.
// No C header translation or references to Tracy symbols in disabled builds.
const SourceLocation = extern struct {
name: [*:0]const u8,
function: [*:0]const u8,
file: [*:0]const u8,
line: u32,
color: u32 = 0,
};
const Token = extern struct {
id: u32 = 0,
active: i32 = 0,
connection: u64 = 0,
};
extern fn ___tracy_emit_zone_begin(source: *const SourceLocation, active: i32) Token;
extern fn ___tracy_emit_zone_end(zone: Token) void;
extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void;
extern fn ___tracy_set_thread_name(name: [*:0]const u8) void;
threadlocal var stack_depth: usize = 0;
pub const Zone = if (enabled) struct {
token: Token,
depth: if (verify_stack_order) usize else void,
owner: if (verify_stack_order) std.Thread.Id else void,
pub inline fn end(self: @This()) void {
if (verify_stack_order) {
std.debug.assert(self.owner == std.Thread.getCurrentId());
std.debug.assert(self.depth == stack_depth);
stack_depth -= 1;
}
if (self.token.active != 0) ___tracy_emit_zone_end(self.token);
}
} else struct {
pub inline fn end(_: @This()) void {}
};
// The complete @src() (including column) specializes this type. Mutable static
// storage guarantees a unique address even when two records have equal fields.
// It is initialized at comptime and never rewritten, so threads can share it.
fn StaticSource(comptime source: std.builtin.SourceLocation, comptime name: [:0]const u8) type {
return struct {
var location: SourceLocation = .{
.name = name,
.function = source.fn_name,
.file = source.file,
.line = source.line,
};
};
}
pub inline fn begin(comptime source: std.builtin.SourceLocation, comptime name: [:0]const u8) Zone {
if (!enabled) return .{};
const Statics = StaticSource(source, name);
const token = ___tracy_emit_zone_begin(&Statics.location, 1);
if (verify_stack_order) stack_depth += 1;
return .{
// Tracy leaves id/connection unspecified for inactive zones.
.token = if (token.active != 0) token else .{},
.depth = if (verify_stack_order) stack_depth else {},
.owner = if (verify_stack_order) std.Thread.getCurrentId() else {},
};
}
pub inline fn frame() void {
if (enabled) ___tracy_emit_frame_mark(null);
}
pub inline fn thread(comptime name: [:0]const u8) void {
if (enabled) ___tracy_set_thread_name(name);
}
extern fn ___tracy_emit_memory_alloc_named(ptr: *const anyopaque, size: usize, name: [*:0]const u8) void;
extern fn ___tracy_emit_memory_free_named(ptr: *const anyopaque, name: [*:0]const u8) void;
pub inline fn alloc(ptr: *const anyopaque, size: usize, comptime pool: [:0]const u8) void {
if (enabled) ___tracy_emit_memory_alloc_named(ptr, size, pool);
}
pub inline fn free(ptr: *const anyopaque, comptime pool: [:0]const u8) void {
if (enabled) ___tracy_emit_memory_free_named(ptr, pool);
}
/// Keep this wrapper alive and at a stable address while its allocator is used.
/// No wrapper or instrumentation overhead when disabled. Tracks backing blocks,
/// not arena suballocations. Thread safety is inherited from the child allocator.
pub fn TrackingAllocator(comptime pool: [:0]const u8) type {
return struct {
child: std.mem.Allocator,
const Self = @This();
pub fn allocator(self: *Self) std.mem.Allocator {
if (!enabled) return self.child;
return .{
.ptr = self,
.vtable = &.{
.alloc = allocate,
.resize = resize,
// Let Allocator.realloc use alloc/copy/free. A moving rawRemap
// releases the old address before we can report its free, so
// another thread could reuse it and emit an out-of-order alloc.
.remap = std.mem.Allocator.noRemap,
.free = release,
},
};
}
fn allocate(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret: usize) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
const ptr = self.child.rawAlloc(len, alignment, ret) orelse return null;
alloc(ptr, len, pool);
return ptr;
}
fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ret: usize) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
if (!self.child.rawResize(memory, alignment, len, ret)) return false;
free(memory.ptr, pool);
alloc(memory.ptr, len, pool);
return true;
}
fn release(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret: usize) void {
const self: *Self = @ptrCast(@alignCast(ctx));
free(memory.ptr, pool);
self.child.rawFree(memory, alignment, ret);
}
};
}
var uhdk_allocator: TrackingAllocator("UHDK") = .{ .child = std.heap.smp_allocator };
pub fn allocator() std.mem.Allocator {
return uhdk_allocator.allocator();
}

29
desktop/vendor/uhdk/src/Request.zig vendored Normal file
View File

@ -0,0 +1,29 @@
//! Internal request ownership.
const std = @import("std");
const c = @import("native");
const abi = @import("abi.zig");
const Event = @import("Event.zig");
const Resource = @import("Resource.zig");
const FileOperation = @import("FileOperation.zig");
const Request = @This();
pub const Completion = enum { request, resource, discard };
next: ?*Request = null,
queued_next: ?*Request = null,
arena: abi.Arena,
gpa: std.mem.Allocator,
data: c.z_command = std.mem.zeroes(c.z_command),
node: *Event,
id: u64 = 0, // Private monotonically increasing native identity.
tag: u64 = 0,
kind: u32 = 0,
cancelled: bool = false,
native_deferred: bool = false,
completion: Completion = .request,
pins: std.ArrayList(*Resource) = .empty,
file_operation: ?FileOperation = null,
io_status: abi.Status = abi.OK,
io_result: c.z_request_result = std.mem.zeroes(c.z_request_result),
io_prepared: ?*anyopaque = null,

96
desktop/vendor/uhdk/src/Resource.zig vendored Normal file
View File

@ -0,0 +1,96 @@
//! Stable handle storage. The active payload determines which fields are valid.
const Resource = @This();
const std = @import("std");
const c = @import("native");
const Application = @import("Application.zig");
app: *Application,
gpa: std.mem.Allocator,
arena: std.heap.ArenaAllocator,
next: ?*Resource = null,
alive: bool = true,
ready: bool,
creation_status: u32 = 0,
refs: usize = 1,
native: ?*anyopaque = null,
payload: Payload,
pub const Kind = enum(u32) {
window = c.Z_KIND_WINDOW,
file = c.Z_KIND_FILE,
menu = c.Z_KIND_MENU,
watch = c.Z_KIND_WATCH,
tray = c.Z_KIND_TRAY,
};
pub const Payload = union(Kind) {
window: Window,
file: File,
menu: Menu,
watch: Watch,
tray: Tray,
};
pub const Window = struct {
cycles: @import("Cycles.zig") = .{},
parent: ?*Resource = null,
metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics),
gl_requested: bool = false,
gl_ready: bool = false,
gl_status: u32 = 0,
bracket: bool = false,
frame_cpu_start: u64 = 0,
swap_cpu_time: u64 = 0,
presented: bool = false,
};
pub const File = struct {
native_path: []const u8 = &.{},
path: [:0]const u8 = "",
uri: []const u8 = "",
display: []const u8 = "",
};
pub const Menu = struct {
owns_submenus: bool = false,
items: []c.uhdk_menu_item = &.{},
};
pub const Watch = struct {
owner: ?*Resource = null,
};
pub const TraySnapshot = struct {
arena: std.heap.ArenaAllocator,
desc: c.uhdk_tray_desc,
};
pub const Tray = struct {
snapshot: ?*TraySnapshot = null,
state: c.uhdk_tray_state = .{
.struct_size = @sizeOf(c.uhdk_tray_state),
.status = c.UHDK_STATUS_UNAVAILABLE,
.available = 0,
},
};
pub fn init(application: *Application, resource_kind: Kind) Resource {
return .{
.app = application,
.gpa = application.gpa,
.arena = .init(application.gpa),
.ready = resource_kind != .window,
.payload = switch (resource_kind) {
.window => .{ .window = .{} },
.file => .{ .file = .{} },
.menu => .{ .menu = .{} },
.watch => .{ .watch = .{} },
.tray => .{ .tray = .{} },
},
};
}
pub fn kind(self: *const Resource) u32 {
return @intFromEnum(std.meta.activeTag(self.payload));
}

87
desktop/vendor/uhdk/src/abi.zig vendored Normal file
View File

@ -0,0 +1,87 @@
//! Validation and representation at the C ABI boundary.
const std = @import("std");
const c = @import("native");
const runtime = @import("runtime.zig");
pub const OK = c.UHDK_STATUS_OK;
pub const INVALID = c.UHDK_STATUS_INVALID_ARGUMENT;
pub const OOM = c.UHDK_STATUS_OUT_OF_MEMORY;
pub const UNAVAILABLE = c.UHDK_STATUS_UNAVAILABLE;
pub const CANCELLED = c.UHDK_STATUS_CANCELLED;
pub const Status = c.uhdk_status;
pub const Arena = std.heap.ArenaAllocator;
pub const IO_READ = 100;
pub const IO_WRITE = 101;
pub const IO_INFO = 102;
pub fn validSpan(ptr: ?*const anyopaque, len: u64) bool {
return len <= std.math.maxInt(usize) and (len == 0 or ptr != null);
}
pub fn bytes(t: c.uhdk_bytes) []const u8 {
return if (t.len == 0) "" else @as([*]const u8, @ptrCast(t.ptr))[0..@intCast(t.len)];
}
pub fn textBytes(text: c.uhdk_text) []const u8 {
return bytes(.{ .ptr = @ptrCast(text.ptr), .len = text.len });
}
pub fn validText(t: c.uhdk_text, no_nul: bool) bool {
return validSpan(t.ptr, t.len) and
std.unicode.utf8ValidateSlice(textBytes(t)) and
(!no_nul or std.mem.findScalar(u8, textBytes(t), 0) == null);
}
pub fn textSpan(s: []const u8) c.uhdk_text {
return .{ .ptr = s.ptr, .len = s.len };
}
pub fn copyText(arena: std.mem.Allocator, t: c.uhdk_text) !c.uhdk_text {
return textSpan(try arena.dupe(u8, textBytes(t)));
}
pub fn copyBytes(arena: std.mem.Allocator, t: c.uhdk_bytes) !c.uhdk_bytes {
const b = try arena.dupe(u8, bytes(t));
return .{ .ptr = b.ptr, .len = b.len };
}
pub fn validDescriptor(comptime T: type, handle: [*c]const T) bool {
return handle != null and handle.*.struct_size >= @sizeOf(T);
}
pub fn writeOutput(comptime T: type, dest: [*c]T, value: T) Status {
if (dest == null or dest.*.struct_size < @sizeOf(T)) return INVALID;
dest.* = value;
dest.*.struct_size = @sizeOf(T);
return OK;
}
pub fn finiteSize(s: c.uhdk_size) bool {
return std.math.isFinite(s.width) and
std.math.isFinite(s.height) and
s.width >= 0 and s.height >= 0 and
s.width <= 65536 and s.height <= 65536;
}
pub fn boundary(s: []const u8, offset: u64) bool {
return offset <= s.len and (offset == s.len or (s[@intCast(offset)] & 0xC0) != 0x80);
}
pub fn statusMessage(status: Status) c.uhdk_text {
return textSpan(switch (status) {
c.UHDK_STATUS_OK => "Success",
c.UHDK_STATUS_CANCELLED => "Operation cancelled",
c.UHDK_STATUS_UNSUPPORTED => "Operation not supported",
c.UHDK_STATUS_INVALID_ARGUMENT => "Invalid argument",
c.UHDK_STATUS_OUT_OF_MEMORY => "Out of memory",
c.UHDK_STATUS_PERMISSION_DENIED => "Permission denied",
c.UHDK_STATUS_UNAVAILABLE => "Resource unavailable",
c.UHDK_STATUS_NOT_FOUND => "Not found",
c.UHDK_STATUS_BUSY => "Resource or request tag is busy",
c.UHDK_STATUS_WRONG_THREAD => "Called from the wrong thread",
c.UHDK_STATUS_OS_ERROR => "Operating system error",
c.UHDK_STATUS_BUFFER_TOO_SMALL => "Buffer or requested size limit is too small",
else => "Unknown UHDK status",
});
}

344
desktop/vendor/uhdk/src/api/app.zig vendored Normal file
View File

@ -0,0 +1,344 @@
//! C ABI entry points for app.
const std = @import("std");
const profile = @import("profile");
const backend_kind = switch (@import("builtin").os.tag) {
.windows => c.UHDK_BACKEND_WINDOWS,
.linux => c.UHDK_BACKEND_WAYLAND,
else => c.UHDK_BACKEND_MACOS,
};
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Application = @import("../Application.zig");
const MinimalIo = @import("../MinimalIo.zig");
pub var singleton: bool = false; // OS-main-thread lifecycle gate.
pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status {
out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
if (!abi.validText(desc.title, true) or !abi.validText(desc.application_id, true)) return abi.INVALID;
if (desc.preferred_backend != c.UHDK_BACKEND_AUTO and desc.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED;
if (singleton) return c.UHDK_STATUS_BUSY;
const gpa = profile.allocator();
const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.title)) catch return abi.OOM;
application.application_id = gpa.dupe(u8, abi.textBytes(desc.application_id)) catch {
application.scratch.deinit();
gpa.free(application.name);
gpa.destroy(application);
return abi.OOM;
};
singleton = true;
const status = initialize(application);
if (status != abi.OK) {
releaseStorage(application);
return status;
}
out.* = runtime.toAppHandle(application);
return abi.OK;
}
fn initialize(application: *Application) abi.Status {
const handle = runtime.toAppHandle(application);
profile.thread("UHDK platform");
const status = c.z_native_start(handle, abi.textSpan(application.name));
if (status != abi.OK) {
return status;
}
application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch {
c.z_native_finish();
return abi.OOM;
};
application.native_started = true;
application.running = true;
application.main_thread = std.Thread.getCurrentId();
return abi.OK;
}
fn shutdown(application: *Application) void {
const handle = runtime.toAppHandle(application);
std.debug.assert(!runtime.hasFrame(application));
_ = c.z_native_gl(null, 4, null);
application.lock();
application.stopping = true;
application.unlock();
// Keep native services alive while cancellation, completion, and destruction drain.
while (true) {
runtime.dispatch(handle);
application.lock();
const drained = application.requests == null and application.queue_head == null;
application.unlock();
if (drained) break;
c.z_native_pump(10 * std.time.ns_per_ms);
}
application.lock();
application.io_exit = true;
application.io_available.set(application.io);
application.unlock();
if (application.io_worker) |worker| worker.join();
application.io_worker = null;
// Native sources stop before any of their Zig records can be released.
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.payload == .tray) {
object.alive = false;
if (object.native) |native| c.z_native_destroy(c.Z_KIND_TRAY, native);
object.native = null;
@import("tray.zig").clear(object);
}
if (object.kind() == c.Z_KIND_WATCH and object.native != null) {
c.z_native_destroy(object.kind(), object.native);
object.native = null;
}
}
cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.kind() == c.Z_KIND_WINDOW and object.native != null) {
if (object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) {
c.z_native_destroy(c.Z_KIND_GL, object.native);
object.payload.window.gl_ready = false;
}
c.z_native_destroy(object.kind(), object.native);
object.native = null;
}
}
c.z_native_finish();
application.native_started = false;
application.running = false;
application.main_thread = null;
}
pub fn poll(
handle: ?*c.uhdk_session,
timeout: u64,
out: [*c]c.uhdk_event_list,
) abi.Status {
if (handle == null or out == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)");
defer poll_zone.end();
runtime.destroyEvents(application.published);
application.published = null;
application.scratch.reset();
out.* = .{ .ptr = null, .len = 0 };
const start = runtime.now(application.io);
const end = start +| timeout;
runtime.dispatch(handle);
if (application.native_started) c.z_native_pump(0);
runtime.dispatch(handle);
application.lock();
defer application.unlock();
if (application.native_error != abi.OK) return application.native_error;
if (application.stopped_seen) return abi.UNAVAILABLE;
if (application.deadline != 0 and runtime.now(application.io) - application.epoch >= application.deadline) {
application.deadline = 0;
application.unlock();
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
application.lock();
}
while (application.pending_head == null and application.event_error == abi.OK and application.native_error == abi.OK) {
const current = runtime.now(application.io);
if (application.deadline != 0 and current - application.epoch >= application.deadline) {
application.deadline = 0;
application.unlock();
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
application.lock();
break;
}
if (current >= end) return abi.OK;
const wake_time = if (application.deadline == 0) end else @min(end, application.epoch +| application.deadline);
const ns = wake_time -| current;
application.unlock();
const wait_zone = profile.begin(@src(), "UHDK wait for events");
defer wait_zone.end();
if (application.native_started) c.z_native_pump(ns);
runtime.dispatch(handle);
application.lock();
}
if (application.native_error != abi.OK) return application.native_error;
if (application.event_error != abi.OK) {
const err = application.event_error;
application.event_error = abi.OK;
return err;
}
var cursor = application.pending_head;
var count: usize = 0;
while (cursor) |node| : (cursor = node.next) {
count += 1;
}
const allocator = application.scratch.allocator();
const events = allocator.alloc(c.uhdk_event, count) catch return abi.OOM;
var len: usize = 0;
cursor = application.pending_head;
// Do not consume nodes until the entire batch has been converted. On OOM,
// the queue (and all terminal request completions) remains retryable.
while (cursor) |node| : (cursor = node.next) {
const event = node.event;
if (event.window != null and !runtime.fromObjectHandle(event.window).alive) continue;
if (event.type == c.UHDK_EVENT_WATCH and !runtime.fromObjectHandle(event.data.watch.watch).alive) continue;
const tray = switch (event.type) {
c.UHDK_EVENT_TRAY_ACTIVATE => event.data.tray.tray,
c.UHDK_EVENT_TRAY_STATE => event.data.tray_state.tray,
c.UHDK_EVENT_MENU_COMMAND => event.data.menu.tray,
else => null,
};
if (tray != null and !runtime.fromObjectHandle(tray).alive) continue;
events[len] = @import("../EventPayload.zig").pack(allocator, event) catch return abi.OOM;
len += 1;
}
application.published = application.pending_head;
application.pending_head = null;
application.pending_tail = null;
cursor = application.published;
while (cursor) |node| : (cursor = node.next) {
// Payload bytes now live in scratch. Keep only resource pins and nodes
// until the next poll; their private producer spans are no longer read.
_ = node.arena.reset(.free_all);
if (node.event.type == c.UHDK_EVENT_STOPPED) application.stopped_seen = true;
}
out.* = .{ .ptr = if (len == 0) null else events.ptr, .len = len };
application.stats.event_count +|= out.*.len;
return abi.OK;
}
pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return abi.writeOutput(c.uhdk_stats, out, application.stats);
}
pub export fn uhdk_quit(handle: ?*c.uhdk_session) void {
if (handle == null) return;
const application = runtime.fromAppHandle(handle);
application.lock();
application.stopping = true;
application.unlock();
c.z_native_wake();
}
pub export fn uhdk_wake(handle: ?*c.uhdk_session) void {
if (handle != null) {
runtime.simpleEvent(runtime.fromAppHandle(handle), c.UHDK_EVENT_WAKE);
c.z_native_wake();
}
}
pub export fn uhdk_get_time_ns(handle: ?*c.uhdk_session) u64 {
const application = runtime.fromAppHandle(handle);
return runtime.now(application.io) - application.epoch;
}
pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
application.deadline = deadline;
application.notify();
application.unlock();
return abi.OK;
}
pub export fn uhdk_get_backend(handle: ?*c.uhdk_session) c.uhdk_backend {
if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").backend(handle);
return backend_kind;
}
pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capability) c.uhdk_bool {
if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").capability(handle, cap);
return switch (cap) {
c.UHDK_CAP_POINTER_CONFINEMENT => @intFromBool(@import("builtin").os.tag == .windows),
c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL, c.UHDK_CAP_TRAY => 1,
else => 0,
};
}
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status {
if (handle == null or tag == 0) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) {
if (command.completion == .request and command.tag == tag) {
command.cancelled = true;
application.unlock();
c.z_native_wake();
return abi.OK;
}
}
application.unlock();
return c.UHDK_STATUS_NOT_FOUND;
}
pub fn destroy(handle: ?*c.uhdk_session) void {
if (handle == null) return;
const application = runtime.fromAppHandle(handle);
std.debug.assert(c.z_native_is_main_thread() != 0);
shutdown(application);
releaseStorage(application);
}
fn releaseStorage(application: *Application) void {
runtime.destroyEvents(application.published);
runtime.destroyEvents(application.pending_head);
application.scratch.deinit();
var cursor = application.objects;
while (cursor) |object| {
cursor = object.next;
if (object.native != null) c.z_native_destroy(object.kind(), object.native);
object.arena.deinit();
application.gpa.destroy(object);
}
const gpa = application.gpa;
gpa.free(application.name);
gpa.free(application.application_id);
gpa.destroy(application);
singleton = false;
}
pub export fn uhdk_status_message(status: abi.Status) c.uhdk_text {
return abi.statusMessage(status);
}

82
desktop/vendor/uhdk/src/api/desktop.zig vendored Normal file
View File

@ -0,0 +1,82 @@
//! C ABI entry points for desktop.
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_clipboard_write_text(
handle: ?*c.uhdk_session,
text: c.uhdk_text,
) abi.Status {
if (!abi.validText(text, false)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_CLIP_WRITE) catch |err| return runtime.applicationError(err);
command.data.text = abi.copyText(command.arena.allocator(), text) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submitCommand(runtime.fromAppHandle(handle), command);
}
pub export fn uhdk_clipboard_read_text_async(
handle: ?*c.uhdk_session,
limit: u64,
tag: u64,
) abi.Status {
const command = runtime.createAppCommand(handle, c.Z_CLIP_READ) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
command.data.limit = limit;
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_shell_open_url_async(
handle: ?*c.uhdk_session,
text: c.uhdk_text,
tag: u64,
) abi.Status {
if (!abi.validText(text, true) or text.len == 0) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_URL) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_SHELL;
command.data.text = abi.copyText(command.arena.allocator(), text) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_set_icon(
handle: ?*c.uhdk_session,
image: [*c]const c.uhdk_image,
) abi.Status {
if (!abi.validDescriptor(c.uhdk_image, image)) return abi.INVALID;
const i = image.*;
if (i.reserved != 0 or
i.width == 0 or
i.height == 0 or
i.width > 4096 or
i.height > 4096 or
i.pixels.len < @as(u64, i.width) * i.height * 4 or
!abi.validSpan(i.pixels.ptr, i.pixels.len)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_ICON) catch |err| return runtime.applicationError(err);
command.data.image = i;
command.data.image.pixels = abi.copyBytes(command.arena.allocator(), i.pixels) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submitCommand(runtime.fromAppHandle(handle), command);
}
pub export fn uhdk_get_preferences(
handle: ?*c.uhdk_session,
out: [*c]c.uhdk_preferences,
) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
defer application.unlock();
return abi.writeOutput(c.uhdk_preferences, out, application.preferences);
}

161
desktop/vendor/uhdk/src/api/files.zig vendored Normal file
View File

@ -0,0 +1,161 @@
//! C ABI entry points for files.
const std = @import("std");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_file_dialog_show_async(
handle: ?*c.uhdk_session,
desc: [*c]const c.uhdk_file_dialog_desc,
tag: u64,
) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_file_dialog_desc, desc)) return abi.INVALID;
const d = desc.*;
if (d.kind > c.UHDK_DIALOG_SAVE_FILE or
!abi.validText(d.title, true) or
!abi.validText(d.accept_label, true) or
!abi.validText(d.suggested_name, true) or
!abi.validSpan(d.filters, d.filters_len) or
d.filters_len > 64) return abi.INVALID;
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or
!runtime.fromObjectHandle(d.parent).alive)) return abi.INVALID;
if (d.initial_directory != null and runtime.fromObjectHandle(d.initial_directory).app != runtime.fromAppHandle(handle)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_DIALOG) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_FILE_DIALOG;
command.data.dialog = d;
runtime.copyDialog(command) catch |err| {
runtime.abandon(command);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
};
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_file_create_from_native_path(
handle: ?*c.uhdk_session,
path: c.uhdk_bytes,
out: [*c]?*c.uhdk_file,
) abi.Status {
if (handle == null or
out == null or
!abi.validSpan(path.ptr, path.len) or
path.len == 0) return abi.INVALID;
if (@import("builtin").os.tag != .windows and
(abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null);
if (status != abi.OK) {
runtime.release(object);
return status;
}
out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK;
}
pub export fn uhdk_file_create_from_uri(
handle: ?*c.uhdk_session,
uri: c.uhdk_text,
out: [*c]?*c.uhdk_file,
) abi.Status {
if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null);
if (status != abi.OK) {
runtime.release(object);
return status;
}
out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK;
}
pub export fn uhdk_file_retain(handle: ?*c.uhdk_file) void {
if (handle != null) runtime.retain(runtime.fromObjectHandle(handle));
}
pub export fn uhdk_file_release(handle: ?*c.uhdk_file) void {
if (handle != null) runtime.release(runtime.fromObjectHandle(handle));
}
pub export fn uhdk_file_copy_representation(
handle: ?*c.uhdk_file,
form: u32,
buffer: [*c]u8,
capacity: u64,
out: [*c]u64,
) abi.Status {
if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE);
if (status != abi.OK) return status;
const data = switch (form) {
c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display,
c.UHDK_FILE_URI => object.payload.file.uri,
c.UHDK_FILE_NATIVE_PATH => object.payload.file.native_path,
else => return abi.INVALID,
};
if (@import("builtin").os.tag == .windows and form == c.UHDK_FILE_URI and data.len == 0)
return c.UHDK_STATUS_UNSUPPORTED;
out.* = data.len;
if (buffer == null and capacity == 0) return abi.OK;
if (capacity < data.len) return c.UHDK_STATUS_BUFFER_TOO_SMALL;
if (data.len > 0) @memcpy(buffer[0..data.len], data);
return abi.OK;
}
pub export fn uhdk_file_read_all_async(handle: ?*c.uhdk_file, limit: u64, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_READ) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_READ;
command.data.limit = limit;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_write_all_async(
handle: ?*c.uhdk_file,
data: c.uhdk_bytes,
tag: u64,
) abi.Status {
if (!abi.validSpan(data.ptr, data.len)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_WRITE) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_WRITE;
command.data.bytes = abi.copyBytes(command.arena.allocator(), data) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_get_info_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_INFO) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_INFO;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, c.Z_WATCH) catch |err| return runtime.objectError(err);
const f = runtime.fromObjectHandle(handle);
const object = runtime.createObject(f.app, c.Z_KIND_WATCH) catch {
runtime.abandon(command);
return abi.OOM;
};
object.payload.watch.owner = f;
runtime.retain(f);
command.data.other = object;
command.kind = c.UHDK_REQUEST_WATCH;
return runtime.submit(f.app, command, tag);
}
pub export fn uhdk_watch_destroy(handle: ?*c.uhdk_watch) void {
if (handle != null) runtime.destroyObject(runtime.fromObjectHandle(handle));
}

104
desktop/vendor/uhdk/src/api/graphics.zig vendored Normal file
View File

@ -0,0 +1,104 @@
//! Private GL ownership and presentation for session boundaries.
const std = @import("std");
const profile = @import("profile");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub fn create(handle: ?*c.uhdk_window) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err);
const w = runtime.fromObjectHandle(handle);
if (w.payload.window.gl_requested) {
runtime.abandon(command);
return c.UHDK_STATUS_BUSY;
}
w.payload.window.gl_requested = true;
return runtime.submitResource(w.app, command);
}
pub fn acquire(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK acquire GL context");
defer zone.end();
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
const status = runtime.glCall(handle, 1, null);
if (status == abi.OK) {
object.payload.window.bracket = true;
object.payload.window.frame_cpu_start = runtime.threadCpuTime(object.app.io);
object.payload.window.swap_cpu_time = 0;
object.payload.window.presented = false;
}
return status;
}
pub fn release(handle: ?*c.uhdk_window) abi.Status {
const status = runtime.glCall(handle, 2, null);
if (status == abi.OK) {
const object = runtime.fromObjectHandle(handle);
object.payload.window.bracket = false;
if (object.payload.window.presented) {
const stats = &object.app.stats;
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.window.frame_cpu_start;
stats.render_time_ns = elapsed -| object.payload.window.swap_cpu_time;
stats.frame_count +|= 1;
const now = runtime.now(object.app.io);
if (object.app.last_frame_time) |previous| {
const interval = now -| previous;
stats.frames_per_second = if (interval == 0) 0 else @as(f32, std.time.ns_per_s) / @as(f32, @floatFromInt(interval));
}
object.app.last_frame_time = now;
}
}
return status;
}
pub fn present(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK present (includes vsync)");
defer zone.end();
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (valid != abi.OK) return valid;
if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
// Exclude even driver CPU work/spinning inside presentation, not just sleep.
const start = runtime.threadCpuTime(object.app.io);
const status = runtime.glCall(handle, 6, null);
object.payload.window.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start;
if (status == abi.OK) object.payload.window.presented = true;
return status;
}
pub fn setSwapInterval(
handle: ?*c.uhdk_window,
interval: i32,
) abi.Status {
if (interval != 0 and interval != 1) return abi.INVALID;
var value = interval;
return runtime.glCall(handle, 7, &value);
}
pub fn getProc(
handle: ?*c.uhdk_window,
name: c.uhdk_text,
out: [*c]c.uhdk_gl_proc,
) abi.Status {
if (handle == null or out == null or !abi.validText(name, true) or name.len == 0 or name.len > 255)
return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
return c.z_native_gl_proc(object.native, name, out);
}

85
desktop/vendor/uhdk/src/api/input.zig vendored Normal file
View File

@ -0,0 +1,85 @@
//! C ABI entry points for input.
const std = @import("std");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_window_set_function_key_policy(handle: ?*c.uhdk_window, policy: u32) abi.Status {
if (policy > c.UHDK_FUNCTION_KEYS_APPLICATION) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_FUNCTION_KEYS, policy);
}
pub export fn uhdk_window_set_cursor_shape(handle: ?*c.uhdk_window, shape: u32) abi.Status {
if (shape > c.UHDK_CURSOR_HIDDEN) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_CURSOR, shape);
}
pub export fn uhdk_window_set_pointer_mode(handle: ?*c.uhdk_window, mode: u32) abi.Status {
if (mode > c.UHDK_POINTER_CONFINED) return abi.INVALID;
const command = runtime.createObjectCommand(
handle,
c.Z_KIND_WINDOW,
c.Z_POINTER,
) catch |err| return runtime.objectError(err);
const application = runtime.fromObjectHandle(handle).app;
if (mode == c.UHDK_POINTER_CONFINED) {
const supported = @import("app.zig").uhdk_has_capability(
runtime.toAppHandle(application),
c.UHDK_CAP_POINTER_CONFINEMENT,
);
if (supported == 0) {
runtime.abandon(command);
return c.UHDK_STATUS_UNSUPPORTED;
}
}
command.data.number = mode;
return runtime.submitCommand(application, command);
}
pub export fn uhdk_window_set_text_input(handle: ?*c.uhdk_window, enabled: c.uhdk_bool) abi.Status {
if (enabled != 0 and enabled != 1) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TEXT_ENABLE, @intCast(enabled));
}
pub export fn uhdk_window_cancel_composition(handle: ?*c.uhdk_window) abi.Status {
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TEXT_CANCEL, 0);
}
pub export fn uhdk_window_set_text_state(
handle: ?*c.uhdk_window,
state: [*c]const c.uhdk_text_state,
) abi.Status {
if (!abi.validDescriptor(c.uhdk_text_state, state) or
state.*.reserved != 0 or
!abi.validText(state.*.surrounding_text, false)) return abi.INVALID;
const s = state.*;
const txt = abi.textBytes(s.surrounding_text);
if (s.selection_start > txt.len or
s.selection_len > txt.len - s.selection_start or
!abi.boundary(txt, s.selection_start) or
!abi.boundary(txt, s.selection_start + s.selection_len) or
s.document_offset > std.math.maxInt(u64) - txt.len) return abi.INVALID;
if (!std.math.isFinite(s.caret.x) or
!std.math.isFinite(s.caret.y) or
!abi.finiteSize(.{ .width = s.caret.width, .height = s.caret.height })) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_TEXT_STATE) catch |err| return runtime.objectError(err);
command.data.text_state = s;
command.data.text_state.surrounding_text = abi.copyText(command.arena.allocator(), s.surrounding_text) catch {
runtime.abandon(command);
return abi.OOM;
};
const application = runtime.fromObjectHandle(handle).app;
application.lock();
if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command;
application.queue_tail = command;
application.unlock();
c.z_native_wake();
return abi.OK;
}
pub export fn uhdk_window_set_drop_enabled(handle: ?*c.uhdk_window, enabled: c.uhdk_bool) abi.Status {
if (enabled != 0 and enabled != 1) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_DROP, @intCast(enabled));
}

122
desktop/vendor/uhdk/src/api/menus.zig vendored Normal file
View File

@ -0,0 +1,122 @@
//! C ABI entry points for menus.
const std = @import("std");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_menu_create(
handle: ?*c.uhdk_session,
items: [*c]const c.uhdk_menu_item,
len: u64,
out: [*c]?*c.uhdk_menu,
) abi.Status {
if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(application, c.Z_KIND_MENU) catch return abi.OOM;
object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch {
runtime.release(object);
return abi.OOM;
};
for (object.payload.menu.items, 0..) |*item, i| {
item.* = items[i];
if (!abi.validText(item.label, true) or
item.flags & ~@as(u32, 7) != 0 or
item.role > c.UHDK_MENU_ROLE_REDO or
(item.command_id == 0 and item.flags & c.UHDK_MENU_SEPARATOR == 0 and item.submenu == null and item.role == c.UHDK_MENU_ROLE_NONE))
{
runtime.release(object);
return abi.INVALID;
}
if (item.submenu != null and (runtime.fromObjectHandle(item.submenu).app != application or
!runtime.fromObjectHandle(item.submenu).alive))
{
runtime.release(object);
return abi.INVALID;
}
item.label = abi.copyText(object.arena.allocator(), item.label) catch {
runtime.release(object);
return abi.OOM;
};
}
var ids: std.AutoHashMap(u64, void) = .init(application.gpa);
defer ids.deinit();
runtime.validateMenu(object, &ids, 0) catch |err| {
runtime.release(object);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
};
for (object.payload.menu.items) |item| if (item.submenu) |sub| {
runtime.retain(runtime.fromObjectHandle(sub));
};
object.payload.menu.owns_submenus = true;
out.* = runtime.castHandle(*c.uhdk_menu, object);
return abi.OK;
}
pub export fn uhdk_menu_retain(handle: ?*c.uhdk_menu) void {
if (handle != null) runtime.retain(runtime.fromObjectHandle(handle));
}
pub export fn uhdk_menu_release(handle: ?*c.uhdk_menu) void {
if (handle != null) runtime.release(runtime.fromObjectHandle(handle));
}
pub export fn uhdk_set_menu(
handle: ?*c.uhdk_session,
menu: ?*c.uhdk_menu,
) abi.Status {
return runtime.attachMenu(handle, null, menu);
}
pub export fn uhdk_window_set_menu(
handle: ?*c.uhdk_window,
menu: ?*c.uhdk_menu,
) abi.Status {
if (handle == null) return abi.INVALID;
return runtime.attachMenu(runtime.toAppHandle(runtime.fromObjectHandle(handle).app), handle, menu);
}
pub export fn uhdk_menu_set_item_flags(
handle: ?*c.uhdk_menu,
id: u64,
flags: u32,
) abi.Status {
if (id == 0 or flags & ~@as(u32, 3) != 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_MENU, c.Z_MENU_FLAGS) catch |err| return runtime.objectError(err);
command.data.number = id;
command.data.limit = flags;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_menu_popup_async(
handle: ?*c.uhdk_menu,
window: ?*c.uhdk_window,
point: c.uhdk_point,
tag: u64,
) abi.Status {
if (handle == null or
window == null or
runtime.fromObjectHandle(handle).app != runtime.fromObjectHandle(window).app or
!runtime.fromObjectHandle(window).alive or
!std.math.isFinite(point.x) or
!std.math.isFinite(point.y)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_MENU, c.Z_POPUP) catch |err| return runtime.objectError(err);
command.data.other = runtime.fromObjectHandle(window);
runtime.pin(&command.pins, runtime.fromObjectHandle(window)) catch {
runtime.abandon(command);
return abi.OOM;
};
command.data.point = point;
command.kind = c.UHDK_REQUEST_MENU_POPUP;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}

263
desktop/vendor/uhdk/src/api/session.zig vendored Normal file
View File

@ -0,0 +1,263 @@
//! Main-thread application iterations. Native work runs only outside GL ownership.
const std = @import("std");
const c = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
const Application = @import("../Application.zig");
const app = @import("app.zig");
const windows = @import("windows.zig");
const graphics = @import("graphics.zig");
fn state(session: *c.uhdk_session) *Application {
return @ptrCast(@alignCast(session));
}
fn handle(a: *Application) *c.uhdk_session {
return runtime.toAppHandle(a);
}
pub fn acquire(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window);
if (window.payload.window.bracket) return abi.OK;
return graphics.acquire(a.session_window);
}
pub fn release(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window);
if (!window.payload.window.bracket) return abi.OK;
return graphics.release(a.session_window);
}
pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
const object = runtime.fromObjectHandle(resource);
while (!object.ready) {
if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status;
if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
}
return abi.OK;
}
fn readyGl(a: *Application, deadline: u64) abi.Status {
const window = runtime.fromObjectHandle(a.session_window);
while (!window.payload.window.gl_ready) {
if (!window.alive) return abi.UNAVAILABLE;
if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
}
return window.payload.window.gl_status;
}
pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
var opts = std.mem.zeroes(c.uhdk_options);
if (options != null) {
if (!abi.validDescriptor(c.uhdk_options, options)) return abi.INVALID;
opts = options.*;
}
if (opts.render_mode > c.UHDK_RENDER_ON_DEMAND) return abi.INVALID;
if (opts.undecorated != 0 and opts.undecorated != 1) return abi.INVALID;
if (opts.fixed_size != 0 and opts.fixed_size != 1) return abi.INVALID;
if (opts.disable_vsync != 0 and opts.disable_vsync != 1) return abi.INVALID;
if (opts.request_focus != 0 and opts.request_focus != 1) return abi.INVALID;
if (opts.no_opengl != 0 and opts.no_opengl != 1) return abi.INVALID;
if (opts.title.len == 0) opts.title = abi.textSpan("UHDK");
var application: ?*c.uhdk_session = null;
var status = app.create(&opts, &application);
if (status != abi.OK) return status;
const a = runtime.fromAppHandle(application);
var success = false;
defer if (!success) {
_ = release(a);
app.destroy(application);
};
a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND;
var window = std.mem.zeroes(c.z_window_desc);
window.struct_size = @sizeOf(c.z_window_desc);
window.title = opts.title;
window.flags = if (opts.no_opengl == 0) c.Z_WINDOW_OPENGL else 0;
window.style = .{
.struct_size = @sizeOf(c.uhdk_window_style),
.decorated = 1 - opts.undecorated,
.resizable = 1 - opts.fixed_size,
.reserved = 0,
};
window.content_size = opts.content_size;
if (window.content_size.width == 0) window.content_size.width = 800;
if (window.content_size.height == 0) window.content_size.height = 600;
window.min_size = opts.min_size;
window.max_size = opts.max_size;
if (opts.startup_timeout_ns != 0) a.startup_timeout_ns = opts.startup_timeout_ns;
const deadline = runtime.now(a.io) +| a.startup_timeout_ns;
status = windows.queueCreate(application, &window, &a.session_window);
if (status != abi.OK) return status;
status = ready(a, a.session_window, deadline);
if (status != abi.OK) return status;
if (opts.no_opengl == 0) {
status = graphics.create(a.session_window);
if (status != abi.OK) return status;
status = readyGl(a, deadline);
if (status != abi.OK) return status;
a.session_has_gl = true;
}
status = windows.uhdk_window_set_visible(a.session_window, 1);
if (status != abi.OK) return status;
if (opts.request_focus != 0) {
status = windows.uhdk_window_request_focus(a.session_window);
if (status != abi.OK) return status;
}
runtime.dispatch(application);
c.z_native_pump(0);
if (a.native_error != abi.OK) return a.native_error;
status = acquire(a);
if (status != abi.OK) return status;
if (opts.no_opengl == 0) {
status = graphics.setSwapInterval(a.session_window, 1 - @as(i32, opts.disable_vsync));
if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status;
if (c.z_gl_load(runtime.fromObjectHandle(a.session_window).native, &a.session_gl) == 0) {
return c.UHDK_STATUS_UNSUPPORTED;
}
}
out.* = @ptrCast(a);
success = true;
return abi.OK;
}
pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool {
const a = state(session orelse return 0);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0;
if (out == null or a.session_active) {
a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY;
return 0;
}
out.* = std.mem.zeroes(c.uhdk_frame);
if (a.session_status != abi.OK or a.stopped_seen) return 0;
var metrics = std.mem.zeroes(c.uhdk_window_metrics);
metrics.struct_size = @sizeOf(c.uhdk_window_metrics);
_ = windows.uhdk_window_get_metrics(a.session_window, &metrics);
const wait = !a.session_first and (a.session_on_demand or !drawable(metrics));
a.session_status = release(a);
if (a.session_status != abi.OK) return 0;
const poll_status = app.poll(handle(a), if (wait) std.math.maxInt(u64) else 0, &out.*.events);
// Restore GL ownership even after polling fails so cleanup can delete resources.
const acquire_status = acquire(a);
a.session_status = if (poll_status != abi.OK) poll_status else acquire_status;
if (a.session_status != abi.OK) return 0;
a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics);
if (a.session_status != abi.OK) return 0;
out.*.gl = if (a.session_has_gl) &a.session_gl else null;
out.*.metrics = metrics;
a.session_drawable = !a.stopping and drawable(metrics);
out.*.drawable = @intFromBool(a.session_drawable);
a.session_first = false;
a.session_active = true;
return 1;
}
fn drawable(metrics: c.uhdk_window_metrics) bool {
const minimized = if (metrics.observations & c.UHDK_WINDOW_OBSERVE_MINIMIZED != 0)
metrics.minimized != 0
else
metrics.state == c.UHDK_WINDOW_MINIMIZED;
const suspended = metrics.observations & c.UHDK_WINDOW_OBSERVE_SUSPENDED != 0 and metrics.suspended != 0;
return metrics.visible != 0 and metrics.framebuffer_width != 0 and metrics.framebuffer_height != 0 and !minimized and !suspended;
}
pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (!a.session_active) return c.UHDK_STATUS_BUSY;
a.session_active = false;
var status: abi.Status = abi.OK;
if (a.session_drawable and !a.stopping and a.session_has_gl) status = graphics.present(a.session_window);
const end_status = release(a);
const begin_status = if (end_status == abi.OK) acquire(a) else end_status;
a.session_status = if (status != abi.OK) status else begin_status;
return a.session_status;
}
pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return a.session_status;
}
pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions {
const a = state(session orelse return null);
return if (a.session_has_gl) &a.session_gl else null;
}
pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window {
return state(session orelse return null).session_window;
}
pub export fn uhdk_close(session: ?*c.uhdk_session) void {
const a = state(session orelse return);
_ = release(a);
app.destroy(handle(a));
}
pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc) abi.Status {
const a = state(session orelse return abi.INVALID);
if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.getProc(a.session_window, name, out);
}
pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status {
const a = state(session orelse return abi.INVALID);
if (enabled != 0 and enabled != 1) return abi.INVALID;
if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.setSwapInterval(a.session_window, enabled);
}

142
desktop/vendor/uhdk/src/api/tray.zig vendored Normal file
View File

@ -0,0 +1,142 @@
//! Session-owned tray snapshots. Native hosts never borrow application storage.
const std = @import("std");
const c = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
const Resource = @import("../Resource.zig");
const session = @import("session.zig");
fn validMenu(menu: *Resource) bool {
if (menu.payload != .menu or !menu.alive) return false;
for (menu.payload.menu.items) |item| {
if (item.role != c.UHDK_MENU_ROLE_NONE and item.role != c.UHDK_MENU_ROLE_QUIT) return false;
if (item.submenu) |sub| if (!validMenu(runtime.fromObjectHandle(sub))) return false;
}
return true;
}
fn snapshot(object: *Resource, desc: [*c]const c.uhdk_tray_desc) !*Resource.TraySnapshot {
if (!abi.validDescriptor(c.uhdk_tray_desc, desc)) return error.Invalid;
const d = desc.*;
const icon = d.icon;
if (d.reserved != 0 or d.hidden < 0 or d.hidden > 1) return error.Invalid;
if (d.menu_on_primary < 0 or d.menu_on_primary > 1) return error.Invalid;
if (d.template_image < 0 or d.template_image > 1) return error.Invalid;
if (!abi.validText(d.id, true) or d.id.len == 0 or d.id.len > 255) return error.Invalid;
if (!abi.validText(d.title, true) or d.title.len > 4096) return error.Invalid;
if (!abi.validText(d.tooltip, true) or d.tooltip.len > 4096) return error.Invalid;
if (d.menu_on_primary != 0 and d.menu == null) return error.Invalid;
if (!abi.validDescriptor(c.uhdk_image, &d.icon) or icon.reserved != 0) return error.Invalid;
if (icon.width == 0 or icon.height == 0 or icon.width > 512 or icon.height > 512) return error.Invalid;
if (icon.pixels.len != @as(u64, icon.width) * icon.height * 4) return error.Invalid;
if (!abi.validSpan(icon.pixels.ptr, icon.pixels.len)) return error.Invalid;
if (d.menu) |menu| {
const root = runtime.fromObjectHandle(menu);
if (root.app != object.app or !validMenu(root)) return error.Invalid;
}
if (object.payload.tray.snapshot) |old| {
if (!std.mem.eql(u8, abi.textBytes(old.desc.id), abi.textBytes(d.id))) return error.Invalid;
}
{
object.app.lock();
defer object.app.unlock();
var cursor = object.app.objects;
while (cursor) |other| : (cursor = other.next) {
if (other != object and other.alive and other.payload == .tray) {
if (other.payload.tray.snapshot) |s| {
if (std.mem.eql(u8, abi.textBytes(s.desc.id), abi.textBytes(d.id))) return error.Invalid;
}
}
}
}
const s = try object.gpa.create(Resource.TraySnapshot);
errdefer object.gpa.destroy(s);
s.* = .{ .arena = .init(object.gpa), .desc = d };
errdefer s.arena.deinit();
const a = s.arena.allocator();
s.desc.id = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.id), 0));
s.desc.title = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.title), 0));
s.desc.tooltip = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.tooltip), 0));
s.desc.icon.pixels = try abi.copyBytes(a, icon.pixels);
if (d.menu) |menu| runtime.retain(runtime.fromObjectHandle(menu));
return s;
}
pub fn freeSnapshot(object: *Resource, s: *Resource.TraySnapshot) void {
if (s.desc.menu) |menu| runtime.release(runtime.fromObjectHandle(menu));
s.arena.deinit();
object.gpa.destroy(s);
}
pub fn clear(object: *Resource) void {
if (object.payload.tray.snapshot) |s| freeSnapshot(object, s);
object.payload.tray.snapshot = null;
}
fn update(object: *Resource, desc: [*c]const c.uhdk_tray_desc) abi.Status {
if (object.app.session_active) return c.UHDK_STATUS_BUSY;
const next = snapshot(object, desc) catch |err| return runtime.objectError(err);
const released = session.release(object.app);
if (released != abi.OK) {
freeSnapshot(object, next);
return released;
}
const old = object.payload.tray.snapshot;
object.payload.tray.snapshot = next;
const status = c.z_native_tray_update(@ptrCast(object), &next.desc);
if (status != abi.OK) {
object.payload.tray.snapshot = old;
freeSnapshot(object, next);
} else if (old) |s| freeSnapshot(object, s);
const restored = session.acquire(object.app);
if (restored != abi.OK) {
object.app.session_status = restored;
return restored;
}
return status;
}
pub export fn uhdk_tray_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_tray_desc, out: [*c]?*c.uhdk_tray) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (handle == null) return abi.INVALID;
const app = runtime.fromAppHandle(handle);
const ready = runtime.validateMainThreadSessionReady(app);
if (ready != abi.OK) return ready;
if (app.session_active) return c.UHDK_STATUS_BUSY;
const object = runtime.createObject(app, c.Z_KIND_TRAY) catch return abi.OOM;
const status = update(object, desc);
if (status != abi.OK) {
runtime.destroyObject(object);
return status;
}
out.* = @ptrCast(object);
return abi.OK;
}
pub export fn uhdk_tray_update(handle: ?*c.uhdk_tray, desc: [*c]const c.uhdk_tray_desc) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
return update(object, desc);
}
pub export fn uhdk_tray_destroy(handle: ?*c.uhdk_tray) abi.Status {
if (handle == null) return abi.OK;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
runtime.destroyObject(object);
return abi.OK;
}
pub export fn uhdk_tray_get_state(handle: ?*c.uhdk_tray, out: [*c]c.uhdk_tray_state) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
return abi.writeOutput(c.uhdk_tray_state, out, object.payload.tray.state);
}

181
desktop/vendor/uhdk/src/api/windows.zig vendored Normal file
View File

@ -0,0 +1,181 @@
//! C ABI entry points for windows.
const std = @import("std");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub fn queueCreate(
handle: ?*c.uhdk_session,
desc: [*c]const c.z_window_desc,
out: [*c]?*c.uhdk_window,
) abi.Status {
if (handle == null or !abi.validDescriptor(c.z_window_desc, desc)) return abi.INVALID;
if (out == null) return abi.INVALID;
const d = desc.*;
if (d.content_size.width == 0 or d.content_size.height == 0)
return abi.INVALID;
if (!abi.finiteSize(d.content_size) or !abi.finiteSize(d.content_size) or !abi.finiteSize(d.min_size) or !abi.finiteSize(d.max_size))
return abi.INVALID;
if (!validStyle(&d.style) or d.content_size.width == 0 or d.content_size.height == 0 or d.flags & ~@as(u32, c.Z_WINDOW_OPENGL) != 0)
return abi.INVALID;
if ((d.max_size.width != 0 and d.max_size.width < d.min_size.width) or (d.max_size.height != 0 and d.max_size.height < d.min_size.height))
return abi.INVALID;
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or !runtime.fromObjectHandle(d.parent).alive))
return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_WINDOW) catch |err| return runtime.applicationError(err);
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_WINDOW) catch {
runtime.abandon(command);
return abi.OOM;
};
object.payload.window.parent = if (d.parent) |parent| runtime.fromObjectHandle(parent) else null;
command.data.target = object;
command.data.window = d;
command.data.window.title = abi.copyText(command.arena.allocator(), d.title) catch {
runtime.abandon(command);
object.alive = false;
return abi.OOM;
};
const status = runtime.submitResource(runtime.fromAppHandle(handle), command);
if (status != abi.OK) object.alive = false;
if (status == abi.OK) out.* = runtime.castHandle(*c.uhdk_window, object);
return status;
}
fn validStyle(style: [*c]const c.uhdk_window_style) bool {
return abi.validDescriptor(c.uhdk_window_style, style) and
(style.*.decorated == 0 or style.*.decorated == 1) and
(style.*.resizable == 0 or style.*.resizable == 1) and
style.*.reserved == 0;
}
pub export fn uhdk_window_set_title(handle: ?*c.uhdk_window, title: c.uhdk_text) abi.Status {
return runtime.textCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TITLE, title);
}
pub export fn uhdk_window_set_size(handle: ?*c.uhdk_window, size: c.uhdk_size) abi.Status {
if (!abi.finiteSize(size) or size.width == 0 or size.height == 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_SIZE) catch |err| return runtime.objectError(err);
command.data.size = size;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_window_set_state(handle: ?*c.uhdk_window, state: c.uhdk_window_state) abi.Status {
if (state > c.UHDK_WINDOW_FULLSCREEN) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_STATE, state);
}
pub export fn uhdk_window_set_visible(handle: ?*c.uhdk_window, visible: c.uhdk_bool) abi.Status {
if (visible != 0 and visible != 1) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_VISIBLE, @intCast(visible));
}
pub export fn uhdk_window_set_style(
handle: ?*c.uhdk_window,
style: [*c]const c.uhdk_window_style,
) abi.Status {
if (!validStyle(style)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_STYLE) catch |err| return runtime.objectError(err);
command.data.style = style.*;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_window_request_focus(handle: ?*c.uhdk_window) abi.Status {
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_FOCUS, 0);
}
pub export fn uhdk_window_get_metrics(
handle: ?*c.uhdk_window,
out: [*c]c.uhdk_window_metrics,
) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
object.app.lock();
defer object.app.unlock();
return abi.writeOutput(c.uhdk_window_metrics, out, object.payload.window.metrics);
}
pub export fn uhdk_window_invalidate(handle: ?*c.uhdk_window) void {
if (handle != null and runtime.fromObjectHandle(handle).alive) runtime.notifyCommand(runtime.fromObjectHandle(handle), c.Z_REDRAW);
}
pub export fn uhdk_window_get_native(
handle: ?*c.uhdk_window,
out: [*c]c.uhdk_native_window,
) abi.Status {
if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
c.z_native_handles(object.native, out);
return abi.OK;
}
pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_window_desc, out: [*c]?*c.uhdk_window) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID;
const a = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (a.session_active) return c.UHDK_STATUS_BUSY;
const session = @import("session.zig");
const d: c.z_window_desc = .{
.struct_size = @sizeOf(c.z_window_desc),
.flags = 0,
.style = desc.*.style,
.title = desc.*.title,
.content_size = desc.*.content_size,
.min_size = desc.*.min_size,
.max_size = desc.*.max_size,
.parent = desc.*.parent,
};
var status = session.release(a);
if (status != abi.OK) return status;
var window: ?*c.uhdk_window = null;
status = queueCreate(handle, &d, &window);
if (status == abi.OK) status = session.ready(a, window, runtime.now(a.io) +| a.startup_timeout_ns);
if (status != abi.OK and window != null) runtime.destroyObject(runtime.fromObjectHandle(window));
const restored = session.acquire(a);
if (restored != abi.OK) {
a.session_status = restored;
if (status == abi.OK) runtime.destroyObject(runtime.fromObjectHandle(window));
return restored;
}
if (status == abi.OK) out.* = window;
return status;
}
pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status {
if (window == null) return abi.OK;
const object = runtime.fromObjectHandle(window);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
if (object.app.session_window == window) return abi.INVALID;
runtime.destroyObject(object);
return abi.OK;
}

371
desktop/vendor/uhdk/src/arenas.zig vendored Normal file
View File

@ -0,0 +1,371 @@
//! UHDK-owned scratch arena and supporting paged storage.
//! Derived from RibtechEngine lib/p2 at 39697f9afba2933f92361586bf8802c22dfbe709.
//! Maintained as part of UHDK; this is not a vendored dependency.
const std = @import("std");
pub const PoolStatistics = struct {
statName: []const u8,
instanceCount: usize,
memoryReserved: usize,
memoryUsed: usize,
};
// mutex based, fast bump-only allocator
pub const BumpArena = struct {
const PageSize = 8192 * 2;
const SmallAllocPages = PagedVectorAdvanced([PageSize]u8, 1);
smallBumpOffset: usize = 0,
pageIndex: usize = 0,
allocatedBytes: usize = 0,
allocCount: usize = 0,
backing: std.mem.Allocator,
io_context: std.Io,
small: SmallAllocPages,
large: std.heap.ArenaAllocator,
mutex: std.Io.Mutex,
pub var vtable: std.mem.Allocator.VTable = .{
.alloc = alloc,
.free = free,
.resize = resize,
.remap = std.mem.Allocator.noRemap,
};
pub fn usage(self: *@This()) usize {
return self.allocatedBytes;
}
pub fn getStatistics(self: *@This()) PoolStatistics {
return .{
.statName = "BumpArena",
.instanceCount = self.allocCount,
.memoryReserved = self.small.pages.items.len * PageSize +
self.small.pages.capacity * @sizeOf(usize) +
self.large.queryCapacity(),
.memoryUsed = self.allocatedBytes,
};
}
pub fn init(backing: std.mem.Allocator, io_context: std.Io) !@This() {
return .{
.backing = backing,
.io_context = io_context,
.small = try SmallAllocPages.init(backing),
.large = std.heap.ArenaAllocator.init(backing),
.mutex = .init,
};
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
pub fn deinit(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
self.small.deinit(self.backing);
self.large.deinit();
}
pub fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
const alignment = ptr_align.toByteUnits();
const result: [*]u8 = if (len > 4096 or alignment > 8) result: {
break :result self.largeAllocator().rawAlloc(len, ptr_align, ret_addr) orelse return null;
} else result: {
var offset = std.mem.alignForward(usize, self.smallBumpOffset, alignment);
if (offset + len > PageSize) {
// The first page exists at init; materialize its logical entry
// before advancing. append is transactional on allocation failure.
if (self.small.pages.items[0].len == 0) self.small.pages.items[0].len = 1;
self.small.append(self.backing, undefined) catch return null;
self.pageIndex += 1;
offset = 0;
}
const memory = self.small.getMutable(self.pageIndex)[offset .. offset + len];
self.smallBumpOffset = offset + len;
break :result memory.ptr;
};
self.allocatedBytes += len;
self.allocCount += 1;
return result;
}
inline fn largeAllocator(self: *@This()) std.mem.Allocator {
return self.large.allocator();
}
pub fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void {
// it's a bump allocator, it does nothing on free.
_ = ctx;
_ = buf;
_ = buf_align;
_ = ret_addr;
}
// do not support resize in place.
pub fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
_ = buf;
_ = buf_align;
_ = new_len;
_ = ret_addr;
return false;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return .{ .ptr = self, .vtable = &vtable };
}
pub fn reset(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
_ = self.large.reset(.free_all);
self.small.reset(self.backing);
self.smallBumpOffset = 0;
self.pageIndex = 0;
self.allocatedBytes = 0;
self.allocCount = 0;
}
};
// it's like an normal vector/ arraylist except it never invalidates old pointers.
// and never causes re-allocations. (excepting in the control block, which is just a vector of things)
//
// It is implemented with a control block which which contains a list of pages.
// these pages contain the actual memory of the vector.
//
// it has a growth factor, which can be configured.
//
// use cases:
//
// - this is highly performant for cases where
// - YOU WANT generally fast insertion time
// - YOU WANT fast random access time
// - YOU WANT cache-coherent and efficient linear iteration
// - YOU WANT to retain pointers across operations
// - YOU WANT to avoid reallocations (eg. if the data set is remarkably big)
// - YOU KNOW that you have linear growth factors and exponential growth is overkill.
//
// great for:
// - event logging.
// - output buffering.
// - recording timelines.
pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type {
return struct {
const Page = struct {
data: [growth]T align(8) = undefined,
len: u32 = 0,
};
pages: std.ArrayListUnmanaged(*Page) = .empty,
currentPageId: usize = 0,
head: *T,
pub fn init(allocator: std.mem.Allocator) !@This() {
var rv = @This(){
.head = undefined,
};
const page = try allocator.create(Page);
errdefer allocator.destroy(page);
page.* = .{};
try rv.pages.append(allocator, page);
rv.head = &rv.pages.items[0].data[0];
return rv;
}
pub fn capacity(self: @This()) usize {
return self.pages.items.len * growth;
}
pub fn len(self: @This()) usize {
return (self.currentPageId) * growth + self.currentPage().len;
}
pub fn getStatistics(self: *const @This()) PoolStatistics {
return .{
.statName = "PagedVector",
.instanceCount = self.len(),
.memoryReserved = self.pages.items.len * @sizeOf(Page) +
self.pages.capacity * @sizeOf(*Page),
.memoryUsed = self.len() * @sizeOf(T),
};
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
for (self.pages.items) |page| {
allocator.destroy(page);
}
self.pages.deinit(allocator);
}
fn maybeExpand(self: *@This(), allocator: std.mem.Allocator) !void {
if (self.currentPageId == self.pages.items.len - 1) {
const page = try allocator.create(Page);
errdefer allocator.destroy(page);
page.* = .{};
try self.pages.append(allocator, page);
self.currentPageId = self.pages.items.len - 1;
} else {
self.currentPageId += 1;
}
}
// Retain pages; no live element survives reset.
pub fn reset(self: *@This(), allocator: std.mem.Allocator) void {
_ = allocator;
for (self.pages.items) |page| page.len = 0;
self.currentPageId = 0;
self.head = &self.pages.items[0].data[0];
}
pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void {
if (self.currentPage().len == growth) try self.maybeExpand(allocator);
const page = self.currentPage();
self.head = &page.data[page.len];
self.head.* = value;
page.len += 1;
}
pub fn appendSlice(self: *@This(), allocator: std.mem.Allocator, slice: []const T) !void {
for (slice) |value| {
try self.append(allocator, value);
}
}
pub fn getMutable(self: *@This(), index: usize) *T {
const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable;
return &self.pages.items[pageIndex].data[index % growth];
}
pub fn get(self: @This(), index: usize) *const T {
const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable;
return &self.pages.items[pageIndex].data[index % growth];
}
// swaps the element at the index with the element currently pointed to by head
// then pops back the head, shrinking length by 1
//
// Efficient removal of an element at an index but does not preserve order.
pub fn swapRemove(self: *@This(), index: usize) void {
const ptr = self.getMutable(index);
ptr.* = self.head.*;
_ = try self.pop();
}
fn currentPage(self: @This()) *Page {
return self.pages.items[self.currentPageId];
}
// // retrieves a value, shrinking length by 1
pub fn pop(self: *@This()) !T {
const rv = self.head.*;
var page = self.currentPage();
page.len -= 1;
if (page.len < 1) {
page.len = 0;
self.currentPageId -= 1;
}
self.head = &self.currentPage().data[self.currentPage().len - 1];
return rv;
}
};
}
test "paged storage preserves values and pointers across growth, removal and reset" {
const gpa = std.testing.allocator;
var vector = try PagedVectorAdvanced(u32, 4).init(gpa);
defer vector.deinit(gpa);
try vector.append(gpa, 0);
const first = vector.get(0);
for (1..13) |i| try vector.append(gpa, @intCast(i));
try std.testing.expect(first == vector.get(0));
for (0..13) |i| try std.testing.expectEqual(@as(u32, @intCast(i)), vector.get(i).*);
// Remove across a page boundary, checking values rather than page layout.
try std.testing.expectEqual(@as(u32, 12), try vector.pop());
vector.swapRemove(1);
try std.testing.expectEqual(@as(u32, 11), vector.get(1).*);
try std.testing.expectEqual(@as(usize, 11), vector.len());
try std.testing.expectEqual(@as(u32, 0), first.*);
vector.reset(gpa);
try std.testing.expectEqual(@as(usize, 0), vector.len());
for (0..13) |_| try vector.append(gpa, 42);
for (0..13) |i| try std.testing.expectEqual(@as(u32, 42), vector.get(i).*);
}
fn exercise(gpa: std.mem.Allocator) !void {
var arena = try BumpArena.init(gpa, std.testing.io);
defer arena.deinit();
const a = arena.allocator();
const first = try a.alloc(u8, 4096);
@memset(first, 17);
_ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4093);
// Alignment rounding takes this allocation across the first page boundary.
const aligned = try a.create(u64);
aligned.* = 0x12345678;
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(aligned) % @alignOf(u64));
const OverAligned = struct { value: u8 align(256) };
const over = try a.create(OverAligned);
over.* = .{ .value = 42 };
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(over) % 256);
const large = try a.alloc(u8, 20000);
@memset(large, 29);
for (first) |v| try std.testing.expectEqual(@as(u8, 17), v);
try std.testing.expectEqual(@as(u64, 0x12345678), aligned.*);
arena.reset();
try std.testing.expectEqual(@as(usize, 0), arena.usage());
const reused = try a.alloc(u8, 4096);
@memset(reused, 31);
for (0..12) |_| _ = try a.alloc(u8, 4096);
arena.reset();
for (0..12) |_| _ = try a.alloc(u8, 4096);
}
test "bump arena alignment page rollover reuse and all allocation failures" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, exercise, .{});
}
test "bump arena failed page allocation can be retried" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var arena = try BumpArena.init(failing.allocator(), std.testing.io);
defer arena.deinit();
const a = arena.allocator();
for (0..4) |_| _ = try a.alloc(u8, 4096);
const before = arena.usage();
failing.fail_index = failing.alloc_index;
try std.testing.expectError(error.OutOfMemory, a.alloc(u8, 4096));
try std.testing.expectEqual(before, arena.usage());
failing.fail_index = std.math.maxInt(usize);
const memory = try a.alloc(u8, 4096);
@memset(memory, 7);
try std.testing.expectEqual(before + 4096, arena.usage());
}

158
desktop/vendor/uhdk/src/callbacks.zig vendored Normal file
View File

@ -0,0 +1,158 @@
//! C ABI entry points for callbacks.
const std = @import("std");
const c = @import("native");
const abi = @import("abi.zig");
const runtime = @import("runtime.zig");
export fn z_tray_desc(handle: ?*c.uhdk_tray) [*c]const c.uhdk_tray_desc {
return &runtime.fromObjectHandle(handle).payload.tray.snapshot.?.desc;
}
export fn z_tray_state(handle: ?*c.uhdk_tray, available: c.uhdk_bool, status: c.uhdk_status) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive) return;
const state = &object.payload.tray.state;
if (state.available == available and state.status == status) return;
state.available = available;
state.status = status;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TRAY_STATE;
event.data.tray_state = .{ .tray = handle, .state = state.* };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_tray_activate(handle: ?*c.uhdk_tray, activation: c.uhdk_tray_activation) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive) return;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TRAY_ACTIVATE;
event.data.tray = .{ .tray = handle, .activation = activation };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_tray_command(handle: ?*c.uhdk_tray, item: [*c]const c.uhdk_menu_item) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive or item == null or item.*.flags & (c.UHDK_MENU_DISABLED | c.UHDK_MENU_SEPARATOR) != 0 or item.*.submenu != null) return;
var event = std.mem.zeroes(c.z_event);
event.type = if (item.*.role == c.UHDK_MENU_ROLE_QUIT) c.UHDK_EVENT_QUIT_REQUESTED else c.UHDK_EVENT_MENU_COMMAND;
event.data.menu = .{ .command_id = item.*.command_id, .tray = handle };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
runtime.emit(handle, event);
}
export fn z_complete(
handle: ?*c.uhdk_session,
id: u64,
status: abi.Status,
result: [*c]const c.z_request_result,
) void {
runtime.complete(handle, id, status, result);
}
export fn z_object_native(handle: ?*anyopaque) ?*anyopaque {
return if (handle == null) null else runtime.fromObjectHandle(handle).native;
}
export fn z_object_set_native(handle: ?*anyopaque, native: ?*anyopaque) void {
runtime.fromObjectHandle(handle).native = native;
}
export fn z_object_kind(handle: ?*anyopaque) u32 {
return runtime.fromObjectHandle(handle).kind();
}
export fn z_object_app(handle: ?*anyopaque) ?*c.uhdk_session {
return runtime.toAppHandle(runtime.fromObjectHandle(handle).app);
}
export fn z_metrics(handle: ?*c.uhdk_window, value: [*c]const c.uhdk_window_metrics) void {
const object = runtime.fromObjectHandle(handle);
object.app.lock();
object.payload.window.metrics = value.*;
object.app.unlock();
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.window = handle;
event.data.metrics = value.*;
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_preferences(handle: ?*c.uhdk_session, value: [*c]const c.uhdk_preferences) void {
const application = runtime.fromAppHandle(handle);
application.lock();
application.preferences = value.*;
application.unlock();
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_PREFERENCES_CHANGED;
event.data.preferences = value.*;
c.z_emit(handle, &event);
}
export fn z_file_init(
handle: ?*c.uhdk_file,
path: c.uhdk_bytes,
uri: c.uhdk_text,
display: c.uhdk_text,
grant: ?*anyopaque,
) abi.Status {
const object = runtime.fromObjectHandle(handle);
const arena = object.arena.allocator();
object.payload.file.native_path = arena.dupe(u8, abi.bytes(path)) catch return abi.OOM;
if (@import("builtin").os.tag == .windows) {
if (path.len % 2 != 0) return abi.INVALID;
const wide = arena.alloc(u16, @intCast(path.len / 2)) catch return abi.OOM;
@memcpy(std.mem.sliceAsBytes(wide), abi.bytes(path));
object.payload.file.path = std.unicode.wtf16LeToWtf8AllocZ(arena, wide) catch return abi.OOM;
} else {
object.payload.file.path = arena.dupeSentinel(u8, abi.bytes(path), 0) catch return abi.OOM;
}
object.payload.file.uri = arena.dupe(u8, abi.textBytes(uri)) catch return abi.OOM;
object.payload.file.display = arena.dupe(u8, abi.textBytes(display)) catch return abi.OOM;
object.native = grant;
return abi.OK;
}
export fn z_file_from_url(
handle: ?*c.uhdk_session,
path: c.uhdk_bytes,
grant: ?*anyopaque,
) ?*c.uhdk_file {
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return null;
if (c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, grant) != abi.OK) {
object.alive = false;
return null;
}
return runtime.castHandle(*c.uhdk_file, object);
}
export fn z_file_path(handle: ?*c.uhdk_file) c.uhdk_bytes {
const object = runtime.fromObjectHandle(handle);
return .{ .ptr = object.payload.file.native_path.ptr, .len = object.payload.file.native_path.len };
}
export fn z_menu_items(handle: ?*c.uhdk_menu, len: [*c]u64) [*c]const c.uhdk_menu_item {
const object = runtime.fromObjectHandle(handle);
len.* = object.payload.menu.items.len;
return object.payload.menu.items.ptr;
}
export fn z_dispatch(handle: ?*c.uhdk_session) void {
runtime.dispatch(handle);
}
export fn z_native_failed(handle: ?*c.uhdk_session, status: abi.Status) void {
const app = runtime.fromAppHandle(handle);
app.lock();
app.native_error = status;
app.stopping = true;
app.notify();
app.unlock();
}

325
desktop/vendor/uhdk/src/core_tests.zig vendored Normal file
View File

@ -0,0 +1,325 @@
const std = @import("std");
const c = @import("native");
const Application = @import("Application.zig");
const runtime = @import("runtime.zig");
const abi = @import("abi.zig");
test "function key policy holds through repeats and release in both directions" {
const suppress = c.z_function_key_suppress;
const native = c.UHDK_FUNCTION_KEYS_NATIVE;
const application = c.UHDK_FUNCTION_KEYS_APPLICATION;
var state = std.mem.zeroes(c.z_function_keys);
var key: u32 = c.UHDK_KEY_F1;
while (key <= c.UHDK_KEY_F24) : (key += 1) {
// Switching to native while an application-owned press is held must
// not leak its repeats or release into native menu handling.
try std.testing.expect(suppress(&state, application, key, 0, 1) != 0);
try std.testing.expect(suppress(&state, native, key, 0, 1) != 0);
try std.testing.expect(suppress(&state, native, key, 0, 0) != 0);
// Conversely, a native key-down must retain native key-up handling so
// DefWindowProc can complete its F10 menu state, despite a policy change.
try std.testing.expect(suppress(&state, native, key, 0, 1) == 0);
try std.testing.expect(suppress(&state, application, key, 0, 1) == 0);
try std.testing.expect(suppress(&state, application, key, 0, 0) == 0);
}
try std.testing.expectEqual(@as(u32, 0), state.down);
try std.testing.expectEqual(@as(u32, 0), state.suppress);
}
fn destroyApplication(application: *Application) void {
runtime.destroyEvents(application.pending_head);
runtime.destroyEvents(application.published);
application.scratch.deinit();
const gpa = application.gpa;
gpa.free(application.name);
application.* = undefined;
gpa.destroy(application);
}
fn allocationLifecycle(gpa: std.mem.Allocator) !void {
const application = try Application.create(gpa, std.testing.io, "test");
defer destroyApplication(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
const command = try runtime.createCommand(application, c.Z_CLIP_WRITE, file);
defer runtime.abandon(command);
command.data.text = try abi.copyText(command.arena.allocator(), .{
.ptr = "owned request text",
.len = "owned request text".len,
});
try std.testing.expectEqualStrings("owned request text", abi.textBytes(command.data.text));
try std.testing.expectEqual(@as(usize, 2), file.refs);
}
test "all request construction failures release partial ownership" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationLifecycle, .{});
}
test "invalid UTF-8 spans and partial scalar ranges are rejected" {
try std.testing.expect(!abi.validText(.{ .ptr = null, .len = 1 }, false));
try std.testing.expect(!abi.validText(.{ .ptr = "\xff", .len = 1 }, false));
try std.testing.expect(abi.validText(.{ .ptr = null, .len = 0 }, true));
try std.testing.expect(!abi.boundary("a😀b", 2));
try std.testing.expect(abi.boundary("a😀b", 5));
}
test "public payload scratch lifetime empty polls and resource pins" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "payloads");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
var handles = [_]?*c.uhdk_file{@ptrCast(file)};
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_OPEN_FILES;
event.data.files = .{ .ptr = &handles, .len = 1 };
runtime.emit(handle, &event);
try std.testing.expectEqual(@as(usize, 2), file.refs);
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_file_list)), batch.ptr[0].data_size);
const payload: *const c.uhdk_file_list = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@intFromPtr(file), @intFromPtr(payload.ptr[0].?));
try std.testing.expectEqual(@as(usize, 2), file.refs);
// Invalid calls must not reset a borrow. Valid empty polls must release it.
try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.poll(handle, 0, null));
try std.testing.expectEqual(@as(u64, 1), payload.len);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expectEqual(@as(usize, 1), file.refs);
}
test "poll allocation failure keeps queued terminal completion retryable" {
const app_api = @import("api/app.zig");
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
const application = try Application.create(failing.allocator(), std.testing.io, "retry");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
var bytes: [20000]u8 = @splat(42);
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_REQUEST_DONE;
event.data.request = .{ .tag = 123, .kind = c.UHDK_REQUEST_FILE_READ, .status = abi.OK, .diagnostic = .{ .ptr = null, .len = 0 }, .value = .{ .bytes = .{ .ptr = &bytes, .len = bytes.len } } };
runtime.emit(handle, &event);
@memset(&bytes, 0);
failing.fail_index = failing.alloc_index;
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expect(application.pending_head != null);
failing.fail_index = std.math.maxInt(usize);
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, 123));
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@as(u64, 123), result.tag);
const data: *const c.uhdk_bytes = @ptrCast(@alignCast(result.data.?));
try std.testing.expectEqual(@as(u64, bytes.len), data.len);
for (data.ptr[0..@intCast(data.len)]) |b| try std.testing.expectEqual(@as(u8, 42), b);
try std.testing.expect(application.pending_head == null);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
}
test {
_ = @import("linux/WindowState.zig");
}
const IoGate = struct {
io: std.Io,
entered: std.Io.Event = .unset,
release: std.Io.Event = .unset,
fn block(context: *anyopaque) void {
const self: *IoGate = @ptrCast(@alignCast(context));
self.entered.set(self.io);
self.release.waitUncancelable(self.io);
}
};
test "blocked file execution leaves event polling live and cancellation drains once" {
const app_api = @import("api/app.zig");
{
const application = try Application.create(std.testing.allocator, std.testing.io, "io gate");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
var gate: IoGate = .{ .io = application.io };
application.io_test_hook = .{ .context = &gate, .before = IoGate.block };
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
const worker = try std.Thread.spawn(.{}, runtime.ioMain, .{application});
defer {
gate.release.set(application.io);
application.lock();
application.io_exit = true;
application.io_available.set(application.io);
application.unlock();
worker.join();
}
const command = try runtime.createCommand(application, abi.IO_INFO, file);
command.kind = c.UHDK_REQUEST_FILE_INFO;
const id: u64 = 42;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, id));
runtime.dispatch(handle);
try gate.entered.waitTimeout(application.io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } });
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
var events: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), events.ptr[0].type);
// Shutdown is requested while the OS operation is still blocked.
app_api.uhdk_quit(handle);
runtime.dispatch(handle);
try std.testing.expect(!application.stopped_sent);
gate.release.set(application.io);
const deadline = runtime.now(application.io) + 5 * std.time.ns_per_s;
while (true) {
runtime.dispatch(handle);
application.lock();
const done = application.requests == null;
application.unlock();
if (done) break;
try std.testing.expect(runtime.now(application.io) < deadline);
try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(1), .clock = .awake }).sleep(application.io);
}
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 2), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(id, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_STOPPED), events.ptr[1].type);
try std.testing.expectEqual(@as(u32, abi.UNAVAILABLE), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(usize, 0), application.io_pending);
}
}
test "fatal native failure persists and wakes subsequent polls" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "native failure");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
c.z_native_failed(handle, c.UHDK_STATUS_OS_ERROR);
var events: c.uhdk_event_list = undefined;
for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.poll(handle, std.math.maxInt(u64), &events));
}
test "caller tags remain reserved until delivery and isolate late native completions" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "tags");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const tag = std.math.maxInt(u64); // The full nonzero caller range is available.
const zero = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.INVALID), runtime.submit(application, zero, 0));
try std.testing.expect(application.requests == null);
const first = try runtime.createCommand(application, c.Z_CLIP_READ, null);
first.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, first, tag));
const old_native_id = first.id;
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, tag));
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
const queued_duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, queued_duplicate, tag));
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_NOT_FOUND), app_api.uhdk_request_cancel(handle, tag));
var events: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(tag, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
const second = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, second, tag));
try std.testing.expect(second.id != old_native_id);
runtime.complete(handle, old_native_id, abi.OK, null);
try std.testing.expect(application.requests == second);
try std.testing.expect(application.pending_head == null);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
}
test "cycle end markers survive public event batching" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "cycles");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const window = try runtime.createObject(application, c.Z_KIND_WINDOW);
defer {
window.arena.deinit();
application.gpa.destroy(window);
}
const handle = runtime.toAppHandle(application);
var event = std.mem.zeroes(c.z_event);
event.window = runtime.castHandle(*c.uhdk_window, window);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
runtime.emit(handle, &event);
event.data.pointer.pressed = 0;
runtime.emit(handle, &event);
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 3), batch.len);
try std.testing.expect(batch.ptr[0].cycle_id != 0);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[1].cycle_id);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[2].cycle_id);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_CYCLE_END), batch.ptr[2].type);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_cycle_end_event)), batch.ptr[2].data_size);
const ending: *const c.uhdk_cycle_end_event = @ptrCast(@alignCast(batch.ptr[2].data.?));
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_COMPLETED), ending.reason);
}

100
desktop/vendor/uhdk/src/edit_keys.h vendored Normal file
View File

@ -0,0 +1,100 @@
#ifndef UHDK_PRIVATE_EDIT_KEYS_H
#define UHDK_PRIVATE_EDIT_KEYS_H
#include "uhdk.h"
/* Shared Windows/Wayland defaults. Alt (including AltGr) and Super belong to
* text/layout or desktop shortcuts, never to these Ctrl editing bindings. */
static inline uint32_t z_edit_key(uint32_t key, uint32_t mods) {
int ctrl = (mods & UHDK_MOD_CONTROL) != 0;
int shift = (mods & UHDK_MOD_SHIFT) != 0;
if (mods & (UHDK_MOD_ALT | UHDK_MOD_SUPER))
return 0;
if (ctrl) {
switch (key) {
case 'a':
case 'A':
return shift ? 0 : UHDK_EDIT_SELECT_ALL;
case 'c':
case 'C':
return shift ? 0 : UHDK_EDIT_COPY;
case 'x':
case 'X':
return shift ? 0 : UHDK_EDIT_CUT;
case 'v':
case 'V':
return shift ? 0 : UHDK_EDIT_PASTE;
case 'z':
case 'Z':
return shift ? UHDK_EDIT_REDO : UHDK_EDIT_UNDO;
case 'y':
case 'Y':
return shift ? 0 : UHDK_EDIT_REDO;
default:
break;
}
}
switch (key) {
case UHDK_KEY_BACKSPACE:
return ctrl ? UHDK_EDIT_DELETE_WORD_BACKWARD : UHDK_EDIT_DELETE_BACKWARD;
case UHDK_KEY_DELETE:
return ctrl ? UHDK_EDIT_DELETE_WORD_FORWARD
: shift ? UHDK_EDIT_CUT
: UHDK_EDIT_DELETE_FORWARD;
case UHDK_KEY_INSERT:
return ctrl && !shift ? UHDK_EDIT_COPY : shift && !ctrl ? UHDK_EDIT_PASTE : 0;
case UHDK_KEY_LEFT:
return ctrl ? UHDK_EDIT_WORD_LEFT : UHDK_EDIT_MOVE_LEFT;
case UHDK_KEY_RIGHT:
return ctrl ? UHDK_EDIT_WORD_RIGHT : UHDK_EDIT_MOVE_RIGHT;
case UHDK_KEY_UP:
return ctrl ? UHDK_EDIT_PARAGRAPH_START : UHDK_EDIT_MOVE_UP;
case UHDK_KEY_DOWN:
return ctrl ? UHDK_EDIT_PARAGRAPH_END : UHDK_EDIT_MOVE_DOWN;
case UHDK_KEY_HOME:
return ctrl ? UHDK_EDIT_DOCUMENT_START : UHDK_EDIT_LINE_START;
case UHDK_KEY_END:
return ctrl ? UHDK_EDIT_DOCUMENT_END : UHDK_EDIT_LINE_END;
case UHDK_KEY_PAGE_UP:
return ctrl ? 0 : UHDK_EDIT_PAGE_UP;
case UHDK_KEY_PAGE_DOWN:
return ctrl ? 0 : UHDK_EDIT_PAGE_DOWN;
case UHDK_KEY_ENTER:
return ctrl ? 0 : shift ? UHDK_EDIT_LINE_BREAK : UHDK_EDIT_NEWLINE;
case UHDK_KEY_TAB:
return ctrl ? 0 : shift ? UHDK_EDIT_BACKTAB : UHDK_EDIT_TAB;
case UHDK_KEY_ESCAPE:
return ctrl || shift ? 0 : UHDK_EDIT_CANCEL;
default:
return 0;
}
}
static inline int z_edit_extends_selection(uint32_t command, uint32_t mods) {
if (!(mods & UHDK_MOD_SHIFT))
return 0;
switch (command) {
case UHDK_EDIT_MOVE_LEFT:
case UHDK_EDIT_MOVE_RIGHT:
case UHDK_EDIT_MOVE_UP:
case UHDK_EDIT_MOVE_DOWN:
case UHDK_EDIT_MOVE_BACKWARD:
case UHDK_EDIT_MOVE_FORWARD:
case UHDK_EDIT_WORD_LEFT:
case UHDK_EDIT_WORD_RIGHT:
case UHDK_EDIT_WORD_BACKWARD:
case UHDK_EDIT_WORD_FORWARD:
case UHDK_EDIT_LINE_START:
case UHDK_EDIT_LINE_END:
case UHDK_EDIT_LINE_LEFT_END:
case UHDK_EDIT_LINE_RIGHT_END:
case UHDK_EDIT_DOCUMENT_START:
case UHDK_EDIT_DOCUMENT_END:
case UHDK_EDIT_PARAGRAPH_START:
case UHDK_EDIT_PARAGRAPH_END:
case UHDK_EDIT_PAGE_UP:
case UHDK_EDIT_PAGE_DOWN:
return 1;
default:
return 0;
}
}
#endif

45
desktop/vendor/uhdk/src/function_keys.h vendored Normal file
View File

@ -0,0 +1,45 @@
#ifndef UHDK_PRIVATE_FUNCTION_KEYS_H
#define UHDK_PRIVATE_FUNCTION_KEYS_H
#include "uhdk.h"
/* Windows fallback must see a consistent down/up pair. In particular, changing
* policy between F10 down and up must not leave DefWindowProc's menu flag armed.
* Keep this state independent of the OS so the transition rules can be tested
* without a desktop. Zero initialization and focus loss clear held state. */
typedef struct z_function_keys {
uint32_t down;
uint32_t suppress;
} z_function_keys;
static inline int z_function_key_suppress(
z_function_keys *state,
uhdk_function_key_policy policy,
uhdk_key key,
uhdk_modifier_flags modifiers,
int pressed
) {
if (key < UHDK_KEY_F1 || key > UHDK_KEY_F24)
return 0;
uint32_t bit = 1u << (key - UHDK_KEY_F1);
int suppress;
if (state->down & bit) {
suppress = (state->suppress & bit) != 0;
} else {
suppress =
policy == UHDK_FUNCTION_KEYS_APPLICATION &&
!(modifiers & (UHDK_MOD_SHIFT | UHDK_MOD_CONTROL | UHDK_MOD_ALT | UHDK_MOD_SUPER));
if (pressed) {
state->down |= bit;
if (suppress)
state->suppress |= bit;
else
state->suppress &= ~bit;
}
}
if (!pressed) {
state->down &= ~bit;
state->suppress &= ~bit;
}
return suppress;
}
#endif

90
desktop/vendor/uhdk/src/gl_loader.c vendored Normal file
View File

@ -0,0 +1,90 @@
/* Private GLAD implementation: never collide with a consumer's own loader. */
#define gladLoadGLContextUserPtr z_gladLoadGLContextUserPtr
#define gladLoadGLContext z_gladLoadGLContext
#define UHDK_ENABLE_OPENGL
#ifdef _WIN32
/* The shared Windows library links no C runtime. Declare the standard headers
* first, then route GLAD's remaining C runtime calls to private helpers. */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "windows/nocrt.h"
static int z_strncmp(const char *a, const char *b, size_t len) {
for (size_t i = 0; i < len; i++) {
if (a[i] != b[i])
return (unsigned char)a[i] < (unsigned char)b[i] ? -1 : 1;
if (!a[i])
return 0;
}
return 0;
}
/* inline: only referenced from GLAD paths the compiler may discard. */
static inline int z_strcmp(const char *a, const char *b) {
return z_strncmp(a, b, SIZE_MAX);
}
static inline char *z_strstr(const char *haystack, const char *needle) {
size_t len = strlen(needle);
for (; *haystack; haystack++)
if (!z_strncmp(haystack, needle, len))
return (char *)haystack;
return len ? NULL : (char *)haystack;
}
static int parse_int(const char **s, int *out) {
const char *p = *s;
while (*p == ' ' || (*p >= '\t' && *p <= '\r'))
p++;
int sign = 1;
if (*p == '+' || *p == '-')
sign = *p++ == '-' ? -1 : 1;
if (*p < '0' || *p > '9')
return 0;
int value = 0;
while (*p >= '0' && *p <= '9' && value <= (INT_MAX - 9) / 10)
value = value * 10 + (*p++ - '0');
*out = sign * value;
*s = p;
return 1;
}
/* GLAD's only scan is "%d.%d" on GL_VERSION; returns the fields assigned. */
static int z_scan_version(const char *s, const char *format, int *major, int *minor) {
(void)format;
if (!parse_int(&s, major))
return 0;
if (*s++ != '.')
return 1;
return 1 + parse_int(&s, minor);
}
#define malloc z_malloc
#define free z_free
#define strncmp z_strncmp
#define strcmp z_strcmp
#define strstr z_strstr
#define GLAD_IMPL_UTIL_C_
#define GLAD_IMPL_UTIL_SSCANF z_scan_version
#endif
#define GLAD_GL_IMPLEMENTATION
#include "glad/gl.h"
#undef GLAD_GL_IMPLEMENTATION
#include "native.h"
#include <string.h>
static GLADapiproc resolve(void *user, const char *name) {
uhdk_gl_proc proc = NULL;
uhdk_text symbol = {name, strlen(name)};
if (z_native_gl_proc(user, symbol, &proc) != UHDK_STATUS_OK)
return NULL;
return (GLADapiproc)proc;
}
int32_t z_gl_load(void *context, uhdk_gl_functions *functions) {
return gladLoadGLContextUserPtr(functions, resolve, context) && functions->VERSION_3_3;
}

181
desktop/vendor/uhdk/src/linux/Bitmap.zig vendored Normal file
View File

@ -0,0 +1,181 @@
//! Fixed 16px menu font and a clipped, opaque software canvas. The packed glyphs
//! decode directly from embedded data without allocation, GPU work, or a parser.
const std = @import("std");
const data = @embedFile("font/roboto-16.fontatlas");
fn word(offset: usize) u16 {
return std.mem.readInt(u16, data[offset..][0..2], .little);
}
const count = word(4);
const fallback = word(6);
const Glyph = struct {
offset: usize,
packed_size: usize,
width: u8,
height: u8,
x: i8,
y: i8,
advance: u8,
};
fn record(index: usize) Glyph {
const offset = 8 + index * 12;
return .{
.offset = word(offset + 2),
.packed_size = word(offset + 4),
.width = data[offset + 6],
.height = data[offset + 7],
.x = @bitCast(data[offset + 8]),
.y = @bitCast(data[offset + 9]),
.advance = data[offset + 10],
};
}
fn glyph(codepoint: u21) Glyph {
var lo: usize = 0;
var hi: usize = count;
if (codepoint <= std.math.maxInt(u16)) {
while (lo < hi) {
const mid = (lo + hi) / 2;
const key = word(8 + mid * 12);
if (key < codepoint) lo = mid + 1 else hi = mid;
}
if (lo < count and word(8 + lo * 12) == codepoint) return record(lo);
}
return record(fallback);
}
pub fn width(text: []const u8) i32 {
var it = std.unicode.Utf8View.initUnchecked(text).iterator();
var result: i32 = 0;
while (it.nextCodepoint()) |cp| {
result += glyph(cp).advance;
if (result >= 1024) break; // Menus constrain/ellipsize long labels.
}
return result;
}
pub const Canvas = struct {
pixels: []u32,
width: i32,
height: i32,
scale: i32,
pub fn rect(self: Canvas, x: i32, y: i32, w: i32, h: i32, color: u32) void {
const x0 = std.math.clamp(x, 0, self.width) * self.scale;
const y0 = std.math.clamp(y, 0, self.height) * self.scale;
const x1 = std.math.clamp(x + w, 0, self.width) * self.scale;
const y1 = std.math.clamp(y + h, 0, self.height) * self.scale;
if (x1 <= x0 or y1 <= y0) return;
var row = y0;
while (row < y1) : (row += 1) {
const offset: usize = @intCast(row * self.width * self.scale);
@memset(self.pixels[offset + @as(usize, @intCast(x0)) .. offset + @as(usize, @intCast(x1))], color | 0xff000000);
}
}
fn pixel(self: Canvas, x: i32, y: i32, color: u32, alpha: u32) void {
if (x < 0 or y < 0 or x >= self.width or y >= self.height or alpha == 0) return;
const index: usize = @intCast((y * self.width * self.scale + x) * self.scale);
const background = self.pixels[index];
var blended: u32 = 0xff000000;
inline for (.{ 0, 8, 16 }) |shift| {
blended |= ((((color >> shift) & 255) * alpha + ((background >> shift) & 255) * (255 - alpha) + 127) / 255) << shift;
}
self.rect(x, y, 1, 1, blended);
}
fn drawGlyph(self: Canvas, value: Glyph, x: i32, baseline: i32, color: u32) void {
if (value.width == 0) return;
const encoded = data[value.offset..][0..value.packed_size];
const pixel_count: usize = @as(usize, value.width) * value.height;
var byte_index: usize = 0;
var pixel_index: usize = 0;
while (byte_index < encoded.len and pixel_index < pixel_count) {
const control = encoded[byte_index];
byte_index += 1;
const run: usize = @as(usize, control & 0x7f) + 1;
if (control & 0x80 != 0) {
pixel_index += run * 2;
continue;
}
for (encoded[byte_index..][0..run]) |pair| {
inline for (.{ pair & 0x0f, pair >> 4 }) |coverage| {
if (pixel_index < pixel_count and coverage != 0) {
const column = pixel_index % value.width;
const row = pixel_index / value.width;
self.pixel(x + value.x + @as(i32, @intCast(column)), baseline + value.y + @as(i32, @intCast(row)), color, @as(u32, coverage) * 17);
}
pixel_index += 1;
}
}
byte_index += run;
}
}
pub fn text(self: Canvas, value: []const u8, x: i32, baseline: i32, limit: i32, color: u32) void {
var it = std.unicode.Utf8View.initUnchecked(value).iterator();
var cursor = x;
const ellipsis = glyph(0x2026);
const clipped = width(value) > limit;
while (it.nextCodepoint()) |cp| {
const g = glyph(cp);
if (cursor + g.advance > x + limit - (if (clipped) @as(i32, ellipsis.advance) else 0)) {
if (limit >= ellipsis.advance) self.drawGlyph(ellipsis, cursor, baseline, color);
return;
}
self.drawGlyph(g, cursor, baseline, color);
cursor += g.advance;
}
}
};
test "bitmap bounds, coverage and clipping" {
try std.testing.expectEqualStrings("FAP1", data[0..4]);
try std.testing.expect(fallback < count);
var previous: u16 = 0;
for (0..count) |i| {
const cp = word(8 + i * 12);
try std.testing.expect(cp > previous);
previous = cp;
const g = glyph(@intCast(cp));
try std.testing.expect(g.offset + g.packed_size <= data.len);
var input: usize = 0;
var decoded_bytes: usize = 0;
while (input < g.packed_size) {
const control = data[g.offset + input];
input += 1;
const run: usize = @as(usize, control & 0x7f) + 1;
decoded_bytes += run;
if (control & 0x80 == 0) input += run;
try std.testing.expect(input <= g.packed_size);
}
try std.testing.expectEqual((@as(usize, g.width) * g.height + 1) / 2, decoded_bytes);
}
try std.testing.expectEqual(@as(u16, '~'), previous);
try std.testing.expectEqual(width("?"), width("漢"));
var pixels: [64 * 32]u32 = @splat(0xff000000);
const canvas: Canvas = .{ .pixels = &pixels, .width = 64, .height = 32, .scale = 1 };
canvas.text("Roboto café", -2, 17, 60, 0xffffff);
try std.testing.expect(!std.mem.allEqual(u32, &pixels, 0xff000000));
canvas.rect(-100, -100, 500, 500, 0x123456);
try std.testing.expect(std.mem.allEqual(u32, &pixels, 0xff123456));
}

117
desktop/vendor/uhdk/src/linux/Bus.zig vendored Normal file
View File

@ -0,0 +1,117 @@
//! Small typed D-Bus message builder/parser. No GLib, process spawning, or
//! synchronous method calls. libdbus owns message storage and the transport.
const std = @import("std");
const c = @import("linux_c");
pub const Error = error{OutOfMemory};
pub const Iter = c.DBusMessageIter;
pub const Message = c.DBusMessage;
pub fn method(destination: [*:0]const u8, path: [*:0]const u8, interface: [*:0]const u8, member: [*:0]const u8) Error!*Message {
return c.z_dbus_message_new_method_call.?(destination, path, interface, member) orelse error.OutOfMemory;
}
pub fn append(message: *Message) Iter {
var i: Iter = undefined;
c.z_dbus_message_iter_init_append.?(message, &i);
return i;
}
pub fn parse(message: *Message) Iter {
var i: Iter = std.mem.zeroes(Iter);
_ = c.z_dbus_message_iter_init.?(message, &i);
return i;
}
pub fn basic(i: *Iter, type_: c_int, value: anytype) Error!void {
var v = value;
if (c.z_dbus_message_iter_append_basic.?(i, type_, @ptrCast(&v)) == 0) return error.OutOfMemory;
}
pub fn string(i: *Iter, value: [*:0]const u8) Error!void {
try basic(i, c.DBUS_TYPE_STRING, value);
}
pub fn open(i: *Iter, type_: c_int, signature: ?[*:0]const u8) Error!Iter {
var nested: Iter = std.mem.zeroes(Iter);
if (c.z_dbus_message_iter_open_container.?(i, type_, signature, &nested) == 0) return error.OutOfMemory;
return nested;
}
pub fn close(i: *Iter, nested: *Iter) Error!void {
if (c.z_dbus_message_iter_close_container.?(i, nested) == 0) return error.OutOfMemory;
}
pub fn option(i: *Iter, key: [*:0]const u8, comptime signature: [:0]const u8, value: anytype) Error!void {
var pair = try open(i, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &pair);
try string(&pair, key);
var payload = try open(&pair, c.DBUS_TYPE_VARIANT, signature);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &payload);
try basic(&payload, signature[0], value);
try close(&pair, &payload);
try close(i, &pair);
}
pub fn kind(i: *Iter) c_int {
return c.z_dbus_message_iter_get_arg_type.?(i);
}
pub fn next(i: *Iter) bool {
return c.z_dbus_message_iter_next.?(i) != 0;
}
pub fn child(i: *Iter) Iter {
var result: Iter = std.mem.zeroes(Iter);
c.z_dbus_message_iter_recurse.?(i, &result);
return result;
}
pub fn str(i: *Iter) ?[]const u8 {
if (kind(i) != c.DBUS_TYPE_STRING and kind(i) != c.DBUS_TYPE_OBJECT_PATH) return null;
var value: [*c]const u8 = null;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return if (value == null) null else std.mem.span(value);
}
pub fn uint(i: *Iter) ?u32 {
if (kind(i) != c.DBUS_TYPE_UINT32) return null;
var value: u32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value;
}
pub fn variant(i: *Iter) ?Iter {
return if (kind(i) == c.DBUS_TYPE_VARIANT) child(i) else null;
}
pub fn entry(i: *Iter, key: []const u8) ?Iter {
if (kind(i) != c.DBUS_TYPE_ARRAY) return null;
var entries = child(i);
while (kind(&entries) == c.DBUS_TYPE_DICT_ENTRY) {
var pair = child(&entries);
const name = str(&pair) orelse return null;
if (!next(&pair)) return null;
if (std.mem.eql(u8, name, key)) return pair;
if (!next(&entries)) break;
}
return null;
}
comptime {
std.debug.assert(@sizeOf(c.dbus_uint32_t) == 4);
std.debug.assert(@sizeOf(c.dbus_uint64_t) == 8);
std.debug.assert(@sizeOf(Iter) == if (@sizeOf(usize) == 8) 72 else 56);
}
pub fn int(i: *Iter) ?i32 {
if (kind(i) != c.DBUS_TYPE_INT32) return null;
var value: i32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value;
}

414
desktop/vendor/uhdk/src/linux/Data.zig vendored Normal file
View File

@ -0,0 +1,414 @@
//! Core Wayland selection and copy-only URI drops. Transfers keep their offers
//! and sources alive until the nonblocking pipe closes, independent of focus.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const Input = @import("Input.zig");
const Files = @import("Files.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Offer = struct {
next: ?*Offer = null,
proxy: ?*c.struct_wl_data_offer,
refs: usize = 1,
text: ?[*:0]const u8 = null,
uris: bool = false,
actions: u32 = 0,
action: u32 = 0,
};
const Source = struct {
next: ?*Source = null,
proxy: ?*c.struct_wl_data_source,
bytes: []u8,
refs: usize = 1,
};
const Transfer = struct {
next: ?*Transfer = null,
fd: c_int,
request: u64 = 0,
offer: ?*Offer = null,
source: ?*Source = null,
window: ?*native.Window = null,
position: n.uhdk_point = .{ .x = 0, .y = 0 },
bytes: std.ArrayList(u8) = .empty,
offset: usize = 0,
limit: u64 = 0,
deadline: u64,
};
pub const State = struct {
manager: ?*c.struct_wl_data_device_manager = null,
device: ?*c.struct_wl_data_device = null,
offers: ?*Offer = null,
sources: ?*Source = null,
selection: ?*Offer = null,
drag: ?*Offer = null,
drag_window: ?*native.Window = null,
drag_serial: u32 = 0,
position: n.uhdk_point = .{ .x = 0, .y = 0 },
transfers: ?*Transfer = null,
};
fn backend() *native.Backend {
return native.instance.?;
}
fn dataState() *State {
return &backend().data;
}
fn data(comptime T: type, raw: ?*anyopaque) *T {
return @ptrCast(@alignCast(raw.?));
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3)
dataState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_data_device_manager_interface, 3));
}
pub fn setup() void {
if (dataState().manager != null and Input.state().seat != null and dataState().device == null) {
dataState().device = c.wl_data_device_manager_get_data_device(dataState().manager, Input.state().seat);
if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null);
}
native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null);
native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null);
}
fn unref(o: *Offer) void {
o.refs -= 1;
if (o.refs != 0) return;
var link = &dataState().offers;
while (link.* != o) link = &link.*.?.next;
link.* = o.next;
c.wl_data_offer_destroy(o.proxy);
backend().app.gpa.destroy(o);
}
fn offer(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
const o = backend().app.gpa.create(Offer) catch {
c.wl_data_offer_destroy(proxy);
return;
};
o.* = .{ .next = dataState().offers, .proxy = proxy };
dataState().offers = o;
_ = c.wl_data_offer_add_listener(proxy, &offer_listener, o);
}
fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void {
const o = data(Offer, raw);
const str = std.mem.span(name);
if (std.mem.eql(u8, str, "text/plain;charset=utf-8")) o.text = "text/plain;charset=utf-8" else if (std.mem.eql(u8, str, "text/plain") and o.text == null) o.text = "text/plain";
if (std.mem.eql(u8, str, "text/uri-list")) o.uris = true;
}
fn actions(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).actions = value;
}
fn action(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).action = value;
}
const offer_listener: c.struct_wl_data_offer_listener = .{ .offer = mime, .source_actions = actions, .action = action };
fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer {
var o = dataState().offers;
while (o) |item| : (o = item.next) if (item.proxy == proxy) return item;
return null;
}
fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
if (dataState().selection) |old| unref(old);
dataState().selection = lookup(proxy); // Takes the initial offer reference.
}
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
leave(null, null);
dataState().drag = lookup(proxy);
dataState().drag_window = Input.find(surface);
dataState().drag_serial = serial;
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
negotiate();
}
fn negotiate() void {
const o = dataState().drag orelse return;
const accepted = o.uris and dataState().drag_window != null and dataState().drag_window.?.drop_enabled;
c.wl_data_offer_accept(o.proxy, dataState().drag_serial, if (accepted) "text/uri-list" else null);
c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0);
}
fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
if (dataState().drag) |o| unref(o);
dataState().drag = null;
dataState().drag_window = null;
}
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void {
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
}
fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
const o = dataState().drag orelse return;
const w = dataState().drag_window orelse return;
if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return;
_ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w);
// drop ends the drag session; no leave is required after a successful drop.
leave(null, null);
}
const device_listener: c.struct_wl_data_device_listener = .{ .data_offer = offer, .enter = enter, .leave = leave, .motion = motion, .drop = drop, .selection = selection };
pub fn enable(w: *native.Window, enabled: bool) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
w.drop_enabled = enabled;
if (dataState().drag_window == w) negotiate();
return abi.OK;
}
fn sourceUnref(source: *Source) void {
source.refs -= 1;
if (source.refs != 0) return;
var link = &dataState().sources;
while (link.* != source) link = &link.*.?.next;
link.* = source.next;
backend().app.gpa.free(source.bytes);
backend().app.gpa.destroy(source);
}
fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {}
fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void {
const source = data(Source, raw);
const str = std.mem.span(name);
if ((!std.mem.eql(u8, str, "text/plain;charset=utf-8") and !std.mem.eql(u8, str, "text/plain")) or c.z_linux_nonblock(fd) != 0) {
_ = c.close(fd);
return;
}
const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fd);
return;
};
source.refs += 1;
transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer;
}
fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void {
const source = data(Source, raw);
c.wl_data_source_destroy(proxy);
source.proxy = null;
sourceUnref(source);
}
fn unused(_: ?*anyopaque, _: ?*c.struct_wl_data_source) callconv(.c) void {}
fn unusedAction(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: u32) callconv(.c) void {}
const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction };
pub fn write(text: n.uhdk_text) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
const input = Input.state();
// Selection changes require an actual input serial. Never queue a write to
// hijack an unrelated future keystroke when the app has no input focus.
if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE;
const source = backend().app.gpa.create(Source) catch return abi.OOM;
const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch {
backend().app.gpa.destroy(source);
return abi.OOM;
};
const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse {
backend().app.gpa.free(bytes);
backend().app.gpa.destroy(source);
return abi.OOM;
};
source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes };
dataState().sources = source;
_ = c.wl_data_source_add_listener(proxy, &source_listener, source);
c.wl_data_source_offer(proxy, "text/plain;charset=utf-8");
c.wl_data_source_offer(proxy, "text/plain");
c.wl_data_device_set_selection(dataState().device, proxy, input.serial);
return abi.OK;
}
pub fn read(id: u64, limit: u64) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (Input.state().key_focus == null) return abi.UNAVAILABLE;
const o = dataState().selection orelse return n.UHDK_STATUS_NOT_FOUND;
const format = o.text orelse return n.UHDK_STATUS_NOT_FOUND;
return receive(o, format, id, limit, null);
}
fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 {
var fds: [2]c_int = undefined;
if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR;
const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fds[0]);
_ = c.close(fds[1]);
return abi.OOM;
};
o.refs += 1;
transfer.* = .{ .next = dataState().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = dataState().position, .limit = limit, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer;
c.wl_data_offer_receive(o.proxy, format, fds[1]);
_ = c.close(fds[1]);
return n.Z_DEFERRED;
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var t = dataState().transfers;
while (t) |item| : (t = item.next) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 });
}
pub fn tick() i32 {
var t = dataState().transfers;
while (t) |item| {
t = item.next;
if (runtime.now(backend().app.io) >= item.deadline) {
finish(item, abi.UNAVAILABLE);
continue;
}
if (item.source) |source| {
const bytes = source.bytes[item.offset..];
if (bytes.len == 0) {
finish(item, abi.OK);
continue;
}
const amount = c.z_linux_pipe_write(item.fd, bytes.ptr, @min(bytes.len, 65536));
if (amount > 0) item.offset += @intCast(amount) else if (amount < 0 and c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
} else {
var buffer: [65536]u8 = undefined;
const amount = c.z_linux_read(item.fd, &buffer, buffer.len);
if (amount == 0) finish(item, abi.OK) else if (amount > 0) {
const length: usize = @intCast(amount);
if (length > item.limit -| item.bytes.items.len) {
finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL);
continue;
}
item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch {
finish(item, abi.OOM);
continue;
};
} else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
}
}
return if (dataState().transfers != null) 100 else -1;
}
fn finish(t: *Transfer, status: u32) void {
if (t.request != 0) {
var result = std.mem.zeroes(n.z_request_result);
result.value.text = abi.textSpan(t.bytes.items);
n.z_complete(runtime.toAppHandle(backend().app), t.request, if (status == abi.OK and !std.unicode.utf8ValidateSlice(t.bytes.items)) abi.INVALID else status, &result);
} else if (t.window) |w| {
if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy);
}
var link = &dataState().transfers;
while (link.* != t) link = &link.*.?.next;
link.* = t.next;
_ = c.close(t.fd);
if (t.offer) |o| unref(o);
if (t.source) |source| sourceUnref(source);
t.bytes.deinit(backend().app.gpa);
backend().app.gpa.destroy(t);
}
fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool {
var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer {
for (files.items) |file| n.uhdk_file_release(file);
files.deinit(backend().app.gpa);
}
var lines = std.mem.splitScalar(u8, bytes, '\n');
while (lines.next()) |line| {
const uri = std.mem.trim(u8, line, "\r");
if (uri.len == 0 or uri[0] == '#') continue;
const path = Files.decode(backend().app.gpa, uri) catch return false;
defer backend().app.gpa.free(path);
const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false;
files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file);
return false;
};
}
if (files.items.len == 0) return false;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_DROP_FILES;
event.data.drop_files = .{ .files = .{ .ptr = files.items.ptr, .len = files.items.len }, .position = position };
Input.send(w, &event);
return true;
}
pub fn cancel(id: u64) bool {
var t = dataState().transfers;
while (t) |item| : (t = item.next) if (item.request == id) {
finish(item, abi.CANCELLED);
return true;
};
return false;
}
pub fn forget(w: *native.Window) void {
if (dataState().drag_window == w) {
dataState().drag_window = null;
negotiate();
}
var t = dataState().transfers;
while (t) |item| {
t = item.next;
if (item.window == w) {
item.window = null;
finish(item, abi.CANCELLED);
}
}
}
pub fn releaseSeat() void {
while (dataState().transfers) |t| finish(t, abi.CANCELLED);
dataState().selection = null;
dataState().drag = null;
dataState().drag_window = null;
while (dataState().offers) |o| unref(o);
while (dataState().sources) |source| {
if (source.proxy != null) c.wl_data_source_destroy(source.proxy);
sourceUnref(source);
}
if (dataState().device != null) c.wl_data_device_release(dataState().device);
dataState().device = null;
native.setCapability(n.UHDK_CAP_CLIPBOARD, false);
native.setCapability(n.UHDK_CAP_DROP_FILES, false);
}
pub fn deinit() void {
releaseSeat();
if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager);
dataState().manager = null;
}

View File

@ -0,0 +1,277 @@
//! Optional Wayland activation and application icons. Activation is always a
//! compositor request, never a promise to bypass focus-stealing policy.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const Input = @import("Input.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Activation = struct {
next: ?*Activation = null,
id: u64,
window: *native.Window,
token: ?*c.struct_xdg_activation_token_v1,
deadline: u64,
};
const Icon = struct {
proxy: ?*c.struct_xdg_toplevel_icon_v1,
buffer: ?*c.struct_wl_buffer,
mapping: *anyopaque,
size: usize,
};
pub const State = struct {
activation: ?*c.struct_xdg_activation_v1 = null,
manager: ?*c.struct_xdg_toplevel_icon_manager_v1 = null,
shm: ?*c.struct_wl_shm = null,
icon: ?Icon = null,
pending: ?*Activation = null,
launch: ?[:0]u8 = null,
tray_token: ?[:0]u8 = null,
tray_token_deadline: u64 = 0,
};
fn backend() *native.Backend {
return native.instance.?;
}
fn desktopState() *State {
return &backend().desktop;
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "xdg_activation_v1")) desktopState().activation = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_activation_v1_interface, 1)) else if (std.mem.eql(u8, interface, "xdg_toplevel_icon_manager_v1")) {
desktopState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1));
if (desktopState().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(desktopState().manager, &icon_listener, null);
} else if (std.mem.eql(u8, interface, "wl_shm")) {
desktopState().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1));
if (desktopState().shm != null) _ = c.wl_shm_add_listener(desktopState().shm, &shm_listener, null);
}
native.setCapability(n.UHDK_CAP_APP_ICON, desktopState().manager != null and desktopState().shm != null);
}
fn iconSize(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1, _: i32) callconv(.c) void {}
fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {}
const icon_listener: c.struct_xdg_toplevel_icon_manager_v1_listener = .{ .icon_size = iconSize, .done = iconDone };
fn format(_: ?*anyopaque, _: ?*c.struct_wl_shm, _: u32) callconv(.c) void {}
const shm_listener: c.struct_wl_shm_listener = .{ .format = format };
var launch_token_read = false;
pub fn initialize() void {
if (launch_token_read) return;
launch_token_read = true;
const token = c.getenv("XDG_ACTIVATION_TOKEN");
if (token != null and token[0] != 0) {
desktopState().launch = backend().app.gpa.dupeSentinel(
u8,
std.mem.span(token),
0,
) catch null;
}
}
// A tray host supplies provenance that a hidden application's own seat lacks.
// Consume it once, promptly, without modifying the process environment.
pub fn trayToken(token: []const u8) !void {
const copy = if (token.len != 0) try backend().app.gpa.dupeSentinel(u8, token, 0) else null;
if (desktopState().tray_token) |old| backend().app.gpa.free(old);
desktopState().tray_token = copy;
desktopState().tray_token_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
}
pub fn focus(w: *native.Window, id: u64) u32 {
if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
if (desktopState().tray_token) |token| {
const fresh = runtime.now(backend().app.io) < desktopState().tray_token_deadline;
if (fresh) c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
backend().app.gpa.free(token);
desktopState().tray_token = null;
if (fresh) return abi.OK;
}
if (desktopState().launch) |token| {
c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
backend().app.gpa.free(token);
desktopState().launch = null;
return abi.OK;
}
const input = Input.state();
if (input.serial == 0 or input.key_focus == null or
runtime.now(backend().app.io) -| input.serial_time > 5 * std.time.ns_per_s)
return abi.UNAVAILABLE;
const p = backend().app.gpa.create(Activation) catch return abi.OOM;
const token = c.xdg_activation_v1_get_activation_token(desktopState().activation) orelse {
backend().app.gpa.destroy(p);
return abi.OOM;
};
p.* = .{
.next = desktopState().pending,
.id = id,
.window = w,
.token = token,
.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s,
};
desktopState().pending = p;
_ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat);
c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface);
const app_id = backend().app.gpa.dupeSentinel(u8, backend().app.application_id, 0) catch {
finish(p, abi.OOM);
return n.Z_DEFERRED;
};
defer backend().app.gpa.free(app_id);
c.xdg_activation_token_v1_set_app_id(token, app_id);
c.xdg_activation_token_v1_commit(token);
return n.Z_DEFERRED;
}
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Activation = @ptrCast(@alignCast(raw.?));
c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface);
finish(p, abi.OK);
}
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn finish(p: *Activation, status: u32) void {
var link = &desktopState().pending;
while (link.* != p) link = &link.*.?.next;
link.* = p.next;
c.xdg_activation_token_v1_destroy(p.token);
n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null);
backend().app.gpa.destroy(p);
}
pub fn tick() i32 {
var cursor = desktopState().pending;
while (cursor) |p| {
cursor = p.next;
if (runtime.now(backend().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE);
}
return if (desktopState().pending != null) 100 else -1;
}
pub fn cancel(id: u64) bool {
var cursor = desktopState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) {
finish(p, abi.CANCELLED);
return true;
};
return false;
}
pub fn forget(w: *native.Window) void {
var cursor = desktopState().pending;
while (cursor) |p| {
cursor = p.next;
if (p.window == w) finish(p, abi.CANCELLED);
}
}
pub fn applyIcon(w: *native.Window) void {
if (desktopState().icon) |icon|
c.xdg_toplevel_icon_manager_v1_set_icon(desktopState().manager, w.top, icon.proxy);
}
/// Public pixels are straight RGBA; wl_shm ARGB8888 uses native-endian,
/// premultiplied channels. Pad rectangular images to a transparent square.
pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
@memset(destination, 0);
const source = abi.bytes(image.pixels);
const x0 = (side - image.width) / 2;
const y0 = (side - image.height) / 2;
for (0..image.height) |y| for (0..image.width) |x| {
const offset = (y * image.width + x) * 4;
const a: u32 = source[offset + 3];
const r = (@as(u32, source[offset]) * a + 127) / 255;
const g = (@as(u32, source[offset + 1]) * a + 127) / 255;
const blue = (@as(u32, source[offset + 2]) * a + 127) / 255;
destination[(y + y0) * side + x + x0] = a << 24 | r << 16 | g << 8 | blue;
};
}
pub fn setIcon(image: n.uhdk_image) u32 {
if (desktopState().manager == null or desktopState().shm == null) return n.UHDK_STATUS_UNSUPPORTED;
const side = @max(image.width, image.height);
const size: usize = @as(usize, side) * side * 4;
const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return n.UHDK_STATUS_OS_ERROR;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return n.UHDK_STATUS_OS_ERROR;
var retained = false;
defer if (!retained) {
_ = c.munmap(mapping, size);
};
const words: [*]u32 = @ptrCast(@alignCast(mapping.?));
pixels(words[0 .. size / 4], side, image);
const pool = c.wl_shm_create_pool(desktopState().shm, fd, @intCast(size)) orelse return abi.OOM;
defer c.wl_shm_pool_destroy(pool);
const buffer = c.wl_shm_pool_create_buffer(
pool,
0,
@intCast(side),
@intCast(side),
@intCast(side * 4),
c.WL_SHM_FORMAT_ARGB8888,
) orelse return abi.OOM;
const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(desktopState().manager) orelse {
c.wl_buffer_destroy(buffer);
return abi.OOM;
};
c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1);
const old = desktopState().icon;
desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size };
retained = true;
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) applyIcon(w);
if (old) |icon| destroyIcon(icon);
return abi.OK;
}
fn destroyIcon(icon: Icon) void {
c.xdg_toplevel_icon_v1_destroy(icon.proxy);
c.wl_buffer_destroy(icon.buffer);
_ = c.munmap(icon.mapping, icon.size);
}
pub fn deinit() void {
while (desktopState().pending) |p| finish(p, abi.CANCELLED);
if (desktopState().icon) |icon| destroyIcon(icon);
if (desktopState().launch) |token| backend().app.gpa.free(token);
if (desktopState().tray_token) |token| backend().app.gpa.free(token);
if (desktopState().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(desktopState().manager);
if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm);
if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation);
}
test "icons premultiply RGBA and pad rectangular images" {
const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 };
var image = std.mem.zeroes(n.uhdk_image);
image.width = 2;
image.height = 1;
image.pixels = .{ .ptr = &rgba, .len = rgba.len };
var result: [4]u32 = undefined;
pixels(&result, 2, image);
try std.testing.expectEqualSlices(u32, &.{ 0x80804000, 0xff00ff00, 0, 0 }, &result);
}

174
desktop/vendor/uhdk/src/linux/Egl.zig vendored Normal file
View File

@ -0,0 +1,174 @@
//! EGL owns presentation resources only. The compositor thread must never wait
//! for a frame lock: drivers may wait for Wayland events during presentation.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const abi = @import("../abi.zig");
const native = @import("native.zig");
pub const Context = struct {
window: *native.Window,
native: ?*c.struct_wl_egl_window,
surface: c.EGLSurface,
context: c.EGLContext,
};
threadlocal var frame: ?*Context = null;
pub fn initialize(b: *native.Backend) void {
if (c.z_linux_egl_available() == 0) return;
const display = c.z_eglGetPlatformDisplay.?(c.EGL_PLATFORM_WAYLAND_KHR, b.display, null);
if (display == null) return;
var major: c.EGLint = 0;
var minor: c.EGLint = 0;
if (c.z_eglInitialize.?(display, &major, &minor) == c.EGL_FALSE) return;
if (major < 1 or (major == 1 and minor < 5)) {
_ = c.z_eglTerminate.?(display);
return;
}
const attributes = [_]c.EGLint{ c.EGL_SURFACE_TYPE, c.EGL_WINDOW_BIT, c.EGL_RENDERABLE_TYPE, c.EGL_OPENGL_BIT, c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_ALPHA_SIZE, 8, c.EGL_NONE };
var config: c.EGLConfig = null;
var count: c.EGLint = 0;
if (c.z_eglChooseConfig.?(display, &attributes, &config, 1, &count) == c.EGL_FALSE or count == 0) {
_ = c.z_eglTerminate.?(display);
return;
}
b.egl_display = display;
b.egl_config = config;
}
pub fn finish(b: *native.Backend) void {
if (b.egl_display != null) {
_ = c.z_eglTerminate.?(b.egl_display);
_ = c.z_eglReleaseThread.?();
b.egl_display = null;
}
}
pub fn create(b: *native.Backend, w: *native.Window) u32 {
if (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED;
if (w.egl != null) return n.UHDK_STATUS_BUSY;
if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
const attrs = [_]c.EGLint{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_CONTEXT_OPENGL_PROFILE_MASK, c.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, c.EGL_NONE };
const context = c.z_eglCreateContext.?(b.egl_display, b.egl_config, null, &attrs);
if (context == null) return n.UHDK_STATUS_UNSUPPORTED;
const win = c.z_wl_egl_window_create.?(w.surface, @intCast(w.metrics.framebuffer_width), @intCast(w.metrics.framebuffer_height));
if (win == null) {
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM;
}
const surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, @ptrCast(win), null);
if (surface == null) {
c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return n.UHDK_STATUS_OS_ERROR;
}
const ctx = b.app.gpa.create(Context) catch {
_ = c.z_eglDestroySurface.?(b.egl_display, surface);
c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM;
};
ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context };
w.egl = ctx;
return abi.OK;
}
pub fn destroy(ctx: *Context) void {
const b = native.instance.?;
_ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
_ = c.z_eglDestroyContext.?(b.egl_display, ctx.context);
c.z_wl_egl_window_destroy.?(ctx.native);
ctx.window.egl = null;
b.app.gpa.destroy(ctx);
}
pub fn resetSurface(ctx: *Context) void {
const b = native.instance.?;
// An unmapped surface may never receive the driver's outstanding frame
// callback. Drop its EGL surface before hiding so remapping cannot wait
// forever in the next swap; the GL context and application resources survive.
if (ctx.surface != null) _ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
ctx.surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, ctx.native, null);
}
fn makeCurrent(b: *native.Backend, ctx: *Context) bool {
return ctx.surface != null and c.z_eglBindAPI.?(c.EGL_OPENGL_API) != c.EGL_FALSE and
c.z_eglMakeCurrent.?(b.egl_display, ctx.surface, ctx.surface, ctx.context) != c.EGL_FALSE;
}
pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
const b = native.instance orelse return abi.UNAVAILABLE;
if (b.egl_display == null) return n.UHDK_STATUS_UNSUPPORTED;
if (op == 4 or op == 8) {
if (op == 8 and frame != null) return n.UHDK_STATUS_BUSY;
return if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) != c.EGL_FALSE) abi.OK else n.UHDK_STATUS_OS_ERROR;
}
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (op == 1) {
if (frame != null) return n.UHDK_STATUS_BUSY;
if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
ctx.window.mutex.lockUncancelable(b.app.io);
if (!makeCurrent(b, ctx)) {
ctx.window.mutex.unlock(b.app.io);
return n.UHDK_STATUS_OS_ERROR;
}
frame = ctx;
return abi.OK;
}
if (frame != ctx) return n.UHDK_STATUS_BUSY;
switch (op) {
2 => {
// Keep ownership on failure so a caller cannot destroy a current context.
if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
frame = null;
ctx.window.mutex.unlock(b.app.io);
n.z_native_wake();
return abi.OK;
},
6 => {
if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
if (!ctx.window.visible or !ctx.window.configured) return abi.UNAVAILABLE;
if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
if (c.z_eglSwapBuffers.?(b.egl_display, ctx.surface) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
},
7 => {
if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const interval: *const i32 = @ptrCast(@alignCast(out.?));
if (c.z_eglSwapInterval.?(b.egl_display, interval.*) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
},
else => return abi.INVALID,
}
return abi.OK;
}
pub fn proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 {
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (frame != ctx or c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const allocator = ctx.window.owner.gpa;
const terminated = allocator.dupeSentinel(u8, abi.textBytes(name), 0) catch return abi.OOM;
defer allocator.free(terminated);
const address = c.z_eglGetProcAddress.?(terminated) orelse return n.UHDK_STATUS_NOT_FOUND;
out.* = @ptrCast(address);
return abi.OK;
}

79
desktop/vendor/uhdk/src/linux/Files.zig vendored Normal file
View File

@ -0,0 +1,79 @@
//! Local file URIs preserve arbitrary POSIX filename bytes.
const std = @import("std");
const n = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
pub fn decode(allocator: std.mem.Allocator, uri: []const u8) ![]u8 {
const encoded = if (std.mem.startsWith(u8, uri, "file:///")) uri[7..] else if (std.mem.startsWith(u8, uri, "file://localhost/")) uri[16..] else return error.Invalid;
var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit();
var i: usize = 0;
while (i < encoded.len) : (i += 1) {
var byte = encoded[i];
if (byte == '%') {
if (encoded.len - i < 3) return error.Invalid;
if (!std.ascii.isHex(encoded[i + 1]) or !std.ascii.isHex(encoded[i + 2])) return error.Invalid;
byte = std.fmt.parseInt(u8, encoded[i + 1 ..][0..2], 16) catch return error.Invalid;
i += 2;
} else if (byte == '?' or byte == '#') return error.Invalid;
if (byte == 0) return error.Invalid;
try result.writer.writeByte(byte);
}
return result.toOwnedSlice();
}
fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit();
try result.writer.writeAll("file://");
for (path) |byte| {
if (std.ascii.isAlphanumeric(byte) or std.mem.findScalar(u8, "/-._~", byte) != null) {
try result.writer.writeByte(byte);
} else try result.writer.print("%{X:0>2}", .{byte});
}
return result.toOwnedSlice();
}
pub fn init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
if (grant != null) return n.UHDK_STATUS_UNSUPPORTED;
const object = runtime.fromObjectHandle(file);
var arena: std.heap.ArenaAllocator = .init(object.app.gpa);
defer arena.deinit();
const allocator = arena.allocator();
const bytes = if (path.len != 0) abi.bytes(path) else decode(allocator, abi.textBytes(uri)) catch |err| return if (err == error.Invalid) abi.INVALID else abi.OOM;
if (bytes.len == 0 or bytes[0] != '/' or std.mem.findScalar(u8, bytes, 0) != null) return abi.INVALID;
const encoded = encode(allocator, bytes) catch return abi.OOM;
const basename = std.fs.path.basename(bytes);
// Display text is lossy only when the native byte name isn't UTF-8.
const display = if (std.unicode.utf8ValidateSlice(basename)) basename else "(non-UTF-8 filename)";
return n.z_file_init(file, .{ .ptr = bytes.ptr, .len = bytes.len }, abi.textSpan(encoded), abi.textSpan(display), null);
}
test "file URI preserves POSIX bytes and rejects remote, NUL, malformed escapes" {
const allocator = std.testing.allocator;
const original = "/tmp/a b%#\xff";
const uri = try encode(allocator, original);
defer allocator.free(uri);
try std.testing.expectEqualStrings("file:///tmp/a%20b%25%23%FF", uri);
const path = try decode(allocator, uri);
defer allocator.free(path);
try std.testing.expectEqualStrings(original, path);
for ([_][]const u8{ "https://host/file", "file://host/path", "file:///a%", "file:///a%XX", "file:///a%00", "file:///a%+1", "file:///a#fragment" }) |bad| {
try std.testing.expectError(error.Invalid, decode(allocator, bad));
}
const local = try decode(allocator, "file://localhost/tmp/a");
defer allocator.free(local);
try std.testing.expectEqualStrings("/tmp/a", local);
}

820
desktop/vendor/uhdk/src/linux/Input.zig vendored Normal file
View File

@ -0,0 +1,820 @@
//! One active Wayland seat. All mutable input state belongs to the native thread.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Popup = @import("Popup.zig");
const KdeAppMenu = @import("KdeAppMenu.zig");
const Keyboard = @import("Keyboard.zig");
const Data = @import("Data.zig");
const Text = @import("Text.zig");
const Key = struct {
code: u32,
down: bool,
repeated: bool,
sym: u32,
modifiers: u32,
text: [256]u8 = undefined,
len: usize = 0,
};
pub const State = struct {
seat: ?*c.struct_wl_seat = null,
seat_name: u32 = 0,
keyboard: ?*c.struct_wl_keyboard = null,
pointer: ?*c.struct_wl_pointer = null,
cursor_manager: ?*c.struct_wp_cursor_shape_manager_v1 = null,
cursor_device: ?*c.struct_wp_cursor_shape_device_v1 = null,
constraints: ?*c.struct_zwp_pointer_constraints_v1 = null,
constraints_name: u32 = 0,
confined: ?*c.struct_zwp_confined_pointer_v1 = null,
text_manager: ?*c.struct_zwp_text_input_manager_v3 = null,
text_input: ?*c.struct_zwp_text_input_v3 = null,
text_focus: ?*native.Window = null,
text_serial: u32 = 0,
key_focus: ?*native.Window = null,
pointer_focus: ?*native.Window = null,
context: ?*c.struct_xkb_context = null,
keymap: ?*c.struct_xkb_keymap = null,
state: ?*c.struct_xkb_state = null,
compose_table: ?*c.struct_xkb_compose_table = null,
compose: ?*c.struct_xkb_compose_state = null,
modifiers: u32 = 0,
active: bool = false,
pending_key: ?Key = null,
key_sync: ?*c.struct_wl_callback = null,
serial: u32 = 0,
serial_time: u64 = 0,
popup_serial: u32 = 0,
popup_time: u64 = 0,
popup_window: ?*native.Window = null,
popup_buttons: u32 = 0,
pointer_serial: u32 = 0,
next_id: u64 = 0,
position: n.uhdk_point = .{ .x = 0, .y = 0 },
buttons: u32 = 0,
pointer_mode: u32 = n.UHDK_POINTER_NORMAL,
mode_window: ?*native.Window = null,
last_click_time: u64 = 0,
last_click_button: u32 = 0,
last_click_position: n.uhdk_point = .{ .x = 0, .y = 0 },
click_count: u32 = 0,
repeat_key: ?u32 = null,
repeat_rate: u32 = 0,
repeat_delay: u32 = 600,
repeat_at: u64 = 0,
held: [256]bool = @splat(false),
menu_keys: [256]bool = @splat(false),
axis: n.uhdk_point = .{ .x = 0, .y = 0 },
wheel: n.uhdk_point = .{ .x = 0, .y = 0 },
axis_source: u32 = c.WL_POINTER_AXIS_SOURCE_WHEEL,
axis_stop: bool = false,
scrolling: bool = false,
};
fn backend() *native.Backend {
return native.instance.?;
}
pub fn state() *State {
return &backend().input;
}
pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window {
var item = backend().windows;
while (item) |w| : (item = w.next) if (w.surface == surface) return w;
return null;
}
pub fn send(w: *native.Window, event: *n.z_event) void {
event.window = w.handle;
n.z_emit(runtime.toAppHandle(w.owner), event);
}
pub fn id() u64 {
state().next_id += 1;
return state().next_id;
}
pub fn provenance(serial: u32) void {
state().serial = serial;
state().serial_time = runtime.now(backend().app.io);
}
pub fn initialize() void {
const s = state();
if (c.z_linux_xkb_available() != 0) {
s.context = c.z_xkb_context_new.?(c.XKB_CONTEXT_NO_FLAGS);
if (s.context != null) {
var locale: [*c]const u8 = c.getenv("LC_ALL");
if (locale == null or locale[0] == 0) locale = c.getenv("LC_CTYPE");
if (locale == null or locale[0] == 0) locale = c.getenv("LANG");
if (locale == null or locale[0] == 0) locale = "C.UTF-8";
s.compose_table = c.z_xkb_compose_table_new_from_locale.?(s.context, locale, c.XKB_COMPOSE_COMPILE_NO_FLAGS);
if (s.compose_table != null) s.compose = c.z_xkb_compose_state_new.?(s.compose_table, c.XKB_COMPOSE_STATE_NO_FLAGS);
}
}
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
const s = state();
if (std.mem.eql(u8, interface, "wl_seat") and s.seat == null and version >= 5) {
s.seat = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_seat_interface, @min(version, 8)));
s.seat_name = name;
if (s.seat != null) _ = c.wl_seat_add_listener(s.seat, &seat_listener, null);
} else if (std.mem.eql(u8, interface, "wp_cursor_shape_manager_v1")) {
s.cursor_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wp_cursor_shape_manager_v1_interface, 1));
} else if (std.mem.eql(u8, interface, "zwp_pointer_constraints_v1") and s.constraints == null) {
s.constraints = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_pointer_constraints_v1_interface, 1));
s.constraints_name = name;
native.setCapability(n.UHDK_CAP_POINTER_CONFINEMENT, s.pointer != null and s.constraints != null);
} else if (std.mem.eql(u8, interface, "zwp_text_input_manager_v3")) {
s.text_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_text_input_manager_v3_interface, 1));
}
}
pub fn setup() void {
const s = state();
if (s.pointer != null and s.cursor_manager != null and s.cursor_device == null)
s.cursor_device = c.wp_cursor_shape_manager_v1_get_pointer(s.cursor_manager, s.pointer);
if (s.seat != null and s.text_manager != null and s.text_input == null) {
s.text_input = c.zwp_text_input_manager_v3_get_text_input(s.text_manager, s.seat);
if (s.text_input != null) Text.listen(s.text_input);
}
Data.setup();
Popup.capability();
native.setCapability(n.UHDK_CAP_POINTER_CAPTURE, s.pointer != null);
native.setCapability(n.UHDK_CAP_POINTER_CONFINEMENT, s.pointer != null and s.constraints != null);
native.setCapability(n.UHDK_CAP_TEXT_INPUT, s.context != null and s.keyboard != null);
}
fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callconv(.c) void {
const s = state();
if (caps & c.WL_SEAT_CAPABILITY_KEYBOARD != 0 and s.keyboard == null) {
s.keyboard = c.wl_seat_get_keyboard(seat);
if (s.keyboard != null) _ = c.wl_keyboard_add_listener(s.keyboard, &keyboard_listener, null);
} else if (caps & c.WL_SEAT_CAPABILITY_KEYBOARD == 0 and s.keyboard != null) {
leaveKeyboard();
c.wl_keyboard_release(s.keyboard);
s.keyboard = null;
}
if (caps & c.WL_SEAT_CAPABILITY_POINTER != 0 and s.pointer == null) {
s.pointer = c.wl_seat_get_pointer(seat);
if (s.pointer != null) _ = c.wl_pointer_add_listener(s.pointer, &pointer_listener, null);
} else if (caps & c.WL_SEAT_CAPABILITY_POINTER == 0 and s.pointer != null) {
leavePointer();
if (s.cursor_device != null) c.wp_cursor_shape_device_v1_destroy(s.cursor_device);
s.cursor_device = null;
c.wl_pointer_release(s.pointer);
s.pointer = null;
}
setup();
}
fn seatName(_: ?*anyopaque, _: ?*c.struct_wl_seat, _: [*c]const u8) callconv(.c) void {}
const seat_listener: c.struct_wl_seat_listener = .{
.capabilities = seatCapabilities,
.name = seatName,
};
fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size: u32) callconv(.c) void {
flushKey();
defer _ = c.close(fd);
const s = state();
s.repeat_key = null;
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
if (s.key_focus) |w| Text.cancel(w);
if (s.state != null) c.z_xkb_state_unref.?(s.state);
if (s.keymap != null) c.z_xkb_keymap_unref.?(s.keymap);
s.state = null;
s.keymap = null;
if (s.context == null or format != c.WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 or size == 0 or size > 16 * 1024 * 1024) return;
const mapped = c.mmap(null, size, c.PROT_READ, c.MAP_PRIVATE, fd, 0);
if (mapped == c.MAP_FAILED) return;
defer _ = c.munmap(mapped, size);
const bytes: [*]const u8 = @ptrCast(mapped.?);
if (bytes[size - 1] != 0) return;
s.keymap = c.z_xkb_keymap_new_from_string.?(s.context, @ptrCast(mapped), c.XKB_KEYMAP_FORMAT_TEXT_V1, c.XKB_KEYMAP_COMPILE_NO_FLAGS);
if (s.keymap != null) s.state = c.z_xkb_state_new.?(s.keymap);
}
fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.struct_wl_surface, keys: [*c]c.struct_wl_array) callconv(.c) void {
leaveKeyboard();
const s = state();
s.key_focus = Popup.owner(surface) orelse find(surface);
const suppressed = s.menu_keys;
s.menu_keys = @splat(false);
if (s.state != null and keys.*.size != 0) {
const held: [*]const u32 = @ptrCast(@alignCast(keys.*.data));
for (held[0 .. keys.*.size / 4]) |code| {
if (code < s.held.len) {
s.held[code] = true;
s.menu_keys[code] = suppressed[code];
}
}
}
}
fn keyLeave(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leaveKeyboard();
}
fn updateModifiers() void {
const s = state();
s.modifiers = 0;
if (s.state == null) return;
const names = [_][*:0]const u8{ "Shift", "Control", "Mod1", "Mod4", "Lock", "Mod2" };
for (names, 0..) |name, index| if (c.z_xkb_state_mod_name_is_active.?(s.state, name, c.XKB_STATE_MODS_EFFECTIVE) > 0) {
s.modifiers |= @as(u32, 1) << @intCast(index);
};
}
fn modifiers(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, depressed: u32, latched: u32, locked: u32, group: u32) callconv(.c) void {
const s = state();
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, depressed, latched, locked, 0, 0, group);
updateModifiers();
flushKey();
}
fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state();
flushKey();
if (code > 0xffff) return;
provenance(serial);
if (pressed != 0 and !Popup.active()) popupTrigger(s.key_focus, serial);
if (code < s.held.len) s.held[code] = pressed != 0;
// The compositor supplies the authoritative modifier/group mask. Running
// XKB key actions locally as well would apply latch/lock actions twice.
s.pending_key = prepareKey(code, pressed != 0, false);
// wl_keyboard has no frame event. A sync boundary lets the following
// authoritative modifiers event supply the public post-event flags even
// when the key and modifier messages arrive in separate socket reads.
if (s.key_sync == null) {
s.key_sync = c.wl_display_sync(backend().display);
if (s.key_sync != null) _ = c.wl_callback_add_listener(s.key_sync, &key_sync_listener, null) else flushKey();
}
if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) {
s.repeat_key = code;
s.repeat_at = runtime.now(backend().app.io) + @as(u64, s.repeat_delay) * std.time.ns_per_ms;
} else if (s.repeat_key == code) s.repeat_key = null;
}
fn prepareKey(code: u32, down: bool, repeated: bool) Key {
const s = state();
var value: Key = .{
.code = code,
.down = down,
.repeated = repeated,
.sym = if (s.state != null)
c.z_xkb_state_key_get_one_sym.?(s.state, code + 8)
else
0,
.modifiers = s.modifiers,
};
if (down and s.state != null) {
const length = c.z_xkb_state_key_get_utf8.?(s.state, code + 8, &value.text, value.text.len);
if (length > 0 and length < value.text.len) value.len = @intCast(length);
}
return value;
}
fn deliverKey(code: u32, down: bool, repeated: bool) void {
emitKey(prepareKey(code, down, repeated));
}
fn emitKey(value: Key) void {
const s = state();
const w = s.key_focus orelse return;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_KEY;
event.input_id = id();
event.data.key = .{
.physical_key = Keyboard.physical(value.code),
.logical_key = if (s.state != null) Keyboard.logical(value.sym) else 0,
.modifiers = s.modifiers,
.pressed = @intFromBool(value.down),
.repeat = @intFromBool(value.repeated),
};
if (value.code < s.menu_keys.len) {
if (s.menu_keys[value.code]) {
if (!value.down) s.menu_keys[value.code] = false else if (Popup.active()) Popup.key(event.data.key.logical_key, true, s.serial);
return; // Consume the release/repeats even after flags or focus change.
}
if (Popup.active()) {
s.menu_keys[value.code] = value.down;
Popup.key(event.data.key.logical_key, value.down, s.serial);
return;
}
if (value.down and
!value.repeated and
!w.text.composing and
KdeAppMenu.shortcut(w, event.data.key.logical_key, value.modifiers, event.input_id))
{
s.menu_keys[value.code] = true;
return;
}
}
if (Popup.active()) return;
send(w, &event);
// Resolve symbols/text before consuming a latched modifier, while reporting
// the compositor's post-event flags in the observational raw event.
if (value.down and w.text.enabled) {
Text.key(
w,
value.sym,
event.data.key.logical_key,
event.input_id,
value.modifiers,
value.text[0..value.len],
);
}
}
pub fn flushKey() void {
if (state().pending_key) |value| {
state().pending_key = null;
emitKey(value);
}
}
fn keySynced(_: ?*anyopaque, callback: ?*c.struct_wl_callback, _: u32) callconv(.c) void {
c.wl_callback_destroy(callback);
state().key_sync = null;
flushKey();
}
const key_sync_listener: c.struct_wl_callback_listener = .{ .done = keySynced };
fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32) callconv(.c) void {
state().repeat_rate = @intCast(std.math.clamp(rate, 0, 1000));
state().repeat_delay = @intCast(@max(0, delay));
if (rate <= 0) state().repeat_key = null;
}
const keyboard_listener: c.struct_wl_keyboard_listener = .{
.keymap = keymap,
.enter = keyEnter,
.leave = keyLeave,
.key = key,
.modifiers = modifiers,
.repeat_info = repeatInfo,
};
pub fn tick() i32 {
const s = state();
const active = s.key_focus != null;
if (active != s.active) {
s.active = active;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_APP_ACTIVATION;
event.data.active = @intFromBool(active);
n.z_emit(runtime.toAppHandle(backend().app), &event);
}
if (s.pending_key != null) return -1;
if (s.repeat_key) |code| {
const now = runtime.now(backend().app.io);
if (now >= s.repeat_at) {
deliverKey(code, true, true);
s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate);
}
return @intCast(@min(1000, (s.repeat_at -| now) / std.time.ns_per_ms + 1));
}
return -1;
}
fn leaveKeyboard() void {
flushKey();
const s = state();
s.modifiers = 0;
s.repeat_key = null;
if (s.key_focus) |w| {
if (!Popup.active()) clearPopupTrigger(w);
for (&s.held, 0..) |*held, code| if (held.*) {
held.* = false;
if (!s.menu_keys[code]) deliverKey(@intCast(code), false, false);
};
Text.cancel(w);
}
s.key_focus = null;
// Preserve consumed held keys until the next enter supplies its held-key set.
s.modifiers = 0;
s.serial = 0;
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, 0, 0, 0, 0, 0, 0);
normal(n.UHDK_CYCLE_FOCUS_LOST);
}
fn pointerEvent(kind: u32, button_: u32, pressed: bool, delta: n.uhdk_point) void {
if (Popup.active()) return;
const s = state();
const w = s.pointer_focus orelse return;
var e = std.mem.zeroes(n.z_event);
e.type = kind;
e.input_id = id();
e.data.pointer = .{
.position = s.position,
.delta = delta,
.button = button_,
.pressed = @intFromBool(pressed),
.modifiers = s.modifiers,
.click_count = if (pressed) s.click_count else 0,
};
send(w, &e);
}
fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32) callconv(.c) void {
leavePointer();
const s = state();
s.pointer_focus = find(surface);
s.pointer_serial = serial;
s.position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
if (Popup.pointerEnter(surface, s.position.x, s.position.y, serial)) return;
pointerEvent(n.UHDK_EVENT_POINTER_ENTER, 0, false, .{ .x = 0, .y = 0 });
if (s.pointer_focus) |w| _ = cursor(w, w.cursor);
}
fn pointerLeave(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leavePointer();
}
fn leavePointer() void {
Popup.pointerLeave();
const s = state();
normal(n.UHDK_CYCLE_CAPTURE_LOST);
pointerEvent(n.UHDK_EVENT_POINTER_LEAVE, 0, false, .{ .x = 0, .y = 0 });
s.pointer_focus = null;
s.buttons = 0;
s.pointer_serial = 0;
s.scrolling = false;
s.axis = .{ .x = 0, .y = 0 };
s.wheel = .{ .x = 0, .y = 0 };
s.axis_stop = false;
s.last_click_button = 0;
}
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) callconv(.c) void {
const s = state();
const previous = s.position;
s.position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
if (Popup.active()) {
Popup.motion(s.position.x, s.position.y);
return;
}
pointerEvent(n.UHDK_EVENT_POINTER_MOVE, 0, false, .{ .x = s.position.x - previous.x, .y = s.position.y - previous.y });
}
fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state();
provenance(serial);
const mapped: u32 = switch (code) {
0x110 => n.UHDK_BUTTON_PRIMARY,
0x111 => n.UHDK_BUTTON_SECONDARY,
0x112 => n.UHDK_BUTTON_MIDDLE,
0x113, 0x116 => n.UHDK_BUTTON_BACK,
0x114, 0x115 => n.UHDK_BUTTON_FORWARD,
else => 0,
};
if (mapped == 0) return;
const mask = @as(u32, 1) << @intCast(mapped);
if (Popup.active()) {
if (pressed != 0) s.popup_buttons |= mask else s.popup_buttons &= ~mask;
Popup.button(code, pressed != 0, serial);
return;
}
if (pressed == 0 and s.popup_buttons & mask != 0) {
s.popup_buttons &= ~mask;
return;
}
if (pressed != 0) popupTrigger(s.pointer_focus, serial);
if (pressed != 0) {
s.buttons |= mask;
const now = runtime.now(backend().app.io);
const dx = s.position.x - s.last_click_position.x;
const dy = s.position.y - s.last_click_position.y;
const repeated_click = s.last_click_button == mapped and
now -| s.last_click_time <= 500 * std.time.ns_per_ms and
dx * dx + dy * dy <= 25;
s.click_count = if (repeated_click) @min(3, s.click_count + 1) else 1;
s.last_click_time = now;
s.last_click_button = mapped;
s.last_click_position = s.position;
} else s.buttons &= ~mask;
pointerEvent(n.UHDK_EVENT_POINTER_BUTTON, mapped, pressed != 0, .{ .x = 0, .y = 0 });
if (s.buttons == 0 and s.pointer_mode == n.UHDK_POINTER_CAPTURE) normal(n.UHDK_CYCLE_COMPLETED);
}
fn axis(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, which: u32, value: i32) callconv(.c) void {
const v: f32 = @as(f32, @floatFromInt(value)) / 256;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().axis.y += v else state().axis.x += v;
}
fn axisSource(_: ?*anyopaque, _: ?*c.struct_wl_pointer, source: u32) callconv(.c) void {
state().axis_source = source;
}
fn axisStop(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: u32) callconv(.c) void {
state().axis_stop = true;
}
fn axisDiscrete(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
if (c.wl_pointer_get_version(state().pointer) >= 8) return;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @floatFromInt(value) else state().wheel.x += @floatFromInt(value);
}
fn axis120(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
const amount = @as(f32, @floatFromInt(value)) / 120;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) {
state().wheel.y += amount;
} else {
state().wheel.x += amount;
}
}
fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void {
const s = state();
defer {
s.axis = .{ .x = 0, .y = 0 };
s.wheel = .{ .x = 0, .y = 0 };
s.axis_stop = false;
}
if (Popup.active()) {
const delta = if (s.wheel.y != 0) s.wheel.y * 26 else s.axis.y;
if (delta != 0) Popup.scroll(delta);
return;
}
const w = s.pointer_focus orelse return;
const discrete = s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL or s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL_TILT;
const has_wheel = s.wheel.x != 0 or s.wheel.y != 0;
if (s.axis.x == 0 and s.axis.y == 0 and !has_wheel and !s.axis_stop) return;
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_SCROLL;
e.input_id = id();
e.data.scroll = .{
.position = s.position,
.delta = if (has_wheel) s.wheel else s.axis,
.unit = if (has_wheel) n.UHDK_SCROLL_LINES else n.UHDK_SCROLL_LOGICAL_PIXELS,
.phase = if (discrete)
n.UHDK_SCROLL_DISCRETE
else if (s.axis_stop)
n.UHDK_SCROLL_END
else if (!s.scrolling)
n.UHDK_SCROLL_BEGIN
else
n.UHDK_SCROLL_UPDATE,
.modifiers = s.modifiers,
.momentum = 0,
};
s.scrolling = !discrete and !s.axis_stop;
send(w, &e);
}
const pointer_listener: c.struct_wl_pointer_listener = .{
.enter = pointerEnter,
.leave = pointerLeave,
.motion = motion,
.button = button,
.axis = axis,
.frame = frame,
.axis_source = axisSource,
.axis_stop = axisStop,
.axis_discrete = axisDiscrete,
.axis_value120 = axis120,
.axis_relative_direction = null,
};
pub fn cursor(w: *native.Window, shape: u32) u32 {
w.cursor = shape;
const s = state();
if (shape != n.UHDK_CURSOR_HIDDEN and s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s.pointer_focus != w) return abi.OK;
if (shape == n.UHDK_CURSOR_HIDDEN) {
c.wl_pointer_set_cursor(s.pointer, s.pointer_serial, null, 0, 0);
return abi.OK;
}
if (s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
const shapes = [_]u32{
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT,
};
c.wp_cursor_shape_device_v1_set_shape(s.cursor_device, s.pointer_serial, shapes[shape]);
return abi.OK;
}
pub fn pointerMode(w: *native.Window, mode: u32) u32 {
const s = state();
if (mode == n.UHDK_POINTER_NORMAL) {
release(w, n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK;
}
if (s.mode_window == w and (s.pointer_mode == mode or (mode == n.UHDK_POINTER_CONFINED and s.confined != null))) {
return abi.OK;
}
if (mode == n.UHDK_POINTER_CAPTURE and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE;
if (mode == n.UHDK_POINTER_CONFINED) {
if (s.constraints == null or s.pointer == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s.key_focus != w or s.pointer_focus != w or !w.want_visible or s.position.x < 0 or s.position.y < 0 or s.position.x >= @as(f32, @floatFromInt(w.width)) or s.position.y >= @as(f32, @floatFromInt(w.height))) {
return abi.UNAVAILABLE;
}
const constraint = c.zwp_pointer_constraints_v1_confine_pointer(
s.constraints,
w.surface,
s.pointer,
null, // The complete surface input region follows content resizes.
c.ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT,
) orelse return abi.OOM;
normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
s.mode_window = w;
s.confined = constraint;
_ = c.zwp_confined_pointer_v1_add_listener(constraint, &confined_listener, null);
return abi.OK; // Only the compositor's confined event confirms activation.
}
normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
s.mode_window = w;
s.pointer_mode = mode;
modeEvent(w, mode, n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK;
}
fn modeEvent(w: *native.Window, mode: u32, reason: n.uhdk_cycle_end_reason) void {
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
e.data.pointer_mode = mode;
e.cycle_end_reason = reason;
send(w, &e);
}
fn normal(reason: n.uhdk_cycle_end_reason) void {
const s = state();
const w = s.mode_window orelse return;
if (s.confined != null) c.zwp_confined_pointer_v1_destroy(s.confined);
s.confined = null;
s.mode_window = null;
s.pointer_mode = n.UHDK_POINTER_NORMAL;
modeEvent(w, n.UHDK_POINTER_NORMAL, reason);
}
pub fn release(w: *native.Window, reason: n.uhdk_cycle_end_reason) void {
if (state().mode_window == w) normal(reason);
}
fn confined(_: ?*anyopaque, object: ?*c.struct_zwp_confined_pointer_v1) callconv(.c) void {
const s = state();
if (object != s.confined) return;
const w = s.mode_window orelse return;
if (s.pointer_mode == n.UHDK_POINTER_CONFINED) return;
s.pointer_mode = n.UHDK_POINTER_CONFINED;
modeEvent(w, n.UHDK_POINTER_CONFINED, n.UHDK_CYCLE_COMPLETED);
}
fn unconfined(_: ?*anyopaque, object: ?*c.struct_zwp_confined_pointer_v1) callconv(.c) void {
if (object == state().confined) normal(n.UHDK_CYCLE_CAPTURE_LOST);
}
const confined_listener: c.struct_zwp_confined_pointer_v1_listener = .{
.confined = confined,
.unconfined = unconfined,
};
fn popupTrigger(w: ?*native.Window, serial: u32) void {
const s = state();
s.popup_window = w;
s.popup_serial = serial;
s.popup_time = runtime.now(backend().app.io);
}
pub fn beginPopup() void {
normal(n.UHDK_CYCLE_CAPTURE_LOST);
state().buttons = 0;
state().scrolling = false;
}
pub fn clearPopupTrigger(w: *native.Window) void {
if (state().popup_window == w) {
state().popup_window = null;
state().popup_serial = 0;
}
}
pub fn forget(w: *native.Window) void {
release(w, n.UHDK_CYCLE_CANCELLED);
clearPopupTrigger(w);
if (state().key_focus == w) leaveKeyboard();
if (state().pointer_focus == w) leavePointer();
Text.forget(w);
}
pub fn remove(name: u32) void {
if (name == state().seat_name) releaseSeat();
if (state().constraints != null and name == state().constraints_name) {
if (state().confined != null) normal(n.UHDK_CYCLE_CAPTURE_LOST);
c.zwp_pointer_constraints_v1_destroy(state().constraints);
state().constraints = null;
state().constraints_name = 0;
setup();
}
}
fn releaseSeat() void {
Popup.deinit();
state().popup_serial = 0;
state().popup_window = null;
Data.releaseSeat();
const s = state();
if (s.key_sync != null) c.wl_callback_destroy(s.key_sync);
s.key_sync = null;
leaveKeyboard();
leavePointer();
if (s.text_focus) |w| Text.forget(w);
if (s.text_input != null) c.zwp_text_input_v3_destroy(s.text_input);
if (s.cursor_device != null) c.wp_cursor_shape_device_v1_destroy(s.cursor_device);
if (s.keyboard != null) c.wl_keyboard_release(s.keyboard);
if (s.pointer != null) c.wl_pointer_release(s.pointer);
if (s.seat != null) c.wl_seat_release(s.seat);
s.text_input = null;
s.cursor_device = null;
s.keyboard = null;
s.pointer = null;
s.seat = null;
setup();
}
pub fn deinit() void {
const s = state();
releaseSeat();
if (s.text_manager != null) c.zwp_text_input_manager_v3_destroy(s.text_manager);
if (s.cursor_manager != null) c.wp_cursor_shape_manager_v1_destroy(s.cursor_manager);
if (s.constraints != null) c.zwp_pointer_constraints_v1_destroy(s.constraints);
if (s.compose != null) c.z_xkb_compose_state_unref.?(s.compose);
if (s.compose_table != null) c.z_xkb_compose_table_unref.?(s.compose_table);
if (s.state != null) c.z_xkb_state_unref.?(s.state);
if (s.keymap != null) c.z_xkb_keymap_unref.?(s.keymap);
if (s.context != null) c.z_xkb_context_unref.?(s.context);
}

View File

@ -0,0 +1,586 @@
//! Optional Plasma appmenu adapter. The session bus transport is shared with
//! portals; no toolkit, registrar, X11 window ID, or consumer process is required.
//! All exports and menu references are owned by the native thread.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const runtime = @import("../runtime.zig");
const Resource = @import("../Resource.zig");
const abi = @import("../abi.zig");
const Bus = @import("Bus.zig");
const Portal = @import("Portal.zig");
const Menu = @import("Menu.zig");
const Input = @import("Input.zig");
const iface = "com.canonical.dbusmenu";
const prefix = "/org/uhdk/menu/";
const properties = [_][:0]const u8{ "type", "label", "enabled", "visible", "children-display", "toggle-type", "toggle-state", "shortcut" };
const Node = struct {
item: ?*const n.uhdk_menu_item = null,
parent: usize = 0,
first: usize = 0,
next: usize = 0,
label: [:0]const u8 = "",
flags: u32 = 0,
};
pub const Export = struct {
next: ?*Export = null, // Temporary transaction list, never an object registry.
window: ?*native.Window,
tray: ?*n.uhdk_tray = null,
registry_next: ?*Export = null,
connection: ?*c.DBusConnection = null,
root: *Resource,
arena: std.heap.ArenaAllocator,
nodes: std.ArrayList(Node) = .empty,
path: [:0]const u8,
proxy: ?*c.struct_org_kde_kwin_appmenu = null,
};
pub const State = struct {
manager: ?*c.struct_org_kde_kwin_appmenu_manager = null,
global_name: u32 = 0,
sequence: u64 = 0,
app_menu: ?*Resource = null,
exports: ?*Export = null,
};
fn backend() *native.Backend {
return native.instance.?;
}
fn menuState() *State {
return &backend().menus;
}
fn same(a: []const u8, z: []const u8) bool {
return std.mem.eql(u8, a, z);
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (!same(interface, "org_kde_kwin_appmenu_manager") or menuState().manager != null) return;
menuState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2)));
menuState().global_name = name;
ready();
}
pub fn remove(name: u32) void {
if (name != menuState().global_name) return;
disconnected();
destroyManager();
}
fn destroyManager() void {
if (menuState().manager) |manager| {
if (c.org_kde_kwin_appmenu_manager_get_version(manager) >= 2) c.org_kde_kwin_appmenu_manager_release(manager) else c.org_kde_kwin_appmenu_manager_destroy(manager);
}
menuState().manager = null;
menuState().global_name = 0;
}
pub fn ready() void {
native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready);
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e);
}
fn associate(e: *Export) void {
const window = e.window orelse return;
if (e.proxy != null or menuState().manager == null or !backend().portal.ready) return;
// The export is already reachable by process() before advertising it.
e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, window.surface) orelse return;
c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr);
}
pub fn disconnected() void {
native.setCapability(n.UHDK_CAP_APP_MENU, false);
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e);
}
fn unassociate(e: *Export) void {
if (e.proxy != null) c.org_kde_kwin_appmenu_release(e.proxy);
e.proxy = null;
}
pub fn destroy(e: *Export) void {
var link = &menuState().exports;
while (link.* != e) link = &link.*.?.registry_next;
link.* = e.registry_next;
unassociate(e);
runtime.release(e.root);
e.arena.deinit();
backend().app.gpa.destroy(e);
}
fn add(e: *Export, menu: *Resource, parent: usize) !void {
var previous: usize = 0;
for (menu.payload.menu.items) |*item| {
// Bound work and D-Bus message size even for repeatedly shared subtrees.
if (e.nodes.items.len >= 65536) return error.OutOfMemory;
const index = e.nodes.items.len;
const allocator = e.arena.allocator();
// D-BusMenu uses '_' as a mnemonic marker; UHDK labels are literal text.
var label: std.ArrayList(u8) = .empty;
for (abi.textBytes(item.label)) |byte| {
try label.append(allocator, byte);
if (byte == '_') try label.append(allocator, '_');
}
try label.append(allocator, 0);
try e.nodes.append(allocator, .{ .item = item, .parent = parent, .label = label.items[0 .. label.items.len - 1 :0], .flags = item.flags });
if (previous == 0) e.nodes.items[parent].first = index else e.nodes.items[previous].next = index;
previous = index;
if (item.submenu) |child| try add(e, @ptrCast(@alignCast(child)), index);
}
}
fn create(w: ?*native.Window, root: *Resource) !*Export {
const e = try backend().app.gpa.create(Export);
errdefer backend().app.gpa.destroy(e);
menuState().sequence += 1;
e.* = .{ .window = w, .root = root, .arena = .init(backend().app.gpa), .path = "" };
errdefer e.arena.deinit();
e.path = try std.fmt.allocPrintSentinel(e.arena.allocator(), prefix ++ "{d}", .{menuState().sequence}, 0);
try e.nodes.append(e.arena.allocator(), .{});
try add(e, root, 0);
runtime.retain(root);
e.registry_next = menuState().exports;
menuState().exports = e;
return e;
}
pub fn createTray(tray: *n.uhdk_tray, root: *Resource) !*Export {
const e = try create(null, root);
e.tray = tray;
return e;
}
fn replace(w: *native.Window, e: ?*Export) void {
const old = w.menu_export;
w.menu_export = e;
if (old) |value| destroy(value);
if (e) |value| associate(value);
}
pub fn inherit(w: *native.Window) !void {
if (menuState().app_menu) |root| replace(w, try create(w, root));
}
pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null;
if (root != null) {
if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED;
if (backend().portal.connection == null) return abi.UNAVAILABLE;
}
if (w) |window| {
const effective = root orelse menuState().app_menu;
const e = if (effective) |r| create(window, r) catch return abi.OOM else null;
if (root) |r| runtime.retain(r);
if (window.menu_override) |r| runtime.release(r);
window.menu_override = root;
replace(window, e);
} else {
// Prepare every replacement before committing; OOM leaves attachments intact.
var pending: ?*Export = null;
defer while (pending) |e| {
pending = e.next;
destroy(e);
};
if (root) |r| {
var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
const e = create(window, r) catch return abi.OOM;
e.next = pending;
pending = e;
};
runtime.retain(r);
}
if (menuState().app_menu) |r| runtime.release(r);
menuState().app_menu = root;
if (root == null) {
var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
replace(window, null);
};
}
while (pending) |e| {
pending = e.next;
e.next = null;
replace(e.window.?, e);
}
}
return abi.OK;
}
pub fn forget(w: *native.Window) void {
replace(w, null);
if (w.menu_override) |root| runtime.release(root);
w.menu_override = null;
}
pub fn deinit() void {
if (menuState().app_menu) |root| runtime.release(root);
menuState().app_menu = null;
destroyManager();
}
fn enabled(e: *Export, index: usize) bool {
var i = index;
while (i != 0) : (i = e.nodes.items[i].parent) if (e.nodes.items[i].item.?.flags & n.UHDK_MENU_DISABLED != 0) return false;
return true;
}
fn activate(e: *Export, index: usize, input_id: u64) void {
const item = e.nodes.items[index].item orelse return;
if (!enabled(e, index) or item.flags & n.UHDK_MENU_SEPARATOR != 0 or item.submenu != null) return;
if (e.tray) |tray| n.z_tray_command(tray, item) else Menu.activate(e.window.?, item, input_id);
}
fn folded(key: u32) u32 {
return if (key >= 'A' and key <= 'Z') key + ('a' - 'A') else key;
}
pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool {
const e = w.menu_export orelse return false;
if (key == 0) return false;
const mask: u32 = n.UHDK_MOD_SHIFT | n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER;
for (e.nodes.items[1..], 1..) |node, i| {
const item = node.item.?;
if (item.submenu != null or item.flags & n.UHDK_MENU_SEPARATOR != 0 or !enabled(e, i)) continue;
if (folded(item.shortcut_key) == folded(key) and item.shortcut_modifiers & mask == mods & mask) {
activate(e, i, input_id);
return true;
}
}
return false;
}
fn nodeId(e: *Export, value: i32) ?usize {
return if (value >= 0 and value < e.nodes.items.len) @intCast(value) else null;
}
fn variant(i: *Bus.Iter, comptime sig: [:0]const u8, value: anytype) !void {
var v = try Bus.open(i, c.DBUS_TYPE_VARIANT, sig);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &v);
try Bus.basic(&v, sig[0], value);
try Bus.close(i, &v);
}
fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
const node = e.nodes.items[index];
const item = node.item;
const flags = if (item) |v| v.flags else 0;
if (same(name, "type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_SEPARATOR != 0) "separator" else "standard")) else if (same(name, "label")) try variant(out, "s", node.label.ptr) else if (same(name, "enabled")) try variant(out, "b", @as(u32, @intFromBool(enabled(e, index)))) else if (same(name, "visible")) try variant(out, "b", @as(u32, 1)) else if (same(name, "children-display")) try variant(out, "s", @as([*:0]const u8, if (index == 0 or (item != null and item.?.submenu != null)) "submenu" else "")) else if (same(name, "toggle-type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_CHECKED != 0) "checkmark" else "")) else if (same(name, "toggle-state")) try variant(out, "i", @as(i32, if (flags & n.UHDK_MENU_CHECKED != 0) 1 else 0)) else if (same(name, "shortcut")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "aas");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var arrays = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &arrays);
var buffer: [32]u8 = undefined;
if (item) |value| if (Menu.keyName(value.shortcut_key, &buffer)) |key_name| {
var keys = try Bus.open(&arrays, c.DBUS_TYPE_ARRAY, "s");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&arrays, &keys);
inline for (.{ .{ n.UHDK_MOD_CONTROL, "Control" }, .{ n.UHDK_MOD_ALT, "Alt" }, .{ n.UHDK_MOD_SHIFT, "Shift" }, .{ n.UHDK_MOD_SUPER, "Super" } }) |mod| {
if (value.shortcut_modifiers & mod[0] != 0) try Bus.string(&keys, mod[1]);
}
try Bus.string(&keys, key_name.ptr);
try Bus.close(&arrays, &keys);
};
try Bus.close(&v, &arrays);
try Bus.close(out, &v);
} else return false;
return true;
}
fn wanted(filter: ?Bus.Iter, name: []const u8) bool {
var iter = filter orelse return true;
if (Bus.kind(&iter) == c.DBUS_TYPE_INVALID) return true;
while (Bus.str(&iter)) |value| {
if (same(value, name)) return true;
if (!Bus.next(&iter)) break;
}
return false;
}
fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var dict = try Bus.open(out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &dict);
for (properties) |name| if (wanted(filter, name)) {
var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
try Bus.string(&pair, name.ptr);
_ = try property(e, index, name, &pair);
try Bus.close(&dict, &pair);
};
try Bus.close(out, &dict);
}
fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter) Bus.Error!void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(index)));
try props(e, index, filter, &tuple);
var children = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "v");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &children);
if (depth != 0) {
var cursor = e.nodes.items[index].first;
while (cursor != 0) : (cursor = e.nodes.items[cursor].next) {
var v = try Bus.open(&children, c.DBUS_TYPE_VARIANT, "(ia{sv}av)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&children, &v);
try layout(e, cursor, if (depth < 0) -1 else depth - 1, filter, &v);
try Bus.close(&children, &v);
}
}
try Bus.close(&tuple, &children);
try Bus.close(out, &tuple);
}
fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(index)));
try props(e, index, filter, &tuple);
try Bus.close(out, &tuple);
}
pub fn updateFlags() u32 {
var cursor = menuState().exports;
while (cursor) |e| : (cursor = e.registry_next) {
changed(e) catch return abi.OOM;
}
return abi.OK;
}
fn changed(e: *Export) !void {
var dirty = false;
for (e.nodes.items[1..]) |node| if (node.flags != node.item.?.flags) {
dirty = true;
break;
};
if (!dirty) return;
if ((backend().portal.ready and e.proxy != null) or e.connection != null) {
const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message);
var out = Bus.append(message);
var updates = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &updates);
// Include descendants: a disabled ancestor also disables their activation.
for (e.nodes.items[1..], 1..) |_, i| try groupItem(e, i, null, &updates);
try Bus.close(&out, &updates);
var removed = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ias)");
try Bus.close(&out, &removed);
_ = try send(e, message);
}
for (e.nodes.items[1..]) |*node| node.flags = node.item.?.flags;
}
fn send(e: *Export, message: *Bus.Message) !u32 {
if (e.connection) |connection| {
var serial: u32 = 0;
if (c.z_dbus_connection_send.?(connection, message, &serial) == 0) return error.OutOfMemory;
return serial;
}
return Portal.send(message);
}
fn fail(e: *Export, message: *Bus.Message, name: [*:0]const u8) !void {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
const reply = c.z_dbus_message_new_error.?(message, name, "Menu request could not be handled") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
_ = try send(e, reply);
}
const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
const missing = "com.canonical.dbusmenu.Error.InvalidMenuItem";
fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool {
const a = c.z_dbus_message_get_interface.?(message);
const z = c.z_dbus_message_get_member.?(message);
return a != null and z != null and same(std.mem.span(a), interface) and same(std.mem.span(z), member);
}
fn signature(message: *Bus.Message, sig: [*:0]const u8) bool {
return c.z_dbus_message_has_signature.?(message, sig) != 0;
}
fn globalProperty(name: []const u8, out: *Bus.Iter) !bool {
if (same(name, "Version")) try variant(out, "u", @as(u32, 3)) else if (same(name, "TextDirection")) try variant(out, "s", @as([*:0]const u8, "ltr")) else if (same(name, "Status")) try variant(out, "s", @as([*:0]const u8, "normal")) else if (same(name, "IconThemePath")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var paths = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "s");
try Bus.close(&v, &paths);
try Bus.close(out, &v);
} else return false;
return true;
}
pub fn process(message: *Bus.Message) !bool {
if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return false;
const path = c.z_dbus_message_get_path.?(message);
if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false;
var found: ?*Export = null;
var cursor = menuState().exports;
while (cursor) |e| : (cursor = e.registry_next) {
if (e.tray == null and same(e.path, std.mem.span(path))) {
found = e;
break;
}
}
if (found) |e| {
try dispatch(e, message);
} else {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return true;
const reply = c.z_dbus_message_new_error.?(message, "org.freedesktop.DBus.Error.UnknownObject", "Unknown menu") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
_ = try Portal.send(reply);
}
return true;
}
pub fn dispatch(e: *Export, message: *Bus.Message) !void {
const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
var out = Bus.append(reply);
var args = Bus.parse(message);
if (callIs(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
if (!signature(message, "")) return fail(e, message, invalid);
try Bus.string(&out, @embedFile("dbusmenu.xml"));
} else if (callIs(message, "org.freedesktop.DBus.Peer", "Ping")) {
if (!signature(message, "")) return fail(e, message, invalid);
} else if (callIs(message, "org.freedesktop.DBus.Properties", "Get") or callIs(message, "org.freedesktop.DBus.Properties", "GetAll")) {
const single = callIs(message, "org.freedesktop.DBus.Properties", "Get");
if (!signature(message, if (single) "ss" else "s")) return fail(e, message, invalid);
if (!same(Bus.str(&args).?, iface)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownInterface");
if (single) {
_ = Bus.next(&args);
if (!try globalProperty(Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else {
var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
for ([_][:0]const u8{ "Version", "TextDirection", "Status", "IconThemePath" }) |name| {
var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
try Bus.string(&pair, name.ptr);
_ = try globalProperty(name, &pair);
try Bus.close(&dict, &pair);
}
try Bus.close(&out, &dict);
}
} else if (callIs(message, iface, "GetLayout")) {
if (!signature(message, "iias")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
const depth = Bus.int(&args).?;
if (depth < -1) return fail(e, message, invalid);
_ = Bus.next(&args);
try Bus.basic(&out, c.DBUS_TYPE_UINT32, @as(u32, 1));
try layout(e, index, depth, Bus.child(&args), &out);
} else if (callIs(message, iface, "GetGroupProperties")) {
if (!signature(message, "aias")) return fail(e, message, invalid);
var ids = Bus.child(&args);
_ = Bus.next(&args);
const filter = Bus.child(&args);
var items = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &items);
if (Bus.kind(&ids) == c.DBUS_TYPE_INVALID) {
for (e.nodes.items, 0..) |_, i| try groupItem(e, i, filter, &items);
} else while (Bus.int(&ids)) |value| {
if (nodeId(e, value)) |i| try groupItem(e, i, filter, &items);
if (!Bus.next(&ids)) break;
}
try Bus.close(&out, &items);
} else if (callIs(message, iface, "GetProperty")) {
if (!signature(message, "is")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
if (!try property(e, index, Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else if (callIs(message, iface, "Event")) {
if (!signature(message, "isvu")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
if (same(Bus.str(&args).?, "clicked")) activate(e, index, Input.id());
} else if (callIs(message, iface, "AboutToShow")) {
if (!signature(message, "i")) return fail(e, message, invalid);
_ = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
try Bus.basic(&out, c.DBUS_TYPE_BOOLEAN, @as(u32, 0));
} else if (callIs(message, iface, "EventGroup") or callIs(message, iface, "AboutToShowGroup")) {
const events = callIs(message, iface, "EventGroup");
if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(e, message, invalid);
var ids = Bus.child(&args);
if (!events) {
var empty = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
try Bus.close(&out, &empty);
}
var errors = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &errors);
var valid_count: usize = 0;
var error_count: usize = 0;
while (Bus.kind(&ids) != c.DBUS_TYPE_INVALID) {
var value = if (events) Bus.child(&ids) else ids;
const number = Bus.int(&value).?;
if (nodeId(e, number)) |index| {
valid_count += 1;
if (events) {
_ = Bus.next(&value);
if (same(Bus.str(&value).?, "clicked")) activate(e, index, Input.id());
}
} else {
error_count += 1;
try Bus.basic(&errors, c.DBUS_TYPE_INT32, number);
}
if (!Bus.next(&ids)) break;
}
try Bus.close(&out, &errors);
if (valid_count == 0 and error_count != 0) return fail(e, message, missing);
} else return fail(e, message, "org.freedesktop.DBus.Error.UnknownMethod");
if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try send(e, reply);
}

View File

@ -0,0 +1,64 @@
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
/// evdev keyboard codes to USB HID keyboard-page usages. Values describe
/// physical positions, independently of the compositor-supplied XKB layout.
pub fn physical(code: u32) u32 {
const map = comptime blk: {
var t: [256]u16 = @splat(0);
const pairs = [_][2]u16{
.{ 1, 41 }, .{ 12, 45 }, .{ 13, 46 }, .{ 14, 42 }, .{ 15, 43 }, .{ 26, 47 }, .{ 27, 48 }, .{ 28, 40 }, .{ 29, 224 },
.{ 39, 51 }, .{ 40, 52 }, .{ 41, 53 }, .{ 42, 225 }, .{ 43, 49 }, .{ 51, 54 }, .{ 52, 55 }, .{ 53, 56 }, .{ 54, 229 },
.{ 55, 85 }, .{ 56, 226 }, .{ 57, 44 }, .{ 58, 57 }, .{ 69, 83 }, .{ 70, 71 }, .{ 71, 95 }, .{ 72, 96 }, .{ 73, 97 },
.{ 74, 86 }, .{ 75, 92 }, .{ 76, 93 }, .{ 77, 94 }, .{ 78, 87 }, .{ 79, 89 }, .{ 80, 90 }, .{ 81, 91 }, .{ 82, 98 },
.{ 83, 99 }, .{ 86, 100 }, .{ 87, 68 }, .{ 88, 69 }, .{ 96, 88 }, .{ 97, 228 }, .{ 98, 84 }, .{ 99, 70 }, .{ 100, 230 },
.{ 102, 74 }, .{ 103, 82 }, .{ 104, 75 }, .{ 105, 80 }, .{ 106, 79 }, .{ 107, 77 }, .{ 108, 81 }, .{ 109, 78 }, .{ 110, 73 },
.{ 111, 76 }, .{ 119, 72 }, .{ 125, 227 }, .{ 126, 231 }, .{ 127, 101 },
};
for (pairs) |p| t[p[0]] = p[1];
for (0..10) |i| t[2 + i] = 30 + i;
for (0..10) |i| t[59 + i] = 58 + i;
for (0..12) |i| t[183 + i] = 104 + i;
for ("qwertyuiop", 16..) |letter, code_| t[code_] = letter - 'a' + 4;
for ("asdfghjkl", 30..) |letter, code_| t[code_] = letter - 'a' + 4;
for ("zxcvbnm", 44..) |letter, code_| t[code_] = letter - 'a' + 4;
break :blk t;
};
return if (code < map.len) map[code] else 0;
}
pub fn logical(sym: u32) u32 {
return switch (sym) {
c.XKB_KEY_Escape => n.UHDK_KEY_ESCAPE,
c.XKB_KEY_Return, c.XKB_KEY_KP_Enter => n.UHDK_KEY_ENTER,
c.XKB_KEY_Tab, c.XKB_KEY_ISO_Left_Tab => n.UHDK_KEY_TAB,
c.XKB_KEY_BackSpace => n.UHDK_KEY_BACKSPACE,
c.XKB_KEY_Delete, c.XKB_KEY_KP_Delete => n.UHDK_KEY_DELETE,
c.XKB_KEY_Insert, c.XKB_KEY_KP_Insert => n.UHDK_KEY_INSERT,
c.XKB_KEY_Left, c.XKB_KEY_KP_Left => n.UHDK_KEY_LEFT,
c.XKB_KEY_Right, c.XKB_KEY_KP_Right => n.UHDK_KEY_RIGHT,
c.XKB_KEY_Up, c.XKB_KEY_KP_Up => n.UHDK_KEY_UP,
c.XKB_KEY_Down, c.XKB_KEY_KP_Down => n.UHDK_KEY_DOWN,
c.XKB_KEY_Home, c.XKB_KEY_KP_Home => n.UHDK_KEY_HOME,
c.XKB_KEY_End, c.XKB_KEY_KP_End => n.UHDK_KEY_END,
c.XKB_KEY_Page_Up, c.XKB_KEY_KP_Page_Up => n.UHDK_KEY_PAGE_UP,
c.XKB_KEY_Page_Down, c.XKB_KEY_KP_Page_Down => n.UHDK_KEY_PAGE_DOWN,
c.XKB_KEY_F1...c.XKB_KEY_F24 => @as(u32, n.UHDK_KEY_F1) + sym - c.XKB_KEY_F1,
else => c.z_xkb_keysym_to_utf32.?(sym),
};
}
pub fn edit(key: u32, mods: u32) u32 {
return n.z_edit_key(key, mods);
}
test "physical positions and editor shortcuts" {
try std.testing.expectEqual(@as(u32, 4), physical(30));
try std.testing.expectEqual(@as(u32, 29), physical(44));
try std.testing.expectEqual(@as(u32, 0), physical(500));
try std.testing.expectEqual(@as(u32, n.UHDK_EDIT_COPY), edit('c', n.UHDK_MOD_CONTROL));
try std.testing.expectEqual(@as(u32, 0), edit('c', n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT));
try std.testing.expectEqual(@as(u32, n.UHDK_EDIT_DOCUMENT_START), edit(n.UHDK_KEY_HOME, n.UHDK_MOD_CONTROL));
}

66
desktop/vendor/uhdk/src/linux/Menu.zig vendored Normal file
View File

@ -0,0 +1,66 @@
//! Linux menu role dispatch and shortcut names shared by desktop exports/popups.
const std = @import("std");
const n = @import("native");
const native = @import("native.zig");
const runtime = @import("../runtime.zig");
const Input = @import("Input.zig");
const Text = @import("Text.zig");
pub fn activate(window: *native.Window, item: *const n.uhdk_menu_item, input_id: u64) void {
var event = std.mem.zeroes(n.z_event);
if (item.role == n.UHDK_MENU_ROLE_QUIT) {
event.type = n.UHDK_EVENT_QUIT_REQUESTED;
n.z_emit(runtime.toAppHandle(window.owner), &event);
} else if (item.role >= n.UHDK_MENU_ROLE_COPY and item.role <= n.UHDK_MENU_ROLE_REDO) {
Text.editCommand(window, @as(u32, n.UHDK_EDIT_COPY) + item.role - n.UHDK_MENU_ROLE_COPY, 0, input_id);
} else {
event.type = n.UHDK_EVENT_MENU_COMMAND;
event.data.menu.command_id = item.command_id;
Input.send(window, &event);
}
}
pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 {
if (key >= n.UHDK_KEY_F1 and key < n.UHDK_KEY_F1 + 24) return std.mem.printSentinel(buffer, "F{d}", .{key - n.UHDK_KEY_F1 + 1}, 0) catch unreachable;
switch (key) {
n.UHDK_KEY_ESCAPE => return "Escape",
n.UHDK_KEY_ENTER => return "Return",
n.UHDK_KEY_TAB => return "Tab",
n.UHDK_KEY_BACKSPACE => return "BackSpace",
n.UHDK_KEY_DELETE => return "Delete",
n.UHDK_KEY_INSERT => return "Insert",
n.UHDK_KEY_LEFT => return "Left",
n.UHDK_KEY_RIGHT => return "Right",
n.UHDK_KEY_UP => return "Up",
n.UHDK_KEY_DOWN => return "Down",
n.UHDK_KEY_HOME => return "Home",
n.UHDK_KEY_END => return "End",
n.UHDK_KEY_PAGE_UP => return "Page_Up",
n.UHDK_KEY_PAGE_DOWN => return "Page_Down",
' ' => return "space",
else => {},
}
if (key < 0x21 or key > 0x10ffff) return null;
const k = if (key >= 'a' and key <= 'z') key - ('a' - 'A') else key;
const len = std.unicode.utf8Encode(@intCast(k), buffer) catch return null;
buffer[len] = 0;
return buffer[0..len :0];
}
pub fn shortcut(item: n.uhdk_menu_item, buffer: *[96]u8) []const u8 {
var key_buffer: [32]u8 = undefined;
const key = keyName(item.shortcut_key, &key_buffer) orelse return "";
var end: usize = 0;
inline for (.{ .{ n.UHDK_MOD_CONTROL, "Ctrl+" }, .{ n.UHDK_MOD_ALT, "Alt+" }, .{ n.UHDK_MOD_SHIFT, "Shift+" }, .{ n.UHDK_MOD_SUPER, "Super+" } }) |mod| {
if (item.shortcut_modifiers & mod[0] != 0) {
@memcpy(buffer[end..][0..mod[1].len], mod[1]);
end += mod[1].len;
}
}
@memcpy(buffer[end..][0..key.len], key);
end += key.len;
return buffer[0..end];
}

554
desktop/vendor/uhdk/src/linux/Popup.zig vendored Normal file
View File

@ -0,0 +1,554 @@
//! Small software-rendered xdg_popup menus. One active request owns a stack of
//! panels, with two wl_shm buffers per panel. Everything runs on the native thread.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const runtime = @import("../runtime.zig");
const Resource = @import("../Resource.zig");
const abi = @import("../abi.zig");
const Input = @import("Input.zig");
const Menu = @import("Menu.zig");
const Bitmap = @import("Bitmap.zig");
const Buffer = struct {
proxy: ?*c.struct_wl_buffer = null,
mapping: ?*anyopaque = null,
size: usize = 0,
busy: bool = false,
};
const Panel = struct {
parent: ?*Panel,
menu: *Resource,
surface: ?*c.struct_wl_surface = null,
xdg: ?*c.struct_xdg_surface = null,
popup: ?*c.struct_xdg_popup = null,
buffers: [2]Buffer = .{ .{}, .{} },
width: i32 = 180,
height: i32 = 32,
scale: i32 = 1,
pending_width: i32 = 180,
pending_height: i32 = 32,
total: i32 = 8,
scroll: i32 = 0,
selected: ?usize = null,
pressed: ?usize = null,
configured: bool = false,
dirty: bool = true,
deadline: u64 = 0,
};
pub const State = struct {
window: ?*native.Window = null,
root: ?*Resource = null,
top: ?*Panel = null,
pointer: ?*Panel = null,
request: u64 = 0,
serial: u32 = 0,
hover_at: u64 = 0,
};
fn backend() *native.Backend {
return native.instance.?;
}
fn popupState() *State {
return &backend().popup;
}
pub fn active() bool {
return popupState().request != 0;
}
pub fn capability() void {
native.setCapability(n.UHDK_CAP_CONTEXT_MENU, backend().desktop.shm != null and Input.state().seat != null);
}
fn panel(raw: ?*anyopaque) *Panel {
return @ptrCast(@alignCast(raw.?));
}
fn rowHeight(item: n.uhdk_menu_item) i32 {
return if (item.flags & n.UHDK_MENU_SEPARATOR != 0) 9 else 26;
}
fn usable(item: n.uhdk_menu_item) bool {
return item.flags & (n.UHDK_MENU_DISABLED | n.UHDK_MENU_SEPARATOR) == 0;
}
fn rowY(p: *Panel, index: usize) i32 {
var y: i32 = 4;
for (p.menu.payload.menu.items[0..index]) |item| y += rowHeight(item);
return y - p.scroll;
}
fn lookup(surface: ?*c.struct_wl_surface) ?*Panel {
var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p;
return null;
}
pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window {
return if (lookup(surface) != null) popupState().window else null;
}
fn freeBuffer(buf: *Buffer) void {
if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy);
if (buf.mapping) |mapping| _ = c.munmap(mapping, buf.size);
buf.* = .{};
}
fn destroy(p: *Panel) void {
if (popupState().pointer == p) popupState().pointer = null;
if (p.popup != null) c.xdg_popup_destroy(p.popup);
if (p.xdg != null) c.xdg_surface_destroy(p.xdg);
if (p.surface != null) c.wl_surface_destroy(p.surface);
for (&p.buffers) |*buf| freeBuffer(buf);
backend().app.gpa.destroy(p);
}
fn closeChildren(p: *Panel) void {
while (popupState().top != p) {
const top = popupState().top orelse return;
popupState().top = top.parent;
destroy(top);
}
}
fn finish(status: u32) void {
if (!active()) return;
const request_id = popupState().request;
while (popupState().top) |top| {
popupState().top = top.parent;
destroy(top);
}
const root = popupState().root.?;
popupState().* = .{};
runtime.release(root);
n.z_complete(runtime.toAppHandle(backend().app), request_id, status, null);
}
pub fn forget(w: *native.Window) void {
if (popupState().window == w) finish(abi.CANCELLED);
}
pub fn cancel(id: u64) bool {
if (popupState().request != id or !active()) return false;
finish(abi.CANCELLED);
return true;
}
pub fn deinit() void {
finish(abi.CANCELLED);
}
pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (active()) return n.UHDK_STATUS_BUSY;
if (backend().desktop.shm == null or Input.state().seat == null) return n.UHDK_STATUS_UNSUPPORTED;
const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.other) orelse return abi.UNAVAILABLE));
const input = Input.state();
if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(backend().app.io) -| input.popup_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE;
const root: *Resource = @ptrCast(@alignCast(cmd.target.?));
if (root.payload.menu.items.len == 0) return abi.CANCELLED;
popupState().window = w;
popupState().root = root;
popupState().serial = input.popup_serial;
runtime.retain(root);
const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) };
const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch {
runtime.release(root);
popupState().* = .{};
return abi.OOM;
};
popupState().top = p;
popupState().request = id;
Input.beginPopup();
input.popup_serial = 0; // A root grab consumes its triggering action.
return n.Z_DEFERRED;
}
fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel {
const p = try backend().app.gpa.create(Panel);
p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((popupState().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s };
errdefer destroy(p);
for (menu.payload.menu.items) |item| {
var buffer: [96]u8 = undefined;
p.width = @max(p.width, 60 + Bitmap.width(abi.textBytes(item.label)) + Bitmap.width(Menu.shortcut(item, &buffer)));
p.total += rowHeight(item);
}
p.width = @min(p.width, 480);
p.height = @min(p.total, 480);
p.pending_width = p.width;
p.pending_height = p.height;
p.surface = c.wl_compositor_create_surface(backend().compositor) orelse return error.OutOfMemory;
if (c.wl_surface_add_listener(p.surface, &surface_listener, p) != 0) return error.OutOfMemory;
p.xdg = c.xdg_wm_base_get_xdg_surface(backend().shell, p.surface) orelse return error.OutOfMemory;
if (c.xdg_surface_add_listener(p.xdg, &xdg_listener, p) != 0) return error.OutOfMemory;
const pos = c.xdg_wm_base_create_positioner(backend().shell) orelse return error.OutOfMemory;
defer c.xdg_positioner_destroy(pos);
c.xdg_positioner_set_size(pos, p.width, p.height);
c.xdg_positioner_set_anchor_rect(pos, x, y, 1, @max(1, anchor_height));
c.xdg_positioner_set_anchor(pos, if (parent != null) c.XDG_POSITIONER_ANCHOR_TOP_RIGHT else c.XDG_POSITIONER_ANCHOR_BOTTOM_LEFT);
c.xdg_positioner_set_gravity(pos, c.XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT);
c.xdg_positioner_set_constraint_adjustment(pos, c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y);
p.popup = c.xdg_surface_get_popup(p.xdg, if (parent) |v| v.xdg else popupState().window.?.xdg, pos) orelse return error.OutOfMemory;
if (c.xdg_popup_add_listener(p.popup, &popup_listener, p) != 0) return error.OutOfMemory;
c.xdg_popup_grab(p.popup, Input.state().seat, popupState().serial);
c.wl_surface_commit(p.surface);
return p;
}
fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i32, height: i32) callconv(.c) void {
const p = panel(raw);
if (width < 1 or height < 1 or width > 1024 or height > 1024) {
finish(n.UHDK_STATUS_OS_ERROR);
return;
}
// Geometry belongs to the next xdg_surface.configure, which can arrive in
// another socket read. Do not render/commit it before acknowledging that.
p.pending_width = width;
p.pending_height = height;
p.configured = false;
p.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
}
fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const p = panel(raw);
c.xdg_surface_ack_configure(p.xdg, serial);
if (p.width != p.pending_width or p.height != p.pending_height) {
for (&p.buffers) |*buf| freeBuffer(buf);
p.width = p.pending_width;
p.height = p.pending_height;
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
}
p.configured = true;
p.deadline = 0;
p.dirty = true;
render(p) catch finish(abi.OOM);
}
fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void {
const p = panel(raw);
if (p.parent) |parent| {
closeChildren(parent);
popupState().hover_at = 0;
} else finish(abi.CANCELLED);
}
fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {}
const popup_listener: c.struct_xdg_popup_listener = .{ .configure = configure, .popup_done = done, .repositioned = repositioned };
const xdg_listener: c.struct_xdg_surface_listener = .{ .configure = configured };
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {}
fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) void {
const p = panel(raw);
const next = std.math.clamp(value, 1, 4);
if (next == p.scale) return;
p.scale = next;
for (&p.buffers) |*buf| freeBuffer(buf);
p.dirty = true;
}
fn transform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {}
const surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = scale, .preferred_buffer_transform = transform };
fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void {
const p = panel(raw);
for (&p.buffers) |*buf| if (buf.proxy == proxy) {
buf.busy = false;
};
}
const buffer_listener: c.struct_wl_buffer_listener = .{ .release = released };
fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
const size: usize = @intCast(p.width * p.height * p.scale * p.scale * 4);
const fd = c.memfd_create("uhdk-menu", c.MFD_CLOEXEC);
if (fd < 0) return error.OutOfMemory;
defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return error.OutOfMemory;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return error.OutOfMemory;
buf.mapping = mapping;
buf.size = size;
errdefer freeBuffer(buf);
const pool = c.wl_shm_create_pool(backend().desktop.shm, fd, @intCast(size)) orelse return error.OutOfMemory;
defer c.wl_shm_pool_destroy(pool);
buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory;
if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory;
}
fn render(p: *Panel) !void {
if (!p.configured or !p.dirty) return;
const buf: *Buffer = for (&p.buffers) |*value| {
if (!value.busy) break value;
} else return;
if (buf.proxy == null) try allocateBuffer(p, buf);
const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?));
const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale };
paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, backend().portal.preferences.appearance == n.UHDK_APPEARANCE_LIGHT);
c.wl_surface_set_buffer_scale(p.surface, p.scale);
c.xdg_surface_set_window_geometry(p.xdg, 0, 0, p.width, p.height);
c.wl_surface_attach(p.surface, buf.proxy, 0, 0);
c.wl_surface_damage_buffer(p.surface, 0, 0, p.width * p.scale, p.height * p.scale);
c.wl_surface_commit(p.surface);
buf.busy = true;
p.dirty = false;
}
pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?usize, scroll_offset: i32, light: bool) void {
const background: u32 = if (light) 0xf6f6f6 else 0x292c30;
const foreground: u32 = if (light) 0x202124 else 0xf1f2f3;
const border: u32 = if (light) 0xc4c7ca else 0x53585e;
canvas.rect(0, 0, canvas.width, canvas.height, background);
var y: i32 = 4 - scroll_offset;
for (items, 0..) |item, i| {
const height = rowHeight(item);
defer y += height;
if (y + height <= 4 or y >= canvas.height - 4) continue;
if (item.flags & n.UHDK_MENU_SEPARATOR != 0) {
canvas.rect(8, y + 4, canvas.width - 16, 1, border);
continue;
}
const color: u32 = if (item.flags & n.UHDK_MENU_DISABLED != 0) (if (light) @as(u32, 0x85888c) else 0x8d939a) else if (selected == i) 0xffffff else foreground;
if (selected == i and usable(item)) canvas.rect(3, y, canvas.width - 6, height, 0x2969b0);
if (item.flags & n.UHDK_MENU_CHECKED != 0) {
for (0..4) |j| canvas.rect(10 + @as(i32, @intCast(j)), y + 12 + @as(i32, @intCast(j)), 2, 2, color);
for (0..7) |j| canvas.rect(13 + @as(i32, @intCast(j)), y + 15 - @as(i32, @intCast(j)), 2, 2, color);
}
var storage: [96]u8 = undefined;
const shortcut = Menu.shortcut(item, &storage);
const shortcut_width = @min(Bitmap.width(shortcut), @max(0, @divTrunc(canvas.width, 2) - 30));
const label_width = @max(0, canvas.width - 52 - (if (shortcut.len != 0) shortcut_width + 18 else 0));
canvas.text(abi.textBytes(item.label), 28, y + 18, label_width, color);
if (shortcut.len != 0) canvas.text(shortcut, canvas.width - 22 - shortcut_width, y + 18, shortcut_width, color);
if (item.submenu != null) for (0..5) |j| {
const offset: i32 = @intCast(j);
canvas.rect(canvas.width - 13 + offset, y + 8 + offset, 1, 9 - 2 * offset, color);
};
}
// Padding masks partially scrolled rows and keeps the border intact.
canvas.rect(0, 0, canvas.width, 4, background);
canvas.rect(0, canvas.height - 4, canvas.width, 4, background);
canvas.rect(0, 0, canvas.width, 1, border);
canvas.rect(0, canvas.height - 1, canvas.width, 1, border);
canvas.rect(0, 0, 1, canvas.height, border);
canvas.rect(canvas.width - 1, 0, 1, canvas.height, border);
if (scroll_offset > 0) canvas.rect(@divTrunc(canvas.width, 2) - 5, 1, 10, 2, foreground);
if (y > canvas.height - 4) canvas.rect(@divTrunc(canvas.width, 2) - 5, canvas.height - 3, 10, 2, foreground);
}
fn choose(p: *Panel, index: ?usize) void {
if (p.selected == index) return;
closeChildren(p);
p.selected = index;
p.pressed = null;
p.dirty = true;
popupState().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(backend().app.io) + 200 * std.time.ns_per_ms else 0;
}
fn hit(p: *Panel, x: f32, y: f32) ?usize {
if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null;
var top: i32 = 4 - p.scroll;
for (p.menu.payload.menu.items, 0..) |item, i| {
const bottom = top + rowHeight(item);
if (y >= @as(f32, @floatFromInt(top)) and y < @as(f32, @floatFromInt(bottom))) return if (usable(item)) i else null;
top = bottom;
}
return null;
}
pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool {
popupState().pointer = lookup(surface);
const p = popupState().pointer orelse return false;
const input = Input.state();
if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT);
choose(p, hit(p, x, y));
return true;
}
pub fn pointerLeave() void {
popupState().pointer = null;
popupState().hover_at = 0;
}
pub fn motion(x: f32, y: f32) void {
if (popupState().pointer) |p| choose(p, hit(p, x, y));
}
pub fn button(code: u32, down: bool, serial: u32) void {
if (down) popupState().serial = serial;
const p = popupState().pointer orelse {
if (down) finish(abi.CANCELLED);
return;
};
if (code != 0x110) return;
if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p);
}
fn openChild(p: *Panel) void {
popupState().hover_at = 0;
const index = p.selected orelse return;
const item = p.menu.payload.menu.items[index];
if (!usable(item) or item.submenu == null) return;
closeChildren(p);
const menu: *Resource = @ptrCast(@alignCast(item.submenu.?));
if (menu.payload.menu.items.len == 0) return;
const y = std.math.clamp(rowY(p, index), 0, p.height - 1);
const child = create(menu, p, p.width - 1, y, @min(26, p.height - y)) catch {
finish(abi.OOM);
return;
};
popupState().top = child;
}
fn select(p: *Panel) void {
const index = p.selected orelse return;
const item = &p.menu.payload.menu.items[index];
if (!usable(item.*)) return;
if (item.submenu != null) {
openChild(p);
return;
}
Menu.activate(popupState().window.?, item, Input.id());
finish(abi.OK); // Command event must precede request completion.
}
fn reveal(p: *Panel) void {
const index = p.selected orelse return;
const y = rowY(p, index);
if (y < 4) p.scroll -= 4 - y;
if (y + 26 > p.height - 4) p.scroll += y + 26 - (p.height - 4);
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
p.dirty = true;
}
fn move(p: *Panel, forward: bool) void {
const items = p.menu.payload.menu.items;
if (items.len == 0) return;
var index = p.selected orelse (if (forward) items.len - 1 else 0);
for (0..items.len) |_| {
index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len;
if (usable(items[index])) {
choose(p, index);
popupState().hover_at = 0;
reveal(p);
return;
}
}
}
pub fn key(logical: u32, down: bool, serial: u32) void {
if (!down) return;
const p = popupState().top orelse return;
popupState().serial = serial;
switch (logical) {
n.UHDK_KEY_ESCAPE => finish(abi.CANCELLED),
n.UHDK_KEY_UP => move(p, false),
n.UHDK_KEY_DOWN, n.UHDK_KEY_TAB => move(p, true),
n.UHDK_KEY_HOME => {
choose(p, null);
move(p, true);
},
n.UHDK_KEY_END => {
choose(p, null);
move(p, false);
},
n.UHDK_KEY_RIGHT => {
openChild(p);
if (popupState().top != p and popupState().top != null) move(popupState().top.?, true);
},
n.UHDK_KEY_LEFT => if (p.parent) |parent| {
closeChildren(parent);
popupState().hover_at = 0;
},
n.UHDK_KEY_ENTER, ' ' => select(p),
else => {},
}
}
pub fn scroll(delta: f32) void {
const p = popupState().pointer orelse return;
closeChildren(p);
p.scroll = std.math.clamp(p.scroll + @as(i32, @intFromFloat(std.math.clamp(delta, -480, 480))), 0, @max(0, p.total - p.height));
p.selected = null;
p.pressed = null;
p.dirty = true;
popupState().hover_at = 0;
}
pub fn flags() void {
var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) {
p.dirty = true;
if (p.selected) |index| if (!usable(p.menu.payload.menu.items[index])) {
closeChildren(p);
p.selected = null;
p.pressed = null;
};
}
}
pub fn tick() i32 {
if (!active()) return -1;
const now = runtime.now(backend().app.io);
if (popupState().hover_at != 0 and now >= popupState().hover_at) {
if (popupState().pointer) |p| openChild(p);
popupState().hover_at = 0;
}
var cursor = popupState().top;
var timeout: i32 = if (popupState().hover_at != 0) 25 else -1;
while (cursor) |p| : (cursor = p.parent) {
if (!p.configured) {
if (now >= p.deadline) {
finish(abi.UNAVAILABLE);
return -1;
}
timeout = 100;
}
render(p) catch {
finish(abi.OOM);
return -1;
};
}
return timeout;
}

636
desktop/vendor/uhdk/src/linux/Portal.zig vendored Normal file
View File

@ -0,0 +1,636 @@
//! Freedesktop portal frontend over a private, asynchronously pumped D-Bus
//! connection. The session chooses its backend (including KDE's native dialogs).
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const KdeAppMenu = @import("KdeAppMenu.zig");
const Bus = @import("Bus.zig");
const Tray = @import("Tray.zig");
const Files = @import("Files.zig");
const Input = @import("Input.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const desktop = "org.freedesktop.portal.Desktop";
const path = "/org/freedesktop/portal/desktop";
const chooser = "org.freedesktop.portal.FileChooser";
const settings = "org.freedesktop.portal.Settings";
const dbus = "org.freedesktop.DBus";
const dbus_path = "/org/freedesktop/DBus";
const Pending = struct {
next: ?*Pending = null,
id: u64,
command: ?*const n.z_command,
serial: u32 = 0,
replied: bool = false,
cancelled: bool = false,
handle: [:0]u8,
token: [:0]u8,
exported: ?*c.struct_zxdg_exported_v2 = null,
activation: ?*c.struct_xdg_activation_token_v1 = null,
deadline: u64,
};
pub const State = struct {
connection: ?*c.DBusConnection = null,
unique: ?[:0]u8 = null,
owner: ?[:0]u8 = null,
hello: u32 = 0,
matches: [5]u32 = @splat(0),
ready: bool = false,
version_serial: u32 = 0,
settings_serial: u32 = 0,
chooser_version: u32 = 0,
startup_deadline: u64 = 0,
pending: ?*Pending = null,
exporter: ?*c.struct_zxdg_exporter_v2 = null,
preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 },
};
fn backend() *native.Backend {
return native.instance.?;
}
fn portalState() *State {
return &backend().portal;
}
pub fn send(message: *Bus.Message) !u32 {
var serial: u32 = 0;
if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory;
return serial;
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) portalState().exporter = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zxdg_exporter_v2_interface, 1));
}
pub fn initialize() void {
if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return;
// Avoid libdbus autolaunch/process spawning. Desktop sessions provide this
// address; absence disables portals without affecting windows or input.
const address = c.getenv("DBUS_SESSION_BUS_ADDRESS");
if (address == null or !std.mem.startsWith(u8, std.mem.span(address), "unix:")) return;
portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return;
c.z_dbus_connection_set_exit_on_disconnect.?(portalState().connection, 0);
portalState().startup_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch {
disconnect();
return;
};
defer c.z_dbus_message_unref.?(message);
portalState().hello = send(message) catch {
disconnect();
return;
};
}
fn addMatches() !void {
const rules = [_][*:0]const u8{
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Request',member='Response'",
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged',path='/org/freedesktop/portal/desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.kde.StatusNotifierWatcher'",
"type='signal',sender='org.kde.StatusNotifierWatcher',interface='org.kde.StatusNotifierWatcher',path='/StatusNotifierWatcher'",
};
for (rules, 0..) |rule, i| {
const message = try Bus.method(dbus, dbus_path, dbus, "AddMatch");
defer c.z_dbus_message_unref.?(message);
var args = Bus.append(message);
try Bus.string(&args, rule);
portalState().matches[i] = try send(message);
}
}
fn discover() !void {
const version = try Bus.method(desktop, path, "org.freedesktop.DBus.Properties", "Get");
defer c.z_dbus_message_unref.?(version);
var args = Bus.append(version);
try Bus.string(&args, chooser);
try Bus.string(&args, "version");
portalState().version_serial = try send(version);
const read = try Bus.method(desktop, path, settings, "ReadAll");
defer c.z_dbus_message_unref.?(read);
args = Bus.append(read);
var namespaces = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "s");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces);
try Bus.string(&namespaces, "org.freedesktop.appearance");
try Bus.close(&args, &namespaces);
portalState().settings_serial = try send(read);
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
const connection = portalState().connection orelse return;
var fd: c_int = -1;
if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0)
try fds.append(backend().app.gpa, .{ .fd = fd, .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(connection) != 0) c.POLLOUT else 0), .revents = 0 });
}
pub fn tick() i32 {
const connection = portalState().connection orelse return -1;
if (c.z_dbus_connection_read_write.?(connection, 0) == 0) {
disconnect();
return -1;
}
// Bound dispatch work so an active bus cannot starve Wayland or app commands.
for (0..64) |_| {
const message = c.z_dbus_connection_pop_message.?(connection) orelse break;
defer c.z_dbus_message_unref.?(message);
process(message) catch {
disconnect();
return -1;
};
if (portalState().connection == null) return -1;
} else return 0;
const now = runtime.now(backend().app.io);
if (!portalState().ready and now >= portalState().startup_deadline) {
disconnect();
return -1;
}
var cursor = portalState().pending;
while (cursor) |pending| {
cursor = pending.next;
if (pending.deadline != 0 and now >= pending.deadline) {
closeRequest(pending.handle);
complete(pending, abi.UNAVAILABLE, null);
destroy(pending);
}
}
return if (portalState().pending != null or !portalState().ready) 100 else -1;
}
fn setOwner(message: *Bus.Message) !void {
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null) return;
if (portalState().owner) |old| backend().app.gpa.free(old);
portalState().owner = try backend().app.gpa.dupeSentinel(u8, std.mem.span(sender), 0);
}
fn process(message: *Bus.Message) !void {
if (try Tray.process(message)) return;
if (try KdeAppMenu.process(message)) return;
const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message);
if (serial != 0 and serial == portalState().hello) {
portalState().hello = 0;
if (failed or c.z_dbus_message_has_signature.?(message, "s") == 0) {
disconnect();
return;
}
portalState().unique = try backend().app.gpa.dupeSentinel(u8, Bus.str(&args).?, 0);
try addMatches();
return;
}
for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) {
if (failed) {
disconnect();
return;
}
match.* = 0;
if (std.mem.allEqual(u32, &portalState().matches, 0)) {
portalState().ready = true;
KdeAppMenu.ready();
try Tray.ready();
try discover();
}
return;
};
if (serial != 0 and serial == portalState().version_serial) {
portalState().version_serial = 0;
if (!failed) {
var value = Bus.variant(&args) orelse return;
portalState().chooser_version = Bus.uint(&value) orelse 0;
try setOwner(message);
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, portalState().chooser_version >= 3);
}
return;
}
if (serial != 0 and serial == portalState().settings_serial) {
portalState().settings_serial = 0;
if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) {
try setOwner(message);
var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return;
inline for (.{ "color-scheme", "contrast", "reduced-motion" }) |key| {
if (Bus.entry(&appearance, key)) |raw| {
var v = raw;
if (Bus.variant(&v)) |inner| {
var value = inner;
preference(key, Bus.uint(&value) orelse 0);
}
}
}
}
return;
}
if (c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0) {
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null or !std.mem.eql(u8, std.mem.span(sender), dbus)) return;
if (!std.mem.eql(u8, Bus.str(&args).?, desktop)) return;
_ = Bus.next(&args);
const old = Bus.str(&args).?;
_ = Bus.next(&args);
const new = Bus.str(&args).?;
if (old.len != 0) {
while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null);
destroy(p);
}
portalState().chooser_version = 0;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
if (portalState().owner) |owner| backend().app.gpa.free(owner);
portalState().owner = null;
preference("color-scheme", 0);
preference("contrast", 0);
preference("reduced-motion", 0);
}
if (new.len != 0) {
if (portalState().owner) |owner| backend().app.gpa.free(owner);
portalState().owner = try backend().app.gpa.dupeSentinel(u8, new, 0);
try discover();
}
return;
}
var cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) {
if (serial != 0 and serial == pending.serial) {
pending.replied = true;
if (failed) {
complete(pending, errorStatus(message), null);
destroy(pending);
return;
}
if (c.z_dbus_message_has_signature.?(message, "o") == 0) {
complete(pending, n.UHDK_STATUS_OS_ERROR, null);
destroy(pending);
return;
}
const handle = try backend().app.gpa.dupeSentinel(u8, Bus.str(&args).?, 0);
backend().app.gpa.free(pending.handle);
pending.handle = handle;
if (pending.id == 0) {
if (pending.cancelled) closeRequest(pending.handle);
destroy(pending);
} else pending.deadline = 0; // Human interaction has no artificial timeout.
return;
}
}
// Match rules are installed on the bus, and sender validation also protects
// against unrelated unicast signals sent directly to our private connection.
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null or portalState().owner == null or !std.mem.eql(u8, std.mem.span(sender), portalState().owner.?)) return;
if (c.z_dbus_message_is_signal.?(message, settings, "SettingChanged") != 0 and c.z_dbus_message_has_signature.?(message, "ssv") != 0) {
if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return;
_ = Bus.next(&args);
const key = Bus.str(&args).?;
_ = Bus.next(&args);
var value = Bus.variant(&args).?;
preference(key, Bus.uint(&value) orelse 0);
} else if (c.z_dbus_message_is_signal.?(message, "org.freedesktop.portal.Request", "Response") != 0 and c.z_dbus_message_has_signature.?(message, "ua{sv}") != 0) {
const response_path = c.z_dbus_message_get_path.?(message);
if (response_path == null) return;
cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) if (std.mem.eql(u8, pending.handle, std.mem.span(response_path))) {
const code = Bus.uint(&args).?;
_ = Bus.next(&args);
if (pending.id != 0) {
if (code != 0) complete(pending, if (code == 1) abi.CANCELLED else n.UHDK_STATUS_OS_ERROR, null) else if (pending.command.?.op == n.Z_URL) complete(pending, abi.OK, null) else responseFiles(pending, &args);
}
if (pending.replied) destroy(pending);
return;
};
}
}
fn errorStatus(message: *Bus.Message) u32 {
const name = c.z_dbus_message_get_error_name.?(message);
if (name != null and (std.mem.endsWith(u8, std.mem.span(name), ".NotFound") or std.mem.endsWith(u8, std.mem.span(name), ".ServiceUnknown") or std.mem.endsWith(u8, std.mem.span(name), ".UnknownMethod"))) return n.UHDK_STATUS_UNSUPPORTED;
return n.UHDK_STATUS_OS_ERROR;
}
fn preference(key: []const u8, value: u32) void {
const old = portalState().preferences;
if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) {
1 => n.UHDK_APPEARANCE_DARK,
2 => n.UHDK_APPEARANCE_LIGHT,
else => n.UHDK_APPEARANCE_UNKNOWN,
} else if (std.mem.eql(u8, key, "contrast")) portalState().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) portalState().preferences.reduced_motion = @intFromBool(value == 1);
if (!std.meta.eql(old, portalState().preferences)) n.z_preferences(runtime.toAppHandle(backend().app), &portalState().preferences);
}
pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (!portalState().ready or portalState().connection == null) return abi.UNAVAILABLE;
if (cmd.op == n.Z_DIALOG and portalState().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED;
const p = allocate(cmd, id) catch return abi.OOM;
p.next = portalState().pending;
portalState().pending = p;
if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and portalState().exporter != null) {
const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.dialog.parent) orelse {
destroy(p);
return abi.UNAVAILABLE;
}));
p.exported = c.zxdg_exporter_v2_export_toplevel(portalState().exporter, w.surface) orelse {
destroy(p);
return abi.OOM;
};
_ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p);
} else if (cmd.op == n.Z_URL and backend().desktop.activation != null and Input.state().key_focus != null and
Input.state().serial != 0 and runtime.now(backend().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s)
{
p.activation = c.xdg_activation_v1_get_activation_token(backend().desktop.activation) orelse {
destroy(p);
return abi.OOM;
};
_ = c.xdg_activation_token_v1_add_listener(p.activation, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(p.activation, Input.state().serial, Input.state().seat);
c.xdg_activation_token_v1_set_surface(p.activation, Input.state().key_focus.?.surface);
c.xdg_activation_token_v1_commit(p.activation);
} else submit(p, "", null) catch {
destroy(p);
return abi.OOM;
};
return n.Z_DEFERRED;
}
fn allocate(cmd: *const n.z_command, id: u64) !*Pending {
const gpa = backend().app.gpa;
const p = try gpa.create(Pending);
errdefer gpa.destroy(p);
const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0);
errdefer gpa.free(token);
const unique = portalState().unique.?;
const name = try gpa.dupe(u8, unique[1..]);
defer gpa.free(name);
std.mem.replaceScalar(u8, name, '.', '_');
p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(backend().app.io) + 30 * std.time.ns_per_s };
return p;
}
fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?));
const parent = std.fmt.allocPrintSentinel(backend().app.gpa, "wayland:{s}", .{std.mem.span(handle)}, 0) catch {
complete(p, abi.OOM, null);
destroy(p);
return;
};
defer backend().app.gpa.free(parent);
submit(p, parent, null) catch {
complete(p, abi.OOM, null);
destroy(p);
};
}
const export_listener: c.struct_zxdg_exported_v2_listener = .{ .handle = exported };
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?));
submit(p, "", token) catch {
complete(p, abi.OOM, null);
destroy(p);
};
}
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8) !void {
const cmd = p.command.?;
const dialog = cmd.op == n.Z_DIALOG;
const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile");
defer c.z_dbus_message_unref.?(message);
var arena: std.heap.ArenaAllocator = .init(backend().app.gpa);
defer arena.deinit();
const gpa = arena.allocator();
var args = Bus.append(message);
try Bus.string(&args, parent);
try Bus.string(&args, try gpa.dupeSentinel(u8, abi.textBytes(if (dialog) cmd.dialog.title else cmd.text), 0));
var options = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &options);
try Bus.option(&options, "handle_token", "s", p.token.ptr);
if (activation_token) |token| try Bus.option(&options, "activation_token", "s", token);
if (dialog) {
try Bus.option(&options, "modal", "b", @as(u32, @intFromBool(cmd.dialog.parent != null)));
if (cmd.dialog.kind != n.UHDK_DIALOG_SAVE_FILE) {
try Bus.option(&options, "multiple", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_FILES)));
try Bus.option(&options, "directory", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_DIRECTORY)));
}
if (cmd.dialog.accept_label.len != 0) try Bus.option(&options, "accept_label", "s", (try gpa.dupeSentinel(u8, abi.textBytes(cmd.dialog.accept_label), 0)).ptr);
if (cmd.dialog.suggested_name.len != 0 and cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) try Bus.option(&options, "current_name", "s", (try gpa.dupeSentinel(u8, abi.textBytes(cmd.dialog.suggested_name), 0)).ptr);
if (cmd.dialog.initial_directory != null) {
const directory = abi.bytes(n.z_file_path(cmd.dialog.initial_directory));
var entry = try Bus.open(&options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&options, &entry);
try Bus.string(&entry, "current_folder");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "ay");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var bytes = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "y");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &bytes);
for (directory) |byte| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, byte);
try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, @as(u8, 0));
try Bus.close(&variant, &bytes);
try Bus.close(&entry, &variant);
try Bus.close(&options, &entry);
}
if (cmd.dialog.filters_len != 0) try filters(&options, cmd.dialog, gpa);
}
try Bus.close(&args, &options);
p.serial = try send(message);
}
fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Allocator) !void {
var entry = try Bus.open(options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(options, &entry);
try Bus.string(&entry, "filters");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "a(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var list = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &list);
for (desc.filters[0..@intCast(desc.filters_len)]) |filter| {
var pair = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &pair);
try Bus.string(&pair, try gpa.dupeSentinel(u8, abi.textBytes(filter.label), 0));
var patterns = try Bus.open(&pair, c.DBUS_TYPE_ARRAY, "(us)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &patterns);
for (0..@max(1, filter.extensions.len)) |index| {
const pattern: [:0]const u8 = if (filter.extensions.len == 0) "*" else try std.fmt.allocPrintSentinel(gpa, "*.{s}", .{abi.textBytes(filter.extensions.ptr[index])}, 0);
var rule = try Bus.open(&patterns, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&patterns, &rule);
try Bus.basic(&rule, c.DBUS_TYPE_UINT32, @as(u32, 0));
try Bus.string(&rule, pattern);
try Bus.close(&patterns, &rule);
}
try Bus.close(&pair, &patterns);
try Bus.close(&list, &pair);
}
try Bus.close(&variant, &list);
try Bus.close(&entry, &variant);
try Bus.close(options, &entry);
}
fn responseFiles(p: *Pending, args: *Bus.Iter) void {
var raw = Bus.entry(args, "uris") orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
var value = Bus.variant(&raw) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
if (Bus.kind(&value) != c.DBUS_TYPE_ARRAY) {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
}
var strings = Bus.child(&value);
var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer {
for (files.items) |file| n.uhdk_file_release(file);
files.deinit(backend().app.gpa);
}
while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) {
const uri = Bus.str(&strings) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
const bytes = Files.decode(backend().app.gpa, uri) catch |err| {
complete(p, if (err == error.OutOfMemory) abi.OOM else n.UHDK_STATUS_UNSUPPORTED, null);
return;
};
defer backend().app.gpa.free(bytes);
const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse {
complete(p, abi.OOM, null);
return;
};
files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file);
complete(p, abi.OOM, null);
return;
};
if (!Bus.next(&strings)) break;
}
var result = std.mem.zeroes(n.z_request_result);
result.value.files = .{ .ptr = files.items.ptr, .len = files.items.len };
complete(p, if (files.items.len == 0) abi.CANCELLED else abi.OK, &result);
}
fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void {
if (p.id != 0) n.z_complete(runtime.toAppHandle(backend().app), p.id, status, result);
p.id = 0;
p.command = null;
}
fn closeRequest(handle: [*:0]const u8) void {
if (portalState().connection == null) return;
const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return;
defer c.z_dbus_message_unref.?(message);
c.z_dbus_message_set_no_reply.?(message, 1);
_ = send(message) catch {};
}
pub fn cancel(id: u64) bool {
var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) {
if (p.serial != 0) closeRequest(p.handle);
p.cancelled = true;
complete(p, abi.CANCELLED, null);
if (p.serial == 0 or p.replied) destroy(p);
return true;
};
return false;
}
fn destroy(p: *Pending) void {
var link = &portalState().pending;
while (link.* != p) link = &link.*.?.next;
link.* = p.next;
if (p.exported != null) c.zxdg_exported_v2_destroy(p.exported);
if (p.activation != null) c.xdg_activation_token_v1_destroy(p.activation);
backend().app.gpa.free(p.handle);
backend().app.gpa.free(p.token);
backend().app.gpa.destroy(p);
}
fn disconnect() void {
Tray.disconnected();
KdeAppMenu.disconnected();
while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null);
destroy(p);
}
if (portalState().connection) |connection| {
c.z_dbus_connection_close.?(connection);
c.z_dbus_connection_unref.?(connection);
}
portalState().connection = null;
portalState().ready = false;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
}
pub fn deinit() void {
var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) closeRequest(p.handle);
disconnect();
if (portalState().unique) |unique| backend().app.gpa.free(unique);
if (portalState().owner) |owner| backend().app.gpa.free(owner);
if (portalState().exporter != null) c.zxdg_exporter_v2_destroy(portalState().exporter);
}

Some files were not shown because too many files have changed in this diff Show More