Drive real workspaces through liblore in the desktop client

forge-service now loads Lore's C library (liblore v0.14.0, pinned in
lore.lock) through generated bindings in desktop/lore-sys, and speaks
protocol v2: status, history, files, revisions, file history, local
changes, sync, submit of chosen files, sign-in through the forge's
device flow, the repository list, clone, and adding or forgetting
workspaces. Requests on one connection run concurrently.

The GUI drops the sample repository and draws the explorer from the
service, with an ADD panel for opening or cloning, a sign-in banner,
and a CHANGES tab whose checked files SUBMIT commits and pushes.

scripts/e2e-lore.sh now also drives forge-service against the real
loreserver and lore-forge through scripts/desktop-e2e.py, and keeps
every login's key in a file so no run asks for the keychain.
fetch-lore.sh gains --liblore. Design docs and agent notes record what
was verified in liblore and the SYNC/SUBMIT decisions.
This commit is contained in:
Peterino 2026-11-26 10:19:27 -07:00
parent 6ebe985668
commit 4c991f3c24
31 changed files with 16579 additions and 742 deletions

View File

@ -110,6 +110,7 @@ never needs Zig. See [desktop-client.md](desktop-client.md).
| Deployment | `loreserver` as a separate process; lore-forge generates its auth config | Recommended; owner had no preference | | Deployment | `loreserver` as a separate process; lore-forge generates its auth config | Recommended; owner had no preference |
| Lore binaries | The official release pinned with SHA-256 in `lore.lock`, fetched into `.lore/`; `scripts/start.sh` runs a whole deployment from `run/` | Owner, 2026-11-25 | | Lore binaries | The official release pinned with SHA-256 in `lore.lock`, fetched into `.lore/`; `scripts/start.sh` runs a whole deployment from `run/` | Owner, 2026-11-25 |
| Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) | | Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) |
| Desktop SYNC and SUBMIT | SYNC pulls and keeps local edits; SUBMIT commits and pushes the files checked in CHANGES, all by default | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) |
| Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference | | Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference |
| Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed | | Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed |
| Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 | | Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 |
@ -154,8 +155,9 @@ never needs Zig. See [desktop-client.md](desktop-client.md).
5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock 5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock
management. management.
The desktop client has its own milestones, in [desktop-client.md](desktop-client.md). Milestone The desktop client has its own milestones, in [desktop-client.md](desktop-client.md).
1, the GUI and tray shell over a stub service, is done. Milestones 1 (the GUI and tray shell) and 2 (liblore in the service: real workspaces, sign-in
through the forge, clone, submit and sync) are done on macOS.
## Things to keep in mind ## Things to keep in mind

View File

@ -1,7 +1,7 @@
# Desktop client # Desktop client
Status: milestone 1 (GUI and tray shell over a stub service) done on macOS. Last updated Status: milestone 2 (liblore in the service: real workspaces, the explorer on real data, sign-in
2026-11-25. through the forge, clone, submit and sync) 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 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 repositories, both driven by one per-user **client service** that does the Lore work and runs
@ -17,7 +17,9 @@ policies such as autosync.
| GUI | C++ with a stylized Dear ImGui, on vendored UHDK (windows, OpenGL, tray) | 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 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 | | 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 | | SYNC and SUBMIT | SYNC pulls remote changes and keeps local edits; SUBMIT asks for a message, then stages, commits and pushes | Owner, 2026-11-25 |
| What SUBMIT sends | The files checked in CHANGES, all checked by default; unchecked files stay local | Owner, 2026-11-25 |
| liblore bindings | Generated by bindgen in dynamic-loading mode (`lore-sys`), checked in; the service loads liblore at run time | Implementation choice |
| Location | `desktop/` in this repository, with its own Cargo workspace and `zig build` | 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 | | 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 | | Frontend protocol | JSON-RPC 2.0, one message per line, over a per-user local socket | Implementation choice |
@ -70,22 +72,44 @@ side in `desktop/zig-out/bin/`, so the GUI can start the service it was built wi
directory, then retries. directory, then retries.
- **Lifetime:** quitting a frontend leaves the service running. `shutdown` stops it. - **Lifetime:** quitting a frontend leaves the service running. `shutdown` stops it.
`forge-protocol` is the reference. Milestone 1 methods: `forge-protocol` is the reference; it is at protocol version 2. Requests on one connection
run concurrently, so a long sync does not hold up the explorer's reads; answers carry the
request's `id`. Workspace ids are `w` and a hash of the path.
| Method | Result | | Method | Result |
| --- | --- | | --- | --- |
| `hello {protocol, client}` | `{protocol, service, pid}` | | `hello {protocol, client}` | `{protocol, service, pid}` |
| `status` | `{workspaces: [{id, name, path, remote, state, autosync}], uptime_s}` | | `status` | `{workspaces, uptime_s, liblore: {loaded: {version}} or {missing: {error}}, accounts}` |
| `sync_now {workspace}` | `{}`; progress follows as `activity` events | | `refresh {workspace}` | `{}`; rescans the working copy, then a `workspaces` event |
| `sync_now {workspace}` | `{}`; `activity` events follow |
| `submit {workspace, message, paths}` | `{}`; stages `paths`, commits, pushes, with `activity` events. No paths: push only |
| `changes {workspace}` | `{changes: [{path, action, from, staged, conflict}]}` |
| `history {workspace, limit}` | `{branches, revisions}`, revisions newest first, children before parents |
| `revision {workspace, signature}` | `{revision, changes}` |
| `files {workspace, path}` | `{path, entries: [{name, path, dir, size, change, lock, lock_mine}]}`, directories first |
| `file_history {workspace, path}` | `{path, revisions}` |
| `login {remote}` | `{}`; `login` events follow |
| `repositories {remote}` | `{repositories: [{id, name}]}` |
| `workspace_add {path}` | The workspace, for an existing working copy |
| `workspace_clone {url, path}` | The workspace; the clone follows as `activity` events of kind `clone` |
| `workspace_remove {workspace}` | `{}`; the files stay |
| `shutdown` | `{}`, then the service exits | | `shutdown` | `{}`, then the service exits |
A workspace is `{id, name, path, remote, state, autosync, branch, revision, signature, changes,
ahead, behind, online, signed_in, error}`. An account is `{auth_url, user_id, name, expires_ms}`.
| Event | Data | | Event | Data |
| --- | --- | | --- | --- |
| `activity` | `{workspace, kind, phase, progress, message}` | | `activity` | `{workspace, kind (sync, submit, clone), phase, progress, message}` |
| `workspaces` | The `status` workspaces list, after any change | | `workspaces` | The `status` workspaces list, after any change |
| `login` | `{remote, phase (waiting, done, failed), url, code, message}` |
In milestone 1 the service **simulates** sync, and its workspaces come from Error codes beyond JSON-RPC's: `-32000` hello first, `-32001` unsupported protocol, `-32002`
`desktop.toml` in the service's config directory. liblore replaces both in milestone 2. no such workspace, `-32003` busy, `-32004` no liblore, `-32005` Lore refused (its message
says why).
The service keeps its workspaces in `desktop.toml` in its config directory and rewrites it when
one is added or removed.
## liblore ## liblore
@ -101,12 +125,41 @@ Verified against the v0.14.0 release and `lore-capi/lore.h` at `6b12f00`:
event, on Lore's worker threads. event, on Lore's worker threads.
- Structures must be zeroed before use. Strings in events are valid only during the callback. - Structures must be zeroed before use. Strings in events are valid only during the callback.
Assumed, to check in milestone 2: Verified in milestone 2 by calling v0.14.0's liblore (`lore-sys/examples/probe.rs` and
`scripts/e2e-lore.sh`):
- liblore shares the CLI's stored logins (`LORE_AUTH_PATH`, the keychain-held key), so a - **Distribution:** `liblore-v0.14.0-<target>.tar.gz` holds the library and a 13,576-line
`lore auth login` also signs the service in. `lore.h` with about 154 operations. `lore_version()` gives `0.14.0+<build>`.
- Generating Rust bindings from `lore.h` at the pinned version is enough; we need no - **Bindings:** bindgen output from `lore.h` is enough; no hand-written ABI. `lore-sys/gen`
hand-written ABI. regenerates `lore-sys/src/bindings.rs`.
- **`lore_shutdown` must be called.** Without it, writes such as staging are lost when the
process exits. The service also calls `repository_flush` after each write.
- **`working_directory`** in the global arguments must be the working copy, or relative paths
(such as `file_history`'s) resolve against the process's directory.
- **History:** `revision_history` gives first-parent entries only. Each is followed by
metadata events: `message`, `created-by` (a user id), `timestamp` (ms) and `branch`.
`history` walks up to 12 branches and merges them newest first.
- **Branches:** `branch_list` reports each branch twice, local and remote.
- **Status:** with a scan, one event per changed file. An edit is action Keep with the dirty
flag; an untracked file is Add.
- **Names and remotes:** `auth_user_info` turns user ids into names; `repository_config_get`
with `remote_url` gives a working copy's remote; `repository_list` lists a server's
repositories through lore-forge's registry.
- **Sign-in:** `auth_login_interactive` with no browser emits the device URL and code, then
completes once the user approves it on the forge's device page. `auth_list` shows the
logins, each with its `oidc+http://` issuer.
- **Logins are shared with the CLI** through `LORE_AUTH_PATH`. The store's key is in the
keychain unless `LORE_AUTH_STORE=fallback` puts it in a file beside the store. A program
linking liblore reads those two variables only, not `lore`'s config.
- **Sync** keeps local edits to files the remote did not change. With overlapping edits it
fails with code 44 ("Local modifications prevent synchronization"); the service says
"local edits to files changed on the remote; submit or revert them first".
- **Commit** with nothing staged fails with code 40.
- **Blame** exists as `lore_file_audit`; nothing uses it yet.
The service finds liblore through `LORE_FORGE_LIBLORE`, else beside its own executable, where
`zig build` installs it (fetched by `scripts/fetch-lore.sh --liblore-to`). Without it the service
still runs, and `status` says why liblore is missing.
## UHDK ## UHDK
@ -144,52 +197,63 @@ The owner asked for a "crunchier", pixel-art look with little copy. `gui/src/the
## Explorer ## Explorer
A draft, drawn over a sample repository (`gui/src/sample_repo.cpp`) and labelled SAMPLE DATA. Everything shown comes from the service. The GUI asks for what it draws (`model::Repo` per
Workspaces in the sidebar are real (from the service); everything about their contents is not. workspace) and drops it when the workspace moves: a new revision, other local changes, a sync
or submit finishing.
- **Sidebar:** workspaces with their sync state, then the branches. Picking a branch selects - **Sidebar:** workspaces with their sync state and change count, ADD, FORGET, then the
its head in the history tabs. branches.
- **Workspace bar:** name, current branch and head revision, sync progress, SYNC. - **ADD:** open an existing working copy (CHOOSE FOLDER), or clone: a SERVER with SIGN IN and
- **FILES:** breadcrumbs with UP, a folder tree, and a list with size, last revision and state LIST, a repository from the list, INTO a folder, CLONE.
(MOD and NEW for working-copy changes, LOCK for locks: blue when yours). Below, the - **Sign-in:** a banner with the device code, OPEN (the forge's device page, also opened
selected file's details and the revisions that changed it. automatically) and COPY CODE.
- **Workspace bar:** branch, revision, AHEAD, BEHIND or OFFLINE, SIGN IN when signed out,
progress, SYNC.
- **FILES:** breadcrumbs with UP and REFRESH, a folder tree, and a list with size and state
(NEW, MOD, DEL, MOVE for working-copy changes, LOCK for locks: blue when yours). Below, the
selected file's revisions.
- **GRAPH:** revisions newest first with lanes. Each lane holds the revision it leads to; a - **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 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 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. branch heads carry a tag. Below, the selected revision's parents and changes. The web GRAPH
uses the same layout, ported to Rust in `crates/forge-web/src/pages/graph.rs`.
- **TREE:** branches, each opening to its revisions, each opening to its changes. - **TREE:** branches, each opening to its revisions, each opening to its changes.
- **CHANGES:** local changes with a checkbox each (ALL, NONE, RESCAN), a MESSAGE, and SUBMIT;
PUSH when nothing is changed but the workspace is ahead.
- A change or history row jumps to the file or the revision. - 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 ## Verified so far
On macOS (Apple silicon), 2026-11-25: On macOS (Apple silicon), 2026-11-25:
- `zig build test` passes. It runs: - `zig build test` passes. It runs:
- the Rust tests (protocol, config, and the service's protocol handling over in-memory - the Rust tests (protocol, config, `lore-sys`, and the service's protocol handling and
streams); liblore mapping over in-memory streams);
- `forge-desktop --test`, which starts a private service in a fresh temporary directory, - `forge-desktop --test`, which starts a private service in a fresh temporary directory,
completes `hello` and `status`, draws, and stops that service. completes `hello` and `status`, draws, and stops that service.
- With two sample workspaces (`--config-from`), the self-test starts a sync from the GUI, - `scripts/e2e-lore.sh` runs `forge-service`, linked to v0.14.0's liblore, against a real
sees the `activity` and `workspaces` events, and captures the window mid-sync with `loreserver` and lore-forge, driven by `scripts/desktop-e2e.py` as the GUI would: sign-in
`--screenshot`. `--tab` captures each explorer tab. Clicking through the explorer has not through the forge's device flow, the repository list, a clone, files, history with a branch
been automated. and a merge, a revision's changes, a file's history, a submit of two of three local changes,
and a sync of the CLI's working copy that keeps its own untracked file.
- With that clone (`--config-from`, `LORE_AUTH_PATH` set to the e2e's store), the GUI
self-test syncs it, waits for the tab's data, and `--screenshot --tab` captures FILES,
GRAPH, TREE and CHANGES drawn from real data. Clicking through the explorer, the ADD panel
and the sign-in banner has not been automated.
- The tray item registers: the window offers HIDE, which it does only when UHDK reports the - The tray item registers: the window offers HIDE, which it does only when UHDK reports the
tray available. tray available.
- **A sleeping display.** On macOS the window cannot open while the display sleeps, most - **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 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. session: Operating system error"; waking the display (`caffeinate -u`) is enough.
- **Keychain prompts.** With the default secure token store, macOS asks once per binary (and
again after each rebuild) before liblore may read the store's key. `LORE_AUTH_STORE=fallback`
avoids that; the e2e uses it.
Compiled and linked only, not run: Compiled and linked only, not run:
- **GUI:** `zig build -Dtarget=x86_64-windows-gnu` (a GUI-subsystem PE) and `x86_64-linux-gnu`. - **GUI:** `zig build -Dtarget=x86_64-windows-gnu` (a GUI-subsystem PE) and `x86_64-linux-gnu`.
- **liblore on Windows and Linux:** `zig build` fetches and installs liblore on macOS and
Linux only; the Windows release is a zip, and nothing unpacks it yet.
- **Service on Windows:** the named-pipe code path has not been compiled; the Rust Windows - **Service on Windows:** the named-pipe code path has not been compiled; the Rust Windows
target is not installed here. target is not installed here.
- **GUI pipe client:** the Windows code path compiles, but no Windows run has exercised it. - **GUI pipe client:** the Windows code path compiles, but no Windows run has exercised it.
@ -209,20 +273,24 @@ Found while building:
- The protocol client: connects to the service, starting it when needed, and shows its - The protocol client: connects to the service, starting it when needed, and shows its
workspaces and live activity. workspaces and live activity.
- A stub service in Rust that speaks the protocol. - A stub service in Rust that speaks the protocol.
2. **liblore in the service.** 2. **liblore in the service.** Done on macOS.
- Bindings and the fetch of liblore from `lore.lock`. - `lore-sys` bindings and the fetch of liblore from `lore.lock`.
- Protocol methods for the explorer, replacing the sample repository. - Protocol v2 with the explorer's methods; the sample repository is gone.
- Real status and sync now, and login state. - Real status, sync, submit of chosen files, sign-in through the forge, the repository
- Workspaces added from the GUI. list, clone, and adding or forgetting workspaces from the GUI.
3. **Policies.** Autosync (on an interval, on file change, never), with conflict handling to 3. **Policies.** Autosync (on an interval, on file change, never), with conflict handling to
design. Then notifications from `NotificationService`. design. Then notifications from `NotificationService`.
4. **TUI.** ratatui over the same protocol. 4. **TUI.** ratatui over the same protocol.
5. **lore-forge integration.** Repository lists and permissions from the forge; sign-in 5. **lore-forge integration.** Sign-in and the repository list came in milestone 2. Left:
through the forge's device flow. permissions from the forge (what the user may push or lock), and links between the GUI and
the forge's pages.
## Open ## Open
- What autosync does on a conflict or with unstaged local changes. - What SYNC and autosync do when local edits overlap remote changes. Today sync refuses
(Lore's code 44) and says to submit or revert first.
- Locking from the GUI: Lore has the operations, and FILES shows locks, but there is no LOCK or
UNLOCK yet.
- Whether the service should start at login (launch agent, systemd user unit, Run key), and - Whether the service should start at login (launch agent, systemd user unit, Run key), and
who installs that. who installs that.
- Packaging and signing per platform. - Packaging and signing per platform.

View File

@ -200,8 +200,8 @@ verify:
Verified against the v0.14.0 GitHub release: Verified against the v0.14.0 GitHub release:
- Each release publishes `lore-<version>-<target>.tar.gz` and `loreserver-<version>-<target>.tar.gz` - Each release publishes `lore-<version>-<target>.tar.gz`, `loreserver-<version>-<target>.tar.gz`
for `aarch64-apple-darwin`, `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`, plus and `liblore-<version>-<target>.tar.gz` (the C library and `lore.h`; a zip on Windows) for `aarch64-apple-darwin`, `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`, plus
Windows and `-debug` variants. There is no Intel macOS build. Windows and `-debug` variants. There is no Intel macOS build.
- GitHub records a SHA-256 for every asset, which `scripts/fetch-lore.sh --pin` copies into - GitHub records a SHA-256 for every asset, which `scripts/fetch-lore.sh --pin` copies into
`lore.lock`. `lore.lock`.
@ -212,6 +212,12 @@ Verified against the v0.14.0 GitHub release:
`[server.quic.certificate]`, it generates a self-signed certificate on every start. `[server.quic.certificate]`, it generates a self-signed certificate on every start.
- On macOS the `lore` CLI stores the key for its token store in the keychain - On macOS the `lore` CLI stores the key for its token store in the keychain
(`tokenstore_encryption_key`). Each process asks for access until "Always Allow" is chosen. (`tokenstore_encryption_key`). Each process asks for access until "Always Allow" is chosen.
`LORE_AUTH_STORE=fallback` keeps the key in a file beside the store (`LORE_AUTH_PATH`)
instead, which is how `scripts/e2e-lore.sh` runs without prompts. Programs linking liblore
read those two variables but not the CLI's `[auth]` config.
- liblore and the CLI share logins through that store. A login made through liblore's
`auth_login_interactive` goes through the same device flow as `lore auth login`. What the
desktop client found about liblore is in [desktop-client.md](desktop-client.md#liblore).
- v0.14.0's `user.proto` differs from `6b12f00` only in comments, so the vendored proto matches. - v0.14.0's `user.proto` differs from `6b12f00` only in comments, so the vendored proto matches.
## Reading repositories ## Reading repositories

View File

@ -24,18 +24,26 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
Set `LORE_BIN_DIR` to test another build, and `LORE_PORT`/`FORGE_PORT` to run it beside a Set `LORE_BIN_DIR` to test another build, and `LORE_PORT`/`FORGE_PORT` to run it beside a
deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or
directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push. directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push.
On macOS each `lore` process asks for keychain access until "Always Allow" is chosen, so do a It also drives the desktop `forge-service` through `scripts/desktop-e2e.py`, so run it after
smoke run first and tell the owner a prompt is coming. service changes too; `NO_DESKTOP=1` skips that. Its logins use `LORE_AUTH_STORE=fallback`,
so it never asks for the keychain.
- To move Lore: `scripts/fetch-lore.sh --pin vX.Y.Z`, then the e2e test, then update the version - To move Lore: `scripts/fetch-lore.sh --pin vX.Y.Z`, then the e2e test, then update the version
recorded in [lore-integration.md](.ai/designs/lore-integration.md). recorded in [lore-integration.md](.ai/designs/lore-integration.md). If `lore.h` changed,
regenerate the bindings (`cargo run -p lore-sys-gen -- .lore/vX.Y.Z/lore.h` in `desktop/`,
after `scripts/fetch-lore.sh --liblore`) and bump `lore_sys::INTERFACE_VERSION`.
- The desktop client in `desktop/` builds separately with Zig 0.17.1 and Cargo: - The desktop client in `desktop/` builds separately with Zig 0.17.1 and Cargo:
- `cd desktop && zig build test` runs its Rust tests and the GUI's self-test against a - `cd desktop && zig build test` runs its Rust tests and the GUI's self-test against a
private service; private service;
- `zig build check -Dtarget=x86_64-windows-gnu` cross-compiles the GUI; - `zig build check -Dtarget=x86_64-windows-gnu` cross-compiles the GUI;
- `cargo clippy --all-targets` in `desktop/` should stay clean; - `cargo clippy --all-targets` in `desktop/` should stay clean;
- `forge-desktop --test --config-from <toml> --screenshot <png>` captures the window, for - `forge-desktop --test --config-from <toml> --screenshot <png> [--tab files|graph|tree|changes]`
checking UI changes without screen-recording permission. captures the window, for checking UI changes without screen-recording permission. With
workspaces it syncs the first and waits for the tab's data, so it needs a live server and
a login (`LORE_AUTH_PATH`); a held e2e run (`HOLD=1 KEEP_WORK=1`) provides both.
- The service finds liblore through `LORE_FORGE_LIBLORE` or beside its executable;
`forge-desktop --liblore=PATH` passes it on. Outside the e2e, the real service on macOS
asks for keychain access once per binary unless `LORE_AUTH_STORE=fallback` is set.
## Where things are ## Where things are
@ -48,9 +56,9 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
| `crates/forge-web` | axum routes: issuer endpoints, pages (maud), CSRF and security headers | | `crates/forge-web` | axum routes: issuer endpoints, pages (maud), CSRF and security headers |
| `crates/lore-forge` | The binary: `serve`, `loreserver-config`, `generate-secret-key`, `create-user` | | `crates/lore-forge` | The binary: `serve`, `loreserver-config`, `generate-secret-key`, `create-user` |
| `scripts/start.sh` | Starts a deployment from `run/` (git-ignored): settings, secret key, both servers | | `scripts/start.sh` | Starts a deployment from `run/` (git-ignored): settings, secret key, both servers |
| `scripts/fetch-lore.sh`, `lore.lock` | Downloads the pinned Lore release into `.lore/` (git-ignored), checking SHA-256 | | `scripts/fetch-lore.sh`, `lore.lock` | Downloads the pinned Lore release into `.lore/` (git-ignored), checking SHA-256; `--liblore` fetches liblore and `lore.h` |
| `scripts/e2e-lore.sh` | End-to-end test against real Lore | | `scripts/e2e-lore.sh`, `scripts/desktop-e2e.py` | End-to-end test against real Lore, including the desktop service |
| `desktop/` | The desktop client: `gui/` (C++ tray app), `service/` and `protocol/` (Rust), `vendor/` (UHDK, Dear ImGui) | | `desktop/` | The desktop client: `gui/` (C++ tray app), `service/` and `protocol/` (Rust), `lore-sys/` (liblore bindings; `gen/` regenerates them), `vendor/` (UHDK, Dear ImGui) |
- [.ai/designs/](.ai/designs/) holds the design documents. Start with - [.ai/designs/](.ai/designs/) holds the design documents. Start with
[architecture-overview.md](.ai/designs/architecture-overview.md), which links to the rest. [architecture-overview.md](.ai/designs/architecture-overview.md), which links to the rest.

136
desktop/Cargo.lock generated
View File

@ -61,6 +61,26 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "bindgen"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 2.0.119",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.13.2" version = "2.13.2"
@ -73,12 +93,32 @@ version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.5" version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "clang-sys"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]] [[package]]
name = "clap" name = "clap"
version = "4.6.10" version = "4.6.10"
@ -125,6 +165,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.3" version = "1.0.3"
@ -161,6 +207,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"clap", "clap",
"forge-protocol", "forge-protocol",
"lore-sys",
"serde", "serde",
"serde_json", "serde_json",
"tempfile", "tempfile",
@ -181,6 +228,12 @@ dependencies = [
"r-efi", "r-efi",
] ]
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.17.2" version = "0.17.2"
@ -209,6 +262,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.19" version = "1.0.19"
@ -227,6 +289,16 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.12.1" version = "0.12.1"
@ -239,6 +311,20 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lore-sys"
version = "0.1.0"
dependencies = [
"libloading",
]
[[package]]
name = "lore-sys-gen"
version = "0.1.0"
dependencies = [
"bindgen",
]
[[package]] [[package]]
name = "matchers" name = "matchers"
version = "0.2.0" version = "0.2.0"
@ -254,6 +340,12 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.2.5" version = "1.2.5"
@ -265,6 +357,16 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@ -292,6 +394,16 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.107" version = "1.0.107"
@ -316,6 +428,18 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]] [[package]]
name = "regex-automata" name = "regex-automata"
version = "0.4.19" version = "0.4.19"
@ -333,6 +457,12 @@ version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.6" version = "1.1.6"
@ -407,6 +537,12 @@ dependencies = [
"lazy_static", "lazy_static",
] ]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "signal-hook-registry" name = "signal-hook-registry"
version = "1.4.8" version = "1.4.8"

View File

@ -1,7 +1,9 @@
# The desktop client's Rust side: the client service and (later) the TUI. Kept apart from the # 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. # server workspace so building lore-forge never needs Zig or the GUI's toolchain.
[workspace] [workspace]
members = ["protocol", "service"] members = ["protocol", "service", "lore-sys", "lore-sys/gen"]
# The generator needs libclang at run time; build it only when asked.
default-members = ["protocol", "service", "lore-sys"]
resolver = "3" resolver = "3"
[workspace.package] [workspace.package]
@ -13,6 +15,8 @@ publish = false
[workspace.dependencies] [workspace.dependencies]
forge-protocol = { path = "protocol" } forge-protocol = { path = "protocol" }
lore-sys = { path = "lore-sys" }
libloading = "0.8"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "signal", "fs"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "signal", "fs"] }

View File

@ -2,7 +2,8 @@
// forge-service (Rust) with Cargo, installing both into zig-out/bin/ so the GUI can start the // forge-service (Rust) with Cargo, installing both into zig-out/bin/ so the GUI can start the
// service beside it. // service beside it.
// //
// zig build build and install both // zig build build and install both, and liblore (fetched by
// scripts/fetch-lore.sh) beside the service
// zig build run run the GUI (it starts the service when none is running) // 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 test the GUI's --test smoke run (private service), then cargo test
// zig build check compile the GUI only (any -Dtarget) // zig build check compile the GUI only (any -Dtarget)
@ -36,7 +37,7 @@ pub fn build(b: *std.Build) void {
.files = &.{ .files = &.{
"gui/src/main.cpp", "gui/src/main.cpp",
"gui/src/explorer.cpp", "gui/src/explorer.cpp",
"gui/src/sample_repo.cpp", "gui/src/model.cpp",
"gui/src/json.cpp", "gui/src/json.cpp",
"gui/src/platform.cpp", "gui/src/platform.cpp",
"gui/src/png.cpp", "gui/src/png.cpp",
@ -74,6 +75,7 @@ pub fn build(b: *std.Build) void {
const service_exe = if (target.result.os.tag == .windows) "forge-service.exe" else "forge-service"; const service_exe = if (target.result.os.tag == .windows) "forge-service.exe" else "forge-service";
var service_built: ?std.Build.LazyPath = null; var service_built: ?std.Build.LazyPath = null;
var cargo_step: ?*std.Build.Step = null; var cargo_step: ?*std.Build.Step = null;
var liblore: ?std.Build.LazyPath = null;
if (with_service) { if (with_service) {
const release = optimize != .debug; const release = optimize != .debug;
const cargo = b.addSystemCommand(&.{ "cargo", "build", "--quiet", "--package", "forge-service", "--manifest-path" }); const cargo = b.addSystemCommand(&.{ "cargo", "build", "--quiet", "--package", "forge-service", "--manifest-path" });
@ -86,6 +88,20 @@ pub fn build(b: *std.Build) void {
b.getInstallStep().dependOn(&install.step); b.getInstallStep().dependOn(&install.step);
service_built = built; service_built = built;
cargo_step = &cargo.step; cargo_step = &cargo.step;
// The service loads liblore from beside itself. The pinned release is fetched once into
// ../.lore/ and copied from there; Windows builds of the service are done by hand.
if (target.result.os.tag != .windows) {
const library = if (target.result.os.tag == .macos) "liblore.dylib" else "liblore.so";
const fetch = b.addSystemCommand(&.{"../scripts/fetch-lore.sh"});
fetch.setCwd(b.path("."));
fetch.addArg("--liblore-to");
const fetched = fetch.addOutputFileArg(library);
fetch.addFileInput(b.path("../lore.lock"));
const install_lib = b.addInstallBinFile(fetched, library);
b.getInstallStep().dependOn(&install_lib.step);
liblore = fetched;
}
} }
// `run` and `test` run the GUI from Zig's cache, so they name the service explicitly. // `run` and `test` run the GUI from Zig's cache, so they name the service explicitly.
@ -94,6 +110,7 @@ pub fn build(b: *std.Build) void {
run.addArg("--service"); run.addArg("--service");
run.addFileArg(built); run.addFileArg(built);
run.step.dependOn(cargo_step.?); run.step.dependOn(cargo_step.?);
if (liblore) |library| run.addPrefixedFileArg("--liblore=", library);
} }
run.addPassthruArgs(); run.addPassthruArgs();
b.step("run", "Run forge-desktop").dependOn(&run.step); b.step("run", "Run forge-desktop").dependOn(&run.step);
@ -103,6 +120,7 @@ pub fn build(b: *std.Build) void {
const smoke = b.addRunArtifact(gui); const smoke = b.addRunArtifact(gui);
smoke.addArg("--service"); smoke.addArg("--service");
smoke.addFileArg(built); smoke.addFileArg(built);
if (liblore) |library| smoke.addPrefixedFileArg("--liblore=", library);
smoke.addArg("--test"); smoke.addArg("--test");
smoke.has_side_effects = true; smoke.has_side_effects = true;
smoke.step.dependOn(cargo_step.?); smoke.step.dependOn(cargo_step.?);

View File

@ -5,12 +5,13 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <functional>
namespace { namespace {
constexpr float kRowH = 20; // list rows: one text line and 2 px above and below constexpr float kRowH = 20; // list rows: one text line and 2 px above and below
constexpr float kLaneW = 14; // graph lane spacing constexpr float kLaneW = 14; // graph lane spacing
constexpr float kRevW = 72; // the revision id column constexpr float kRevW = 72; // the revision id column
void Box(ImVec2 a, ImVec2 b, ImU32 colour) { 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)}, ImGui::GetWindowDrawList()->AddRectFilled({std::floor(a.x), std::floor(a.y)}, {std::floor(b.x), std::floor(b.y)},
@ -45,6 +46,13 @@ void HeaderRow(std::initializer_list<std::pair<float, const char *>> columns) {
theme::TextAt({p.x + x, p.y + 2}, theme::kMuted, label); theme::TextAt({p.x + x, p.y + 2}, theme::kMuted, label);
} }
// A muted line inside a list, for loading and empty states.
void Note(const char *text, ImU32 colour = theme::kMuted) {
ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::Dummy({ImGui::GetContentRegionAvail().x, kRowH});
theme::TextAt({p.x + 8, p.y + 2}, colour, text, p.x + ImGui::GetItemRectSize().x);
}
std::string Size(uint64_t bytes) { std::string Size(uint64_t bytes) {
char out[32]; char out[32];
if (bytes < 1024) if (bytes < 1024)
@ -61,11 +69,11 @@ ImU32 FileTint(const std::string &name) {
size_t n = std::char_traits<char>::length(suffix); size_t n = std::char_traits<char>::length(suffix);
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0; return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
}; };
if (ends(".cpp") || ends(".h")) if (ends(".cpp") || ends(".h") || ends(".hpp") || ends(".rs") || ends(".cs"))
return theme::kGreen; return theme::kGreen;
if (ends(".png") || ends(".fbx")) if (ends(".png") || ends(".fbx") || ends(".psd") || ends(".jpg"))
return theme::kBlue; return theme::kBlue;
if (ends(".umap")) if (ends(".umap") || ends(".uasset"))
return theme::kForge; return theme::kForge;
if (ends(".ogg") || ends(".wav")) if (ends(".ogg") || ends(".wav"))
return theme::kSpark; return theme::kSpark;
@ -77,18 +85,73 @@ std::string Parent(const std::string &path) {
return slash == std::string::npos ? std::string() : path.substr(0, slash); return slash == std::string::npos ? std::string() : path.substr(0, slash);
} }
const char *ChangeLabel(char kind, ImU32 &colour) { std::string BaseName(const std::string &path) {
switch (kind) { size_t slash = path.rfind('/');
case 'A': colour = theme::kGreen; return "A"; return slash == std::string::npos ? path : path.substr(slash + 1);
case 'D': colour = theme::kRed; return "D"; }
const char *ChangeLabel(model::Action action, ImU32 &colour) {
switch (action) {
case model::Action::Add: colour = theme::kGreen; return "A";
case model::Action::Delete: colour = theme::kRed; return "D";
case model::Action::Move: colour = theme::kBlue; return "R";
case model::Action::Copy: colour = theme::kBlue; return "C";
default: colour = theme::kSpark; return "M"; default: colour = theme::kSpark; return "M";
} }
} }
// The working-copy state tag for a file list row.
const char *StateLabel(model::Action action, ImU32 &colour) {
switch (action) {
case model::Action::Add: colour = theme::kGreen; return "NEW";
case model::Action::Delete: colour = theme::kRed; return "DEL";
case model::Action::Move:
case model::Action::Copy: colour = theme::kBlue; return "MOVE";
case model::Action::Modify: colour = theme::kSpark; return "MOD";
default: return nullptr;
}
}
} // namespace } // namespace
Explorer::Explorer() : repo_(sample::Get()) { void Explorer::SetTab(const std::string &name) {
// Lane layout, newest first: each lane holds the revision it is waiting to reach. if (name == "graph")
tab_ = Tab::Graph;
else if (name == "tree")
tab_ = Tab::Tree;
else if (name == "changes")
tab_ = Tab::Changes;
else
tab_ = Tab::Files;
}
ImU32 Explorer::BranchColour(const model::Repo &repo, const std::string &branch_id) const {
const model::Branch *b = repo.FindBranch(branch_id);
return b ? b->colour : theme::kMuted;
}
void Explorer::GoToFile(const std::string &path) {
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 &signature) {
selected_rev_ = signature;
scroll_to_rev_ = true;
}
// Lane layout, newest first: each lane holds the revision it is waiting to reach. The web
// GRAPH uses the same rules (crates/forge-web/src/pages/graph.rs).
void Explorer::Layout(const model::Repo &repo) {
size_t key = repo.revisions.size() * 31 + (repo.revisions.empty() ? 0 : std::hash<std::string>()(repo.revisions[0].signature));
if (key == graph_key_ && graph_.size() == repo.revisions.size())
return;
graph_key_ = key;
graph_.clear();
lanes_ = 1;
std::vector<std::string> lanes; std::vector<std::string> lanes;
auto free_lane = [&lanes] { auto free_lane = [&lanes] {
for (size_t i = 0; i < lanes.size(); ++i) for (size_t i = 0; i < lanes.size(); ++i)
@ -97,12 +160,12 @@ Explorer::Explorer() : repo_(sample::Get()) {
lanes.emplace_back(); lanes.emplace_back();
return int(lanes.size() - 1); return int(lanes.size() - 1);
}; };
for (const auto &rev : repo_.revisions) { for (const auto &rev : repo.revisions) {
GraphRow row; GraphRow row;
row.before = lanes; row.before = lanes;
row.node = -1; row.node = -1;
for (size_t i = 0; i < lanes.size(); ++i) for (size_t i = 0; i < lanes.size(); ++i)
if (lanes[i] == rev.id) { if (lanes[i] == rev.signature) {
row.incoming.push_back(int(i)); row.incoming.push_back(int(i));
if (row.node < 0) if (row.node < 0)
row.node = int(i); row.node = int(i);
@ -129,87 +192,111 @@ Explorer::Explorer() : repo_(sample::Get()) {
lanes_ = std::max({lanes_, int(row.before.size()), int(row.after.size()), row.node + 1}); lanes_ = std::max({lanes_, int(row.before.size()), int(row.after.size()), row.node + 1});
graph_.push_back(std::move(row)); 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) { void Explorer::DrawBranches(const model::Repo &repo) {
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"); theme::TextColoured(theme::kMuted, "BRANCHES");
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &b : repo_.branches) { for (const auto &b : repo.branches) {
ImGui::PushID(b.name.c_str()); ImGui::PushID(b.id.c_str());
if (theme::Row("branch", tab_ != Tab::Files && selected_rev_ == b.head, kRowH)) { if (theme::Row("branch", tab_ != Tab::Files && tab_ != Tab::Changes && selected_rev_ == b.head, kRowH)) {
SelectRevision(b.head); SelectRevision(b.head);
open_branches_.insert(b.name); open_branches_.insert(b.id);
if (tab_ == Tab::Files) if (tab_ == Tab::Files || tab_ == Tab::Changes)
tab_ = Tab::Graph; tab_ = Tab::Graph;
} }
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
Box({p.x + 8, p.y + 6}, {p.x + 16, p.y + 14}, b.colour); 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); theme::TextAt({p.x + 24, p.y + 2}, b.remote_only ? theme::kMuted : theme::kPaper, b.name.c_str(),
if (b.name == repo_.current_branch) ImGui::GetItemRectMax().x - 20);
if (b.current)
theme::TextAt({ImGui::GetItemRectMax().x - 16, p.y + 2}, theme::kForge, "*"); theme::TextAt({ImGui::GetItemRectMax().x - 16, p.y + 2}, theme::kForge, "*");
ImGui::PopID(); ImGui::PopID();
} }
ImGui::PopStyleVar(); ImGui::PopStyleVar();
if (repo.history == model::Load::Loading && repo.branches.empty())
theme::TextColoured(theme::kMuted, "reading");
} }
bool Explorer::Draw(const WorkspaceView &ws) { void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, ExplorerHost &host, bool connected) {
// The workspace bar: name, branch and head on the left, sync on the right. // Name, branch, revision and flags on the left; sign-in, progress and SYNC on the right.
ImVec2 p = ImGui::GetCursorScreenPos(); ImVec2 p = ImGui::GetCursorScreenPos();
float right = p.x + ImGui::GetContentRegionAvail().x; float right = p.x + ImGui::GetContentRegionAvail().x;
float x = p.x, y = p.y + 4; float x = p.x, y = p.y + 4;
theme::TextAt({x, y}, theme::kPaper, ws.name.c_str()); theme::TextAt({x, y}, theme::kPaper, ws.name.c_str());
x += ImGui::CalcTextSize(ws.name.c_str()).x + 12; x += ImGui::CalcTextSize(ws.name.c_str()).x + 12;
const sample::Branch *current = repo_.FindBranch(repo_.current_branch); if (!ws.branch.empty()) {
theme::TagAt({x, y}, current->name.c_str(), current->colour); const model::Branch *current = repo.CurrentBranch();
x += theme::TagWidth(current->name.c_str()) + 8; ImU32 colour = current && current->name == ws.branch ? current->colour : theme::kForge;
theme::TextAt({x, y}, theme::kMuted, current->head.c_str()); theme::TagAt({x, y}, ws.branch.c_str(), colour);
x += theme::TagWidth(ws.branch.c_str()) + 8;
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}); if (ws.revision) {
bool sync = theme::Button("SYNC", ws.can_sync && !ws.syncing, true); std::string rev = "r" + std::to_string(ws.revision) + " " + model::Short(ws.signature);
ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 10}); theme::TextAt({x, y}, theme::kMuted, rev.c_str());
x += ImGui::CalcTextSize(rev.c_str()).x + 12;
}
auto flag = [&](const char *label, ImU32 colour) {
theme::TagAt({x, y}, label, colour);
x += theme::TagWidth(label) + 6;
};
if (ws.ahead)
flag("AHEAD", theme::kBlue);
if (ws.behind)
flag("BEHIND", theme::kSpark);
if (ws.state != "unknown" && !ws.online)
flag("OFFLINE", theme::kRed);
bool busy = ws.state == "syncing";
float button_x = std::floor(right - theme::ButtonWidth("SYNC"));
bool sign_in = ws.state != "unknown" && ws.online && !ws.signed_in;
if (sign_in)
button_x -= theme::ButtonWidth("SIGN IN") + 12;
if (busy) {
const float bar = 160;
ImGui::SetCursorScreenPos({button_x - 12 - bar, p.y + 5});
theme::Progress(ws.activity.progress < 0 ? 0 : ws.activity.progress, bar);
float mw = ImGui::CalcTextSize(ws.activity.message.c_str()).x;
theme::TextAt({std::max(x, button_x - 24 - bar - mw), y}, theme::kMuted, ws.activity.message.c_str(), button_x - 24 - bar);
}
ImGui::SetCursorScreenPos({button_x, p.y});
if (sign_in) {
if (theme::Button("SIGN IN", connected, true))
host.SignIn();
ImGui::SameLine(0, 12);
}
if (theme::Button("SYNC", connected && !busy && ws.signed_in, !sign_in))
host.Sync();
ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 6});
if (!ws.error.empty()) {
ImGui::PushStyleColor(ImGuiCol_Text, theme::kRed);
ImGui::TextWrapped("%s", ws.error.c_str());
ImGui::PopStyleColor();
}
Gap(4);
}
void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected) {
if (workspace_ != ws.id) {
workspace_ = ws.id;
dir_.clear();
selected_path_.clear();
selected_rev_.clear();
open_dirs_.clear();
open_branches_.clear();
open_revisions_.clear();
graph_key_ = 0;
graph_.clear();
}
if (connected && repo.history == model::Load::None)
host.LoadHistory();
Layout(repo);
if (selected_rev_.empty() || (!repo.revisions.empty() && !repo.FindRevision(selected_rev_)))
selected_rev_ = !ws.signature.empty() ? ws.signature : repo.revisions.empty() ? "" : repo.revisions[0].signature;
if (const model::Branch *current = repo.CurrentBranch(); current && open_branches_.empty())
open_branches_.insert(current->id);
DrawBar(ws, repo, host, connected);
// Tabs, touching the panel below. // Tabs, touching the panel below.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {4, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {4, 0});
@ -221,56 +308,50 @@ bool Explorer::Draw(const WorkspaceView &ws) {
ImGui::SameLine(); ImGui::SameLine();
if (theme::Tab("TREE", tab_ == Tab::Tree)) if (theme::Tab("TREE", tab_ == Tab::Tree))
tab_ = Tab::Tree; tab_ = Tab::Tree;
ImVec2 tabs = ImGui::GetItemRectMin(); ImGui::SameLine();
theme::TagAt({right - theme::TagWidth("SAMPLE DATA"), tabs.y + 4}, "SAMPLE DATA", theme::kSpark); std::string changes = ws.changes ? "CHANGES " + std::to_string(ws.changes) : "CHANGES";
if (theme::Tab(changes.c_str(), tab_ == Tab::Changes))
tab_ = Tab::Changes;
ImGui::PopStyleVar(); ImGui::PopStyleVar();
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel); ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8}); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});
ImGui::BeginChild("panel", {0, 0}, ImGuiChildFlags_Borders); ImGui::BeginChild("panel", {0, 0}, ImGuiChildFlags_Borders);
switch (tab_) { if (!connected) {
case Tab::Files: DrawFiles(); break; theme::TextColoured(theme::kMuted, "no service");
case Tab::Graph: DrawGraph(); break; } else {
case Tab::Tree: DrawTree(); break; switch (tab_) {
case Tab::Files: DrawFiles(repo, host); break;
case Tab::Graph: DrawGraph(repo, host); break;
case Tab::Tree: DrawTree(repo, host); break;
case Tab::Changes: DrawChanges(ws, repo, host, connected); break;
}
if (tab_ == Tab::Files)
DrawFileDetails(ws, repo, host);
} }
ImGui::EndChild(); ImGui::EndChild();
ImGui::PopStyleVar(); ImGui::PopStyleVar();
ImGui::PopStyleColor(); ImGui::PopStyleColor();
return sync;
} }
// ---- Files // ---- Files
void Explorer::DrawFiles() { void Explorer::DrawFiles(model::Repo &repo, ExplorerHost &host) {
DrawBreadcrumbs(); if (repo.dir_state[dir_] == model::Load::None)
const float details_h = 156; host.LoadDir(dir_);
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())) if (theme::Button("UP", !dir_.empty()))
dir_ = Parent(dir_); dir_ = Parent(dir_);
ImGui::SameLine(0, 12);
if (theme::Button("REFRESH"))
host.Refresh();
float y = ImGui::GetItemRectMin().y + 4; float y = ImGui::GetItemRectMin().y + 4;
std::vector<std::pair<std::string, std::string>> crumbs = {{repo_.name, ""}}; std::vector<std::pair<std::string, std::string>> crumbs = {{"/", ""}};
for (std::string d = dir_; !d.empty(); d = Parent(d)) for (std::string d = dir_; !d.empty(); d = Parent(d))
crumbs.insert(crumbs.begin() + 1, {d.substr(d.rfind('/') + 1), d}); crumbs.insert(crumbs.begin() + 1, {BaseName(d), d});
for (size_t i = 0; i < crumbs.size(); ++i) { for (size_t i = 0; i < crumbs.size(); ++i) {
ImGui::SameLine(0, i ? 6 : 14); ImGui::SameLine(0, i ? 6 : 14);
ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y}); ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y});
if (i) { if (i > 1) {
theme::TextColoured(theme::kRaised, "/"); theme::TextColoured(theme::kRaised, "/");
ImGui::SameLine(0, 6); ImGui::SameLine(0, 6);
ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y}); ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, y});
@ -285,45 +366,70 @@ void Explorer::DrawBreadcrumbs() {
ImGui::PopID(); ImGui::PopID();
} }
Gap(6); Gap(6);
const float details_h = 156;
float list_h = std::floor(ImGui::GetContentRegionAvail().y - details_h - 8);
BeginList("dirs", {220, list_h});
DrawDirTree(repo, host, "", "/", 0);
EndList();
ImGui::SameLine(0, 8);
BeginList("files", {0, list_h});
DrawFileList(repo, host);
EndList();
Gap(8);
} }
void Explorer::DrawDirTree(const sample::Entry &dir, int depth) { void Explorer::DrawDirTree(model::Repo &repo, ExplorerHost &host, const std::string &dir, const std::string &name,
bool has_sub = std::any_of(dir.children.begin(), dir.children.end(), [](const auto &c) { return c.dir; }); int depth) {
bool open = depth == 0 || open_dirs_.count(dir.path); auto listed = repo.dirs.find(dir);
ImGui::PushID(("/" + dir.path).c_str()); bool has_sub = listed == repo.dirs.end() ||
if (theme::Row("dir", dir_ == dir.path, kRowH)) { std::any_of(listed->second.begin(), listed->second.end(), [](const auto &e) { return e.dir; });
if (dir_ == dir.path && has_sub && depth > 0) { bool open = depth == 0 || open_dirs_.count(dir);
ImGui::PushID(("/" + dir).c_str());
if (theme::Row("dir", dir_ == dir, kRowH)) {
if (dir_ == dir && has_sub && depth > 0) {
if (open) if (open)
open_dirs_.erase(dir.path); open_dirs_.erase(dir);
else else
open_dirs_.insert(dir.path); open_dirs_.insert(dir);
} else { } else {
dir_ = dir.path; dir_ = dir;
if (has_sub) if (has_sub)
open_dirs_.insert(dir.path); open_dirs_.insert(dir);
} }
} }
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
float x = p.x + 6 + depth * 12; float x = p.x + 6 + depth * 12;
if (has_sub && depth > 0) if (has_sub && depth > 0)
theme::TextAt({x, p.y + 2}, theme::kMuted, open ? "-" : "+"); theme::TextAt({x, p.y + 2}, theme::kMuted, open ? "-" : "+");
theme::FolderIcon({x + 12, p.y + 4}, dir_ == dir.path); theme::FolderIcon({x + 12, p.y + 4}, dir_ == dir);
theme::TextAt({x + 32, p.y + 2}, theme::kPaper, dir.name.c_str(), ImGui::GetItemRectMax().x); theme::TextAt({x + 32, p.y + 2}, theme::kPaper, name.c_str(), ImGui::GetItemRectMax().x);
ImGui::PopID(); ImGui::PopID();
if (open) if (!open)
for (const auto &child : dir.children) return;
if (child.dir) if (listed == repo.dirs.end()) {
DrawDirTree(child, depth + 1); if (repo.dir_state[dir] == model::Load::None)
host.LoadDir(dir);
return;
}
for (const auto &child : listed->second)
if (child.dir)
DrawDirTree(repo, host, child.path, child.name, depth + 1);
} }
void Explorer::DrawFileList() { void Explorer::DrawFileList(model::Repo &repo, ExplorerHost &host) {
const sample::Entry *dir = repo_.FindEntry(dir_);
if (!dir)
return;
float width = ImGui::GetContentRegionAvail().x; float width = ImGui::GetContentRegionAvail().x;
const float state_x = width - 120, rev_x = state_x - 80, size_right = rev_x - 20; const float state_x = width - 120, size_right = state_x - 20;
HeaderRow({{30, "NAME"}, {size_right - 32, "SIZE"}, {rev_x, "REV"}, {state_x, "STATE"}}); HeaderRow({{30, "NAME"}, {size_right - 32, "SIZE"}, {state_x, "STATE"}});
auto listed = repo.dirs.find(dir_);
if (listed == repo.dirs.end()) {
auto error = repo.dir_errors.find(dir_);
if (error != repo.dir_errors.end())
Note(error->second.c_str(), theme::kRed);
else
Note("reading");
return;
}
if (!dir_.empty()) { if (!dir_.empty()) {
if (theme::Row("..", false, kRowH)) if (theme::Row("..", false, kRowH))
dir_ = Parent(dir_); dir_ = Parent(dir_);
@ -331,134 +437,155 @@ void Explorer::DrawFileList() {
theme::FolderIcon({p.x + 8, p.y + 4}, false); theme::FolderIcon({p.x + 8, p.y + 4}, false);
theme::TextAt({p.x + 30, p.y + 2}, theme::kMuted, ".."); theme::TextAt({p.x + 30, p.y + 2}, theme::kMuted, "..");
} }
for (const auto &e : dir->children) { if (listed->second.empty())
Note("empty");
std::string open_dir;
for (const auto &e : listed->second) {
ImGui::PushID(e.name.c_str()); ImGui::PushID(e.name.c_str());
if (theme::Row("entry", selected_path_ == e.path, kRowH)) if (theme::Row("entry", selected_path_ == e.path, kRowH))
selected_path_ = e.path; selected_path_ = e.path;
bool hovered = ImGui::IsItemHovered(); bool hovered = ImGui::IsItemHovered();
if (hovered && e.dir && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { if (hovered && e.dir && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
dir_ = e.path; open_dir = e.path;
open_dirs_.insert(e.path); if (hovered && !e.lock.empty())
} ImGui::SetTooltip("locked by %s", e.lock.c_str());
if (hovered && !e.lock_owner.empty())
ImGui::SetTooltip("locked by %s", e.lock_owner.c_str());
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
float y = p.y + 2; float y = p.y + 2;
if (e.dir) if (e.dir)
theme::FolderIcon({p.x + 8, p.y + 4}, false); theme::FolderIcon({p.x + 8, p.y + 4}, false);
else else
theme::FileIcon({p.x + 8, p.y + 4}, FileTint(e.name)); 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); theme::TextAt({p.x + 30, y}, e.change == model::Action::Delete ? theme::kMuted : theme::kPaper, e.name.c_str(),
if (!e.dir) { p.x + size_right - 80);
if (!e.dir && e.change != model::Action::Delete) {
std::string size = Size(e.size); 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 + 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; float tx = p.x + state_x;
if (e.local == 'M' || e.local == 'A') { ImU32 colour = 0;
const char *label = e.local == 'M' ? "MOD" : "NEW"; if (const char *label = StateLabel(e.change, colour)) {
theme::TagAt({tx, y}, label, e.local == 'M' ? theme::kSpark : theme::kGreen); theme::TagAt({tx, y}, label, colour);
tx += theme::TagWidth(label) + 4; tx += theme::TagWidth(label) + 4;
} }
if (!e.lock_owner.empty()) if (!e.lock.empty())
theme::TagAt({tx, y}, "LOCK", e.lock_owner == "you" ? theme::kBlue : theme::kRed); theme::TagAt({tx, y}, "LOCK", e.lock_mine ? theme::kBlue : theme::kRed);
ImGui::PopID(); ImGui::PopID();
} }
if (!open_dir.empty()) {
dir_ = open_dir;
open_dirs_.insert(open_dir);
if (repo.dir_state[open_dir] == model::Load::None)
host.LoadDir(open_dir);
}
} }
void Explorer::DrawFileDetails() { void Explorer::DrawFileDetails(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host) {
const sample::Entry *e = repo_.FindEntry(selected_path_.empty() ? dir_ : selected_path_); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 4});
if (!e) BeginList("details", {0, 0}, {10, 8});
e = &repo_.root; const model::FileEntry *e = selected_path_.empty() ? nullptr : repo.FindEntry(selected_path_);
std::string name = e ? e->name : dir_.empty() ? ws.name : BaseName(dir_);
ImVec2 p = ImGui::GetCursorScreenPos(); ImVec2 p = ImGui::GetCursorScreenPos();
if (e->dir) if (!e || e->dir)
theme::FolderIcon({p.x, p.y + 2}, false); theme::FolderIcon({p.x, p.y + 2}, false);
else else
theme::FileIcon({p.x, p.y + 2}, FileTint(e->name)); theme::FileIcon({p.x, p.y + 2}, FileTint(e->name));
ImGui::Indent(22); ImGui::Indent(22);
ImGui::TextUnformatted(e->name.c_str()); ImGui::TextUnformatted(name.c_str());
ImGui::Unindent(22); ImGui::Unindent(22);
std::string path = repo_.name + (e->path.empty() ? "" : "/" + e->path); std::string path = e ? e->path : dir_;
theme::TextColoured(theme::kMuted, path.c_str()); theme::TextColoured(theme::kMuted, (ws.path + (path.empty() ? "" : "/" + path)).c_str());
std::string facts; std::string facts;
if (e->dir) { if (!e || e->dir) {
facts = std::to_string(e->children.size()) + " items"; auto listed = repo.dirs.find(e ? e->path : dir_);
if (listed != repo.dirs.end())
facts = std::to_string(listed->second.size()) + " items";
} else { } else {
facts = Size(e->size) + " rev " + (e->revision.empty() ? "-" : e->revision); facts = e->change == model::Action::Delete ? "deleted here" : Size(e->size);
if (e->local == 'M') ImU32 colour = 0;
facts += " modified"; if (StateLabel(e->change, colour) && e->change != model::Action::Delete)
if (e->local == 'A') facts += e->change == model::Action::Add ? " new here" : " changed here";
facts += " added"; if (!e->lock.empty())
if (!e->lock_owner.empty()) facts += " locked by " + e->lock;
facts += " locked by " + e->lock_owner;
} }
theme::TextColoured(theme::kMuted, facts.c_str()); theme::TextColoured(theme::kMuted, facts.c_str());
if (e->dir) if (e && !e->dir && e->change != model::Action::Add) {
return; Gap(4);
theme::TextColoured(theme::kMuted, "HISTORY");
Gap(4); auto history = repo.file_history.find(e->path);
theme::TextColoured(theme::kMuted, "HISTORY"); if (history == repo.file_history.end()) {
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); if (!repo.file_history_loading.count(e->path))
for (const auto &rev : repo_.revisions) { host.LoadFileHistory(e->path);
bool touches = std::any_of(rev.changes.begin(), rev.changes.end(), Note("reading");
[&](const sample::Change &c) { return c.path == e->path; }); } else {
if (!touches) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
continue; for (const auto &rev : history->second) {
ImGui::PushID(rev.id.c_str()); ImGui::PushID(rev.signature.c_str());
if (theme::Row("rev", false, kRowH)) { if (theme::Row("rev", false, kRowH)) {
SelectRevision(rev.id); SelectRevision(rev.signature);
tab_ = Tab::Graph; tab_ = Tab::Graph;
}
ImVec2 r = ImGui::GetItemRectMin();
Box({r.x + 4, r.y + 6}, {r.x + 12, r.y + 14}, BranchColour(repo, rev.branch));
DrawRevisionLine(repo, rev, r.x + 20, r.y + 2, ImGui::GetItemRectMax().x);
ImGui::PopID();
}
ImGui::PopStyleVar();
} }
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();
} }
EndList();
ImGui::PopStyleVar(); ImGui::PopStyleVar();
} }
// ---- History // ---- History
void Explorer::DrawRevisionLine(const sample::Revision &rev, float x, float y, float right) { void Explorer::DrawRevisionLine(const model::Repo &repo, const model::Revision &rev, float x, float y, float right) {
const float author_x = right - 168, date_x = right - 100; const float author_x = right - 228, date_x = right - 140;
theme::TextAt({x, y}, theme::kSpark, rev.id.c_str()); std::string id = model::Short(rev.signature);
theme::TextAt({x, y}, theme::kSpark, id.c_str());
float mx = x + kRevW; float mx = x + kRevW;
for (const auto &b : repo_.branches) for (const auto &b : repo.branches)
if (b.head == rev.id) { if (b.head == rev.signature) {
theme::TagAt({mx, y}, b.name.c_str(), b.colour); theme::TagAt({mx, y}, b.name.c_str(), b.colour);
mx += theme::TagWidth(b.name.c_str()) + 6; mx += theme::TagWidth(b.name.c_str()) + 6;
} }
theme::TextAt({mx, y}, theme::kPaper, rev.message.c_str(), author_x - 12); const char *message = rev.message.empty() ? (rev.parents.size() > 1 ? "(merge)" : "(no message)") : rev.message.c_str();
theme::TextAt({mx, y}, rev.message.empty() ? theme::kMuted : theme::kPaper, message, author_x - 12);
theme::TextAt({author_x, y}, theme::kMuted, rev.author.c_str(), date_x - 8); 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); theme::TextAt({date_x, y}, theme::kMuted, model::Date(rev.timestamp_ms).c_str(), right);
} }
void Explorer::DrawGraph() { void Explorer::DrawGraph(model::Repo &repo, ExplorerHost &host) {
const float details_h = 176; const float details_h = 176;
float list_h = std::floor(ImGui::GetContentRegionAvail().y - details_h - 8); float list_h = std::floor(ImGui::GetContentRegionAvail().y - details_h - 8);
BeginList("graph", {0, list_h}); BeginList("graph", {0, list_h});
const float graph_w = 10 + lanes_ * kLaneW; const float graph_w = 10 + lanes_ * kLaneW;
float width = ImGui::GetContentRegionAvail().x; float width = ImGui::GetContentRegionAvail().x;
HeaderRow({{graph_w, "REV"}, {graph_w + kRevW, "MESSAGE"}, {width - 168, "AUTHOR"}, {width - 100, "DATE"}}); HeaderRow({{graph_w, "REV"}, {graph_w + kRevW, "MESSAGE"}, {width - 228, "AUTHOR"}, {width - 140, "DATE"}});
if (repo.history == model::Load::Loading && repo.revisions.empty())
Note("reading");
else if (repo.history == model::Load::Failed)
Note(repo.history_error.c_str(), theme::kRed);
else if (repo.revisions.empty())
Note("no revisions");
auto lane_x = [](ImVec2 p, int lane) { return std::floor(p.x + 10 + lane * kLaneW); }; 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 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) { 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); Box({std::min(x0, x1) - 1, y - 1}, {std::max(x0, x1) + 1, y + 1}, c);
}; };
auto colour_of = [this](const std::string &id) { auto colour_of = [this, &repo](const std::string &signature) {
const sample::Revision *r = repo_.FindRevision(id); const model::Revision *r = repo.FindRevision(signature);
return r ? BranchColour(r->branch) : theme::kMuted; return r ? BranchColour(repo, r->branch) : theme::kMuted;
}; };
for (size_t i = 0; i < repo_.revisions.size(); ++i) { for (size_t i = 0; i < repo.revisions.size() && i < graph_.size(); ++i) {
const sample::Revision &rev = repo_.revisions[i]; const model::Revision &rev = repo.revisions[i];
const GraphRow &row = graph_[i]; const GraphRow &row = graph_[i];
ImGui::PushID(rev.id.c_str()); ImGui::PushID(rev.signature.c_str());
bool selected = selected_rev_ == rev.id; bool selected = selected_rev_ == rev.signature;
if (theme::Row("rev", selected, kRowH)) if (theme::Row("rev", selected, kRowH))
SelectRevision(rev.id); SelectRevision(rev.signature);
if (selected && scroll_to_rev_) { if (selected && scroll_to_rev_) {
ImGui::SetScrollHereY(0.5f); ImGui::SetScrollHereY(0.5f);
scroll_to_rev_ = false; scroll_to_rev_ = false;
@ -468,11 +595,11 @@ void Explorer::DrawGraph() {
float nx = lane_x(p, row.node); float nx = lane_x(p, row.node);
// Lanes passing straight through. // Lanes passing straight through.
for (size_t l = 0; l < row.before.size(); ++l) for (size_t l = 0; l < row.before.size(); ++l)
if (!row.before[l].empty() && row.before[l] != rev.id && l < row.after.size() && if (!row.before[l].empty() && row.before[l] != rev.signature && l < row.after.size() &&
row.after[l] == row.before[l]) row.after[l] == row.before[l])
vline(lane_x(p, int(l)), y0, y1, colour_of(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. // Lines into this revision from its children, then out to its parents.
ImU32 own = BranchColour(rev.branch); ImU32 own = BranchColour(repo, rev.branch);
for (int l : row.incoming) { for (int l : row.incoming) {
vline(lane_x(p, l), y0, yc, own); vline(lane_x(p, l), y0, yc, own);
hline(lane_x(p, l), nx, yc, own); hline(lane_x(p, l), nx, yc, own);
@ -487,104 +614,213 @@ void Explorer::DrawGraph() {
Box({nx - 4, yc - 4}, {nx + 4, yc + 4}, own); Box({nx - 4, yc - 4}, {nx + 4, yc + 4}, own);
if (rev.parents.size() > 1) if (rev.parents.size() > 1)
Box({nx - 2, yc - 2}, {nx + 2, yc + 2}, theme::kInk); // merges are hollow 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); DrawRevisionLine(repo, rev, p.x + graph_w, p.y + 2, ImGui::GetItemRectMax().x);
ImGui::PopID(); ImGui::PopID();
} }
EndList(); EndList();
Gap(8); Gap(8);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 4}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 4});
BeginList("details", {0, 0}, {10, 8}); BeginList("details", {0, 0}, {10, 8});
DrawRevisionDetails(); DrawRevisionDetails(repo, host);
EndList(); EndList();
ImGui::PopStyleVar(); ImGui::PopStyleVar();
} }
void Explorer::DrawChangeRow(const sample::Change &change, float indent) { void Explorer::DrawChangeRow(const model::Change &change, float indent) {
ImGui::PushID(change.path.c_str()); ImGui::PushID(change.path.c_str());
if (theme::Row("change", false, kRowH)) if (theme::Row("change", false, kRowH))
GoToFile(change.path); GoToFile(change.path);
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
ImU32 colour; ImU32 colour;
const char *label = ChangeLabel(change.kind, colour); const char *label = ChangeLabel(change.action, colour);
theme::TagAt({p.x + indent, p.y + 2}, label, colour); theme::TagAt({p.x + indent, p.y + 2}, label, colour);
theme::FileIcon({p.x + indent + 20, p.y + 4}, FileTint(change.path)); 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, std::string text = change.from.empty() ? change.path : change.from + " -> " + change.path;
change.path.c_str(), ImGui::GetItemRectMax().x); theme::TextAt({p.x + indent + 40, p.y + 2}, change.action == model::Action::Delete ? theme::kMuted : theme::kPaper,
text.c_str(), ImGui::GetItemRectMax().x);
ImGui::PopID(); ImGui::PopID();
} }
void Explorer::DrawRevisionDetails() { void Explorer::DrawRevisionDetails(model::Repo &repo, ExplorerHost &host) {
const sample::Revision *rev = repo_.FindRevision(selected_rev_); const model::Revision *rev = repo.FindRevision(selected_rev_);
if (!rev) if (!rev)
return; return;
theme::TextColoured(theme::kSpark, rev->id.c_str()); theme::TextColoured(theme::kSpark, model::Short(rev->signature).c_str());
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
theme::Tag(rev->branch.c_str(), BranchColour(rev->branch)); if (const model::Branch *b = repo.FindBranch(rev->branch)) {
ImGui::SameLine(0, 12); theme::Tag(b->name.c_str(), b->colour);
ImGui::TextUnformatted(rev->message.c_str()); ImGui::SameLine(0, 12);
std::string facts = rev->author + " " + rev->date + " parents"; }
ImGui::TextUnformatted(rev->message.empty() ? "(no message)" : rev->message.c_str());
std::string facts = "r" + std::to_string(rev->number) + " " + rev->author + " " + model::Date(rev->timestamp_ms) +
" parents";
for (const auto &parent : rev->parents) for (const auto &parent : rev->parents)
facts += " " + parent; facts += " " + model::Short(parent);
if (rev->parents.empty()) if (rev->parents.empty())
facts += " -"; facts += " -";
theme::TextColoured(theme::kMuted, facts.c_str()); theme::TextColoured(theme::kMuted, facts.c_str());
Gap(4); Gap(4);
theme::TextColoured(theme::kMuted, "CHANGES"); theme::TextColoured(theme::kMuted, "CHANGES");
auto changes = repo.revision_changes.find(rev->signature);
if (changes == repo.revision_changes.end()) {
if (!repo.revisions_loading.count(rev->signature))
host.LoadRevision(rev->signature);
Note("reading");
return;
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &change : rev->changes) for (const auto &change : changes->second)
DrawChangeRow(change, 4); DrawChangeRow(change, 4);
if (changes->second.empty())
Note("no file changes");
ImGui::PopStyleVar(); ImGui::PopStyleVar();
} }
void Explorer::DrawTree() { void Explorer::DrawTree(model::Repo &repo, ExplorerHost &host) {
BeginList("tree", {0, 0}); BeginList("tree", {0, 0});
float width = ImGui::GetContentRegionAvail().x; float width = ImGui::GetContentRegionAvail().x;
HeaderRow({{24, "BRANCH / REV"}, {width - 168, "AUTHOR"}, {width - 100, "DATE"}}); HeaderRow({{24, "BRANCH / REV"}, {width - 228, "AUTHOR"}, {width - 140, "DATE"}});
for (const auto &b : repo_.branches) { if (repo.history == model::Load::Loading && repo.branches.empty())
ImGui::PushID(b.name.c_str()); Note("reading");
bool open = open_branches_.count(b.name); for (const auto &b : repo.branches) {
ImGui::PushID(b.id.c_str());
bool open = open_branches_.count(b.id);
if (theme::Row("branch", false, kRowH)) { if (theme::Row("branch", false, kRowH)) {
if (open) if (open)
open_branches_.erase(b.name); open_branches_.erase(b.id);
else else
open_branches_.insert(b.name); open_branches_.insert(b.id);
} }
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
int count = 0; int count = 0;
for (const auto &rev : repo_.revisions) for (const auto &rev : repo.revisions)
count += rev.branch == b.name; count += rev.branch == b.id;
theme::TextAt({p.x + 8, p.y + 2}, theme::kMuted, open ? "-" : "+"); 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); 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; std::string facts = std::to_string(count) + (count == 1 ? " revision head " : " revisions head ") + (b.head.empty() ? "-" : model::Short(b.head));
if (b.name == repo_.current_branch) if (b.current)
facts += " current"; facts += " current";
if (b.remote_only)
facts += " remote only";
theme::TextAt({p.x + 36 + theme::TagWidth(b.name.c_str()), p.y + 2}, theme::kMuted, facts.c_str()); theme::TextAt({p.x + 36 + theme::TagWidth(b.name.c_str()), p.y + 2}, theme::kMuted, facts.c_str());
if (open) if (open)
for (const auto &rev : repo_.revisions) { for (const auto &rev : repo.revisions) {
if (rev.branch != b.name) if (rev.branch != b.id)
continue; continue;
ImGui::PushID(rev.id.c_str()); ImGui::PushID(rev.signature.c_str());
bool rev_open = open_revisions_.count(rev.id); bool rev_open = open_revisions_.count(rev.signature);
if (theme::Row("rev", selected_rev_ == rev.id, kRowH)) { if (theme::Row("rev", selected_rev_ == rev.signature, kRowH)) {
SelectRevision(rev.id); SelectRevision(rev.signature);
if (rev_open) if (rev_open)
open_revisions_.erase(rev.id); open_revisions_.erase(rev.signature);
else else
open_revisions_.insert(rev.id); open_revisions_.insert(rev.signature);
} }
ImVec2 r = ImGui::GetItemRectMin(); ImVec2 r = ImGui::GetItemRectMin();
theme::TextAt({r.x + 28, r.y + 2}, theme::kMuted, rev_open ? "-" : "+"); 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); Box({r.x + 42, r.y + 6}, {r.x + 50, r.y + 14}, b.colour);
if (rev.parents.size() > 1) if (rev.parents.size() > 1)
Box({r.x + 44, r.y + 8}, {r.x + 48, r.y + 12}, theme::kInk); 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); DrawRevisionLine(repo, rev, r.x + 58, r.y + 2, ImGui::GetItemRectMax().x);
if (rev_open) if (rev_open) {
for (const auto &change : rev.changes) auto changes = repo.revision_changes.find(rev.signature);
DrawChangeRow(change, 58); if (changes == repo.revision_changes.end()) {
if (!repo.revisions_loading.count(rev.signature))
host.LoadRevision(rev.signature);
} else {
for (const auto &change : changes->second)
DrawChangeRow(change, 58);
}
}
ImGui::PopID(); ImGui::PopID();
} }
ImGui::PopID(); ImGui::PopID();
} }
EndList(); EndList();
} }
// ---- Changes
void Explorer::DrawChanges(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected) {
if (repo.changes_state == model::Load::None)
host.LoadChanges();
bool busy = ws.state == "syncing";
if (theme::Button("RESCAN", !busy))
host.LoadChanges();
ImGui::SameLine(0, 12);
int checked = 0;
for (const auto &c : repo.changes)
checked += !repo.unchecked.count(c.path);
if (theme::Button("ALL", !repo.changes.empty()))
repo.unchecked.clear();
ImGui::SameLine(0, 12);
if (theme::Button("NONE", !repo.changes.empty()))
for (const auto &c : repo.changes)
repo.unchecked.insert(c.path);
ImGui::SameLine(0, 16);
ImGui::AlignTextToFramePadding();
std::string count = std::to_string(checked) + "/" + std::to_string(repo.changes.size()) + " chosen";
theme::TextColoured(theme::kMuted, count.c_str());
Gap(6);
const float compose_h = 128;
float list_h = std::floor(ImGui::GetContentRegionAvail().y - compose_h - 8);
BeginList("changes", {0, list_h});
float width = ImGui::GetContentRegionAvail().x;
HeaderRow({{30, "FILE"}, {width - 80, "STATE"}});
if (repo.changes_state == model::Load::Loading && repo.changes.empty())
Note("scanning");
else if (repo.changes.empty())
Note(ws.ahead ? "nothing changed here; unpushed revisions remain" : "nothing changed here");
for (const auto &c : repo.changes) {
ImGui::PushID(c.path.c_str());
bool on = !repo.unchecked.count(c.path);
if (theme::Row("change", false, kRowH)) {
if (on)
repo.unchecked.insert(c.path);
else
repo.unchecked.erase(c.path);
on = !on;
}
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
GoToFile(c.path);
ImVec2 p = ImGui::GetItemRectMin();
// A pixel checkbox: an inset square, filled when chosen.
Box({p.x + 8, p.y + 4}, {p.x + 20, p.y + 16}, theme::kMuted);
Box({p.x + 9, p.y + 5}, {p.x + 19, p.y + 15}, theme::kInk);
if (on)
Box({p.x + 11, p.y + 7}, {p.x + 17, p.y + 13}, theme::kForge);
std::string text = c.from.empty() ? c.path : c.from + " -> " + c.path;
theme::TextAt({p.x + 30, p.y + 2}, on ? theme::kPaper : theme::kMuted, text.c_str(), p.x + width - 90);
ImU32 colour = 0;
if (const char *label = StateLabel(c.action, colour))
theme::TagAt({p.x + width - 80, p.y + 2}, label, colour);
if (c.conflict)
theme::TagAt({p.x + width - 40, p.y + 2}, "!", theme::kRed);
ImGui::PopID();
}
EndList();
Gap(8);
theme::TextColoured(theme::kMuted, "MESSAGE");
float button_w = theme::ButtonWidth("SUBMIT");
ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk);
ImGui::InputTextMultiline("##message", message_, sizeof message_,
{ImGui::GetContentRegionAvail().x - button_w - 12, compose_h - 32});
ImGui::PopStyleColor();
ImGui::SameLine(0, 12);
bool has_message = message_[0] != 0;
bool can_submit = connected && !busy && ws.signed_in && checked > 0 && has_message;
bool can_push = connected && !busy && ws.signed_in && repo.changes.empty() && ws.ahead;
if (can_push) {
if (theme::Button("PUSH", true, true))
host.Submit("", {});
} else if (theme::Button("SUBMIT", can_submit, true)) {
std::vector<std::string> paths;
for (const auto &c : repo.changes)
if (!repo.unchecked.count(c.path))
paths.push_back(c.path);
host.Submit(message_, paths);
}
}

View File

@ -1,59 +1,70 @@
// The repository explorer: a files tab, the revision graph and a branch tree, over the sample // The repository explorer: files, the revision graph, a branch tree and local changes, for
// repository until the service can report real ones. // the workspace selected in the sidebar. It draws what model::Repo holds and asks its host
// for anything missing; the host fetches it from the service.
#pragma once #pragma once
#include "sample_repo.hpp" #include "model.hpp"
#include <set> #include <set>
#include <string> #include <string>
#include <vector> #include <vector>
// What the explorer shows about the workspace selected in the sidebar. // What the explorer asks of the app. Load* calls mark the item loading before they return.
struct WorkspaceView { class ExplorerHost {
std::string name; public:
bool syncing = false; virtual ~ExplorerHost() = default;
float progress = -1; virtual void LoadHistory() = 0;
std::string message; virtual void LoadDir(const std::string &dir) = 0;
bool can_sync = false; virtual void LoadRevision(const std::string &signature) = 0;
virtual void LoadFileHistory(const std::string &path) = 0;
virtual void LoadChanges() = 0;
virtual void Refresh() = 0;
virtual void Sync() = 0;
virtual void Submit(const std::string &message, const std::vector<std::string> &paths) = 0;
virtual void SignIn() = 0;
}; };
class Explorer { class Explorer {
public: public:
Explorer(); // "files", "graph", "tree" or "changes".
// "files", "graph" or "tree".
void SetTab(const std::string &name); void SetTab(const std::string &name);
// The sidebar's branch list. // The sidebar's branch list for `repo`.
void DrawBranches(); void DrawBranches(const model::Repo &repo);
// The main area. Returns true when the user asked to sync the workspace. // The main area. `connected` is whether the service is there to ask.
bool Draw(const WorkspaceView &workspace); void Draw(const model::Workspace &workspace, model::Repo &repo, ExplorerHost &host, bool connected);
// After a submit finishes, so the message box starts empty.
void ClearMessage() { message_[0] = 0; }
private: private:
enum class Tab { Files, Graph, Tree }; enum class Tab { Files, Graph, Tree, Changes };
// One row of the revision graph: which lanes carry lines in and out, where the node sits. // One row of the revision graph: which lanes carry lines in and out, where the node sits.
struct GraphRow { struct GraphRow {
std::vector<std::string> before, after; // the revision each lane waits for std::vector<std::string> before, after; // the revision each lane waits for
int node = 0; int node = 0;
std::vector<int> incoming; // lanes that end in this node 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 std::vector<std::pair<int, bool>> parents; // lane of each parent; true for the first
}; };
void DrawFiles(); void Layout(const model::Repo &repo);
void DrawBreadcrumbs(); void DrawBar(const model::Workspace &ws, const model::Repo &repo, ExplorerHost &host, bool connected);
void DrawDirTree(const sample::Entry &dir, int depth); void DrawFiles(model::Repo &repo, ExplorerHost &host);
void DrawFileList(); void DrawBreadcrumbs(const model::Workspace &ws);
void DrawFileDetails(); void DrawDirTree(model::Repo &repo, ExplorerHost &host, const std::string &dir, const std::string &name, int depth);
void DrawGraph(); void DrawFileList(model::Repo &repo, ExplorerHost &host);
void DrawRevisionDetails(); void DrawFileDetails(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host);
void DrawTree(); void DrawGraph(model::Repo &repo, ExplorerHost &host);
void DrawRevisionLine(const sample::Revision &rev, float x, float y, float right); void DrawRevisionDetails(model::Repo &repo, ExplorerHost &host);
void DrawChangeRow(const sample::Change &change, float indent); void DrawTree(model::Repo &repo, ExplorerHost &host);
void DrawChanges(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected);
void DrawRevisionLine(const model::Repo &repo, const model::Revision &rev, float x, float y, float right);
void DrawChangeRow(const model::Change &change, float indent);
void GoToFile(const std::string &path); void GoToFile(const std::string &path);
void SelectRevision(const std::string &id); void SelectRevision(const std::string &signature);
ImU32 BranchColour(const std::string &branch) const; ImU32 BranchColour(const model::Repo &repo, const std::string &branch_id) const;
const sample::Repository &repo_; std::string workspace_; // the workspace the state below belongs to
std::vector<GraphRow> graph_; std::vector<GraphRow> graph_;
size_t graph_key_ = 0; // which revision list graph_ was laid out for
int lanes_ = 1; int lanes_ = 1;
Tab tab_ = Tab::Files; Tab tab_ = Tab::Files;
@ -62,4 +73,5 @@ class Explorer {
std::string selected_rev_; std::string selected_rev_;
bool scroll_to_rev_ = false; bool scroll_to_rev_ = false;
std::set<std::string> open_dirs_, open_branches_, open_revisions_; std::set<std::string> open_dirs_, open_branches_, open_revisions_;
char message_[2048] = {};
}; };

View File

@ -1,18 +1,19 @@
// forge-desktop: lore-forge's tray application. // forge-desktop: lore-forge's tray application.
// //
// A UHDK window drawn with Dear ImGui, a tray icon, and a connection to forge-service, which // 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 // does the actual work through liblore. Closing the window hides it to the tray when there is
// Quit ends the GUI, and the service keeps running. // one; the tray's Quit ends the GUI, and the service keeps running.
// //
// forge-desktop open the window // forge-desktop open the window
// forge-desktop --hidden start in the tray // forge-desktop --hidden start in the tray
// forge-desktop --test against a private service in a temporary directory: connect, // forge-desktop --test against a private service in a temporary directory: connect,
// draw, stop that service, and exit 0 once it has answered // draw, stop that service, and exit 0 once it has answered
// --service PATH the forge-service to start (default: the one beside this program) // --service PATH the forge-service to start (default: the one beside this program)
// --liblore=PATH the liblore that service loads (default: beside the service)
// --config-from FILE with --test: the private service's desktop.toml; the test then // --config-from FILE with --test: the private service's desktop.toml; the test then
// syncs the first workspace and waits for its progress // syncs the first workspace and waits for it and its explorer data
// --screenshot FILE with --test: write the final frame as a PNG // --screenshot FILE with --test: write the final frame as a PNG
// --tab files|graph|tree the explorer tab to open on // --tab files|graph|tree|changes the explorer tab to open on
// forge-desktop --licenses print the licences of what is compiled in // forge-desktop --licenses print the licences of what is compiled in
#define UHDK_ENABLE_OPENGL #define UHDK_ENABLE_OPENGL
#include "uhdk.h" #include "uhdk.h"
@ -20,17 +21,21 @@
#include "backends/imgui_impl_opengl3.h" #include "backends/imgui_impl_opengl3.h"
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_uhdk.h" #include "imgui_impl_uhdk.h"
#include "explorer.hpp"
#include "json.hpp" #include "json.hpp"
#include "model.hpp"
#include "png.hpp" #include "png.hpp"
#include "platform.hpp" #include "platform.hpp"
#include "service_client.hpp" #include "service_client.hpp"
#include "explorer.hpp"
#include "theme.hpp" #include "theme.hpp"
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <cstdlib>
#include <cstring> #include <cstring>
#include <fstream> #include <fstream>
#include <functional>
#include <map>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
@ -51,62 +56,123 @@ bool Check(uhdk_status status, const char *operation) {
return false; return false;
} }
enum : uhdk_request_tag { kClipboardTag = 1, kOpenUrlTag = 2 }; enum : uhdk_request_tag { kClipboardTag = 1, kOpenUrlTag = 2, kOpenFolderTag = 3, kCloneFolderTag = 4 };
enum : uint64_t { kMenuOpen = 1, kMenuSyncAll = 2 }; enum : uint64_t { kMenuOpen = 1, kMenuSyncAll = 2 };
struct Activity { std::string Q(const std::string &text) {
std::string phase; // started, running, finished, failed; empty when none return json::Quote(text);
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 { // The native path of a file a dialog returned, as UTF-8.
std::string NativePath(uhdk_file *file) {
uint64_t len = 0;
if (uhdk_file_copy_representation(file, UHDK_FILE_NATIVE_PATH, nullptr, 0, &len) != UHDK_STATUS_OK)
return {};
std::vector<uint8_t> bytes(len);
if (uhdk_file_copy_representation(file, UHDK_FILE_NATIVE_PATH, bytes.data(), len, &len) != UHDK_STATUS_OK)
return {};
#if defined(_WIN32)
// UTF-16LE to UTF-8.
std::string out;
for (size_t i = 0; i + 1 < bytes.size(); i += 2) {
uint32_t c = bytes[i] | (uint32_t(bytes[i + 1]) << 8);
if (c >= 0xD800 && c < 0xDC00 && i + 3 < bytes.size()) {
uint32_t low = bytes[i + 2] | (uint32_t(bytes[i + 3]) << 8);
c = 0x10000 + ((c - 0xD800) << 10) + (low - 0xDC00);
i += 2;
}
if (c < 0x80) {
out += char(c);
} else if (c < 0x800) {
out += char(0xC0 | (c >> 6));
out += char(0x80 | (c & 0x3F));
} else if (c < 0x10000) {
out += char(0xE0 | (c >> 12));
out += char(0x80 | ((c >> 6) & 0x3F));
out += char(0x80 | (c & 0x3F));
} else {
out += char(0xF0 | (c >> 18));
out += char(0x80 | ((c >> 12) & 0x3F));
out += char(0x80 | ((c >> 6) & 0x3F));
out += char(0x80 | (c & 0x3F));
}
}
return out;
#else
return std::string(bytes.begin(), bytes.end());
#endif
}
std::string HomeDir() {
const char *home = std::getenv("HOME");
if (!home || !*home)
home = std::getenv("USERPROFILE");
return home ? home : "";
}
// The repository URL's base, `lore://host:port`.
std::string RemoteBase(const std::string &url) {
size_t scheme = url.find("://");
if (scheme == std::string::npos)
return url;
size_t slash = url.find('/', scheme + 3);
return slash == std::string::npos ? url : url.substr(0, slash);
}
// A sign-in in progress or just finished.
struct LoginState {
std::string remote, url, code, phase, message;
};
using Handler = std::function<void(const json::Value &result, const json::Value &error)>;
class App : public ExplorerHost {
public: public:
App(bool test, std::string screenshot, const std::string &tab) : test_(test), screenshot_(std::move(screenshot)) { App(bool test, std::string screenshot, const std::string &tab) : test_(test), screenshot_(std::move(screenshot)) {
explorer_.SetTab(tab); explorer_.SetTab(tab);
test_tab_ = tab;
} }
bool Run(bool start_hidden); bool Run(bool start_hidden);
// ExplorerHost: for the selected workspace.
void LoadHistory() override;
void LoadDir(const std::string &dir) override;
void LoadRevision(const std::string &signature) override;
void LoadFileHistory(const std::string &path) override;
void LoadChanges() override;
void Refresh() override;
void Sync() override;
void Submit(const std::string &message, const std::vector<std::string> &paths) override;
void SignIn() override;
private: private:
bool Initialize(); bool Initialize();
void Shutdown(); void Shutdown();
void CreateTray(); void CreateTray();
void UpdateTray(); void UpdateTray();
void HandleEvent(const uhdk_event &event); void HandleEvent(const uhdk_event &event);
void HandleRequestDone(const uhdk_request_result &result);
void HandleIncoming(); void HandleIncoming();
void HandleMessage(const json::Value &message); void HandleMessage(const json::Value &message);
void SetWorkspaces(const json::Value &list);
void Draw(const uhdk_window_metrics &metrics); void Draw(const uhdk_window_metrics &metrics);
void DrawHeader(); void DrawHeader();
void DrawLogin();
void DrawSidebar(); void DrawSidebar();
void DrawAdd();
void DrawFooter(); void DrawFooter();
const Workspace *SelectedWorkspace() const; const model::Workspace *SelectedWorkspace() const;
model::Repo &RepoOf(const std::string &id) { return repos_[id]; }
void Call(const std::string &method, const std::string &params, Handler handler = nullptr);
void SyncAll(); void SyncAll();
void StartLogin(const std::string &remote);
void ListRepositories();
void ChooseFolder(uhdk_request_tag tag, const char *title);
void OpenUrl(const std::string &url);
void Show(); void Show();
bool Connected() const { return client_ && client_->GetState() == ServiceClient::State::Connected && greeted_; } bool Connected() const { return client_ && client_->GetState() == ServiceClient::State::Connected && greeted_; }
void TestStep();
bool test_; bool test_;
uhdk_session *session_ = nullptr; uhdk_session *session_ = nullptr;
@ -125,17 +191,33 @@ class App {
std::unique_ptr<ServiceClient> client_; std::unique_ptr<ServiceClient> client_;
bool greeted_ = false; bool greeted_ = false;
std::string service_name_; std::string service_name_;
std::string liblore_, liblore_error_;
std::vector<std::string> accounts_; // "alice at localhost:18081"
std::string error_; std::string error_;
std::vector<Workspace> workspaces_; std::map<uint64_t, Handler> pending_;
std::vector<model::Workspace> workspaces_;
std::map<std::string, model::Repo> repos_;
bool have_status_ = false; bool have_status_ = false;
std::string selected_workspace_; std::string selected_workspace_;
Explorer explorer_; Explorer explorer_;
LoginState login_;
// The ADD panel.
bool adding_ = false;
char server_[256] = "lore://localhost:41337";
char clone_into_[1024] = {};
std::vector<std::pair<std::string, std::string>> repositories_; // name, id
std::string repositories_note_;
std::string chosen_repository_;
std::string tray_tooltip_; std::string tray_tooltip_;
bool tray_sync_enabled_ = false; bool tray_sync_enabled_ = false;
bool test_drawn_ = false; bool test_drawn_ = false;
bool test_sync_sent_ = false; bool test_sync_sent_ = false;
bool test_saw_progress_ = false; bool test_sync_done_ = false;
bool test_failed_ = false;
std::string test_tab_;
int test_settled_frames_ = 0;
std::string screenshot_; std::string screenshot_;
void Screenshot(const uhdk_window_metrics &metrics); void Screenshot(const uhdk_window_metrics &metrics);
@ -259,14 +341,192 @@ void App::Show() {
redraw_frames_ = 2; redraw_frames_ = 2;
} }
void App::Call(const std::string &method, const std::string &params, Handler handler) {
if (!client_)
return;
uint64_t id = client_->Call(method, params);
if (handler)
pending_[id] = std::move(handler);
}
void App::SyncAll() { void App::SyncAll() {
if (!Connected()) if (!Connected())
return; return;
for (const auto &w : workspaces_) for (const auto &w : workspaces_)
if (w.state != "syncing") if (w.state != "syncing" && w.signed_in)
client_->Call("sync_now", "{\"workspace\":" + json::Quote(w.id) + "}"); Call("sync_now", "{\"workspace\":" + Q(w.id) + "}");
} }
void App::OpenUrl(const std::string &url) {
Check(uhdk_shell_open_url_async(session_, Text(url), kOpenUrlTag), "open url");
}
void App::ChooseFolder(uhdk_request_tag tag, const char *title) {
uhdk_file_dialog_desc desc = {};
desc.struct_size = sizeof desc;
desc.kind = UHDK_DIALOG_OPEN_DIRECTORY;
desc.parent = window_;
desc.title = {title, std::strlen(title)};
desc.accept_label = {"Choose", 6};
if (!Check(uhdk_file_dialog_show_async(session_, &desc, tag), "folder dialog"))
error_ = "cannot show a folder dialog here; type the path";
}
// ---- ExplorerHost
void App::LoadHistory() {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string id = w->id;
model::Repo &repo = RepoOf(id);
repo.history = model::Load::Loading;
unsigned generation = repo.generation;
Call("history", "{\"workspace\":" + Q(id) + "}", [this, id, generation](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
if (repo.generation != generation)
return;
if (error.is_object()) {
repo.history = model::Load::Failed;
repo.history_error = error["message"].str();
return;
}
repo.branches = model::ParseBranches(result["branches"]);
repo.revisions = model::ParseRevisions(result["revisions"]);
repo.history = model::Load::Ready;
});
}
void App::LoadDir(const std::string &dir) {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string id = w->id;
model::Repo &repo = RepoOf(id);
repo.dir_state[dir] = model::Load::Loading;
unsigned generation = repo.generation;
Call("files", "{\"workspace\":" + Q(id) + ",\"path\":" + Q(dir) + "}",
[this, id, dir, generation](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
if (repo.generation != generation)
return;
if (error.is_object()) {
repo.dir_state[dir] = model::Load::Failed;
repo.dir_errors[dir] = error["message"].str();
return;
}
repo.dirs[dir] = model::ParseEntries(result["entries"]);
repo.dir_state[dir] = model::Load::Ready;
});
}
void App::LoadRevision(const std::string &signature) {
const model::Workspace *w = SelectedWorkspace();
if (!w || signature.empty())
return;
std::string id = w->id;
RepoOf(id).revisions_loading.insert(signature);
Call("revision", "{\"workspace\":" + Q(id) + ",\"signature\":" + Q(signature) + "}",
[this, id, signature](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
repo.revisions_loading.erase(signature);
// A revision's changes never change; keep them across resets.
repo.revision_changes[signature] = error.is_object() ? std::vector<model::Change>{}
: model::ParseChanges(result["changes"]);
});
}
void App::LoadFileHistory(const std::string &path) {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string id = w->id;
model::Repo &repo = RepoOf(id);
repo.file_history_loading.insert(path);
unsigned generation = repo.generation;
Call("file_history", "{\"workspace\":" + Q(id) + ",\"path\":" + Q(path) + "}",
[this, id, path, generation](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
if (repo.generation != generation)
return;
repo.file_history_loading.erase(path);
repo.file_history[path] = error.is_object() ? std::vector<model::Revision>{}
: model::ParseRevisions(result["revisions"]);
});
}
void App::LoadChanges() {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string id = w->id;
RepoOf(id).changes_state = model::Load::Loading;
Call("changes", "{\"workspace\":" + Q(id) + "}", [this, id](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
if (error.is_object()) {
repo.changes_state = model::Load::Failed;
error_ = error["message"].str();
return;
}
repo.changes = model::ParseChanges(result["changes"]);
repo.changes_state = model::Load::Ready;
});
}
void App::Refresh() {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
RepoOf(w->id).Reset();
Call("refresh", "{\"workspace\":" + Q(w->id) + "}");
}
void App::Sync() {
if (const model::Workspace *w = SelectedWorkspace())
Call("sync_now", "{\"workspace\":" + Q(w->id) + "}");
}
void App::Submit(const std::string &message, const std::vector<std::string> &paths) {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string list = "[";
for (size_t i = 0; i < paths.size(); ++i)
list += (i ? "," : "") + Q(paths[i]);
list += "]";
Call("submit", "{\"workspace\":" + Q(w->id) + ",\"message\":" + Q(message) + ",\"paths\":" + list + "}");
}
void App::SignIn() {
if (const model::Workspace *w = SelectedWorkspace())
StartLogin(RemoteBase(w->remote));
}
void App::StartLogin(const std::string &remote) {
if (remote.empty())
return;
login_ = {remote, "", "", "starting", ""};
Call("login", "{\"remote\":" + Q(remote) + "}");
}
void App::ListRepositories() {
repositories_.clear();
chosen_repository_.clear();
repositories_note_ = "reading";
std::string remote = server_;
Call("repositories", "{\"remote\":" + Q(remote) + "}", [this](const json::Value &result, const json::Value &error) {
if (error.is_object()) {
repositories_note_ = error["message"].str();
return;
}
for (const auto &item : result["repositories"].items())
repositories_.push_back({item["name"].str(), item["id"].str()});
repositories_note_ = repositories_.empty() ? "no repositories you can read" : "";
});
}
// ---- Events
void App::HandleEvent(const uhdk_event &event) { void App::HandleEvent(const uhdk_event &event) {
if (platform_ready_) if (platform_ready_)
ImGui_ImplUHDK_ProcessEvent(&event); ImGui_ImplUHDK_ProcessEvent(&event);
@ -301,6 +561,10 @@ void App::HandleEvent(const uhdk_event &event) {
SyncAll(); SyncAll();
break; break;
} }
case UHDK_EVENT_REQUEST_DONE:
HandleRequestDone(*static_cast<const uhdk_request_result *>(event.data));
redraw_frames_ = 2;
break;
case UHDK_EVENT_WAKE: case UHDK_EVENT_WAKE:
break; break;
default: default:
@ -309,6 +573,32 @@ void App::HandleEvent(const uhdk_event &event) {
} }
} }
void App::HandleRequestDone(const uhdk_request_result &result) {
if (result.tag != kOpenFolderTag && result.tag != kCloneFolderTag)
return;
if (result.status != UHDK_STATUS_OK || !result.data)
return; // cancelled
const auto *files = static_cast<const uhdk_file_list *>(result.data);
if (!files->len)
return;
std::string path = NativePath(files->ptr[0]);
if (path.empty())
return;
if (result.tag == kOpenFolderTag) {
Call("workspace_add", "{\"path\":" + Q(path) + "}", [this](const json::Value &result, const json::Value &error) {
if (error.is_object()) {
error_ = error["message"].str();
return;
}
selected_workspace_ = result["id"].str();
adding_ = false;
});
} else {
std::string name = chosen_repository_.substr(chosen_repository_.rfind('/') + 1);
std::snprintf(clone_into_, sizeof clone_into_, "%s/%s", path.c_str(), name.c_str());
}
}
void App::HandleIncoming() { void App::HandleIncoming() {
if (!client_) if (!client_)
return; return;
@ -321,8 +611,11 @@ void App::HandleIncoming() {
case ServiceClient::Incoming::Kind::Disconnected: case ServiceClient::Incoming::Kind::Disconnected:
greeted_ = false; greeted_ = false;
have_status_ = false; have_status_ = false;
pending_.clear();
for (auto &w : workspaces_) for (auto &w : workspaces_)
w.state = "unknown"; w.state = "unknown";
for (auto &[id, repo] : repos_)
repo.Reset();
break; break;
case ServiceClient::Incoming::Kind::Message: case ServiceClient::Incoming::Kind::Message:
HandleMessage(incoming.message); HandleMessage(incoming.message);
@ -331,21 +624,64 @@ void App::HandleIncoming() {
} }
} }
// New workspace state: a workspace that moved has its repository read again.
void App::SetWorkspaces(const json::Value &list) {
std::vector<model::Workspace> next = model::ParseWorkspaces(list, workspaces_);
for (const auto &w : next) {
for (const auto &old : workspaces_)
if (old.id == w.id && (old.signature != w.signature || old.branch != w.branch || old.changes != w.changes ||
old.ahead != w.ahead || (old.state == "syncing" && w.state != "syncing")))
RepoOf(w.id).Reset();
}
workspaces_ = std::move(next);
}
void App::HandleMessage(const json::Value &message) { void App::HandleMessage(const json::Value &message) {
const std::string &method = message["method"].str(); const std::string &method = message["method"].str();
if (!method.empty()) { if (!method.empty()) {
const json::Value &params = message["params"]; const json::Value &params = message["params"];
if (method == "workspaces") { if (method == "workspaces") {
workspaces_ = ParseWorkspaces(params, workspaces_); SetWorkspaces(params);
} else if (method == "activity") { } else if (method == "activity") {
for (auto &w : workspaces_) for (auto &w : workspaces_)
if (w.id == params["workspace"].str()) { if (w.id == params["workspace"].str()) {
w.activity.kind = params["kind"].str();
w.activity.phase = params["phase"].str(); w.activity.phase = params["phase"].str();
w.activity.message = params["message"].str(); w.activity.message = params["message"].str();
w.activity.progress = float(params["progress"].num(-1)); w.activity.progress = float(params["progress"].num(-1));
if (test_ && w.activity.phase == "running" && w.activity.progress >= 0.5f) bool done = w.activity.phase == "finished";
test_saw_progress_ = true; if (w.activity.phase == "failed")
error_ = w.name + ": " + w.activity.message;
if (done && w.activity.kind == "submit" && w.id == selected_workspace_) {
explorer_.ClearMessage();
RepoOf(w.id).unchecked.clear();
}
if (done || w.activity.phase == "failed")
RepoOf(w.id).Reset();
if (test_ && w.activity.kind == "sync" && (done || w.activity.phase == "failed")) {
test_sync_done_ = true;
if (!done) {
std::fprintf(stderr, "forge-desktop: --test: sync failed: %s\n", w.activity.message.c_str());
test_failed_ = true;
}
}
} }
} else if (method == "login") {
login_.remote = params["remote"].str();
login_.phase = params["phase"].str();
login_.message = params["message"].str();
if (login_.phase == "waiting") {
bool first = login_.url.empty();
login_.url = params["url"].str();
login_.code = params["code"].str();
if (first && !login_.url.empty())
OpenUrl(login_.url);
} else if (login_.phase == "failed") {
error_ = "sign-in failed: " + login_.message;
login_ = {};
} else if (login_.phase == "done") {
Call("status", "{}");
}
} }
return; return;
} }
@ -362,14 +698,38 @@ void App::HandleMessage(const json::Value &message) {
} }
return; return;
} }
if (id.is_number()) {
auto handler = pending_.find(uint64_t(id.num()));
if (handler != pending_.end()) {
Handler run = std::move(handler->second);
pending_.erase(handler);
run(message["result"], error);
return;
}
}
if (error.is_object()) { if (error.is_object()) {
error_ = error["message"].str(); error_ = error["message"].str();
return; return;
} }
const json::Value &result = message["result"]; const json::Value &result = message["result"];
if (result.has("workspaces")) { if (result.has("workspaces")) {
workspaces_ = ParseWorkspaces(result["workspaces"], workspaces_); SetWorkspaces(result["workspaces"]);
have_status_ = true; have_status_ = true;
const json::Value &liblore = result["liblore"];
liblore_ = liblore["loaded"]["version"].str();
liblore_error_ = liblore["missing"]["error"].str();
accounts_.clear();
for (const auto &account : result["accounts"].items()) {
std::string where = account["auth_url"].str();
size_t scheme = where.find("://");
if (scheme != std::string::npos)
where = where.substr(scheme + 3);
std::string name = account["name"].str();
accounts_.push_back((name.empty() ? std::string("signed in") : name) + " at " + where);
}
// Offer the server of the first workspace for cloning.
if (!workspaces_.empty() && !workspaces_[0].remote.empty() && !std::strcmp(server_, "lore://localhost:41337"))
std::snprintf(server_, sizeof server_, "%s", RemoteBase(workspaces_[0].remote).c_str());
} }
} }
@ -428,21 +788,58 @@ static ImU32 StateColour(const std::string &state) {
return theme::kRaised; return theme::kRaised;
} }
const Workspace *App::SelectedWorkspace() const { const model::Workspace *App::SelectedWorkspace() const {
for (const auto &w : workspaces_) for (const auto &w : workspaces_)
if (w.id == selected_workspace_) if (w.id == selected_workspace_)
return &w; return &w;
return workspaces_.empty() ? nullptr : &workspaces_.front(); return workspaces_.empty() ? nullptr : &workspaces_.front();
} }
// A sign-in waiting for approval in the browser: its code, and a way back to the page.
void App::DrawLogin() {
if (login_.phase.empty())
return;
if (login_.phase == "done") {
if (theme::Button("X"))
login_ = {};
ImGui::SameLine(0, 12);
ImGui::AlignTextToFramePadding();
std::string text = "signed in" + (login_.message.empty() ? std::string() : " as " + login_.message) + " at " +
login_.remote;
theme::TextColoured(theme::kGreen, text.c_str());
return;
}
if (theme::Button("X"))
login_ = {};
ImGui::SameLine(0, 12);
ImGui::AlignTextToFramePadding();
theme::TextColoured(theme::kSpark, "SIGN IN");
ImGui::SameLine(0, 12);
if (login_.url.empty()) {
theme::TextColoured(theme::kMuted, ("asking " + login_.remote).c_str());
return;
}
theme::TextColoured(theme::kMuted, "approve in the browser; code");
ImGui::SameLine(0, 8);
theme::Tag(login_.code.empty() ? "-" : login_.code.c_str(), theme::kSpark);
ImGui::SameLine(0, 12);
if (theme::Button("OPEN"))
OpenUrl(login_.url);
ImGui::SameLine(0, 12);
if (theme::Button("COPY CODE", !login_.code.empty()))
Check(uhdk_clipboard_write_text(session_, Text(login_.code)), "copy code");
}
void App::DrawSidebar() { void App::DrawSidebar() {
theme::TextColoured(theme::kMuted, "WORKSPACES"); theme::TextColoured(theme::kMuted, "WORKSPACES");
const Workspace *selected = SelectedWorkspace(); const model::Workspace *selected = adding_ ? nullptr : SelectedWorkspace();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto &w : workspaces_) { for (const auto &w : workspaces_) {
ImGui::PushID(w.id.c_str()); ImGui::PushID(w.id.c_str());
if (theme::Row("ws", selected == &w, 38)) if (theme::Row("ws", selected == &w, 38)) {
selected_workspace_ = w.id; selected_workspace_ = w.id;
adding_ = false;
}
ImVec2 p = ImGui::GetItemRectMin(), q = ImGui::GetItemRectMax(); 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)); ImGui::GetWindowDrawList()->AddRectFilled({p.x + 8, p.y + 6}, {p.x + 16, p.y + 14}, StateColour(w.state));
float right = q.x - 6; float right = q.x - 6;
@ -452,20 +849,135 @@ void App::DrawSidebar() {
right -= ImGui::CalcTextSize(percent).x; right -= ImGui::CalcTextSize(percent).x;
theme::TextAt({right, p.y + 2}, theme::kSpark, percent); theme::TextAt({right, p.y + 2}, theme::kSpark, percent);
right -= 8; right -= 8;
} else if (w.changes) {
std::string count = std::to_string(w.changes);
right -= ImGui::CalcTextSize(count.c_str()).x;
theme::TextAt({right, p.y + 2}, theme::kSpark, count.c_str());
right -= 8;
} }
theme::TextAt({p.x + 24, p.y + 2}, theme::kPaper, w.name.c_str(), right); 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); std::string where = w.branch.empty() ? w.path : w.branch + " " + w.path;
theme::TextAt({p.x + 24, p.y + 19}, theme::kMuted, where.c_str(), q.x - 6);
ImGui::PopID(); ImGui::PopID();
} }
ImGui::PopStyleVar(); ImGui::PopStyleVar();
if (Connected() && have_status_ && workspaces_.empty()) { if (Connected() && have_status_ && workspaces_.empty())
theme::TextColoured(theme::kPaper, "no workspaces"); theme::TextColoured(theme::kMuted, "no workspaces");
ImGui::PushStyleColor(ImGuiCol_Text, theme::kMuted); ImGui::Dummy({0, 4});
ImGui::TextWrapped("add [[workspace]] to %s", paths_.config_file.c_str()); if (theme::Button("ADD", Connected(), workspaces_.empty()))
ImGui::PopStyleColor(); adding_ = true;
if (selected && !adding_) {
ImGui::SameLine(0, 12);
if (theme::Button("FORGET", Connected() && selected->state != "syncing")) {
std::string id = selected->id;
Call("workspace_remove", "{\"workspace\":" + Q(id) + "}", [this, id](const json::Value &, const json::Value &error) {
if (error.is_object())
error_ = error["message"].str();
else
repos_.erase(id);
});
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("stop looking after this workspace; its files stay");
} }
ImGui::Dummy({0, 8}); ImGui::Dummy({0, 8});
explorer_.DrawBranches(); if (selected && !adding_)
explorer_.DrawBranches(RepoOf(selected->id));
}
// Adding a workspace: an existing working copy, or a clone of a repository on a server.
void App::DrawAdd() {
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 10});
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 8});
ImGui::BeginChild("add", {0, 0}, ImGuiChildFlags_Borders);
theme::TextColoured(theme::kPaper, "ADD WORKSPACE");
if (!workspaces_.empty()) {
ImGui::SameLine(ImGui::GetContentRegionMax().x - theme::ButtonWidth("CLOSE"));
if (theme::Button("CLOSE"))
adding_ = false;
}
theme::Rule();
theme::TextColoured(theme::kMuted, "OPEN A WORKING COPY");
if (theme::Button("CHOOSE FOLDER", Connected()))
ChooseFolder(kOpenFolderTag, "Open a Lore working copy");
theme::Rule();
theme::TextColoured(theme::kMuted, "CLONE");
ImGui::AlignTextToFramePadding();
theme::TextColoured(theme::kMuted, "SERVER");
ImGui::SameLine(80);
ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk);
ImGui::SetNextItemWidth(320);
ImGui::InputText("##server", server_, sizeof server_);
ImGui::PopStyleColor();
ImGui::SameLine(0, 12);
if (theme::Button("SIGN IN", Connected() && server_[0]))
StartLogin(RemoteBase(server_));
ImGui::SameLine(0, 12);
if (theme::Button("LIST", Connected() && server_[0], true))
ListRepositories();
if (!accounts_.empty()) {
std::string who;
for (const auto &account : accounts_)
who += (who.empty() ? "" : ", ") + account;
theme::TextColoured(theme::kMuted, who.c_str());
}
const float list_h = std::max(120.0f, ImGui::GetContentRegionAvail().y - 110);
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kInk);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {1, 1});
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
ImGui::BeginChild("repositories", {0, list_h}, ImGuiChildFlags_Borders);
if (!repositories_note_.empty()) {
ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::Dummy({0, 20});
theme::TextAt({p.x + 8, p.y + 2}, theme::kMuted, repositories_note_.c_str(), p.x + ImGui::GetContentRegionAvail().x);
}
for (const auto &[name, id] : repositories_) {
ImGui::PushID(id.c_str());
if (theme::Row("repo", chosen_repository_ == name, 20)) {
chosen_repository_ = name;
std::string leaf = name.substr(name.rfind('/') + 1);
std::string home = HomeDir();
std::snprintf(clone_into_, sizeof clone_into_, "%s/lore/%s", home.c_str(), leaf.c_str());
}
ImVec2 p = ImGui::GetItemRectMin();
theme::TextAt({p.x + 8, p.y + 2}, theme::kPaper, name.c_str(), ImGui::GetItemRectMax().x);
ImGui::PopID();
}
ImGui::EndChild();
ImGui::PopStyleVar(2);
ImGui::PopStyleColor();
ImGui::AlignTextToFramePadding();
theme::TextColoured(theme::kMuted, "INTO");
ImGui::SameLine(80);
ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk);
ImGui::SetNextItemWidth(std::max(200.0f, ImGui::GetContentRegionAvail().x - theme::ButtonWidth("CHOOSE") -
theme::ButtonWidth("CLONE") - 24));
ImGui::InputText("##into", clone_into_, sizeof clone_into_);
ImGui::PopStyleColor();
ImGui::SameLine(0, 12);
if (theme::Button("CHOOSE", !chosen_repository_.empty()))
ChooseFolder(kCloneFolderTag, "Clone into a folder in");
ImGui::SameLine(0, 12);
if (theme::Button("CLONE", Connected() && !chosen_repository_.empty() && clone_into_[0], true)) {
std::string url = RemoteBase(server_) + "/" + chosen_repository_;
Call("workspace_clone", "{\"url\":" + Q(url) + ",\"path\":" + Q(clone_into_) + "}",
[this](const json::Value &result, const json::Value &error) {
if (error.is_object()) {
error_ = error["message"].str();
return;
}
selected_workspace_ = result["id"].str();
adding_ = false;
});
}
ImGui::EndChild();
ImGui::PopStyleVar(2);
ImGui::PopStyleColor();
} }
void App::DrawFooter() { void App::DrawFooter() {
@ -483,10 +995,22 @@ void App::DrawFooter() {
ImVec2 p = ImGui::GetCursorScreenPos(); ImVec2 p = ImGui::GetCursorScreenPos();
float right = p.x + ImGui::GetContentRegionAvail().x; float right = p.x + ImGui::GetContentRegionAvail().x;
std::string status = Connected() ? service_name_ std::string status;
: client_ ? (client_->Detail().empty() ? "looking for service" : client_->Detail()) ImU32 colour = theme::kMuted;
: error_; if (Connected()) {
theme::TextAt({p.x, p.y + 4}, theme::kMuted, status.c_str(), right - buttons_w - 12); status = service_name_;
if (!liblore_.empty())
status += " liblore " + liblore_;
if (!liblore_error_.empty()) {
status += " no liblore: " + liblore_error_;
colour = theme::kRed;
}
for (const auto &account : accounts_)
status += " " + account;
} else {
status = client_ ? (client_->Detail().empty() ? "looking for service" : client_->Detail()) : error_;
}
theme::TextAt({p.x, p.y + 4}, colour, status.c_str(), right - buttons_w - 12);
ImGui::SetCursorScreenPos({right - buttons_w, p.y}); ImGui::SetCursorScreenPos({right - buttons_w, p.y});
for (size_t i = 0; i < buttons.size(); ++i) { for (size_t i = 0; i < buttons.size(); ++i) {
if (i) if (i)
@ -518,6 +1042,7 @@ void App::Draw(const uhdk_window_metrics &metrics) {
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoBringToFrontOnFocus); ImGuiWindowFlags_NoBringToFrontOnFocus);
DrawHeader(); DrawHeader();
DrawLogin();
if (!error_.empty()) { if (!error_.empty()) {
if (theme::Button("X")) if (theme::Button("X"))
@ -539,15 +1064,11 @@ void App::Draw(const uhdk_window_metrics &metrics) {
ImGui::SameLine(0, 16); ImGui::SameLine(0, 16);
ImGui::BeginChild("explorer", {0, -footer}, ImGuiChildFlags_None); ImGui::BeginChild("explorer", {0, -footer}, ImGuiChildFlags_None);
ImGui::PopStyleColor(); ImGui::PopStyleColor();
WorkspaceView view; const model::Workspace *w = SelectedWorkspace();
const Workspace *w = SelectedWorkspace(); if (adding_ || (!w && Connected() && have_status_))
view.name = w ? w->name : "sample"; DrawAdd();
view.syncing = w && w->state == "syncing"; else if (w)
view.progress = w ? w->activity.progress : -1; explorer_.Draw(*w, RepoOf(w->id), *this, Connected());
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(); ImGui::EndChild();
DrawFooter(); DrawFooter();
@ -563,6 +1084,47 @@ void App::Draw(const uhdk_window_metrics &metrics) {
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
} }
// --test: with workspaces, sync the first, then wait until the explorer has what it shows on
// the chosen tab. Without, an answered status is enough.
void App::TestStep() {
if (!Connected() || !have_status_)
return;
bool ready = workspaces_.empty();
if (!workspaces_.empty()) {
const model::Workspace &w = workspaces_[0];
if (!test_sync_sent_ && w.state != "unknown" && w.state != "syncing") {
test_sync_sent_ = true;
Call("sync_now", "{\"workspace\":" + Q(w.id) + "}", [this](const json::Value &, const json::Value &error) {
if (error.is_object()) {
std::fprintf(stderr, "forge-desktop: --test: sync_now: %s\n", error["message"].str().c_str());
test_failed_ = true;
}
});
}
const model::Repo &repo = RepoOf(w.id);
// The sidebar's branches come from history, which not every tab asks for.
if (test_sync_done_ && w.state != "syncing" && repo.history == model::Load::None)
LoadHistory();
ready = test_sync_done_ && w.state != "syncing" && repo.history == model::Load::Ready;
if (test_tab_ == "files" || test_tab_.empty()) {
auto root = repo.dir_state.find("");
ready = ready && root != repo.dir_state.end() && root->second == model::Load::Ready;
} else if (test_tab_ == "changes") {
ready = ready && repo.changes_state == model::Load::Ready;
} else if (test_tab_ == "graph" || test_tab_ == "tree") {
ready = ready && repo.revisions_loading.empty();
}
}
if (!ready) {
test_settled_frames_ = 0;
return;
}
// A few frames for answers asked for while drawing to land and be drawn.
if (++test_settled_frames_ < 3)
return;
test_drawn_ = true;
}
void App::Screenshot(const uhdk_window_metrics &metrics) { void App::Screenshot(const uhdk_window_metrics &metrics) {
uint32_t w = metrics.framebuffer_width, h = metrics.framebuffer_height; uint32_t w = metrics.framebuffer_width, h = metrics.framebuffer_height;
std::vector<uint8_t> pixels(size_t(w) * h * 4), flipped(pixels.size()); std::vector<uint8_t> pixels(size_t(w) * h * 4), flipped(pixels.size());
@ -595,7 +1157,7 @@ bool App::Run(bool start_hidden) {
CreateTray(); CreateTray();
hide_when_tray_ready_ = start_hidden; hide_when_tray_ready_ = start_hidden;
const uint64_t deadline = uhdk_get_time_ns(session_) + 20'000'000'000ull; const uint64_t deadline = uhdk_get_time_ns(session_) + 60'000'000'000ull;
if (test_) if (test_)
Check(uhdk_set_wake_deadline(session_, deadline), "set test deadline"); Check(uhdk_set_wake_deadline(session_, deadline), "set test deadline");
@ -604,20 +1166,19 @@ bool App::Run(bool start_hidden) {
for (uint64_t i = 0; i < frame.events.len; ++i) for (uint64_t i = 0; i < frame.events.len; ++i)
HandleEvent(frame.events.ptr[i]); HandleEvent(frame.events.ptr[i]);
HandleIncoming(); HandleIncoming();
if (test_ && !quitting_ && uhdk_get_time_ns(session_) >= deadline) { if (test_ && !quitting_ && (test_failed_ || uhdk_get_time_ns(session_) >= deadline)) {
std::fprintf(stderr, "forge-desktop: --test: the service did not answer in time (%s)\n", if (!test_failed_)
client_ ? client_->Detail().c_str() : error_.c_str()); std::fprintf(stderr, "forge-desktop: --test: not done in time (%s)\n",
client_ ? client_->Detail().c_str() : error_.c_str());
ok = false; ok = false;
uhdk_quit(session_); uhdk_quit(session_);
} }
if (!quitting_ && frame.drawable) { if (!quitting_ && frame.drawable) {
Draw(frame.metrics); Draw(frame.metrics);
if (test_ && Connected() && have_status_ && !test_sync_sent_ && !workspaces_.empty()) { if (test_) {
test_sync_sent_ = true; bool was_drawn = test_drawn_;
client_->Call("sync_now", "{\"workspace\":" + json::Quote(workspaces_[0].id) + "}"); TestStep();
} if (was_drawn) {
if (test_ && Connected() && have_status_ && (workspaces_.empty() || test_saw_progress_)) {
if (test_drawn_) {
if (!screenshot_.empty()) if (!screenshot_.empty())
Screenshot(frame.metrics); Screenshot(frame.metrics);
std::printf("forge-desktop: --test: PASS (%s, %zu workspaces)\n", service_name_.c_str(), std::printf("forge-desktop: --test: PASS (%s, %zu workspaces)\n", service_name_.c_str(),
@ -627,7 +1188,6 @@ bool App::Run(bool start_hidden) {
quitting_ = true; quitting_ = true;
uhdk_quit(session_); uhdk_quit(session_);
} }
test_drawn_ = true;
} }
} }
if (!Check(uhdk_end_frame(session_), "end frame")) { if (!Check(uhdk_end_frame(session_), "end frame")) {
@ -651,7 +1211,7 @@ bool App::Run(bool start_hidden) {
ok = false; ok = false;
Shutdown(); Shutdown();
uhdk_close(session_); uhdk_close(session_);
return ok; return ok && !test_failed_;
} }
} // namespace } // namespace
@ -674,6 +1234,9 @@ int main(int argc, char **argv) {
test = true; test = true;
} else if (!std::strcmp(argv[i], "--service") && i + 1 < argc) { } else if (!std::strcmp(argv[i], "--service") && i + 1 < argc) {
platform::SetServiceExecutable(argv[++i]); platform::SetServiceExecutable(argv[++i]);
} else if (!std::strncmp(argv[i], "--liblore=", 10)) {
// Read by the service this GUI starts.
platform::SetEnv("LORE_FORGE_LIBLORE", argv[i] + 10);
} else if (!std::strcmp(argv[i], "--config-from") && i + 1 < argc) { } else if (!std::strcmp(argv[i], "--config-from") && i + 1 < argc) {
config_from = argv[++i]; config_from = argv[++i];
} else if (!std::strcmp(argv[i], "--tab") && i + 1 < argc) { } else if (!std::strcmp(argv[i], "--tab") && i + 1 < argc) {
@ -681,10 +1244,10 @@ int main(int argc, char **argv) {
} else if (!std::strcmp(argv[i], "--screenshot") && i + 1 < argc) { } else if (!std::strcmp(argv[i], "--screenshot") && i + 1 < argc) {
screenshot = argv[++i]; screenshot = argv[++i];
} else { } else {
std::fprintf(stderr, "Usage: forge-desktop [--hidden] [--service PATH]\n" std::fprintf(stderr, "Usage: forge-desktop [--hidden] [--service PATH] [--liblore=PATH]\n"
" forge-desktop --licenses\n" " forge-desktop --licenses\n"
" forge-desktop --test [--service PATH] [--config-from FILE] [--screenshot FILE]\n" " forge-desktop --test [--service PATH] [--liblore=PATH] [--config-from FILE]\n"
" [--tab files|graph|tree]\n"); " [--screenshot FILE] [--tab files|graph|tree|changes]\n");
return 2; return 2;
} }
} }

180
desktop/gui/src/model.cpp Normal file
View File

@ -0,0 +1,180 @@
#include "model.hpp"
#include "theme.hpp"
#include <ctime>
namespace model {
Action ParseAction(const std::string &text) {
if (text == "add")
return Action::Add;
if (text == "modify")
return Action::Modify;
if (text == "delete")
return Action::Delete;
if (text == "move")
return Action::Move;
if (text == "copy")
return Action::Copy;
return Action::None;
}
void Repo::Reset() {
++generation;
history = Load::None;
history_error.clear();
branches.clear();
revisions.clear();
dirs.clear();
dir_state.clear();
dir_errors.clear();
file_history.clear();
file_history_loading.clear();
changes_state = Load::None;
changes.clear();
}
const Revision *Repo::FindRevision(const std::string &signature) const {
for (const auto &r : revisions)
if (r.signature == signature)
return &r;
return nullptr;
}
const Branch *Repo::FindBranch(const std::string &id) const {
for (const auto &b : branches)
if (b.id == id)
return &b;
return nullptr;
}
const Branch *Repo::CurrentBranch() const {
for (const auto &b : branches)
if (b.current)
return &b;
return branches.empty() ? nullptr : &branches.front();
}
const FileEntry *Repo::FindEntry(const std::string &path) const {
size_t slash = path.rfind('/');
std::string dir = slash == std::string::npos ? std::string() : path.substr(0, slash);
auto it = dirs.find(dir);
if (it == dirs.end())
return nullptr;
for (const auto &e : it->second)
if (e.path == path)
return &e;
return nullptr;
}
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();
w.branch = item["branch"].str();
w.signature = item["signature"].str();
w.error = item["error"].str();
w.revision = uint64_t(item["revision"].num());
w.changes = uint64_t(item["changes"].num());
w.ahead = item["ahead"].boolean();
w.behind = item["behind"].boolean();
w.online = item["online"].boolean();
w.signed_in = item["signed_in"].boolean();
for (const auto &old : previous)
if (old.id == w.id)
w.activity = old.activity;
out.push_back(std::move(w));
}
return out;
}
std::vector<Change> ParseChanges(const json::Value &list) {
std::vector<Change> out;
for (const auto &item : list.items()) {
Change c;
c.path = item["path"].str();
c.from = item["from"].str();
c.action = ParseAction(item["action"].str());
c.staged = item["staged"].boolean();
c.conflict = item["conflict"].boolean();
out.push_back(std::move(c));
}
return out;
}
std::vector<Branch> ParseBranches(const json::Value &list) {
static const ImU32 palette[] = {theme::kForge, theme::kBlue, theme::kGreen, theme::kSpark, theme::kRed, theme::kMuted};
std::vector<Branch> out;
for (const auto &item : list.items()) {
Branch b;
b.id = item["id"].str();
b.name = item["name"].str();
b.head = item["head"].str();
b.current = item["current"].boolean();
b.remote_only = item["remote_only"].boolean();
b.colour = palette[out.size() % (sizeof palette / sizeof palette[0])];
out.push_back(std::move(b));
}
return out;
}
std::vector<Revision> ParseRevisions(const json::Value &list) {
std::vector<Revision> out;
for (const auto &item : list.items()) {
Revision r;
r.signature = item["signature"].str();
r.branch = item["branch"].str();
r.message = item["message"].str();
r.author = item["author"].str();
r.number = uint64_t(item["number"].num());
r.timestamp_ms = uint64_t(item["timestamp_ms"].num());
for (const auto &parent : item["parents"].items())
r.parents.push_back(parent.str());
out.push_back(std::move(r));
}
return out;
}
std::vector<FileEntry> ParseEntries(const json::Value &list) {
std::vector<FileEntry> out;
for (const auto &item : list.items()) {
FileEntry e;
e.name = item["name"].str();
e.path = item["path"].str();
e.lock = item["lock"].str();
e.dir = item["dir"].boolean();
e.lock_mine = item["lock_mine"].boolean();
e.size = uint64_t(item["size"].num());
e.change = ParseAction(item["change"].str());
out.push_back(std::move(e));
}
return out;
}
std::string Short(const std::string &signature) {
return signature.substr(0, 7);
}
std::string Date(uint64_t timestamp_ms) {
if (!timestamp_ms)
return {};
std::time_t seconds = std::time_t(timestamp_ms / 1000);
std::tm local = {};
#if defined(_WIN32)
localtime_s(&local, &seconds);
#else
localtime_r(&seconds, &local);
#endif
char out[32];
std::strftime(out, sizeof out, "%Y-%m-%d %H:%M", &local);
return out;
}
} // namespace model

102
desktop/gui/src/model.hpp Normal file
View File

@ -0,0 +1,102 @@
// What the GUI knows about the service's workspaces and their repositories, parsed from the
// protocol's JSON (desktop/protocol/src/lib.rs is the reference for every field).
#pragma once
#include "imgui.h"
#include "json.hpp"
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <vector>
namespace model {
enum class Action { None, Add, Modify, Delete, Move, Copy };
Action ParseAction(const std::string &text);
struct Activity {
std::string kind, phase; // phase: started, running, finished, failed; empty when none
std::string message;
float progress = -1;
};
struct Workspace {
std::string id, name, path, remote, state, autosync;
std::string branch, signature, error;
uint64_t revision = 0, changes = 0;
bool ahead = false, behind = false, online = false, signed_in = false;
Activity activity;
};
struct Change {
std::string path, from;
Action action = Action::Modify;
bool staged = false, conflict = false;
};
struct Branch {
std::string id, name, head;
bool current = false, remote_only = false;
ImU32 colour = 0;
};
struct Revision {
std::string signature, branch, message, author;
std::vector<std::string> parents; // first parent first
uint64_t number = 0, timestamp_ms = 0;
};
struct FileEntry {
std::string name, path, lock;
bool dir = false, lock_mine = false;
uint64_t size = 0;
Action change = Action::None;
};
// Something read from the service: absent, on its way, there, or failed.
enum class Load { None, Loading, Ready, Failed };
// One workspace's repository as the explorer has read it so far. Reset when the workspace
// moves (a new revision or different local changes); revisions' changes never change and stay.
struct Repo {
// Bumped by Reset, so answers to requests made before it are dropped.
unsigned generation = 0;
Load history = Load::None;
std::string history_error;
std::vector<Branch> branches;
std::vector<Revision> revisions; // newest first; children before parents
std::map<std::string, std::vector<FileEntry>> dirs; // by directory; "" is the root
std::map<std::string, Load> dir_state;
std::map<std::string, std::string> dir_errors;
std::map<std::string, std::vector<Change>> revision_changes; // by signature
std::set<std::string> revisions_loading;
std::map<std::string, std::vector<Revision>> file_history; // by path
std::set<std::string> file_history_loading;
Load changes_state = Load::None;
std::vector<Change> changes;
std::set<std::string> unchecked; // changes left out of the next submit
void Reset(); // everything but revision_changes
const Revision *FindRevision(const std::string &signature) const;
const Branch *FindBranch(const std::string &id) const;
const Branch *CurrentBranch() const;
const FileEntry *FindEntry(const std::string &path) const;
};
std::vector<Workspace> ParseWorkspaces(const json::Value &list, const std::vector<Workspace> &previous);
std::vector<Change> ParseChanges(const json::Value &list);
std::vector<Branch> ParseBranches(const json::Value &list);
std::vector<Revision> ParseRevisions(const json::Value &list);
std::vector<FileEntry> ParseEntries(const json::Value &list);
// "a3f9c21": the first seven hex digits of a signature.
std::string Short(const std::string &signature);
// "2026-11-25 14:03" in local time; empty for 0.
std::string Date(uint64_t timestamp_ms);
} // namespace model

View File

@ -1,161 +0,0 @@
#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

@ -1,52 +0,0 @@
// 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

@ -21,7 +21,7 @@
class ServiceClient { class ServiceClient {
public: public:
static constexpr int kProtocolVersion = 1; static constexpr int kProtocolVersion = 2;
enum class State { Connecting, StartingService, Connected, Unavailable }; enum class State { Connecting, StartingService, Connected, Unavailable };

View File

@ -0,0 +1,11 @@
[package]
name = "lore-sys"
description = "Bindings to liblore, Lore's C API, loaded at run time"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
libloading.workspace = true

View File

@ -0,0 +1,42 @@
//! Prints the events of one liblore operation, for checking what liblore reports.
//!
//! LORE_FORGE_LIBLORE=<liblore> cargo run -p lore-sys --example probe -- <op> <working copy> [arg]
//!
//! Operations: status, scan, branches, history, info <rev>, diff <from> <to>, locks, files <path>,
//! repos <remote>, users <id>, logins, clone <url>, sync, login <remote>, stage <path>,
//! commit <message>, push.
use lore_sys::Globals;
use lore_sys::Lore;
fn main() {
let lib = std::env::var_os("LORE_FORGE_LIBLORE").expect("set LORE_FORGE_LIBLORE");
let lore = Lore::load(std::path::Path::new(&lib)).unwrap();
let args: Vec<String> = std::env::args().skip(1).collect();
let op = args.first().map(String::as_str).unwrap_or("status");
let globals = Globals { repository_path: args.get(1).cloned().unwrap_or_default(), ..Globals::default() };
let a = args.get(2).cloned().unwrap_or_default();
let b = args.get(3).cloned().unwrap_or_default();
let print = |event| println!("{event:?}");
let result = match op {
"status" => lore.repository_status(&globals, false, print),
"scan" => lore.repository_status(&globals, true, print),
"branches" => lore.branch_list(&globals, print),
"history" => lore.revision_history(&globals, &a, "", 20, print),
"info" => lore.revision_info(&globals, &a, true, true, print),
"diff" => lore.revision_diff(&globals, &a, &b, print),
"locks" => lore.lock_file_query(&globals, &a, print),
"files" => lore.file_history(&globals, &a, 20, print),
"repos" => lore.repository_list(&globals, &a, print),
"users" => lore.auth_user_info(&globals, std::slice::from_ref(&a), print),
"logins" => lore.auth_list(&globals, print),
"clone" => lore.repository_clone(&globals, &a, print),
"sync" => lore.revision_sync(&globals, print),
"stage" => lore.file_stage(&globals, std::slice::from_ref(&a), print),
"commit" => lore.revision_commit(&globals, &a, print),
"push" => lore.branch_push(&globals, print),
"login" => lore.auth_login_interactive(&globals, &a, true, print),
other => panic!("unknown operation {other}"),
};
println!("=> {result:?}");
}

View File

@ -0,0 +1,11 @@
[package]
name = "lore-sys-gen"
description = "Regenerates lore-sys's bindings from liblore's lore.h"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
bindgen = "0.72"

View File

@ -0,0 +1,46 @@
//! Regenerates `lore-sys/src/bindings.rs` from liblore's `lore.h`.
//!
//! cargo run -p lore-sys-gen -- <path to lore.h>
//!
//! `scripts/fetch-lore.sh --liblore` prints the directory holding the pinned release's
//! `lore.h`. Needs libclang (Xcode's command-line tools on macOS, `libclang-dev` on Linux).
use std::path::PathBuf;
use std::process::ExitCode;
fn main() -> ExitCode {
let Some(header) = std::env::args_os().nth(1).map(PathBuf::from) else {
eprintln!("usage: lore-sys-gen <lore.h>");
return ExitCode::from(2);
};
let out = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../src/bindings.rs");
let bindings = bindgen::Builder::default()
.header(header.to_string_lossy())
.allowlist_item("lore_.*|LORE_.*")
// Loaded at run time with libloading, so the service builds and runs without liblore.
.dynamic_library_name("LoreLib")
.dynamic_link_require_all(true)
.derive_default(true)
.prepend_enum_name(false)
.layout_tests(false)
.generate_comments(true)
.raw_line("// Generated by lore-sys-gen from liblore's lore.h. Do not edit.")
.raw_line("#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code, unsafe_op_in_unsafe_fn, clippy::all)]")
.generate();
match bindings {
Ok(bindings) => match bindings.write_to_file(&out) {
Ok(()) => {
println!("wrote {}", out.display());
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("{}: {error}", out.display());
ExitCode::FAILURE
}
},
Err(error) => {
eprintln!("bindgen: {error}");
ExitCode::FAILURE
}
}
}

File diff suppressed because it is too large Load Diff

750
desktop/lore-sys/src/lib.rs Normal file
View File

@ -0,0 +1,750 @@
//! liblore, Lore's C API, loaded at run time.
//!
//! [`bindings`] is generated from the pinned release's `lore.h` by `lore-sys-gen`. The rest is
//! a small safe layer over the operations the client service uses: [`Lore::load`] opens the
//! library, and each operation runs one asynchronous liblore call, handing its events to a
//! closure as owned [`Event`]s until the call ends. Calls block the calling thread, so run
//! them on a blocking thread (`tokio::task::spawn_blocking`).
//!
//! See `.ai/designs/desktop-client.md`, "liblore".
// lore.h asks for every structure to be zeroed, then the fields a call uses set: `default()`
// and assignments say exactly that.
#![allow(clippy::field_reassign_with_default)]
pub mod bindings;
use std::path::Path;
use std::sync::mpsc;
use bindings as b;
/// The interface version these bindings were generated from.
pub const INTERFACE_VERSION: &str = "0.14.0";
/// The library's file name on this platform.
pub const LIBRARY_FILE: &str = if cfg!(windows) {
"lore.dll"
} else if cfg!(target_os = "macos") {
"liblore.dylib"
} else {
"liblore.so"
};
pub struct Lore {
lib: b::LoreLib,
version: String,
}
/// Arguments every operation takes. Empty strings select liblore's defaults.
#[derive(Clone, Debug, Default)]
pub struct Globals {
/// The working copy, or the directory to clone into.
pub repository_path: String,
/// Use only local data.
pub local: bool,
/// Do not connect to the server.
pub offline: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
/// liblore's error code; -1 for an internal error. 0 here means the call never reported
/// completion.
pub code: i32,
pub message: String,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.message.is_empty() {
write!(f, "liblore error {}", self.code)
} else {
f.write_str(&self.message)
}
}
}
impl std::error::Error for Error {}
/// What happened to a file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
Keep,
Add,
Delete,
Move,
Copy,
}
impl Action {
fn from_raw(raw: u32) -> Action {
match raw {
b::LORE_FILE_ACTION_ADD => Action::Add,
b::LORE_FILE_ACTION_DELETE => Action::Delete,
b::LORE_FILE_ACTION_MOVE => Action::Move,
b::LORE_FILE_ACTION_COPY => Action::Copy,
_ => Action::Keep,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind {
Directory,
File,
Link,
}
/// A metadata value, as revision metadata carries them.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Text(String),
Number(u64),
Bool(bool),
/// A hash, context or address, as lowercase hex.
Hex(String),
Binary(Vec<u8>),
}
/// An event from a liblore call, copied out of the callback.
///
/// Signatures, branch and repository ids are lowercase hex. A zero hash is `None` or empty.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
/// A non-fatal error during the call.
Error { code: u32, message: String },
/// A login wants the user to open `url`, entering or confirming `code`.
AuthUrl { url: String, code: String },
/// A login is still waiting for approval.
AuthPending { elapsed_s: u64, remaining_s: u64 },
UserInfo { id: String, name: String },
Identity { auth_url: String, resource: String, user_id: String, expires_ms: u64 },
Branch { id: String, name: String, latest: Option<String>, remote: bool, current: bool, archived: bool },
HistoryEntry { signature: String, number: u64, parents: Vec<String> },
RevisionInfo { signature: String, number: u64, parents: Vec<String> },
/// A file changed by a revision, against its first parent.
Delta { path: String, action: Action, modified: bool, file: bool, from: String },
Metadata { key: String, value: Value },
Status(Status),
StatusFile(StatusFile),
SyncProgress { files_done: u64, files_total: u64, bytes_done: u64, bytes_total: u64 },
SyncRevision { signature: String, number: u64, merge: bool, conflict: bool },
CommitRevision { signature: String, number: u64 },
PushProgress { bytes_done: u64, bytes_total: u64 },
CloneProgress { files_done: u64, files_total: u64, bytes_done: u64, bytes_total: u64 },
DiffFile { path: String, action: Action, file: bool, from: String },
FileHistory { signature: String, number: u64, action: Action, size: u64, from: String },
Lock { branch: String, path: String, owner: String, locked_at: u64 },
Repository { id: String, name: String },
/// A repository configuration value.
Config { key: String, value: String },
/// Any other event, by tag.
Other(u32),
}
/// A working copy's position, from `repository_status`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Status {
pub repository: String,
pub branch: String,
pub branch_name: String,
pub revision: Option<String>,
pub number: u64,
pub staged: Option<String>,
pub merging: Option<String>,
pub local: Option<String>,
pub local_number: u64,
pub remote: Option<String>,
pub remote_number: u64,
pub local_ahead: bool,
pub remote_ahead: bool,
pub remote_available: bool,
pub remote_authorized: bool,
}
/// A file with local changes, from `repository_status`.
#[derive(Clone, Debug, PartialEq)]
pub struct StatusFile {
pub path: String,
pub size: u64,
pub action: Action,
pub kind: NodeKind,
pub staged: bool,
pub dirty: bool,
pub conflict: bool,
pub conflict_unresolved: bool,
pub from: String,
}
impl Lore {
/// Opens liblore at `path` and checks it is the interface version these bindings expect.
pub fn load(path: &Path) -> Result<Lore, String> {
// SAFETY: loading runs the library's initialisers; liblore is a plain Rust cdylib.
let lib = unsafe { b::LoreLib::new(path) }.map_err(|error| format!("{}: {error}", path.display()))?;
// SAFETY: lore_version returns a static NUL-terminated string.
let version = unsafe { std::ffi::CStr::from_ptr(lib.lore_version()) }.to_string_lossy().into_owned();
let interface = version.split('+').next().unwrap_or_default();
if interface != INTERFACE_VERSION {
return Err(format!(
"{} is liblore {version}; this build needs interface {INTERFACE_VERSION}",
path.display()
));
}
Ok(Lore { lib, version })
}
/// The library's version: the interface version, `+`, and the build name.
pub fn version(&self) -> &str {
&self.version
}
/// Runs one asynchronous call. `start` makes the call with the callback configuration;
/// events other than completion go to `on` on this thread, until the call ends.
fn call(&self, start: impl FnOnce(b::lore_event_callback_config_t), mut on: impl FnMut(Event)) -> Result<(), Error> {
let (tx, rx) = mpsc::channel::<Raw>();
let context = Box::into_raw(Box::new(tx)) as u64;
start(b::lore_event_callback_config_t { user_context: context, func: Some(callback) });
let mut result = Err(Error { code: 0, message: "liblore ended the call without completing it".into() });
for raw in rx {
match raw {
Raw::Event(event) => on(event),
Raw::Complete(status, message) => {
result = if status == 0 { Ok(()) } else { Err(Error { code: status, message }) }
}
}
}
result
}
pub fn auth_login_interactive(
&self,
globals: &Globals,
remote_url: &str,
reuse_session: bool,
on: impl FnMut(Event),
) -> Result<(), Error> {
let mut args = b::lore_auth_login_interactive_args_t::default();
args.remote_url = s(remote_url);
args.no_browser = 1;
args.reuse_session = reuse_session.into();
with_globals(globals, |g| {
// SAFETY: `g` and `args` outlive the call, and liblore copies them before it returns.
self.call(|cb| unsafe { self.lib.lore_auth_login_interactive_async(g, &args, cb) }, on)
})
}
/// Stored logins, as [`Event::Identity`].
pub fn auth_list(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_auth_list_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_auth_list_async(g, &args, cb) }, on))
}
/// Display names for user ids, as [`Event::UserInfo`]. No ids resolves the current user.
pub fn auth_user_info(&self, globals: &Globals, ids: &[String], on: impl FnMut(Event)) -> Result<(), Error> {
let ids = strings(ids);
let mut args = b::lore_auth_user_info_args_t::default();
args.user_ids = array(&ids);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_auth_user_info_async(g, &args, cb) }, on))
}
/// The repositories at a remote, as [`Event::Repository`].
pub fn repository_list(&self, globals: &Globals, url: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_repository_list_args_t::default();
args.url = s(url);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_repository_list_async(g, &args, cb) }, on))
}
/// Clones `url` (a remote and repository name) into `globals.repository_path`.
pub fn repository_clone(&self, globals: &Globals, url: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_repository_clone_args_t::default();
args.repository_url = s(url);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_repository_clone_async(g, &args, cb) }, on))
}
/// A working copy's configuration value: `remote_url` or `identity`.
pub fn repository_config_get(&self, globals: &Globals, key: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_repository_config_get_args_t::default();
args.key = s(key);
with_globals(globals, |g| {
self.call(|cb| unsafe { self.lib.lore_repository_config_get_async(g, &args, cb) }, on)
})
}
/// Waits for the working copy's outstanding background writes, so other processes (the
/// CLI) see what the last call did.
pub fn repository_flush(&self, globals: &Globals) -> Result<(), Error> {
let args = b::lore_repository_flush_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_repository_flush_async(g, &args, cb) }, |_| {}))
}
/// The working copy's position and its changed files. `scan` walks the file system
/// first, so edits made outside Lore are seen.
pub fn repository_status(&self, globals: &Globals, scan: bool, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_repository_status_args_t::default();
args.staged = 1;
args.scan = scan.into();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_repository_status_async(g, &args, cb) }, on))
}
pub fn branch_list(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_branch_list_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_branch_list_async(g, &args, cb) }, on))
}
pub fn branch_switch(&self, globals: &Globals, branch: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_branch_switch_args_t::default();
args.branch = s(branch);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_branch_switch_async(g, &args, cb) }, on))
}
/// Up to `length` revisions back from `revision` (or the branch tip), first parents
/// first, as [`Event::HistoryEntry`].
pub fn revision_history(
&self,
globals: &Globals,
branch: &str,
revision: &str,
length: u32,
on: impl FnMut(Event),
) -> Result<(), Error> {
let mut args = b::lore_revision_history_args_t::default();
args.branch = s(branch);
args.revision = s(revision);
args.length = length;
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_revision_history_async(g, &args, cb) }, on))
}
/// A revision's record; `delta` adds its changed files, `metadata` its message and
/// authors.
pub fn revision_info(
&self,
globals: &Globals,
revision: &str,
delta: bool,
metadata: bool,
on: impl FnMut(Event),
) -> Result<(), Error> {
let mut args = b::lore_revision_info_args_t::default();
args.revision = s(revision);
args.delta = delta.into();
args.metadata = metadata.into();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_revision_info_async(g, &args, cb) }, on))
}
pub fn revision_diff(&self, globals: &Globals, from: &str, to: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_revision_diff_args_t::default();
args.revision_source = s(from);
args.revision_target = s(to);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_revision_diff_async(g, &args, cb) }, on))
}
/// Brings the working copy to the branch tip, keeping local changes.
pub fn revision_sync(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_revision_sync_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_revision_sync_async(g, &args, cb) }, on))
}
pub fn file_stage(&self, globals: &Globals, paths: &[String], on: impl FnMut(Event)) -> Result<(), Error> {
let paths = strings(paths);
let mut args = b::lore_file_stage_args_t::default();
args.paths = array(&paths);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_file_stage_async(g, &args, cb) }, on))
}
pub fn file_unstage(&self, globals: &Globals, paths: &[String], on: impl FnMut(Event)) -> Result<(), Error> {
let paths = strings(paths);
let mut args = b::lore_file_unstage_args_t::default();
args.paths = array(&paths);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_file_unstage_async(g, &args, cb) }, on))
}
pub fn revision_commit(&self, globals: &Globals, message: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_revision_commit_args_t::default();
args.message = s(message);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_revision_commit_async(g, &args, cb) }, on))
}
/// Pushes the current branch.
pub fn branch_push(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_branch_push_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_branch_push_async(g, &args, cb) }, on))
}
/// Locks on `branch` (empty: every branch), as [`Event::Lock`].
pub fn lock_file_query(&self, globals: &Globals, branch: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_lock_file_query_args_t::default();
args.branch = s(branch);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_query_async(g, &args, cb) }, on))
}
/// The revisions that changed `path`, newest first, as [`Event::FileHistory`].
pub fn file_history(&self, globals: &Globals, path: &str, length: u32, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_file_history_args_t::default();
args.path = s(path);
args.length = length;
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_file_history_async(g, &args, cb) }, on))
}
}
impl Drop for Lore {
/// Shuts liblore down, which flushes what its stores hold in memory. Every call has
/// completed by now: each operation waits for its END.
fn drop(&mut self) {
// SAFETY: no call is in flight, as above.
let status = unsafe { self.lib.lore_shutdown() };
if status != 0 {
eprintln!("liblore shutdown returned {status}");
}
}
}
/// What the callback hands back to [`Lore::call`].
enum Raw {
Event(Event),
Complete(i32, String),
}
/// liblore's callback. `context` is the boxed sender [`Lore::call`] made; END frees it.
unsafe extern "C" fn callback(event: *const b::lore_event_t, context: u64) {
let sender = context as *mut mpsc::Sender<Raw>;
// SAFETY: liblore passes a valid event for the duration of the callback.
let event = unsafe { &*event };
match event.tag {
b::LORE_EVENT_END => {
// SAFETY: END is the last event of the call, so nothing uses the sender after this.
drop(unsafe { Box::from_raw(sender) });
}
b::LORE_EVENT_LOG | b::LORE_EVENT_PROGRESS => {}
_ => {
// SAFETY: the sender lives until END, and events of one call arrive one at a time.
let sender = unsafe { &*sender };
let raw = if event.tag == b::LORE_EVENT_COMPLETE {
// SAFETY: the tag says which union member is set.
let complete = unsafe { &event.__bindgen_anon_1.complete };
Raw::Complete(complete.status, text(&complete.error.message))
} else {
// SAFETY: as above; decode reads only the member the tag names.
Raw::Event(unsafe { decode(event) })
};
// The receiver is gone only if the caller panicked; nothing to do then.
let _ = sender.send(raw);
}
}
}
/// Copies an event's data out.
///
/// # Safety
/// `event.tag` must name the union member that is set, as liblore guarantees.
unsafe fn decode(event: &b::lore_event_t) -> Event {
let data = &event.__bindgen_anon_1;
unsafe {
match event.tag {
b::LORE_EVENT_ERROR => {
let e = &data.error;
Event::Error { code: e.error_type, message: text(&e.error_inner) }
}
b::LORE_EVENT_AUTH_URL => {
let e = &data.auth_url;
Event::AuthUrl { url: text(&e.url), code: text(&e.user_code) }
}
b::LORE_EVENT_AUTH_PENDING => {
let e = &data.auth_pending;
Event::AuthPending { elapsed_s: e.elapsed_secs, remaining_s: e.remaining_secs }
}
b::LORE_EVENT_AUTH_USER_INFO => {
let e = &data.auth_user_info;
Event::UserInfo { id: text(&e.id), name: text(&e.name) }
}
b::LORE_EVENT_AUTH_IDENTITY => {
let e = &data.auth_identity;
Event::Identity {
auth_url: text(&e.auth_url),
resource: text(&e.resource),
user_id: text(&e.user_id),
expires_ms: e.expires,
}
}
b::LORE_EVENT_BRANCH_LIST_ENTRY => {
let e = &data.branch_list_entry;
Event::Branch {
id: hex(&e.id.data),
name: text(&e.name),
latest: hash(&e.latest),
remote: e.location == b::LORE_BRANCH_LOCATION_REMOTE,
current: e.is_current != 0,
archived: e.archived != 0,
}
}
b::LORE_EVENT_REVISION_HISTORY_ENTRY => {
let e = &data.revision_history_entry;
Event::HistoryEntry {
signature: hex(&e.revision.data),
number: e.revision_number,
parents: e.parent.iter().filter_map(hash).collect(),
}
}
b::LORE_EVENT_REVISION_INFO => {
let e = &data.revision_info;
Event::RevisionInfo {
signature: hex(&e.revision.data),
number: e.revision_number,
parents: e.parent.iter().filter_map(hash).collect(),
}
}
b::LORE_EVENT_REVISION_INFO_DELTA => {
let e = &data.revision_info_delta;
Event::Delta {
path: text(&e.path),
action: Action::from_raw(e.action),
modified: e.flag_modify != 0,
file: e.flag_file != 0,
from: text(&e.from_path),
}
}
b::LORE_EVENT_METADATA => {
let e = &data.metadata;
Event::Metadata { key: text(&e.key), value: metadata(&e.value) }
}
b::LORE_EVENT_REPOSITORY_STATUS_REVISION => {
let e = &data.repository_status_revision;
Event::Status(Status {
repository: hex(&e.repository.data),
branch: hex(&e.branch.data),
branch_name: text(&e.branch_name),
revision: hash(&e.revision),
number: e.revision_number,
staged: hash(&e.revision_staged),
merging: hash(&e.revision_merged),
local: hash(&e.revision_local),
local_number: e.revision_local_number,
remote: hash(&e.revision_remote),
remote_number: e.revision_remote_number,
local_ahead: e.is_local_ahead != 0,
remote_ahead: e.is_remote_ahead != 0,
remote_available: e.remote_available != 0,
remote_authorized: e.remote_authorized != 0,
})
}
b::LORE_EVENT_REPOSITORY_STATUS_FILE => {
let e = &data.repository_status_file;
Event::StatusFile(StatusFile {
path: text(&e.path),
size: e.size,
action: Action::from_raw(e.action),
kind: match e.type_ {
b::LORE_NODE_TYPE_DIRECTORY => NodeKind::Directory,
b::LORE_NODE_TYPE_LINK => NodeKind::Link,
_ => NodeKind::File,
},
staged: e.flag_staged != 0,
dirty: e.flag_dirty != 0,
conflict: e.flag_conflict != 0,
conflict_unresolved: e.flag_conflict_unresolved != 0,
from: text(&e.from_path),
})
}
b::LORE_EVENT_REVISION_SYNC_PROGRESS => {
let e = &data.revision_sync_progress;
Event::SyncProgress {
files_done: (e.file_update + e.file_delete) as u64,
files_total: (e.file_update_total + e.file_delete_total) as u64,
bytes_done: e.bytes_update,
bytes_total: e.bytes_update_total,
}
}
b::LORE_EVENT_REVISION_SYNC_REVISION => {
let e = &data.revision_sync_revision;
Event::SyncRevision {
signature: hex(&e.revision.data),
number: e.revision_number,
merge: e.flag_merge != 0,
conflict: e.flag_conflict != 0,
}
}
b::LORE_EVENT_REVISION_COMMIT_REVISION => {
let e = &data.revision_commit_revision;
Event::CommitRevision { signature: hex(&e.revision.data), number: e.revision_number }
}
b::LORE_EVENT_BRANCH_PUSH_FRAGMENT_PROGRESS => {
let e = &data.branch_push_fragment_progress;
Event::PushProgress { bytes_done: e.bytes_transferred, bytes_total: e.bytes_total }
}
b::LORE_EVENT_REPOSITORY_CLONE_PROGRESS => {
let c = &data.repository_clone_progress.count;
Event::CloneProgress {
files_done: c.file_complete,
files_total: c.file_count,
bytes_done: c.bytes_transferred,
bytes_total: c.bytes_total,
}
}
b::LORE_EVENT_REVISION_DIFF_FILE => {
let e = &data.revision_diff_file;
Event::DiffFile {
path: text(&e.path),
action: Action::from_raw(e.action),
file: e.new_is_file != 0 || e.old_is_file != 0,
from: text(&e.from_path),
}
}
b::LORE_EVENT_FILE_HISTORY => {
let e = &data.file_history;
Event::FileHistory {
signature: hex(&e.revision.data),
number: e.revision_number,
action: Action::from_raw(e.action),
size: e.size,
from: text(&e.from_path),
}
}
b::LORE_EVENT_LOCK_FILE_QUERY => {
let e = &data.lock_file_query;
Event::Lock {
branch: hex(&e.branch.data),
path: text(&e.path),
owner: text(&e.owner),
locked_at: e.locked_at,
}
}
b::LORE_EVENT_REPOSITORY_LIST_ENTRY => {
let e = &data.repository_list_entry;
Event::Repository { id: hex(&e.id.data), name: text(&e.name) }
}
b::LORE_EVENT_REPOSITORY_CONFIG_GET => {
let e = &data.repository_config_get;
Event::Config { key: text(&e.key), value: text(&e.value) }
}
other => Event::Other(other),
}
}
}
/// # Safety
/// `value.tag` must name the union member that is set.
unsafe fn metadata(value: &b::lore_metadata_t) -> Value {
let data = &value.__bindgen_anon_1;
unsafe {
match value.tag {
b::LORE_METADATA_TYPE_STRING => Value::Text(text(&data.string)),
b::LORE_METADATA_TYPE_NUMERIC => Value::Number(data.numeric),
b::LORE_METADATA_TYPE_BOOLEAN => Value::Bool(data.boolean != 0),
b::LORE_METADATA_TYPE_HASH => Value::Hex(hex(&data.hash.data)),
b::LORE_METADATA_TYPE_CONTEXT => Value::Hex(hex(&data.context.data)),
b::LORE_METADATA_TYPE_ADDRESS => {
Value::Hex(format!("{}-{}", hex(&data.address.hash.data), hex(&data.address.context.data)))
}
_ => {
let binary = &data.binary;
if binary.payload.is_null() || binary.length == 0 {
Value::Binary(Vec::new())
} else {
Value::Binary(std::slice::from_raw_parts(binary.payload.cast::<u8>(), binary.length).to_vec())
}
}
}
}
}
/// Builds the globals structure, borrowing `globals`' strings for the call.
fn with_globals<R>(globals: &Globals, f: impl FnOnce(&b::lore_global_args_t) -> R) -> R {
let mut g = b::lore_global_args_t::default();
g.repository_path = s(&globals.repository_path);
// Relative paths (file arguments, and the scan's root) resolve against the working copy
// rather than the service's own directory.
g.working_directory = s(&globals.repository_path);
g.local = globals.local.into();
g.offline = globals.offline.into();
f(&g)
}
/// Borrows `text` as a liblore string. liblore copies it before the call returns.
fn s(text: &str) -> b::lore_string_t {
if text.is_empty() {
b::lore_string_t { string: std::ptr::null(), length: 0 }
} else {
b::lore_string_t { string: text.as_ptr().cast(), length: text.len() }
}
}
fn strings(items: &[String]) -> Vec<b::lore_string_t> {
items.iter().map(|item| s(item)).collect()
}
fn array(items: &[b::lore_string_t]) -> b::lore_string_array_t {
b::lore_string_array_t { ptr: if items.is_empty() { std::ptr::null() } else { items.as_ptr() }, count: items.len() }
}
/// Copies a liblore string; invalid UTF-8 is replaced.
fn text(value: &b::lore_string_t) -> String {
if value.length == 0 || value.string.is_null() {
return String::new();
}
// SAFETY: liblore guarantees `length` bytes at `string` for the callback's duration.
let bytes = unsafe { std::slice::from_raw_parts(value.string.cast::<u8>(), value.length) };
String::from_utf8_lossy(bytes).into_owned()
}
pub fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push(DIGITS[usize::from(byte >> 4)] as char);
out.push(DIGITS[usize::from(byte & 15)] as char);
}
out
}
fn hash(value: &b::lore_hash_t) -> Option<String> {
value.data.iter().any(|byte| *byte != 0).then(|| hex(&value.data))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strings_borrow_and_copy() {
let empty = s("");
assert!(empty.string.is_null());
assert_eq!(text(&empty), "");
let owned = String::from("héllo");
assert_eq!(text(&s(&owned)), "héllo");
}
#[test]
fn zero_hashes_are_none() {
assert_eq!(hash(&b::lore_hash_t { data: [0; 32] }), None);
let mut data = [0; 32];
data[31] = 0xab;
assert_eq!(hash(&b::lore_hash_t { data }).unwrap(), format!("{}ab", "0".repeat(62)));
}
#[test]
fn a_missing_library_is_reported() {
let error = Lore::load(Path::new("/nonexistent/liblore")).err().unwrap();
assert!(error.contains("/nonexistent/liblore"), "{error}");
}
/// Runs against a real liblore when `LORE_FORGE_LIBLORE` names one.
#[test]
fn loads_the_pinned_library_when_present() {
let Some(path) = std::env::var_os("LORE_FORGE_LIBLORE") else { return };
let lore = Lore::load(Path::new(&path)).unwrap();
assert!(lore.version().starts_with(INTERFACE_VERSION));
let mut identities = 0;
let dir = tempfile_dir();
let globals = Globals { repository_path: dir.clone(), ..Globals::default() };
// A directory that is not a working copy fails cleanly rather than hanging.
let result = lore.repository_status(&globals, false, |_| identities += 1);
assert!(result.is_err(), "{result:?}");
let _ = std::fs::remove_dir_all(dir);
}
fn tempfile_dir() -> String {
let dir = std::env::temp_dir().join(format!("lore-sys-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir.to_string_lossy().into_owned()
}
}

View File

@ -15,7 +15,7 @@ use serde::Serialize;
use serde_json::Value; use serde_json::Value;
/// The protocol version this build speaks. /// The protocol version this build speaks.
pub const PROTOCOL_VERSION: u32 = 1; pub const PROTOCOL_VERSION: u32 = 2;
/// Overrides the directory holding the socket, configuration and log, for tests and for /// Overrides the directory holding the socket, configuration and log, for tests and for
/// running more than one service. /// running more than one service.
@ -24,7 +24,23 @@ pub const DIR_ENV: &str = "LORE_FORGE_DESKTOP_DIR";
pub mod methods { pub mod methods {
pub const HELLO: &str = "hello"; pub const HELLO: &str = "hello";
pub const STATUS: &str = "status"; pub const STATUS: &str = "status";
/// Re-reads a workspace's position and scans it for local changes.
pub const REFRESH: &str = "refresh";
/// Pulls the branch tip into a workspace, keeping local edits.
pub const SYNC_NOW: &str = "sync_now"; pub const SYNC_NOW: &str = "sync_now";
/// Stages the given files, commits them and pushes: [`SubmitParams`].
pub const SUBMIT: &str = "submit";
pub const CHANGES: &str = "changes";
pub const HISTORY: &str = "history";
pub const REVISION: &str = "revision";
pub const FILES: &str = "files";
pub const FILE_HISTORY: &str = "file_history";
/// Starts a sign-in to a remote; progress follows as [`super::events::LOGIN`].
pub const LOGIN: &str = "login";
pub const REPOSITORIES: &str = "repositories";
pub const WORKSPACE_ADD: &str = "workspace_add";
pub const WORKSPACE_CLONE: &str = "workspace_clone";
pub const WORKSPACE_REMOVE: &str = "workspace_remove";
pub const SHUTDOWN: &str = "shutdown"; pub const SHUTDOWN: &str = "shutdown";
} }
@ -33,6 +49,8 @@ pub mod events {
pub const ACTIVITY: &str = "activity"; pub const ACTIVITY: &str = "activity";
/// The workspace list changed: [`super::StatusResult`]'s `workspaces`. /// The workspace list changed: [`super::StatusResult`]'s `workspaces`.
pub const WORKSPACES: &str = "workspaces"; pub const WORKSPACES: &str = "workspaces";
/// A sign-in moved on: [`super::Login`].
pub const LOGIN: &str = "login";
} }
/// JSON-RPC error codes. The standard ones, then ours from -32000. /// JSON-RPC error codes. The standard ones, then ours from -32000.
@ -50,6 +68,10 @@ pub mod codes {
pub const NO_SUCH_WORKSPACE: i64 = -32002; pub const NO_SUCH_WORKSPACE: i64 = -32002;
/// The workspace is already doing something that conflicts. /// The workspace is already doing something that conflicts.
pub const BUSY: i64 = -32003; pub const BUSY: i64 = -32003;
/// liblore could not be loaded; the message says where the service looked.
pub const NO_LIBLORE: i64 = -32004;
/// liblore refused or failed the operation; the message is liblore's.
pub const LORE_ERROR: i64 = -32005;
} }
/// A request from a frontend. /// A request from a frontend.
@ -126,18 +148,66 @@ pub struct HelloResult {
pub struct StatusResult { pub struct StatusResult {
pub workspaces: Vec<Workspace>, pub workspaces: Vec<Workspace>,
pub uptime_s: u64, pub uptime_s: u64,
/// liblore's version, or why it could not be loaded.
pub liblore: Liblore,
/// The stored sign-ins.
pub accounts: Vec<Account>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Liblore {
Loaded { version: String },
Missing { error: String },
}
/// A stored sign-in: one per auth service.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
/// The auth service, such as `oidc+https://forge.example.com`.
pub auth_url: String,
pub user_id: String,
/// The user's name, when known.
pub name: String,
pub expires_ms: u64,
} }
/// A working copy the service looks after. /// A working copy the service looks after.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Workspace { pub struct Workspace {
/// Stable for the service's lifetime; frontends address the workspace by it. /// Derived from the path, so it stays the same across restarts.
pub id: String, pub id: String,
pub name: String, pub name: String,
pub path: String, pub path: String,
/// The repository's URL, `lore://host:port/owner/name`.
pub remote: String, pub remote: String,
pub state: WorkspaceState, pub state: WorkspaceState,
pub autosync: Autosync, pub autosync: Autosync,
/// The current branch's name; empty until read.
#[serde(default)]
pub branch: String,
/// The current revision's number and signature.
#[serde(default)]
pub revision: u64,
#[serde(default)]
pub signature: String,
/// Files changed in the working copy, at the last scan.
#[serde(default)]
pub changes: u64,
/// Local revisions the remote does not have.
#[serde(default)]
pub ahead: bool,
/// Remote revisions not synced here.
#[serde(default)]
pub behind: bool,
/// Whether the remote answered, and accepted our sign-in.
#[serde(default)]
pub online: bool,
#[serde(default)]
pub signed_in: bool,
/// The last failure, until the next success.
#[serde(default)]
pub error: String,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -146,6 +216,7 @@ pub enum WorkspaceState {
/// Not checked yet. /// Not checked yet.
Unknown, Unknown,
Idle, Idle,
/// Busy with a sync, submit or clone.
Syncing, Syncing,
Error, Error,
} }
@ -164,11 +235,198 @@ pub struct WorkspaceParams {
pub workspace: String, pub workspace: String,
} }
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SubmitParams {
pub workspace: String,
pub message: String,
/// Repository-relative paths to commit; other local changes stay local.
pub paths: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryParams {
pub workspace: String,
/// Revisions to read per branch, newest first. 0 means 50.
#[serde(default)]
pub limit: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RevisionParams {
pub workspace: String,
pub signature: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathParams {
pub workspace: String,
/// Repository-relative, `/`-separated; empty for the root.
#[serde(default)]
pub path: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RemoteParams {
/// A remote, `lore://host:port`, or a repository URL on it.
pub remote: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkspaceAddParams {
/// An existing working copy.
pub path: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkspaceCloneParams {
/// The repository's URL, `lore://host:port/owner/name`.
pub url: String,
/// The directory to clone into; created if missing, and must be empty.
pub path: String,
}
/// A local change, from `changes`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Change {
pub path: String,
pub action: ChangeAction,
/// The old path of a move or copy.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub from: String,
#[serde(default)]
pub staged: bool,
#[serde(default)]
pub conflict: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeAction {
Add,
Modify,
Delete,
Move,
Copy,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChangesResult {
pub changes: Vec<Change>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Branch {
pub id: String,
pub name: String,
/// The tip's signature; empty for a branch with no revisions.
pub head: String,
pub current: bool,
/// Known only on the remote.
#[serde(default)]
pub remote_only: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revision {
pub signature: String,
pub number: u64,
/// First parent first.
pub parents: Vec<String>,
/// The id of the branch it was committed on.
pub branch: String,
pub message: String,
/// The creator's name, or their user id when the name is unknown.
pub author: String,
pub timestamp_ms: u64,
}
/// `history`: every branch, and their revisions in one list, newest first with every child
/// before its parents, as the graph's lane layout needs.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryResult {
pub branches: Vec<Branch>,
pub revisions: Vec<Revision>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RevisionResult {
pub revision: Revision,
pub changes: Vec<Change>,
}
/// One entry of a directory listing: the working copy on disk, with local state and locks.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileEntry {
pub name: String,
pub path: String,
pub dir: bool,
pub size: u64,
/// The local change, if any. A deleted file is listed though it is not on disk.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub change: Option<ChangeAction>,
/// Who holds a lock on it: a name, or empty.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub lock: String,
/// Whether the lock is the signed-in user's.
#[serde(default)]
pub lock_mine: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FilesResult {
pub path: String,
/// Directories first, then by name.
pub entries: Vec<FileEntry>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileHistoryResult {
pub path: String,
pub revisions: Vec<Revision>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Repository {
pub id: String,
/// `owner/name`.
pub name: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepositoriesResult {
pub remote: String,
pub repositories: Vec<Repository>,
}
/// A sign-in's progress.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Login {
pub remote: String,
pub phase: LoginPhase,
/// Where to approve it, and the code to enter or confirm there.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub url: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub code: String,
/// The signed-in user's name, once done; the failure, once failed.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub message: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoginPhase {
/// Waiting for the user to approve at `url`.
Waiting,
Done,
Failed,
}
/// Progress of one piece of work. /// Progress of one piece of work.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Activity { pub struct Activity {
pub workspace: String, pub workspace: String,
/// What is being done, such as `sync`. /// What is being done: `sync`, `submit` or `clone`.
pub kind: String, pub kind: String,
pub phase: Phase, pub phase: Phase,
/// 0 to 1 while running, when known. /// 0 to 1 while running, when known.
@ -286,6 +544,16 @@ mod tests {
assert_eq!(serde_json::to_string(&WorkspaceState::Syncing).unwrap(), r#""syncing""#); assert_eq!(serde_json::to_string(&WorkspaceState::Syncing).unwrap(), r#""syncing""#);
} }
#[test]
fn workspaces_without_lore_fields_still_parse() {
let workspace: Workspace = serde_json::from_value(serde_json::json!({
"id": "w", "name": "n", "path": "/p", "remote": "", "state": "idle", "autosync": "off"
}))
.unwrap();
assert_eq!(workspace.branch, "");
assert!(!workspace.signed_in);
}
#[test] #[test]
fn fnv1a_matches_reference() { fn fnv1a_matches_reference() {
// Reference values for FNV-1a 64. // Reference values for FNV-1a 64.

View File

@ -9,6 +9,7 @@ publish.workspace = true
[dependencies] [dependencies]
forge-protocol.workspace = true forge-protocol.workspace = true
lore-sys.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
tokio.workspace = true tokio.workspace = true

View File

@ -1,10 +1,11 @@
//! `desktop.toml`: the workspaces the service looks after. //! `desktop.toml`: the workspaces the service looks after. The service writes it when a
//! frontend adds or removes a workspace; hand edits made while it runs are overwritten then.
//! //!
//! ```toml //! ```toml
//! [[workspace]] //! [[workspace]]
//! name = "my-game" //! name = "my-game"
//! path = "/Users/me/lore/my-game" //! path = "/Users/me/lore/my-game"
//! remote = "lore://localhost:41337/me/my-game" //! remote = "lore://localhost:41337/me/my-game" # read from the working copy when empty
//! autosync = "off" # off, interval or on_change //! autosync = "off" # off, interval or on_change
//! ``` //! ```
@ -12,20 +13,21 @@ use std::path::Path;
use forge_protocol::Autosync; use forge_protocol::Autosync;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct Config { pub struct Config {
#[serde(default, rename = "workspace")] #[serde(default, rename = "workspace")]
pub workspaces: Vec<WorkspaceConfig>, pub workspaces: Vec<WorkspaceConfig>,
} }
#[derive(Debug, Deserialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct WorkspaceConfig { pub struct WorkspaceConfig {
pub name: String, pub name: String,
pub path: String, pub path: String,
#[serde(default)] #[serde(default, skip_serializing_if = "String::is_empty")]
pub remote: String, pub remote: String,
#[serde(default)] #[serde(default)]
pub autosync: Autosync, pub autosync: Autosync,
@ -40,6 +42,20 @@ impl Config {
Err(error) => Err(format!("{}: {error}", path.display())), Err(error) => Err(format!("{}: {error}", path.display())),
} }
} }
/// Writes `path` through a temporary file, so a crash leaves the old file or the new one.
pub fn save(&self, path: &Path) -> Result<(), String> {
let text = toml::to_string(self).map_err(|error| error.to_string())?;
let temporary = path.with_extension("toml.tmp");
let write = || -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&temporary, text.as_bytes())?;
std::fs::rename(&temporary, path)
};
write().map_err(|error| format!("{}: {error}", path.display()))
}
} }
#[cfg(test)] #[cfg(test)]
@ -78,4 +94,22 @@ mod tests {
fn unknown_keys_are_refused() { fn unknown_keys_are_refused() {
assert!(toml::from_str::<Config>("[[workspace]]\nname='a'\npath='/a'\ncolour='red'").is_err()); assert!(toml::from_str::<Config>("[[workspace]]\nname='a'\npath='/a'\ncolour='red'").is_err());
} }
#[test]
fn saves_and_reloads() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub/desktop.toml");
let config = Config {
workspaces: vec![WorkspaceConfig {
name: "game".into(),
path: "/w/game".into(),
remote: String::new(),
autosync: Autosync::Off,
}],
};
config.save(&path).unwrap();
let loaded = Config::load(&path).unwrap();
assert_eq!(loaded.workspaces[0].path, "/w/game");
assert!(!std::fs::read_to_string(&path).unwrap().contains("remote"));
}
} }

397
desktop/service/src/lore.rs Normal file
View File

@ -0,0 +1,397 @@
//! The service's Lore work: liblore calls run on blocking threads, and their events become
//! protocol values. The pure parts (ordering history, merging a listing with local state) are
//! here too, so they are tested without liblore.
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use forge_protocol::Branch;
use forge_protocol::Change;
use forge_protocol::ChangeAction;
use forge_protocol::FileEntry;
use forge_protocol::Revision;
use lore_sys::Action;
use lore_sys::Event;
use lore_sys::Globals;
use lore_sys::Lore;
use lore_sys::StatusFile;
use lore_sys::Value;
/// Where to find liblore: `LORE_FORGE_LIBLORE`, else beside this executable.
pub const LIBLORE_ENV: &str = "LORE_FORGE_LIBLORE";
pub fn locate() -> PathBuf {
if let Some(path) = std::env::var_os(LIBLORE_ENV).filter(|path| !path.is_empty()) {
return PathBuf::from(path);
}
let dir = std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf)).unwrap_or_default();
dir.join(lore_sys::LIBRARY_FILE)
}
pub fn load() -> Result<Arc<Lore>, String> {
Lore::load(&locate()).map(Arc::new)
}
pub fn globals(path: &str) -> Globals {
Globals { repository_path: path.to_owned(), ..Globals::default() }
}
/// What `repository_status` reported.
#[derive(Debug, Default)]
pub struct Position {
pub status: lore_sys::Status,
pub files: Vec<StatusFile>,
}
pub fn status(lore: &Lore, path: &str, scan: bool) -> Result<Position, lore_sys::Error> {
let mut position = Position::default();
lore.repository_status(&globals(path), scan, |event| match event {
Event::Status(status) => position.status = status,
Event::StatusFile(file) => position.files.push(file),
_ => {}
})?;
Ok(position)
}
pub fn remote_url(lore: &Lore, path: &str) -> Result<String, lore_sys::Error> {
let mut url = String::new();
lore.repository_config_get(&globals(path), "remote_url", |event| {
if let Event::Config { value, .. } = event {
url = value;
}
})?;
Ok(url)
}
/// The local changes in a status report: files only, as the commit list shows them.
pub fn changes(files: &[StatusFile]) -> Vec<Change> {
let mut changes: Vec<Change> = files
.iter()
.filter(|file| file.kind != lore_sys::NodeKind::Directory)
.filter_map(|file| {
let action = change_action(file.action, file.dirty || file.staged)?;
Some(Change {
path: file.path.clone(),
action,
from: file.from.clone(),
staged: file.staged,
conflict: file.conflict_unresolved,
})
})
.collect();
changes.sort_by(|a, b| a.path.cmp(&b.path));
changes.dedup_by(|a, b| a.path == b.path);
changes
}
/// liblore reports a modification as "keep" with a changed flag.
pub fn change_action(action: Action, changed: bool) -> Option<ChangeAction> {
match action {
Action::Add => Some(ChangeAction::Add),
Action::Delete => Some(ChangeAction::Delete),
Action::Move => Some(ChangeAction::Move),
Action::Copy => Some(ChangeAction::Copy),
Action::Keep if changed => Some(ChangeAction::Modify),
Action::Keep => None,
}
}
/// The repository's base, `lore://host:port`, from a repository URL.
pub fn remote_base(url: &str) -> String {
let Some((scheme, rest)) = url.split_once("://") else { return url.to_owned() };
let host = rest.split('/').next().unwrap_or(rest);
format!("{scheme}://{host}")
}
/// Branches as `branch_list` reports them, once each: the local copy where there is one.
pub fn branches(events: Vec<Event>) -> Vec<Branch> {
let mut out: Vec<Branch> = Vec::new();
for event in events {
let Event::Branch { id, name, latest, remote, current, archived } = event else { continue };
if archived {
continue;
}
let branch = Branch { id: id.clone(), name, head: latest.unwrap_or_default(), current, remote_only: remote };
match out.iter_mut().find(|known| known.id == id) {
Some(known) if known.remote_only && !remote => *known = branch,
Some(_) => {}
None => out.push(branch),
}
}
// The current branch first, then by name.
out.sort_by(|a, b| b.current.cmp(&a.current).then_with(|| a.name.cmp(&b.name)));
out
}
/// Collects revisions from a history or file-history stream: each entry is followed by its
/// metadata.
#[derive(Default)]
pub struct RevisionCollector {
pub revisions: Vec<Revision>,
/// The file-history action of each revision, alongside `revisions`.
pub actions: Vec<Action>,
}
impl RevisionCollector {
pub fn push(&mut self, event: Event) {
match event {
Event::HistoryEntry { signature, number, parents } | Event::RevisionInfo { signature, number, parents } => {
self.start(signature, number, parents, Action::Keep);
}
Event::FileHistory { signature, number, action, .. } => {
self.start(signature, number, Vec::new(), action);
}
Event::Metadata { key, value } => {
let Some(revision) = self.revisions.last_mut() else { return };
match (key.as_str(), value) {
("message", Value::Text(text)) => revision.message = text,
("created-by", Value::Text(text)) => revision.author = text,
("timestamp", Value::Number(ms)) => revision.timestamp_ms = ms,
("branch", Value::Hex(id)) => revision.branch = id,
_ => {}
}
}
_ => {}
}
}
fn start(&mut self, signature: String, number: u64, parents: Vec<String>, action: Action) {
self.revisions.push(Revision {
signature,
number,
parents,
branch: String::new(),
message: String::new(),
author: String::new(),
timestamp_ms: 0,
});
self.actions.push(action);
}
}
/// Orders revisions newest first with every child before its parents: of the revisions whose
/// children are all placed, the newest goes next. Duplicates are dropped.
pub fn newest_first(revisions: Vec<Revision>) -> Vec<Revision> {
let mut by_signature: HashMap<String, Revision> = HashMap::new();
for revision in revisions {
by_signature.entry(revision.signature.clone()).or_insert(revision);
}
let mut children: HashMap<&str, usize> = HashMap::new();
for revision in by_signature.values() {
for parent in &revision.parents {
if by_signature.contains_key(parent) {
*children.entry(parent.as_str()).or_default() += 1;
}
}
}
let mut ready: BinaryHeap<(u64, u64, &str)> = by_signature
.values()
.filter(|revision| !children.contains_key(revision.signature.as_str()))
.map(|revision| (revision.timestamp_ms, revision.number, revision.signature.as_str()))
.collect();
let mut order: Vec<String> = Vec::with_capacity(by_signature.len());
while let Some((_, _, signature)) = ready.pop() {
order.push(signature.to_owned());
for parent in &by_signature[signature].parents {
if let Some(count) = children.get_mut(parent.as_str()) {
*count -= 1;
if *count == 0 {
let parent = &by_signature[parent.as_str()];
ready.push((parent.timestamp_ms, parent.number, parent.signature.as_str()));
}
}
}
}
order.into_iter().filter_map(|signature| by_signature.remove(&signature)).collect()
}
/// A directory of the working copy as the explorer lists it: what is on disk, the local change
/// of each entry (deleted files included, though they are gone), and locks.
pub fn list_directory(
root: &Path,
dir: &str,
changes: &[Change],
locks: &HashMap<String, (String, bool)>,
) -> std::io::Result<Vec<FileEntry>> {
let full = if dir.is_empty() { root.to_path_buf() } else { root.join(dir) };
let join = |name: &str| if dir.is_empty() { name.to_owned() } else { format!("{dir}/{name}") };
let mut entries = Vec::new();
for item in std::fs::read_dir(&full)? {
let item = item?;
let name = item.file_name().to_string_lossy().into_owned();
// The working copy's own state.
if dir.is_empty() && (name == ".lore" || name == ".urc") {
continue;
}
let meta = item.metadata()?;
let path = join(&name);
let change = changes.iter().find(|change| change.path == path).map(|change| change.action);
let (lock, lock_mine) = locks.get(&path).cloned().unwrap_or_default();
entries.push(FileEntry {
name,
path,
dir: meta.is_dir(),
size: if meta.is_dir() { 0 } else { meta.len() },
change,
lock,
lock_mine,
});
}
// Files deleted locally are gone from disk but still part of the listing.
for change in changes.iter().filter(|change| change.action == ChangeAction::Delete) {
let parent = change.path.rsplit_once('/').map(|(parent, _)| parent).unwrap_or("");
if parent == dir && !entries.iter().any(|entry| entry.path == change.path) {
let name = change.path.rsplit('/').next().unwrap_or(&change.path).to_owned();
entries.push(FileEntry {
name,
path: change.path.clone(),
dir: false,
size: 0,
change: Some(ChangeAction::Delete),
lock: String::new(),
lock_mine: false,
});
}
}
// A directory holding changes is marked modified, so they can be found from the root.
for entry in entries.iter_mut().filter(|entry| entry.dir && entry.change.is_none()) {
let prefix = format!("{}/", entry.path);
if changes.iter().any(|change| change.path.starts_with(&prefix)) {
entry.change = Some(ChangeAction::Modify);
}
}
entries.sort_by(|a, b| b.dir.cmp(&a.dir).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
Ok(entries)
}
/// A user-facing message for a liblore failure.
pub fn describe(operation: &str, error: &lore_sys::Error) -> String {
match error.code {
// "Local modifications prevent synchronization".
44 => format!("{operation}: local edits to files changed on the remote; submit or revert them first"),
40 => format!("{operation}: nothing to commit"),
_ => format!("{operation}: {error}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn revision(signature: &str, number: u64, timestamp_ms: u64, parents: &[&str]) -> Revision {
Revision {
signature: signature.into(),
number,
parents: parents.iter().map(|p| p.to_string()).collect(),
branch: String::new(),
message: String::new(),
author: String::new(),
timestamp_ms,
}
}
#[test]
fn history_is_newest_first_with_children_before_parents() {
// main: r1 - r2 - r4(merge of r2 and f3); feature: f3 off r2, committed before r2's
// child r4 but after... and a stale clock on f3 must not put it below its parent.
let ordered = newest_first(vec![
revision("r1", 1, 10, &[]),
revision("r2", 2, 20, &["r1"]),
revision("f3", 3, 5, &["r2"]),
revision("r4", 4, 40, &["r2", "f3"]),
revision("r2", 2, 20, &["r1"]),
]);
let order: Vec<&str> = ordered.iter().map(|r| r.signature.as_str()).collect();
assert_eq!(order, ["r4", "f3", "r2", "r1"]);
}
#[test]
fn metadata_fills_the_revision_before_it() {
let mut collector = RevisionCollector::default();
collector.push(Event::HistoryEntry { signature: "a".into(), number: 2, parents: vec!["b".into()] });
collector.push(Event::Metadata { key: "message".into(), value: Value::Text("Fix".into()) });
collector.push(Event::Metadata { key: "created-by".into(), value: Value::Text("u1".into()) });
collector.push(Event::Metadata { key: "timestamp".into(), value: Value::Number(7) });
collector.push(Event::Metadata { key: "branch".into(), value: Value::Hex("br".into()) });
collector.push(Event::HistoryEntry { signature: "b".into(), number: 1, parents: vec![] });
assert_eq!(collector.revisions.len(), 2);
let first = &collector.revisions[0];
assert_eq!((first.message.as_str(), first.author.as_str(), first.timestamp_ms), ("Fix", "u1", 7));
assert_eq!(first.branch, "br");
assert_eq!(collector.revisions[1].message, "");
}
#[test]
fn a_modification_is_keep_with_a_flag() {
assert_eq!(change_action(Action::Keep, true), Some(ChangeAction::Modify));
assert_eq!(change_action(Action::Keep, false), None);
assert_eq!(change_action(Action::Delete, true), Some(ChangeAction::Delete));
}
#[test]
fn branches_prefer_the_local_copy() {
let branch = |id: &str, name: &str, latest: &str, remote, current| Event::Branch {
id: id.into(),
name: name.into(),
latest: Some(latest.into()),
remote,
current,
archived: false,
};
let list = branches(vec![
branch("2", "feature", "f-remote", true, false),
branch("1", "main", "m-local", false, true),
branch("2", "feature", "f-local", false, false),
branch("1", "main", "m-remote", true, false),
branch("3", "other", "o", true, false),
]);
let names: Vec<(&str, &str, bool)> =
list.iter().map(|b| (b.name.as_str(), b.head.as_str(), b.remote_only)).collect();
assert_eq!(names, [("main", "m-local", false), ("feature", "f-local", false), ("other", "o", true)]);
}
#[test]
fn remote_base_drops_the_repository() {
assert_eq!(remote_base("lore://host:41337/alice/demo"), "lore://host:41337");
assert_eq!(remote_base("lore://host:41337"), "lore://host:41337");
}
#[test]
fn listings_merge_disk_changes_and_locks() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join(".lore")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("a.txt"), "one").unwrap();
std::fs::write(root.join("src/b.rs"), "two").unwrap();
let change = |path: &str, action| Change {
path: path.into(),
action,
from: String::new(),
staged: false,
conflict: false,
};
let changes = vec![change("a.txt", ChangeAction::Modify), change("gone.txt", ChangeAction::Delete), change("src/b.rs", ChangeAction::Add)];
let locks = HashMap::from([("a.txt".to_owned(), ("bob".to_owned(), false))]);
let top = list_directory(root, "", &changes, &locks).unwrap();
let summary: Vec<(&str, bool, Option<ChangeAction>, &str)> =
top.iter().map(|e| (e.name.as_str(), e.dir, e.change, e.lock.as_str())).collect();
assert_eq!(
summary,
[
("src", true, Some(ChangeAction::Modify), ""),
("a.txt", false, Some(ChangeAction::Modify), "bob"),
("gone.txt", false, Some(ChangeAction::Delete), ""),
]
);
assert_eq!(top[1].size, 3);
let sub = list_directory(root, "src", &changes, &locks).unwrap();
assert_eq!(sub[0].path, "src/b.rs");
assert_eq!(sub[0].change, Some(ChangeAction::Add));
}
}

View File

@ -2,9 +2,11 @@
//! //!
//! It listens on a local socket private to the user (see `forge_protocol::Paths`) and exits //! 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 //! quietly when another service already holds it, so frontends may start it whenever they
//! cannot connect. //! cannot connect. Lore work goes through liblore, loaded at start from `LORE_FORGE_LIBLORE` or
//! from beside this executable; without it the service still runs and says why.
mod config; mod config;
mod lore;
mod server; mod server;
use std::path::PathBuf; use std::path::PathBuf;
@ -43,9 +45,19 @@ fn main() -> ExitCode {
return ExitCode::FAILURE; return ExitCode::FAILURE;
} }
}; };
let liblore = lore::load();
match &liblore {
Ok(lore) => tracing::info!(version = lore.version(), "liblore loaded"),
Err(error) => tracing::warn!("liblore not loaded: {error}"),
}
let runtime = tokio::runtime::Runtime::new().expect("a tokio runtime"); let runtime = tokio::runtime::Runtime::new().expect("a tokio runtime");
let service = Service::new(config, Duration::from_millis(600)); let service = Service::new(config, paths.config_file(), liblore);
match runtime.block_on(listen::run(service, &paths)) { // The service starts its Lore work once it holds the socket, not in a copy about to exit.
let result = runtime.block_on(listen::run(Arc::clone(&service), &paths));
// Let liblore calls in flight finish, then drop the library, which flushes its stores.
runtime.shutdown_timeout(Duration::from_secs(10));
drop(service);
match result {
Ok(()) => ExitCode::SUCCESS, Ok(()) => ExitCode::SUCCESS,
Err(listen::Error::AlreadyRunning) => { Err(listen::Error::AlreadyRunning) => {
tracing::info!("another service is already running"); tracing::info!("another service is already running");
@ -140,6 +152,7 @@ mod listen {
let listener = UnixListener::bind(&socket)?; let listener = UnixListener::bind(&socket)?;
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?; std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
tracing::info!(socket = %socket.display(), pid = std::process::id(), "forge-service is listening"); tracing::info!(socket = %socket.display(), pid = std::process::id(), "forge-service is listening");
service.start();
let result = loop { let result = loop {
tokio::select! { tokio::select! {
@ -172,6 +185,7 @@ mod listen {
Err(error) => return Err(Error::Io(error)), Err(error) => return Err(Error::Io(error)),
}; };
tracing::info!(pipe = %name, pid = std::process::id(), "forge-service is listening"); tracing::info!(pipe = %name, pid = std::process::id(), "forge-service is listening");
service.start();
let result = loop { let result = loop {
tokio::select! { tokio::select! {
connected = server.connect() => { connected = server.connect() => {

File diff suppressed because it is too large Load Diff

View File

@ -10,3 +10,8 @@ sha256 loreserver-v0.14.0-aarch64-apple-darwin.tar.gz 38192a71c9341b4d2ab5891713
sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu-neoverse-512tvb.tar.gz a25fba6be87529e6448180fec9d9af5b254d9ecadf4160f59ec7aad30801b077 sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu-neoverse-512tvb.tar.gz a25fba6be87529e6448180fec9d9af5b254d9ecadf4160f59ec7aad30801b077
sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu.tar.gz 1e05734bc99af913bf3643cce64dec97258adb6f892aae97b0f85df1ec15719a sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu.tar.gz 1e05734bc99af913bf3643cce64dec97258adb6f892aae97b0f85df1ec15719a
sha256 loreserver-v0.14.0-x86_64-unknown-linux-gnu.tar.gz 900c0b508d2bb8856d9de1824c457b10bd3b33c1e0927fdecd9ed8511446cf81 sha256 loreserver-v0.14.0-x86_64-unknown-linux-gnu.tar.gz 900c0b508d2bb8856d9de1824c457b10bd3b33c1e0927fdecd9ed8511446cf81
sha256 liblore-v0.14.0-aarch64-apple-darwin.tar.gz 0233553f87af407523f8c0ce4a1191aade21a9733302d93611b4fad4a200d752
sha256 liblore-v0.14.0-aarch64-unknown-linux-gnu-neoverse-512tvb.tar.gz ae64513fc31fb39145013034ba9c43e54e1cff474c9171c8828cb0bf460e727c
sha256 liblore-v0.14.0-aarch64-unknown-linux-gnu.tar.gz 3e0a531aa60ec608e5066c3954991d88c432809b4d24cdf89d3ee6586ba2cd27
sha256 liblore-v0.14.0-x86_64-pc-windows-msvc.zip e5a1bccd59dd8b4a5cc898f3a0e1e381a4b48f0c087df1d26f29361a76f95768
sha256 liblore-v0.14.0-x86_64-unknown-linux-gnu.tar.gz 9cdbd569f1ae55ef08824f563daea374394fd4ef18f7aa0cb330c4dcf488006d

227
scripts/desktop-e2e.py Normal file
View File

@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""Drives forge-service over its socket as the desktop GUI would, against a real loreserver
and lore-forge. Run by scripts/e2e-lore.sh, which starts everything and passes:
desktop-e2e.py SOCKET FORGE_URL COOKIE_JAR LORE_REMOTE WORK_DIR
Signs in through the device flow (approving it as the cookie jar's user), lists and clones
alice/demo, reads files, history and a revision, submits some of the local changes, then adds
the CLI's working copy and syncs it. Exits nonzero with a message on the first failure.
"""
import json
import os
import socket
import sys
import time
import urllib.parse
import urllib.request
TIMEOUT_S = 60
def fail(message):
print(f"FAIL: {message}", file=sys.stderr)
sys.exit(1)
class Service:
def __init__(self, path):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
self.sock.settimeout(TIMEOUT_S)
self.buffer = b""
self.next_id = 0
self.notifications = []
self.responses = {}
def _read(self):
while b"\n" not in self.buffer:
chunk = self.sock.recv(65536)
if not chunk:
fail("the service closed the connection")
self.buffer += chunk
line, self.buffer = self.buffer.split(b"\n", 1)
message = json.loads(line)
if "method" in message:
self.notifications.append(message)
else:
self.responses[message["id"]] = message
def send(self, method, params=None):
self.next_id += 1
line = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}}
self.sock.sendall(json.dumps(line).encode() + b"\n")
return self.next_id
def response(self, id):
while id not in self.responses:
self._read()
return self.responses.pop(id)
def call(self, method, params=None):
answer = self.response(self.send(method, params))
if "error" in answer:
fail(f"{method}: {answer['error']['message']}")
return answer["result"]
def wait(self, method, match):
"""The first notification `method` whose params satisfy `match`, dropping those before."""
deadline = time.monotonic() + TIMEOUT_S
while time.monotonic() < deadline:
while self.notifications:
note = self.notifications.pop(0)
if note["method"] == method and match(note["params"]):
return note["params"]
self._read()
fail(f"no {method} notification in {TIMEOUT_S}s")
def finished(self, workspace, kind):
params = self.wait(
"activity",
lambda p: p["workspace"] == workspace and p["kind"] == kind and p["phase"] in ("finished", "failed"),
)
if params["phase"] == "failed":
fail(f"{kind} failed: {params.get('message', '')}")
return params
def approve(forge, jar, code):
"""Approves a device code on the forge as the user whose session cookie is in `jar`."""
cookies = {}
with open(jar) as f:
for line in f:
line = line.strip()
if line.startswith("#HttpOnly_"):
line = line[len("#HttpOnly_"):]
elif not line or line.startswith("#"):
continue
fields = line.split("\t")
if len(fields) == 7:
cookies[fields[5]] = fields[6]
header = "; ".join(f"{k}={v}" for k, v in cookies.items())
body = urllib.parse.urlencode({"csrf": cookies["lf_csrf"], "user_code": code, "decision": "approve"}).encode()
request = urllib.request.Request(
f"{forge}/device", data=body, headers={"Cookie": header, "Origin": forge}, method="POST"
)
with urllib.request.urlopen(request, timeout=TIMEOUT_S) as answer:
if "Client signed in" not in answer.read().decode():
fail("the forge did not approve the desktop sign-in")
def main():
sock_path, forge, jar, remote, work = sys.argv[1:6]
service = Service(sock_path)
step = lambda text: print(f" {text}")
hello = service.call("hello", {"protocol": 2, "client": "desktop-e2e"})
step(f"hello: {hello['service']}")
status = service.call("status")
if "loaded" not in status["liblore"]:
fail(f"liblore did not load: {status['liblore']}")
step(f"liblore {status['liblore']['loaded']['version']}")
# Sign in: the service starts liblore's device flow and says which code to approve.
service.call("login", {"remote": remote})
waiting = service.wait("login", lambda p: p["phase"] in ("waiting", "failed") and (p.get("code") or p["phase"] == "failed"))
if waiting["phase"] == "failed":
fail(f"sign-in failed: {waiting.get('message')}")
step(f"user code {waiting['code']}")
approve(forge, jar, waiting["code"])
done = service.wait("login", lambda p: p["phase"] in ("done", "failed"))
if done["phase"] != "done" or done.get("message") != "alice":
fail(f"sign-in ended {done}")
accounts = service.call("status")["accounts"]
if not any(a.get("name") == "alice" for a in accounts):
fail(f"status does not list alice's account: {accounts}")
step("signed in as alice")
names = [r["name"] for r in service.call("repositories", {"remote": remote})["repositories"]]
if "alice/demo" not in names:
fail(f"repositories lacks alice/demo: {names}")
step(f"repositories {names}")
# Clone, then read it back as the explorer does.
into = os.path.join(work, "desktop-clone")
ws = service.call("workspace_clone", {"url": f"{remote}/alice/demo", "path": into})["id"]
service.finished(ws, "clone")
with open(os.path.join(into, "a.txt")) as f:
if f.read().strip() != "two":
fail("the clone's a.txt is not the latest")
root = service.call("files", {"workspace": ws, "path": ""})["entries"]
listed = {(e["name"], e["dir"]) for e in root}
for want in [("sub", True), ("a.txt", False), ("c.txt", False), ("d.txt", False)]:
if want not in listed:
fail(f"files lacks {want}: {sorted(listed)}")
if root[0]["name"] != "sub":
fail("files does not list directories first")
history = service.call("history", {"workspace": ws})
branches = {b["name"] for b in history["branches"]}
if not {"main", "feature"} <= branches:
fail(f"history lacks a branch: {branches}")
messages = [r["message"] for r in history["revisions"]]
for want in ["First revision", "Second revision", "Feature work", "Main moves on"]:
if want not in messages:
fail(f"history lacks {want!r}: {messages}")
if any(r["author"] != "alice" for r in history["revisions"] if r["message"]):
fail("history does not name alice as the author")
merge = history["revisions"][0]
if len(merge["parents"]) != 2:
fail(f"the newest revision is not the merge: {merge}")
second = next(r for r in history["revisions"] if r["message"] == "Second revision")
changed = {(c["path"], c["action"]) for c in service.call("revision", {"workspace": ws, "signature": second["signature"]})["changes"]}
if changed != {("a.txt", "modify"), ("sub/b.txt", "add")}:
fail(f"the second revision's changes are {changed}")
file_history = [r["message"] for r in service.call("file_history", {"workspace": ws, "path": "a.txt"})["revisions"]]
if file_history[:2] != ["Second revision", "First revision"]:
fail(f"a.txt's history is {file_history}")
step(f"clone reads back: {len(messages)} revisions, branches {sorted(branches)}")
# Local changes, and a submit of some of them.
with open(os.path.join(into, "a.txt"), "w") as f:
f.write("five\n")
for name in ("e.txt", "kept.txt"):
with open(os.path.join(into, name), "w") as f:
f.write(name + "\n")
service.call("refresh", {"workspace": ws})
changes = {(c["path"], c["action"]) for c in service.call("changes", {"workspace": ws})["changes"]}
if changes != {("a.txt", "modify"), ("e.txt", "add"), ("kept.txt", "add")}:
fail(f"changes are {changes}")
service.call("submit", {"workspace": ws, "message": "From the desktop", "paths": ["a.txt", "e.txt"]})
service.finished(ws, "submit")
left = [c["path"] for c in service.call("changes", {"workspace": ws})["changes"]]
if left != ["kept.txt"]:
fail(f"after submit the changes are {left}")
newest = service.call("history", {"workspace": ws})["revisions"][0]
if newest["message"] != "From the desktop" or newest["author"] != "alice":
fail(f"the newest revision is {newest}")
step(f"submitted r{newest['number']}, kept.txt left out")
# The CLI's working copy, added and synced: it gets the desktop's revision.
cli = os.path.join(work, "alice-work")
with open(os.path.join(cli, "local.txt"), "w") as f:
f.write("local\n")
cli_ws = service.call("workspace_add", {"path": cli})["id"]
service.call("sync_now", {"workspace": cli_ws})
service.finished(cli_ws, "sync")
with open(os.path.join(cli, "a.txt")) as f:
if f.read().strip() != "five":
fail("sync did not bring a.txt from the desktop's submit")
if not os.path.exists(os.path.join(cli, "e.txt")) or os.path.exists(os.path.join(cli, "kept.txt")):
fail("sync did not bring exactly the submitted files")
synced = [c["path"] for c in service.call("changes", {"workspace": cli_ws})["changes"]]
if synced != ["local.txt"]:
fail(f"sync lost or invented local changes: {synced}")
status = service.call("status")
ws_state = {w["id"]: w for w in status["workspaces"]}
if ws_state[cli_ws]["revision"] != newest["number"]:
fail(f"the synced workspace is at r{ws_state[cli_ws]['revision']}, not r{newest['number']}")
step(f"working copy synced to r{newest['number']}, local.txt kept")
service.call("workspace_remove", {"workspace": cli_ws})
service.call("shutdown")
if __name__ == "__main__":
main()

View File

@ -17,11 +17,17 @@
# LORE_PORT+2, so the test can run beside a deployment started by scripts/start.sh; FORGE_PORT # LORE_PORT+2, so the test can run beside a deployment started by scripts/start.sh; FORGE_PORT
# does the same for lore-forge. # does the same for lore-forge.
# #
# Then it runs the desktop client's forge-service, linked to the pinned liblore, through
# scripts/desktop-e2e.py: sign-in, clone, the explorer's reads, submit and sync. NO_DESKTOP=1
# skips that.
#
# HOLD=1 keeps both servers running after the browser checks, for a look at the pages. # HOLD=1 keeps both servers running after the browser checks, for a look at the pages.
# #
# SMOKE=1 stops after one user's login, create and push. On macOS the lore CLI keeps its token # SMOKE=1 stops after one user's login, create and push.
# store key in the keychain and every lore process asks for it, so a smoke run is the place to #
# answer "Always Allow" once. # Every login goes to a token store of its own (LORE_AUTH_PATH) whose key is kept in a file
# beside it (LORE_AUTH_STORE=fallback), so no run touches the user's own logins or asks the
# macOS keychain for anything.
set -euo pipefail set -euo pipefail
@ -35,6 +41,7 @@ LORE_PORT="${LORE_PORT:-41337}"
LORE_REMOTE="lore://localhost:$LORE_PORT" LORE_REMOTE="lore://localhost:$LORE_PORT"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/lore-forge-e2e.XXXXXX")" WORK="$(mktemp -d "${TMPDIR:-/tmp}/lore-forge-e2e.XXXXXX")"
PIDS=() PIDS=()
export LORE_AUTH_STORE=fallback
cleanup() { cleanup() {
local status=$? local status=$?
@ -326,8 +333,32 @@ for path in /alice/demo /alice/demo/graph "$SECOND"; do
[ "$status" = 404 ] || fail "bob got $status for $path" [ "$status" = 404 ] || fail "bob got $status for $path"
done done
if [ -z "${NO_DESKTOP:-}" ]; then
step "desktop: forge-service signs in, clones, submits and syncs through liblore"
cargo build --quiet --manifest-path "$ROOT/desktop/Cargo.toml" -p forge-service
LIBLORE_DIR="$("$ROOT/scripts/fetch-lore.sh" --liblore)"
case "$(uname -s)" in Darwin) LIBLORE_FILE=liblore.dylib ;; *) LIBLORE_FILE=liblore.so ;; esac
mkdir -p "$WORK/desktop"
(
export LORE_FORGE_DESKTOP_DIR="$WORK/desktop"
export LORE_FORGE_LIBLORE="$LIBLORE_DIR/$LIBLORE_FILE"
export LORE_AUTH_PATH="$WORK/auth-desktop"
exec "$ROOT/desktop/target/debug/forge-service"
) >"$WORK/desktop/stdout.log" 2>&1 &
DESKTOP_PID=$!
PIDS+=("$DESKTOP_PID")
for _ in $(seq 1 100); do
[ -S "$WORK/desktop/service.sock" ] && break
kill -0 "$DESKTOP_PID" 2>/dev/null || { cat "$WORK/desktop/stdout.log" >&2; fail "forge-service exited"; }
sleep 0.2
done
python3 -I "$ROOT/scripts/desktop-e2e.py" "$WORK/desktop/service.sock" "$FORGE" "$JAR" "$LORE_REMOTE" "$WORK" \
|| { tail -20 "$WORK/desktop/service.log" >&2; fail "the desktop service checks failed"; }
wait "$DESKTOP_PID" || fail "forge-service did not stop cleanly"
fi
if [ -n "${HOLD:-}" ]; then if [ -n "${HOLD:-}" ]; then
echo "holding both servers for a look: $FORGE (alice / alice password); Ctrl-C ends" echo "holding both servers for a look: $FORGE (alice / alice password), state in $WORK; Ctrl-C ends"
wait "$LORE_PID" wait "$LORE_PID"
fi fi

View File

@ -2,6 +2,10 @@
# Fetches the pinned Lore release (`lore` and `loreserver`) into .lore/<version>/. # Fetches the pinned Lore release (`lore` and `loreserver`) into .lore/<version>/.
# #
# scripts/fetch-lore.sh download if needed, print the directory holding the binaries # scripts/fetch-lore.sh download if needed, print the directory holding the binaries
# scripts/fetch-lore.sh --liblore the same for liblore (the library and lore.h), which the
# desktop client's service loads
# scripts/fetch-lore.sh --liblore-to FILE
# fetch liblore, then copy the library to FILE (for zig build)
# scripts/fetch-lore.sh --pin vX.Y.Z re-pin lore.lock to another release (needs `gh`) # scripts/fetch-lore.sh --pin vX.Y.Z re-pin lore.lock to another release (needs `gh`)
# #
# The version and the SHA-256 of every archive are pinned in lore.lock, so a download that does # The version and the SHA-256 of every archive are pinned in lore.lock, so a download that does
@ -48,7 +52,7 @@ pin() {
echo "# Re-run scripts/e2e-lore.sh after changing it." echo "# Re-run scripts/e2e-lore.sh after changing it."
echo "version $version" echo "version $version"
gh release view "$version" --repo "$REPO" --json assets \ gh release view "$version" --repo "$REPO" --json assets \
--jq '.assets[] | select(.name | test("^lore(server)?-v.*\\.tar\\.gz$")) | select(.name | test("-debug\\.") | not) | "sha256 \(.name) \(.digest | ltrimstr("sha256:"))"' --jq '.assets[] | select(.name | test("^(lib)?lore(server)?-v.*\\.(tar\\.gz|zip)$")) | select(.name | test("-debug\\.") | not) | "sha256 \(.name) \(.digest | ltrimstr("sha256:"))"'
} >"$LOCK.tmp" } >"$LOCK.tmp"
grep -q '^sha256 loreserver-' "$LOCK.tmp" || { rm -f "$LOCK.tmp"; die "$version has no loreserver archives"; } grep -q '^sha256 loreserver-' "$LOCK.tmp" || { rm -f "$LOCK.tmp"; die "$version has no loreserver archives"; }
mv "$LOCK.tmp" "$LOCK" mv "$LOCK.tmp" "$LOCK"
@ -96,8 +100,51 @@ fetch() {
echo "$dir" echo "$dir"
} }
# The library's file name in the release archive for this machine.
library_file() {
case "$(uname -s)" in
Darwin) echo liblore.dylib ;;
*) echo liblore.so ;;
esac
}
fetch_liblore() {
[ -f "$LOCK" ] || die "$LOCK is missing"
local version target dir file
version=$(awk '$1 == "version" { print $2 }' "$LOCK")
target=$(target)
dir="$ROOT/.lore/$version"
file=$(library_file)
if [ -f "$dir/$file" ] && [ -f "$dir/lore.h" ]; then
echo "$dir"
return
fi
local archive="liblore-$version-$target.tar.gz" expected actual
expected=$(awk -v a="$archive" '$1 == "sha256" && $2 == a { print $3 }' "$LOCK")
[ -n "$expected" ] || die "$LOCK pins no $archive; re-pin with --pin $version"
WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/fetch-lore.XXXXXX")
trap 'rm -rf "$WORK_DIR"' EXIT
say "downloading $archive"
curl -fsSL --retry 3 -o "$WORK_DIR/$archive" "https://github.com/$REPO/releases/download/$version/$archive"
actual=$(sha256 "$WORK_DIR/$archive")
[ "$actual" = "$expected" ] || die "$archive has SHA-256 $actual, but lore.lock pins $expected"
mkdir -p "$WORK_DIR/lib"
tar -xzf "$WORK_DIR/$archive" -C "$WORK_DIR/lib"
[ -f "$WORK_DIR/lib/$file" ] && [ -f "$WORK_DIR/lib/lore.h" ] || die "$archive holds no $file and lore.h"
mkdir -p "$dir"
cp "$WORK_DIR/lib/$file" "$WORK_DIR/lib/lore.h" "$dir/"
say "liblore $version is in $dir"
echo "$dir"
}
case "${1:-}" in case "${1:-}" in
--liblore) fetch_liblore ;;
--liblore-to)
[ -n "${2:-}" ] || die "usage: $0 --liblore-to FILE"
dir=$(fetch_liblore)
cp "$dir/$(library_file)" "$2"
;;
--pin) [ -n "${2:-}" ] || die "usage: $0 --pin vX.Y.Z"; pin "$2" ;; --pin) [ -n "${2:-}" ] || die "usage: $0 --pin vX.Y.Z"; pin "$2" ;;
"") fetch ;; "") fetch ;;
*) die "usage: $0 [--pin vX.Y.Z]" ;; *) die "usage: $0 [--liblore | --liblore-to FILE | --pin vX.Y.Z]" ;;
esac esac