Author SHA1 Message Date
faumaray a3964f65f9 Merge branch phase5/gpui-voice into main (GPUI slice 3: voice page, call bar, PTT guards)
CI / Linux checks (push) Failing after 1m47s
2026-11-23 18:38:46 +03:00
faumarayandGemini 4 Neon f4afd83a5f docs: document GPUI voice fix round (PTT guards, compact stage, tooltips)
Update `docs/ui.md` ("The voice page and the call bar") and `CHANGELOG.md` for the fix round: fail-closed `hotkey.rs` loop, hardened `AppState` / `Sidebar` / `MainView` push-to-talk state machine (`button_held`, `hotkey_held`, `shutting_down`, per-event disconnect handling, mode/server/delete/focus/shutdown guards), centred smaller stage and re-shot compact screenshots (`15a1b60`, Xvfb `:621`/`:622`, Mesa 26.3.0 lavapipe), and `IconButton` dynamic tooltip refresh via `ElementId::NamedChild`.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:35:10 +03:00
faumarayandGemini 4 Neon b83481e4cc voelin-gpui: refresh toggle icon button tooltips when their label changes
Key `IconButton`'s GPUI element ID by both its base ID and its label (`ElementId::NamedChild(Arc::new(self.id), self.label)`) while keeping `.debug_selector(...)` equal to `self.id.to_string()`. When a toggle button's label changes (e.g. `call-mic`, `call-sound`, `member-mute`, `user-mic`, `user-sound`, `voice-stage`), GPUI drops stale hover/tooltip state from the old ID and builds the updated tooltip label while all existing debug selectors stay unchanged.

Add a GPUI test covering `call-mic`, `call-sound`, `member-mute`, and `voice-stage` across state flips while hovered.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:31:11 +03:00
faumarayandGemini 4 Neon 15a1b60d8a voelin-gpui: centre the voice page's smaller stage while it fits
Make the compact stage scroll container a flex row (`.flex().flex_row()`) and mark its inner participant row `.flex_none().mx_auto()`, so 1–5 participants centre horizontally above the call bar when they fit while crowded channels (12–25+ people) still start at the left padding and scroll sideways without clipping the first participant.

Add a GPUI layout test pinning both cases (2 and 5 people centred, 25 people unclipped on the left and overflowing horizontally) and re-shoot the two compact screenshots at 1440×960.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:26:14 +03:00
faumarayandGemini 4 Neon a16e4d4b93 voelin-gpui: harden push-to-talk and global hotkey transmit state machine
Track the window hold-to-talk button (`button_held`) beside the global hotkey (`hotkey_held`) and a `shutting_down` flag in `AppState`, closing Security Review MEDIUM #2 and Opus gate probes P1, P2, P3, P4, P5, P6, and P8:

- `stop_transmitting_if_unheld`, `release_button_hold`, and `release_hotkey_hold` keep transmit active while either source holds the session and avoid duplicate start/stop commands (P6).
- `hotkey_transmit(true)` on a different connected server stops the previous held session before starting the new one (Security MEDIUM #2 / P2), while `select_server` preserves `hotkey_held` (P2b) and releases `button_held` when the held server leaves the screen (P8).
- `handle_events` checks `Connected -> !Connected` transitions per event inside the batch loop so a drop and reconnect within one 64-event batch still releases both holds and emits `SetTransmitting(false)` once (P3).
- `setting_changed` releases `button_held` when `audio.transmit` leaves `PushToTalk` (P1/P1b); `delete_bookmark` clears holds on the removed session (P4); `shutdown` sets `shutting_down`, drops `ptt`, and releases both holds before closing sessions, ignoring late `Later` presses (P5).
- `Sidebar` clears `holding` whenever voice disconnects, transmit leaves push-to-talk, the shown server changes, or `AppState::button_held` no longer matches; `MainView`'s focus-loss observer unconditionally releases `Sidebar` and `AppState::push_to_talk(false)` without cutting `hotkey_held`.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:21:09 +03:00
faumarayandGemini 4 Neon 116a26652a voelin-gpui: release global hotkey transmit on desktop removal and task exit
When the desktop's GlobalShortcuts portal or backend removes the registered push-to-talk hotkey while it is held, or when the hotkey command channel closes on task exit, GlobalPtt's event loop now calls transmit(false) before reporting the status or exiting so the microphone cannot stay open.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:13:07 +03:00
faumarayandClaude Sonnet 5.5 1a656eef86 voelin-gpui: a test that the voice page marks no chat as read; a heading
Asking for the voice page opens the channel's chat tab in the state
(logic::show_voice_view, open_chat with focus), which a front end that shows no
chat must not mark as read: the test looks at the store. The properties and
callbacks heading of the voice section is named for the page, so that its anchor
does not collide with the tree section's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 11:00:45 +03:00
faumarayandClaude Sonnet 5.5 4b83c649f7 docs/ui.md: the displays of the voice page's final runs, and a sentence
The pictures were taken on Xvfb :511 to :514 and the figures on :531 and :532 of
the final build (the earlier figures, of 65b60f2, on :431 and :432); the
sentence on the smaller stage said something about the phone it did not mean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:56:12 +03:00
faumarayandClaude Sonnet 5.5 bc22a97372 docs: the voice page and the call bar (GPUI slice 3)
docs/ui.md: the voice page section (what is on screen, the release guard of Hold
to talk, the global push-to-talk key, the properties and callbacks of the
slice, what the page costs idle and with a talker at 10 Hz, what was seen against
the TeamSpeak 3 and 6 development servers), "What is next" item 3 done, "For the
next slices" pruned (the Hold to talk risk, the hotkey's runtime note and the
SettingChanged note settled, the tree model's note updated) and what this slice
leaves to the chat and stream slices added, the tree section's tables and the
settings row brought up to date; the CHANGELOG entry; the spikes report's
status; six pictures under docs/ui/ (the larger and the smaller stage, dark and
light, the page against a real TeamSpeak 3 talker, a person's card).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:50:09 +03:00
faumarayandClaude Sonnet 5.5 71407181c0 voelin-gpui: the voice page's larger stage scrolls when its rows outgrow the page
A channel of fifty people wraps into ten rows of large avatars, which pushed the
call bar off the page (found with a test of 45 people: the bar was 600 pixels
under the page). The people shrink to what the header and the call bar leave and
scroll with the wheel; the smaller stage's row scrolls sideways (GPUI turns a
vertical wheel into a sideways one for a container that scrolls only that way).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:42:01 +03:00
faumarayandClaude Sonnet 5.5 373805984c voelin-gpui: a disabled icon button keeps its tooltip
The Slint IconButton shows its tooltip while disabled too, which is how the
voice page's stage button says why it is off in a window too short for the
larger stage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:33:18 +03:00
faumarayandClaude Sonnet 5.5 d2267e55e7 voelin-gpui: run starts the hotkey, the state does not
The previous commit started the global push-to-talk task in AppState::new when
there was an engine, which a test of the state with a real engine has: it
asked the desktop for a shortcut (the X11 backend on whatever DISPLAY is set,
the portal on a Wayland session: a dialog on the user's desktop) and the task's
status line came back to the foreground from a tokio thread, which the test
scheduler reported as a test that is not deterministic (one run in six of
closing_counts_the_sessions_the_engine_was_told_to_close). run() starts it
once the window is open (AppState::start_global_ptt), the state never does,
and the test says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:33:18 +03:00
faumarayandClaude Sonnet 5.5 65b60f2bb7 voelin-gpui: a test for the deafen mark of the voice page
A person whose sound is off has the headphone mark in the corner of their
avatar, and a talker's bars win over the marks, as in the Slint page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:18:15 +03:00
faumarayandClaude Sonnet 5.5 c566716b45 voelin-gpui: the volume of a person, on the member card
The Volume rows of the Slint member card (members.slint): what the person is
played at in percent, a mute for us and a slider (0 to 200, steps of 5), both
off for a person the server gave no unique id, since the choice is kept by it.
A click on a person on the voice page or in the members panel opens the card,
so the volume is a click away from the people the voice page shows. The slider
and the button are the actions SetMemberVolume and SetMemberMuted, which go
through voelin-ui-vm's settings_page logic (open_client, then
client_playback_changed: the engine's SetClientVolume and SetClientMuted, the
`client_playback` key, the tree's mark of who is muted), the logic the Slint
front end's volume dialog calls; the dialogs slice keeps the dialog itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:17:49 +03:00
faumarayandClaude Sonnet 5.5 04223a785c voelin-gpui: the transmit mode, the volumes and the stage follow the settings
SettingChanged is no longer ignored for the keys the voice page depends on, as
the Slint front end's setting_changed reads them again: `audio` (the transmit
mode: the voice card has Hold to talk for push-to-talk and says "Voice
activity" or "Open microphone" for the other modes, where it had a button or
nothing), `client_playback` (the clients' volumes: the tree and the card show
who is muted) and `ui.voice_compact` (the voice page's stage). The areas that
show them are raised; the development switches keep what they set, and the
sample servers' stage is not read back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:15:31 +03:00
faumarayandClaude Sonnet 5.5 0b55811e5a voelin-gpui: the global push-to-talk hotkey, started on the engine's runtime
docs/ui.md's list for the next slices: the hotkey portal calls tokio::spawn and
panics where no tokio runtime is current, and a GPUI foreground task has none,
so the task of voelin_platform's HotkeyManager is spawned on the engine's
runtime (hotkey.rs, the Slint front end's GlobalPtt repeated as engine.rs
repeats HostedEngine: it needs the runtime and the front end's own way back to
its state, and the Slint crate cannot be a dependency; tokio's `macros` feature
for its select!, Cargo.lock unchanged). It starts at launch with the settings'
`ui` key (`global_ptt`, `ptt_key`) when there is an engine and no sample
servers, and says how the key stands in the log and in AppState::ptt_status. Its
presses and releases cross to GPUI's thread through Later: a press transmits
into the session on screen while that has voice, and the release ends the
session the press began in, whichever is on screen then; the voice that drops
under a held key ends the hold. The window losing the focus does not cut it:
the key is meant for use while another window has the focus. A change of the key
at run time is the settings slice's (AppState::set_global_ptt is its entry).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:13:46 +03:00
faumarayandClaude Sonnet 5.5 3253357eda voelin-gpui: the release guard of Hold to talk
The risk slice 2 recorded: a key or the button held while voice drops leaves
transmit on. Two cases, two guards. Voice that drops: the voice card, with the
button, goes with it and nothing is left to release, and the session keeps
`transmitting` into the next connection; after each batch of engine events the
root state tells the session SetTransmitting(false) once for every session that
was connected before it and is not after it and still says it transmits (the
engine's own report, so no flag of ours can go stale; it does not answer the
engine's answer, nor a reconnect). The sidebar's own hold is cleared by its
observer of the state, which sets its own field and sends nothing. A window
that loses the focus while the button is held: the mouse button comes up
elsewhere, so MainView's window-activation observer lets the button go and the
session is told. A window that holds nothing sends nothing, since the global
hotkey is meant for use while another window has the focus.

Tests: both guards (and that each fails without its guard, which was checked by
removing it), the hold that is not one, nothing sent for a window that held
nothing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:10:29 +03:00
faumarayandClaude Sonnet 5.5 3bf21f1b26 voelin-gpui: the sidebar's server card has the server's banner behind it
server_banner, which the tree slice left out, is behind the card as in
ServerHeader of channels.slint: the picture covers the card (cropped to its
padding box, so the border stays), the same surface veil as the tree's banner
rows lies over it, and the stats line reads in the text colour instead of the
muted one. A server without a banner, or whose picture has not arrived, has the
plain card. The picture's corners are square, as the tree's banner rows': GPUI
clips to rectangles.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:05:25 +03:00
faumarayandClaude Sonnet 5.5 ba4fe3c8ca voelin-gpui: the voice channel page and its call bar
Slice 3 of plan section 6 step 3, first part. VoicePage is a cached pane of its
own, a sibling of the server page that MainView puts in the main area while
the page is asked for (show_voice_view, through voelin-ui-vm's logic) and voice
is connected, as the Slint VoiceView is. It shows the channel (name, topic,
banner under the surface veil, "N in voice / limit total"), the people of our
channel as TreeView::members gives them through the tree model's Voice event
(the ring that is green while they talk and blue while they stream, the bars or
the microphone and sound marks in the corner, the crown, "Speaking",
"Streaming", "Away"; a click opens the card), and the call bar: mute, deafen,
Share and the voice settings (both logged until their slices), Leave. The
smaller stage, one row of small avatars, is ui.voice_compact and always in a
window under 800 pixels tall, which MainView pushes into the pane (a cached
pane does not see a resize); VOELIN_OPEN=voice[:compact] asks for it, the
sample servers keep nothing. The server page gets a Voice channel button for
the way in, and the meter counts the page's renders.

Tests on the test platform: the page takes the main area and gives it back, the
people and their marks, talking and mute events redraw the page once and the
rail, top bar and main area not at all (one model build for three lists),
Leave reaches the engine, the call bar's buttons, the stage kept in the
settings and forced short, the banner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:02:35 +03:00
faumarayandClaude Sonnet 5.5 3fb5de8f32 voelin-gpui: an avatar's picture rounds its own corners
The avatar's face clipped its picture with overflow_hidden, which GPUI makes a
rectangle: a person's picture was a square with the round avatar's ring around
it (the members panel and the tree showed it at 22 to 46 pixels, the voice
page's 80 pixel avatars make it plain). The image element takes the radius
itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:01:34 +03:00
faumarayandClaude Sonnet 5.5 6e866b95f6 voelin-gpui: the tree model keeps the people of our voice channel
TreeView::members was built with every tree build and thrown away. The model
keeps it now and emits it as TreeEvent::Voice (the whole list, as it is now)
when it differs from the last: the voice page of the next commits takes its
people from the same build as the tree and the members panel, not from one
of its own, so a talker is still one build for three lists.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 09:51:33 +03:00
faumarayandClaude Fable 5.1 42d74b9594 Merge phase5/gpui-tree-minors: the minors of GPUI slice 2's gate and review (rows in the pane events, talking marks restored for parity, restore_tree on a removed server, banner tints, the no-match text, Escape after a click, the demo-folder leak, the cost records)
CI / Linux checks (push) Successful in 28m17s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 09:25:47 +03:00
faumarayandClaude Fable 5.1 50071d39f4 voelin-gpui: TreeModel watches the one AREAS list; docs/ui.md's signals intro names the parity ruling (review minors)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 09:25:47 +03:00
faumarayandClaude Sonnet 5.5 64b17159be voelin-gpui: the tree has no words of its own for a search it does not have
The tree's empty_words had an arm for Emptiness::NoMatch with a string no user
can reach: the tree's emptiness comes from Emptiness::of, which never says
NoMatch (the members' search is the panel's, TreeModel::people_emptiness). The
arm shares the Connect words now, with the reason in a comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:26:15 +03:00
faumarayandClaude Sonnet 5.5 a2bdc9d745 docs/ui.md: the tree and the members on the sample server and the dev servers again, after the minors round
The runs of the round's acceptance on the release build of the branch's tip,
each on a display of its own: the talking ring and bars and a selected and a
hovered banner row on the sample server, the Escape after a click on the
password prompt's card, the members search with no match against the
TeamSpeak 3 and 6 development servers (one connect to each, read-only, a clean
close with status 0 and no ghost client on the TeamSpeak 3 one), and the
talking run's figures again at the tip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:25:56 +03:00
faumarayandClaude Sonnet 5.5 1dbe5d5dca docs/ui.md: the records of the tree slice's gate and review for the next slices
What the gate and the review left to the slices that meet them, in "For the
next slices": the model builds the whole tree_view for every batch it hears of
(O(people), a stat per picture; a batch is one build now, a talking-only
refresh path or a reuse of the ImageRefs belongs to the voice page or later);
the rail, the top bar and the main area refresh on the servers flag only, so a
flag voelin-ui-vm forgets to set leaves both front ends stale; the members
search's caret blink draws the window twice a second (measured: 2.00 frames, 2.00
renders of the sidebar and the panel, llvmpipe at 21 % of a core); the
voelin-ui-vm versions of the joins and the card that only the GPUI front end
calls, whose Slint copies can drift; and the TeamSpeak 3 development server's
ban of a burst of connects from one address. The coalescing of the three
signals of a picture that arrives is the commit before, and the first of the
round's has the rule for observers of the signals.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:07:11 +03:00
faumarayandClaude Sonnet 5.5 0352d67651 voelin-gpui: the tree model builds its rows once for a change that raises three signals
The model listens to the tree, toolbar and member card signals, and one batch
can raise all three (a picture that arrives raises them all): every observer
call built the whole tree_view again, O(people) with two stats per picture,
so an AvatarReady or PictureReady cost three builds, two of them to find the
rows the first had made. The signals of a batch are raised before the first
is heard, so the model now keeps the generations it last built at and a
refresh finds nothing new when it is the second or third of the batch.

A test counts the builds (TreeModel::refreshes): a picture that arrives is
one build, and so is a batch of two events that raise the same signals (the
picture was three builds with the check disabled). The probe of the first
commit of the round still has its two refreshes in one flush (its observer
raises the signals again), and passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:04:33 +03:00
faumarayandClaude Sonnet 5.5 5a5fd9978d voelin-gpui: the banner test removes the sample pictures' folder it made
a_banner_is_drawn_under_a_veil opens the sample servers with their pictures,
which are files of a folder named voelin-gpui-demo-<pid>-N in the temporary
directory; the window's close removes it (AppState::shutdown), but the test
never closes the window and the entity of a gpui test is not released when the
test ends, so every run of the lib binary left a folder: eight runs with TMPDIR
pointing at an empty directory left eight. The test ends with the app's
shutdown now, after asserting that the folder was there and is gone; eight
runs leave TMPDIR empty.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:03:17 +03:00
faumarayandClaude Sonnet 5.5 244226d15c voelin-gpui: Escape closes the password prompt wherever in it the last click was
The prompt closed on Escape only while its field had the focus: the field's
own Escape has nothing to undo and passes the key on, and a listener on the
prompt took it. A click on the card off the field (its heading, the disabled
Join) moves the focus away from the field, and with nothing in the prompt
focusable the window's root took it (MainView's focus handle), so the prompt's
key context was off the dispatch path and Escape did nothing.

Escape is now a key binding of the prompt's key context (bound by
shell::bind_keys beside gpui_kit::init, in run() and in the tests), which
dispatches CancelChannelPassword, and the prompt's scrim holds a focus handle
of its own, so a click anywhere in the card leaves the context on the path.
The field's Escape still passes the key on and the binding closes the prompt;
the listener on the field's action is gone (with it the binding would close
twice). A test clicks the card's corner and the disabled Join and presses
Escape: it failed before (the prompt stayed), and the existing prompt test,
which presses Escape in the field, still passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:01:54 +03:00
faumarayandClaude Sonnet 5.5 c044f7279a voelin-gpui: a search with no match says "Nobody matches."; connecting is loading
The members panel said "Connect to see who is here." for every empty list
that was not loading, so a search that matched nobody on a connected server
told the user to connect. Emptiness has NoMatch now ("Nobody matches."), for
a non-empty search over a server that has people and leaves none of them; it
is the panel's own (TreeModel::people_emptiness): the tree is not searched,
so the shared Emptiness::of never says it and the tree pane is not told when
the search comes to match nobody (a test counts its renders across the
change). A server whose voice is connecting is Loading, as one that is
observed is, in both panes: its channels and people are on the way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:00:33 +03:00
faumarayandClaude Sonnet 5.5 f28c02a18c voelin-gpui: a banner row shows its selection and its hover over the picture
A channel row paints its selected and hover backgrounds on the row, and the
banner picture, drawn from the indent on, covers them: a banner row showed a
strip of hover left of the picture and no selection at all. channels.slint
tints the hover over the picture with a translucent child (surface-3 at 50 %),
as the own channel's tint is drawn here; the row now does the same, with a
child above the veil for the selected row (surface 3 at 75 %, a state Slint
has none for) and one for the hover (50 %, through the row's group, so the
pointer anywhere on the row tints it). Our own channel keeps its accent tint.

A test selects two banner rows of the sample server in turn and finds the
tint on the selected one only; docs/ui/gpui-tree-banner-selected-dark.png
shows Raid Night selected and the pointer on Music (release build, lavapipe on
Xvfb :233 with openbox).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:48:58 +03:00
faumarayandClaude Sonnet 5.5 cc143f312d voelin-gpui: the server shown after a removal has its remembered folds
restore_tree (the folds ui.tree remembers for a server, put into its session
once) ran only in select_server, so the server that came on screen when the
one shown was removed, or when a save or a connect put another on screen, had
none of its folds: its tree showed everything open, and the next fold wrote
the one just made over what was stored.

transition_with, which every transition runs through, now restores the folds
of whichever server it leaves on screen before anything draws it, and
select_server no longer does it by itself. Two tests: removing the server on
screen shows the next with its stored fold, and a fold made then is added to
it where it used to replace it ([3, 7], not [3]); a save of another server
shows it the same way. Both failed on the code before (no session for the
server shown, so no folds).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:43:24 +03:00
faumarayandClaude Sonnet 5.5 122b2d29fa voelin-gpui: the tree marks who talks again, the ring on the avatar and the bars on the row
The gate ruled for parity: the tree cleared `talking` on every row to keep its
pane from being drawn with each start and stop of someone's voice, and the
Slint tree (channels.slint) has the speaking ring on the avatar and the bars
on the row. The model keeps the flag now and client_row draws the ring
(Avatar::speaking) and the bars, 14 pixels as SpeakingBars is, after the badges
and before the LIVE mark, as the Slint row orders them.

The cost was measured with the meter at 10 starts and stops a second (the
sample server, release build, lavapipe on Xvfb :231): the tree pane is
rendered once for each, 9.97 a second for 9.97 events, as the members panel is,
and the rail, the top bar and the main area not at all; 102 % of a core in
all, 5.0 % of it GPUI's thread, which is what the run before the change had
(3.1 % to 5.0 %). docs/ui.md replaces the paragraph that said the tree carries
no talking with the figure; the tests that counted the tree as not drawn count
it as drawn once (a talker changes one row and draws the tree once; the tree
and the members panel and no other pane), and the sample server's tree marks
Kairo.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:42:20 +03:00
faumarayandClaude Sonnet 5.5 6b01e25391 voelin-gpui: the tree and members events carry the rows their operations lead to
TreeEvent::Rows and ::People carried the row operations only, and the panes
applied them to the model's rows read when the event was delivered. A model
that refreshes twice in one flush (it listens to the tree, toolbar and member
card signals, and a batch raises several) holds the second rows by the time a
pane hears of the first operations, so an observer that changes the state
inside the flush made the first operations index the second rows: the gate's
probe, select_server from the observer of the toolbar signal during a
Presence flush, panicked in ChannelTree::apply on the shrink.

The events now carry the rows (Rows(Changes, Arc<Vec<TreeItem>>), People the
same) and the panes apply the operations to the rows they have and keep the
carried ones, so the events lead from the rows a pane started with to the
model's last whatever the order of the flush. apply checks the counts in
debug builds (debug_check), and "For the next slices" has the rule: a signal's
observer reads the state and sets its own fields, a change of the root state
is an action's or a task's. The probe is a test
(a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows); it
panicked on the code before ("index out of bounds: the len is 0 but the index
is 3", channels.rs) and passes now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:22:58 +03:00
faumarayandClaude Fable 5.1 e61919ebf4 Merge phase5/gpui-tree: slice 2 of the GPUI front end, the channel tree and the members panel as cached panes with per-area signals (plus the shell minors' three preliminaries)
CI / Linux checks (push) Successful in 31m33s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 07:13:40 +03:00
Aleksey Selihov b08bda599d Merge pull request 'CI: the VoelinProtocol deploy key lives for one trusted fetch step' (#2) from phase5/ci-deploy-key-hardening into main
CI / Linux checks (push) Successful in 32m20s
2026-10-28 01:27:14 +00:00
faumarayandClaude Sonnet 5.5 9139e50b5e docs/ui.md: the server card's banner has a home in the next slice's list
The table of the Bridge's properties says server_banner is not drawn by the
sidebar's server card and that the voice page and call bar slice takes it;
that slice's item in "What is next" now names it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 04:18:55 +03:00
faumarayandClaude Sonnet 5.5 4141b9b3aa docs/ui.md: the meter and the live runs again on the build with the review's fixes
The release build of bad5312 on my own displays: idle 0.6 % and no pane
rendered, a sample person talking 10 times a second rendered the sidebar and
the members panel 10 times a second and no other pane; against the TeamSpeak 3
development server the double-click join, the password prompt (Join dimmed,
Enter on an empty field and Escape, a wrong password asked again in words, the
right one joining) and the close (status 0, no ghost client), and the TeamSpeak
6 server's tree and panel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 04:01:28 +03:00
faumarayandClaude Sonnet 5.5 14091c4202 docs: the ui.tree row, every property and callback of the two panes, the long lines
The review of the channel tree slice: the Settings table of docs/ui.md has a
ui.tree row (JSON by server id, written by the GPUI front end only); "The
callbacks and the properties" lists every Bridge property and callback (and
the Nav functions) that channels.slint and members.slint use, with the plan's
13 and 6 named inside them and each with its GPUI counterpart or the slice
that takes it (watch_client, member_action, member_volume and server_banner
included); the tree's banner veil, the one-letter small avatars and the
password prompt's empty field and Escape are described; the two tree pictures
with banners (light and dark) are taken again on the release build of bad5312.
The paragraphs the previous re-wrap left long are wrapped, the CHANGELOG entry
and the spikes report's status say what the review closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:54:35 +03:00
faumarayandClaude Sonnet 5.5 bad5312bfd voelin-gpui: the password prompt ignores an empty field and Escape closes it
The Slint dialog (ChannelPasswordDialog) turns Join off and ignores Enter
while the field is empty, keeping the dialog open, and closes on Escape. The
prompt here took itself away before join_with_password refused an empty
password, so Join or Enter on an empty field closed it without a join, and
Escape did nothing (the field's own Escape passes the key on).

The submit now reads the field first and leaves the prompt open when it is
empty; Join is disabled while it is (the field's changes redraw the prompt);
the prompt handles the Escape the field passes on and cancels. The prompt's
test covers Join and Enter on an empty field, Escape (nothing sent, the
channel no longer the one to join), and a typed password entered with Enter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:49:05 +03:00
faumarayandClaude Sonnet 5.5 c158bdda00 voelin-gpui: an avatar under 28 pixels shows one letter, at half its size
The tree's 22 pixel avatars wrote two-letter initials at 0.38 of their size,
about 8 pixels, cramped; avatar.slint writes the first letter at 0.5 of the
size under 28 pixels, through voelin_ui_vm::avatar::first_letter. The rail's
and the cards' larger avatars are as they were. A test states the rule at 22,
27.9 and 28 pixels, for an empty name and for a letter with a mark.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:48:47 +03:00
faumarayandClaude Sonnet 5.5 f8cf6a3561 voelin-gpui: a channel's banner is drawn under the surface veil, as the Slint tree's
A channel row drew its banner picture at full strength under the name, so
Theme.text could sit on a picture of its own colour (dark text on the sample
server's dark banners in the light theme, light text on a bright TS6 banner in
the dark one). banner-picture.slint lays the surface colour over the picture,
74 % opaque on the left and 66 % on the right; the row now does the same, over
the picture and under the tint of our own channel.

A test keeps the veil: the text of both themes has more than 4.5 to 1 against
the weakest end over a black and over a white picture, and the gradient is the
surface colour at those two opacities; another finds the veil on the sample
server's banner rows and on no other.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:48:31 +03:00
faumarayandClaude Sonnet 5.5 3f7aecfd61 docs: ci.md, wording of the run 1224 note
CI / Linux checks (pull_request) Successful in 32m49s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:39:51 +03:00
faumarayandClaude Sonnet 5.5 06478dc13a docs: ci.md says what run 1224's cancellation was (observed, not explained)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:37:47 +03:00
faumarayandClaude Sonnet 5.5 36c90c4595 docs: ci.md records what was seen on runs 1225 and 1226 and what was only rehearsed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:37:38 +03:00
faumarayandClaude Sonnet 5.5 4b31564d51 ci: the temporary commit reverted (MIN_MASKING_RUNNER_VERSION back to 3.1.0): the workflow is that of the commit before it
Run 1225 of the temporary commit: the runner "Perfrormance Runner" (v3.1.0) was
refused by the check, the job failed there, the system packages, the toolchain,
the key step, the fetch and the checks were not started and left no line in the
log, the cleanup step said that no key is left, and the log has no mention of the
secret.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:00:05 +03:00
faumarayandClaude Sonnet 5.5 2005d26649 ci: TEMPORARY, MIN_MASKING_RUNNER_VERSION 99.0.0, to see the gate refuse a real runner (reverted by the next commit)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:59:14 +03:00
faumarayandClaude Sonnet 5.5 2cf8bc7fda docs: VoelinProtocol access (ci.md) for the fetch-then-delete key, the runner gate and the fork check; deploy key id 7
ci.md rewrites "VoelinProtocol access" on the model of VoelinGateWay's: the
steps in order, the fork rule in the expression and the script, the release
agent, the four images, the runners that printed the keys, how to look at a run,
what the hardening does not do. The Gitea intro no longer says that pushes and
pull requests are off (the workflow has run on them since 2026-10-12).
building.md and release.md follow; CHANGELOG appended.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 91dce84b36 release and the images: the agent only for cargo fetch, stopped after the builds, never on a runner that may print the key
release.yml checks the runner version before any step names the secret (same
gate as ci.yml), starts the ssh-agent only on the positive flag, and stops it in
an always() step right after the last build, so the artifact upload and the
release draft have neither the key nor the socket. The four Dockerfiles (linux,
windows, android, the gateway image) give the agent to `RUN cargo fetch --locked`
only; the build after it has no ssh mount and is offline (--offline, and
CARGO_NET_OFFLINE for the Android Gradle task, which starts cargo-ndk).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 cfde421af4 CI: the VoelinProtocol deploy key lives for one step, cargo fetch, and the checks run offline
The job checks first that it may hold the key (a runner that reports 3.1.0 or
newer, which masks a multi-line secret in the log; on a pull request, a head
branch in this repository, asked in the job-level expression and again in the
script from the head repository's name), installs the system packages and the
toolchain, writes the key to a directory of its own for one step (no ~/.ssh
configuration; the step removes the directory itself on any way out but its last
line), fetches with `ssh -i` and the committed host key (`cargo fetch --locked`)
and deletes it, and a step that always runs deletes it again. The checks action
has no input and no secret and every cargo command in it is --offline.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 0e01b60930 docs: re-wrap three lines the slice's own edits left long
The maximized paragraph of docs/ui.md (the guard sentence joined onto a
line), the sequences bullet of "Shared with the Slint front end", and the
spikes report's shell paragraph. Prose only; no word changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:56:39 +03:00
faumarayandClaude Sonnet 5.5 639a173092 docs/ui.md: name the binary of the first meter run and of the live run exactly
Both were release builds of the tree that aa640cf then committed (built just
before it; the commit added tests after), not of a commit of their own.
Prose only: the own-crates result of b27b7c7 applies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:56:02 +03:00
faumarayandClaude Sonnet 5.5 b27b7c7f32 docs/ui.md: the figures of the final code commit and where each run's binary came from
The idle and talking figures are measured again on the release build of
faef132 (97 % of a core at 9.7 frames a second with a sample person talking
ten times a second, of it 91 % the software renderer and 5 % GPUI's thread;
the first, quieter run is kept beside it), the live run names its binary
(aa640cf), and the sample pictures' folder is said to go when the window
closes (checked on a real Alt+F4).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:47:23 +03:00
faumarayandClaude Sonnet 5.5 faef1325ab voelin-gpui: the sample pictures only when asked and removed at close; two small fixes
- The sample servers' pictures were written to a folder of the temporary
  directory by every state that showed them, tests included, and the folder
  went only with a dropped state, which the test platform and a killed run
  never do. The pictures are now a switch (Switches::demo_pictures: what
  VOELIN_DEMO_UI sets, and what a test asks for by name) and the folder is
  removed when the window closes (AppState::shutdown) as well as with the
  state.
- The tree does not redraw for a change of the people's count, which is the
  members panel's, and an unfolded channel leaves no empty entry in what the
  trees remember.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:40:25 +03:00
faumarayandClaude Sonnet 5.5 68a1694d7b docs: the channel tree and the members panel, its pictures, figures and records
docs/ui.md: a section for slice 2 (what is on screen, the per-area signals
and cached panes with the three rules GPUI taught, what a change costs, seen
against the TeamSpeak 3 and 6 development servers, the callbacks and the
properties as tables, what differs from the Slint tree and panel), the
switches VOELIN_DEMO_SERVER and VOELIN_DEMO_TALK and the per-pane counters of
the meter, what is shared with the Slint front end, "What is next" (the voice
page and the call bar are next) and "For the next slices" without what this
slice did (cached panes and signals, the pictures), with the click and hover
cost, the missing scrollbar and the three copies that stay in the Slint
crate. The four pictures are the shell at 1440 by 960 under
scripts/gpui-shot.sh on a display of its own. The CHANGELOG and the spikes
report's status say what landed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:24:28 +03:00
faumarayandClaude Sonnet 5.5 aa640cf2b0 voelin-gpui: VOELIN_DEMO_SERVER, the logged Move to my channel, and what a click costs
- VOELIN_DEMO_SERVER=<0..2> puts another sample server on screen: the second
  is observed and the third is not connected, both with empty trees, which is
  how the pictures of an empty server are made.
- The person's context menu offers Move to my channel; the engine has no
  command to move another client, so the action is logged.
- A test that holds what the caches cannot save: pressing and releasing a
  clickable element refresh the window, so a click renders every pane, and a
  hover renders only the pane the pointer is over.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:14:46 +03:00
faumarayandClaude Sonnet 5.5 26302bcdde voelin-gpui: the members panel and the member card, the sample server's pictures and a talker
Slice 2, second half. The right panel of a server on screen (as wide as
ui.members_width) is everyone on the server in sections from voelin-ui-vm's
rows (server_members: those streaming first, then each server group), with
"Members - N", a search (search_members), and per person the avatar with its
presence dot and speaking ring, the name with the admin, priority, commander
and recording marks and their myTeamSpeak badges, what they do, the role,
LIVE, the mute marks and the hand of a person who needs talk power. It is a
cached pane over a virtual list that applies the model's row operations, and
the pane a talker redraws: nothing else of the window is told.

A click on a person opens their card over the panel (tree::member_card:
name, status, description, groups, badges, talk power, country) with a scrim
a click outside closes; it follows the person while open and goes when they
leave. Its buttons (volume, message, poke, friends, block) are the slices
of those dialogs.

Development: VOELIN_DEMO_UI now also delivers the first sample server's
avatars, icons, banners and badges as files of a folder of the state's own
(removed with it), and VOELIN_DEMO_TALK=10 makes a sample person start and
stop talking that many times a second through the app's events: what the
meter measures while someone talks.

Tests: the sections and the search, a talker redraws the members panel and
no other pane, the card (open, follows, closes three ways, goes with the
person), an avatar written again shows under a new key and the old copy goes
from the asset cache, the sample pictures and the talker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:03:39 +03:00
faumarayandClaude Sonnet 5.5 b1f673fce3 voelin-gpui: the channel tree, with a password prompt and what it remembers
Slice 2, first half: the sidebar's placeholder becomes the selected
server's channel tree from voelin-ui-vm's rows (tree_view): nested
channels with their spacers, icons, banners, lock and counts, and the
people in them with their avatar, badges and marks. A TreeModel entity
builds the rows once for both panes on the tree, toolbar and member-card
signals and tells what differs (list::diff, the row operations the Slint
front end applies to its VecModel); ChannelTree is a cached pane over a
virtual list that applies them, so a person who joins is a row inserted
and the scroll stays. The rows carry no `talking`: a talker redraws the
members panel, not the tree (docs/ui.md says so).

A click selects a channel, a double-click joins it (sequence::join_channel:
the move, the prompt for a locked channel's password, a connect into it
without voice), the chevron folds it, a right-click offers Join, fold and
Edit channel (logged: the channel editor is another slice), a click on a
person is logged (their volume dialog is another slice). The password
prompt (Update::password) is a card over the window, asking again when the
server refuses the password. The folds and the selection are kept per
server in ui.tree and found again by the next run.

The shell's cached panes lay out their root at the size the place gives
them (size_full), which the main area needed.

Tests: the sample server's rows, folding and its settings, the round trip
through a closed run, double-click and action join, the password prompt
and its refusal, a move (the exact row operations) and a mute (one row),
a talker leaves the tree alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:56:39 +03:00
faumarayandClaude Sonnet 5.5 d0bcf1f5b2 voelin-gpui: pictures keyed by the file and its stamp, Update.reloaded honoured
GPUI's img(path) keeps what it decoded under the path alone, so a
picture the engine writes again into the same cache file (an avatar or
a server icon that changed) stayed stale on screen. Pictures are now
drawn through a loader keyed by PictureKey, the path and the Stamp the
reference carries (voelin-ui-vm's ImageSource::File): a reference made
after the file changed is another picture, decoded anew, and the lists
that show it compare unequal and draw the row again. perform hands the
paths of Update.reloaded to pictures::forget_stale, which drops the
copies decoded under a stamp the file no longer has and the textures the
atlas made of them. The Avatar widget uses it.

Tests: the key follows the file; a picture rewritten into the same file
is decoded again and the old copy is dropped from the asset cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:40:36 +03:00
faumarayandClaude Sonnet 5.5 b133412700 voelin-gpui: Update.refresh as per-area signals, the shell's panes cached
The "for the next slices" design of the shell's review. The root state
turns the flags of an update into entities with a generation, one per
area (servers, toolbar, tree, member card; crate::signals), raised once
per batch of engine events and once per transition, and the rail, the
top bar, the sidebar and the main area listen to their areas instead of
asking the root whether anything changed for them. The rail, the top bar
and the main area are embedded with Entity::cached and a size of their
own, so gpui-pre renders them again only when they were notified, and
the meter counts the renders of each pane (rail, topbar, sidebar, tree,
main, members) beside the window's frames.

voelin-ui-vm: Refresh::merge, for the flags of a batch.

Tests: a burst raises each area once per batch; a change of the voice
card renders the sidebar with every frame and none of the cached panes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:37:37 +03:00
faumarayandClaude Sonnet 5.5 a2b064bb57 voelin-ui-vm: what the channel tree and the members need of both front ends
The GPUI tree and members pane (the next commits) call these; the Slint
front end keeps its own copies of two of them, since voelin-ui is not
edited in this round (docs/ui.md says which).

- tree::member_card: the card over a member row, built from the session,
  the contacts and the local playback (the Slint members.rs builds the
  same inline).
- servers::sequence::join_channel, join_with_password and connect_into:
  a double-click in the tree, the password dialog's Join, and the connect
  into a channel of a server with no voice (the Slint bind/servers.rs
  has the same three, over logic::join_channel).
- servers::logic::open_member: the card of a client opens or closes.
- settings::UI_TREE (ui.tree), TreeState: the channels each server's tree
  has folded shut and the channel selected, by bookmark id. Like ui.window
  it is the GPUI front end's own key; Slint's tree forgets both at exit.
- image::Stamp is Hash, so a front end can key a decoded picture by the
  file and the stamp it had.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:30:59 +03:00
faumarayandClaude Sonnet 5.5 6b8f933ece Re-wrap the four over-long lines the shell's review named
CHANGELOG.md (the shell's entry), docs/ui.md (the maximized paragraph),
docs/design/gpui-spikes.md (the status paragraph) and the module doc of
voelin-gpui's app.rs: prose only, no word changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:23:36 +03:00
faumarayandClaude Sonnet 5.5 870eb5d938 voelin-ui: the settings page asks the store which identity a bookmark uses
The Slint settings page kept its own copy of Store::identity_id_for and
Store::identity_for (the bookmark's identity if the store has it, else
the default). Both now call the store's, after looking the bookmark's
named identity up: the shell's minors review found the copy, and the
GPUI front end and voelin-ui-vm already use the store's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:23:31 +03:00
faumarayandClaude Sonnet 5.5 9ab56ec973 voelin-gpui: the maximize guard covers the first two reports only
A window opened to be maximized dropped every windowed report until it
was seen maximized, so a resize the user made before the window manager
answered (or under one that never maximizes, a tiling one) was never
kept. The guard is now a budget of OPENING_REPORTS = 2 windowed reports,
the place the window opened with and the configure an X11 window manager
may send at the map; a maximized report ends it, and the reports after
it are the user's. Tests on the GPUI test platform: the root state keeps
the third report, the shell keeps a resize that follows the two. The
sentence in docs/ui.md says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:22:40 +03:00
faumarayandClaude Fable 5.1 0d44148ef5 Merge phase5/gpui-shell-minors: the minors of the shell's gate (the redraw records and the cached-panes note, the maximize restored on X11 after the first frame, the pictures at 1440x960, no DNS in a test, the helpers both front ends share moved into voelin-ui-vm, the ui.window row)
CI / Linux checks (push) Failing after 50m20s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:50:32 +03:00
faumaray daa2111ea1 Merge remote-tracking branch 'origin/main' into phase5/gpui-shell-minors 2026-10-27 22:50:14 +03:00
faumarayandClaude Fable 5.1 cc7c45b371 Merge phase4/protocol-pin-v0.2.0: VoelinProtocol pinned at the tag v0.2.0 (root and spikes workspaces), the spikes' stale lock repaired
CI / Linux checks (push) Has been cancelled
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:18:48 +03:00
faumarayandClaude Fable 5.1 5710aa9f79 docs: building.md says tag, not rev, and warns about cargo update -p; the seam's header names 17.9 (review nits of the pin move)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:18:48 +03:00
faumarayandClaude Sonnet 5.5 463ce872f2 docs/ui.md: corrections to the minors round's records
Update's description lists the gateways to look up (Update::discover), the
Wayland maximize is said to be expected, not seen (it was not run here), and
three lines of the new text are wrapped like the rest.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:55:51 +03:00
faumarayandClaude Sonnet 5.5 fd6bc19c78 docs: the pin is the tag v0.2.0
CHANGELOG.md, "Unreleased": the line that VoelinProtocol's CHANGELOG offers
consumers when they pin (the sign-out lists a key once, Debug of the
messages prints <redacted> for secrets). docs/building.md names the tag, how
a later release is taken and the spikes' own lock; docs/ci.md and
docs/architecture.md name the three crates and the tag, and ci.md says that
the deploy key, the host key and the read check of the CI step are the same
for a tag. docs/session-seam.md: 17.9 records the move (the commits, the lock
edited by hand and why, what "For consumers" meant for the tests, what ran),
and the four sentences that named the old rev name the tag or the pin of
task 34.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:17:53 +03:00
faumarayandClaude Sonnet 5.5 6938dbed3a Pin VoelinProtocol at the tag v0.2.0
The three entries of [workspace.dependencies] (voelin-identity, voelin-proto,
voelin-model) were pinned by rev c5bb6b9 and are now { git, tag = "v0.2.0" }
(a45c154), and so is voelin-model in spikes/gpui. Cargo.lock of both
workspaces changes in those packages only: the three sources, and
voelin-model 0.1.0 -> 0.2.0 (the crates' manifests are otherwise the same
at both revisions, so the lock was edited by hand and checked with
--locked; `cargo update -p` also moved eleven unrelated edges, such as
windows-sys 0.61.2 -> 0.52.0, and was discarded). One revision of each
crate in both locks. THIRD_PARTY_NOTICES.md is unchanged
(scripts/notices.sh --check is clean).

What "For consumers" of the protocol's CHANGELOG lists for this pin:
- KeyStore::sign_out lists a device key once. The test that unbinds a device
  key whose row carries a device-only binding counted it with `contains`; it
  now counts one entry in `unbound` and none in `removed`, and a new test
  does the same for Forget (one entry in `removed`, none in `unbound`). Both
  fail with the pin at c5bb6b9.
- Debug of Hello, Welcome, Server and others prints <redacted>: no test of
  the client compares a Debug text of a protocol message.
- The conformance suite still has 17 cases; the two places that named the old
  rev in a string or a comment name the tag.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:03:05 +03:00
faumarayandClaude Sonnet 5.5 dccedf2fcd spikes/gpui: Cargo.lock follows voelin-platform's zbus change
ed49c28 (zbus on async-io alone in every binary) changed what the spikes'
graph enables of tokio and zbus, and the spikes' lock was not refreshed:
`cargo build --locked` in spikes/gpui failed on main with "cannot update the
lock file". The lock loses three dependency edges and nothing else: tokio's
signal-hook-registry and tracing, and zbus's tokio. No package is added,
removed or moved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:45:58 +03:00
faumarayandClaude Sonnet 5.5 4f85b5539e docs: the shell's minors round recorded, with the gate's four risks
docs/ui.md: a paragraph in the shell section for the minors round, the run
under openbox before and after the maximize fix (the same copy of a database
that says maximized: true: not maximized and overwritten with false before,
maximized and kept after), the maximize beside the position caveat of "For the
next slices" with the one race it cannot rule out, and the four risks the gate
found by reading: the server on screen not remembered across restarts, an open
form dropped without asking on a rail click, Hold to talk staying on if voice
drops while held, a tiling compositor's tile stored as the window size.
The spikes report's status paragraph says the shell was gated and its minors
closed on this branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:40:06 +03:00
faumarayandClaude Sonnet 5.5 f7ebab0859 docs/ui.md: the ui.window row of the settings table, and assets.rs in the step 9 note
The settings table lacked the key the shell added: ui.window, JSON
{width, height, x?, y?, maximized}, no default, written by the GPUI front end
only. The note on what reads crates/voelin-ui/ui until Slint goes lists
assets.rs's include_bytes! of logo.svg beside the parity test, build.rs and
fonts.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:08:49 +03:00
faumarayandClaude Sonnet 5.5 a77ccc0415 voelin-ui-vm: the server sequences both front ends ran twice are one
The GPUI shell repeated the Slint crate's connect, observe, gateway lookup,
save and remove of a server, its default nickname, its FallbackSecrets and its
settings opening and key registration. They now live once and both front ends
call them:

- voelin_ui_vm::servers::sequence: connect_voice(_to), observe,
  discover_gateway, gateway_found, select_server, save_bookmark,
  save_and_connect, delete_bookmark, bookmark_form and default_nickname, as
  transitions over the state, the Cx and a Backing (the store, the secrets,
  the identity a connection uses). The commands, the status line and what to
  keep go out through the Update as for every other transition; a new field,
  Update::discover, asks the front end to look a gateway up (the thread hop
  stays with each front end: Later in GPUI, later() in Slint). stream_peer is
  the one input a front end gives (Slint's codecs; GPUI passes none).
- voelin_ui_vm::settings::open_settings and register_keys; a front end adds
  its own key (ui.window, studio.ui) through a function it passes, so Slint's
  settings page still lists what it listed.
- voelin_store::FallbackSecrets (feature keyring) and Store::identity_for.
- voelin-ui: the methods of servers/bind.rs, open_settings and default_secrets
  call them, so their call sites are unchanged; host.rs gets transition_with
  and the discover arm of perform. voelin-gpui: AppState's methods and the
  Backend call them. What cannot move is named in docs/ui.md.

voelin-ui-vm now depends on tracing (the sequences log as the copies did): one
line of Cargo.lock, THIRD_PARTY_NOTICES.md unchanged (scripts/notices.sh
--check clean), cargo deny check clean. The sequences have ten tests over a
fake front end (commands, status, store, secrets, gateways), open_settings and
Store::identity_for one each; the GPUI and Slint suites pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:05:46 +03:00
faumarayandClaude Sonnet 5.5 01bf128c58 voelin-gpui: the connect test makes no DNS query
a_connect_reaches_the_engine_and_its_answer_reaches_the_rail connects a
server called ts.example, and a connect looks the server's gateway up:
SRV queries for _tsgws._tcp.ts.example sent to the resolver (docs/ci.md
says tests use no DNS). The test now marks the lookup done before the
connect, as the second connect of a run finds it, and its comment says so
(it also claimed nothing left the machine).

strace -f -e trace=connect,sendto,sendmsg,sendmmsg on the lib test binary:
the old binary's test sends to 127.0.0.53:53 (and asks nscd over a unix
socket); the new one, alone and with all 79 tests of the binary, makes
no connect and no send at all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:32:14 +03:00
faumarayandClaude Sonnet 5.5 806f9c6f2e docs/ui: the shell and swatch pictures at 1440 by 960
The committed pictures were 1438 by 935 (and the form 1280 by 800): taken
on a screen as large as the window, where openbox fits the window and its
frame into the screen. Regenerated the five shell pictures and the two
swatch pictures on a headless X display of 3840 by 2160 (scripts/gpui-shot.sh
under spikes/gpui/headless.sh; the form with xdotool clicks and typing), all
exactly 1440 by 960 and truecolour. docs/ui.md and the script's header now say
the screen must be larger than the window, and how the form was taken.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:31:30 +03:00
faumarayandClaude Sonnet 5.5 302524a144 voelin-gpui: a window left maximized is maximized again, and stays remembered so
GPUI asks for a maximized window before it maps it, and an X11 window manager
manages a window only from its map (openbox loses the request), so a window
the last run left maximized opened at its restored size, and the next close
overwrote maximized:true with false.

MainView now zooms the window at its first frame when it was opened to be
maximized and is not by then (zoom toggles on X11, so a maximized one is left
alone). The root state keeps what such a window reports as not the user's
until the window has been seen maximized, so a run that ends first, or one
whose window manager never maximizes, leaves maximized:true as it found it;
a maximized window is kept with the size it returns to (X11 reports the
screen's). GPUI's test platform has no zoom, so the tests count the request
and play the window manager's answer; the X11 behaviour was seen under
openbox on a private Xvfb and is recorded in docs/ui.md. CHANGELOG notes it.

Also wraps the module comment of app.rs that the previous commit left long.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:29:29 +03:00
faumarayandClaude Sonnet 5.5 7c0f385f2f docs: a part's notify draws the whole window, not just the part
The records said the shell's parts draw only when what they show changed.
In gpui-pre 0.3.10 a child view embedded with .child(entity) is rendered
on every frame (only Entity::cached and AnyView::cached reuse a subtree),
so a part that is told tells the window, and the window draws every part.
Correct the shell section of docs/ui.md, the status paragraph of the
spikes report and the module comments of the shell and the root state,
and add to "For the next slices" the gate's notes: heavy panes cached and
Update.refresh turned into per-area signals, Update.reloaded ignored and
img() caching by path, SettingChanged for audio and playback not reloaded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:12:52 +03:00
faumarayandClaude Fable 5.1 0d32ac25f0 Merge phase5/gpui-shell: slice 1 of the GPUI front end, the desktop shell (the store at start, the server rail, the sidebar, the top bar, the main area, window state in ui.window, the bookmark and connect actions through voelin-ui-vm)
CI / Linux checks (push) Successful in 40m16s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 19:07:32 +03:00
faumarayandClaude Sonnet 5.5 8773d8df5b docs/ui.md: the idle figures name the commit they were measured on
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:29:56 +03:00
faumarayandClaude Sonnet 5.5 770943cde9 docs/ui: the swatch pictures without the line of state
The window's line of state (the version, the connections, the engine events,
the seconds up) is gone with the shell: the swatch page fills the window, so
the two pictures are made again with the binary of this branch
(scripts/gpui-shot.sh swatch 1440x960, dark and light).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:27:07 +03:00
faumarayandClaude Sonnet 5.5 2e961eb411 docs: the GPUI desktop shell (docs/ui.md, CHANGELOG, the spikes report's status)
docs/ui.md, "The GPUI front end": what exists now (the store at start, the
shell's entities, the quiet tick), the shell's section with its pictures (the
empty shell and a server on screen, dark and light, and the server form, made
with scripts/gpui-shot.sh on a headless display), the eleven actions against
the Slint callbacks, the store, the window's place and what the shell leaves
out, the figures idle (0.3 to 0.5 % of a core, 192 MiB, no frame drawn while
nothing happens) and what was seen against the TeamSpeak 3 development server
(connect, mute, disconnect, reconnect, close with no ghost client); the
slice list says the shell is done and the channel tree is next, and "For the
next slices" says what the shell settled (the event task, the tick, the close
grace) and what it found (the focus the root's handlers need, the window
manager's say over the position).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:24:56 +03:00
faumarayandClaude Sonnet 5.5 b218059a20 voelin-gpui: the close grace sleeps inside the runtime
`runtime.block_on(tokio::time::sleep(CLOSE_GRACE))` makes the Sleep before
block_on enters the runtime, which panics ("there is no reactor running") on
the GPUI thread; the foundation had it because no slice opened a session, so
the grace never ran. The first end-to-end close against a server (the TS3 dev
server, a connected window closed with Alt+F4) found it: exit status 101 after
the engine had sent the close. The sleep is made in an async block now, as the
Slint front end does, and a test calls the wait from a thread that is no
runtime thread (it fails with the old form).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:24:30 +03:00
faumarayandClaude Sonnet 5.5 6b4341ab8c voelin-gpui: the desktop shell, the server rail, the sidebar, the top bar and the main area
Slice 1 of plan section 6 step 3 (docs/ui.md, "The GPUI front end"). The window
is the shell of ui/shells/desktop.slint, as entities that observe the root
state and tell the window only when what they show changed (they compare their
view of the state, so an engine event about a talker, a tick or a setting that
is not the theme's draws nothing):

- shell/rail.rs: the saved servers as avatars with their tints, initials,
  presence dots, unread and live marks, the selection pill and ring, the plus
  that adds a server and the settings button; a second click edits a server,
  as the Slint rail's double click does.
- shell/sidebar.rs: the server on screen with its stats, the place of the
  channel tree (slice 2), the voice card (disconnect, copy an invite, hold to
  talk) while voice is connecting or connected, and the user card with the
  microphone and sound buttons.
- shell/topbar.rs: the page's title, the search box and the settings button;
  the last two are logged until their slices exist.
- shell/main_panel.rs: "No server selected" with the way to add one, or the
  server on screen with Connect, Disconnect and Edit.
- shell/form.rs: the server form (address, name, nickname, password; Save,
  Save and connect, Cancel, and a Remove that asks twice) in the place of the
  main area until the dialogs slice.
- shell/toast.rs: the status line as a toast for a few seconds.

The eleven callbacks of bind/servers.rs that the shell has are GPUI actions
(shell/actions.rs: select, connect, disconnect, mute the microphone, mute the
sound, push to talk, edit, save, save and connect, delete, invite): a click
dispatches one, the window's root view handles it by asking the root state.
The window takes its title from the server on screen ("Voelin - Nightfall"),
keeps a focus of its own so that actions always find their handlers, tells the
root state where it is (ui.window), and opens where it was left (the size
always; the position where a screen still shows it and the window manager
honours one). The logo is served by the assets.

scripts/gpui-shot.sh finds the window by its title's prefix now that the title
follows the server.

Tests on GPUI's test platform draw the window and click it: a server added
appears in the rail, a click selects it and titles the window, a connect
reaches the engine, an engine event updates the rail and the cards, the form
adds, edits and removes, the toast goes, the window's place round-trips, an
idle window is not told, the sample servers fill the shell.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:53:03 +03:00
faumarayandClaude Sonnet 5.5 e66238847d voelin-gpui: the store at start, the shell's actions on the root state, quiet loops
The window opens the client's store as the Slint front end's run() does
(backend.rs): the database in the platform's data directory (VOELIN_DATA_DIR
moves it), the settings service on it with the UI's keys, the secrets (the OS
keyring, memory when it refuses), the default identity (made and kept when the
store has none), the chat history and the settings handed to the engine. The
state starts from the store's bookmarks, the settings' theme and text size
(a development switch still wins), and the sample servers of VOELIN_DEMO_UI
through the app's own events with nothing sent to the engine or kept.

AppState gains the callbacks of bind/servers.rs that the shell has: select a
server (and observe it through its gateway or query login, the gateway looked
up on the engine's runtime and handed back through Later), connect and
disconnect voice, mute the microphone and the sound, hold to talk, copy an
invite, and add, edit, save-and-connect and remove a bookmark, all through
voelin-ui-vm's logic; perform() carries out an Update as far as this front end
has the parts (commands, status, what to keep, the theme settings). It keeps
the window's place in ui.window at the tick and at close, and opens the window
where it was left if a screen still shows its corner.

The engine-event task takes what is queued (BATCH, 64) in one update with one
notification and yields to GPUI's executor between steps; the tick counts and
notifies nobody, since nothing the shell shows moves with the clock.

Tests: one per behaviour on GPUI's test platform (the store's servers, select,
save, edit, remove, connect, the other commands, observe, the sample servers,
the theme settings, the window's place, the burst and the quiet tick), and a
connect through a real engine with no connector, which answers that none
serves the address.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:34:14 +03:00
faumarayandClaude Sonnet 5.5 bc390f433c voelin-ui-vm: the setting ui.window, the main window's size and position
WindowState (size, position when the platform tells one, maximized) kept as
the optional JSON key ui.window: whole pixels, a damaged value refused by its
validation, none until a run has left one. A key of its own, not a field of
the ui blob (which both front ends read) and not in appearance_keys() (which
the Slint front end registers): the GPUI front end registers and writes it,
the Slint one does not know it. Its stored value survives in the database
either way, as every unregistered key does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:34:14 +03:00
faumarayandClaude Fable 5.1 ba224e1dff Merge phase5/gpui-foundation: the foundation of the GPUI front end (Rust 1.95, ashpd on async-io with zbus on one executor, crates/voelin-gpui on gpui-kit 0.8.1, the root entity and the engine's event loop, VoelinTheme with Inter and Lucide, the meter)
CI / Linux checks (push) Successful in 1h10m33s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 15:22:04 +03:00
faumarayandClaude Sonnet 5.5 d84b54270c docs/design/gpui-spikes.md: the status paragraph records the foundation's review, gate and minors round
The report's status paragraph said the foundation landed and stopped there, and
that the figures on the page were still 0.8.0's. It now says the foundation was
reviewed and gated the same day (no blocker, no major, six minors), lists the
minors that are closed in the commits after it, points at docs/ui.md "For the
next slices" for the risks left to the slices, and excepts the two video cases
the review ran again on 0.8.1 from "still 0.8.0's".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:35 +03:00
faumarayandClaude Sonnet 5.5 2e22fd567c docs/media.md: the portal capture no longer needs a tokio runtime to start
The Portal note said `start` needs a tokio runtime because zbus runs on it. Since
the move of ashpd to `async-io` (e325b65) zbus runs every connection on an I/O
thread of its own, whichever thread builds it, and the note in portal.rs says
so (corrected in ed49c28); this record was not among the four the gate listed
and had been left behind. `stop` is the one that needs the runtime, and only to
close the portal session in the background (elsewhere the session closes with
the connection): the note now says both.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 8f3d809e8a voelin-gpui: fonts.rs points at the report's "Open choices for step 3", which exist
The module comment sent the colour emoji to docs/design/gpui-spikes.md,
"Emoji", a section the report does not have (the colour emoji gap is a
paragraph of spike 2, and the choice is under "Open choices for step 3"): the
same dangling pointer docs/ui.md had in the slice 4 line, found by grep in the
round that fixed that one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 e5f8821f67 docs/ui.md: "For the next slices", the risks of the gate and the review; the report's quiet-machine figures
The risks the Opus gate and the review of the foundation left to the slices
that meet them, each with where it sits in the code: the engine-event task
drains its channel without yielding, the tick notifies the root every second,
voelin-platform's hotkey portal calls tokio::spawn (start it on the engine's
runtime as Slint's GlobalPtt::start does), PortalCapture::stop closes the
portal session only inside a tokio runtime, gpui-component's ThemeRegistry
observer overwrites VoelinTheme's mapping on any registry change, the parity
test and build.rs read crates/voelin-ui/ui (they move at step 9), system
mode's first frame is Light until the colour-scheme portal answers, the gate's
deviations from the report's mapping table (bg-rail not mapped, one scrim for
three, gpui-base's non-colour tokens not written), and the close grace not
seen end to end until a slice opens sessions.

docs/design/gpui-spikes.md: "the 1440p60 figures were not reproduced on
0.8.1" now carries the review's quiet-machine re-run of the two cases (static
61 fps, raw 59.1 fps, load average 8 to 12, llvmpipe).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:31:05 +03:00
faumarayandClaude Sonnet 5.5 5c94b15820 voelin-gpui: the parity test notices a second brush or string in theme.slint
The test compared the brush and string declarations of theme.slint by name
only (one backdrop, one font-family and the mode string), so a second brush or
string token in the Slint file passed unseen while docs/ui.md said a token on
one side only fails the test. It now asserts the brush declarations are
exactly {backdrop} and the strings exactly {mode, font-family}, and a test
adds a brush and a string to a copy of the file (a mutant) and checks both are
named: red with the previous rule ("backdrop-soft goes unnoticed"), green
with this one.

A Rust-only second brush or string is still not seen (tokens.rs has one
gradient and one family that the test cannot enumerate); docs/ui.md says so
instead of promising it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:29:02 +03:00
faumarayandClaude Sonnet 5.5 977b942cd0 docs/ui.md: slice 4 points at the report's "Open choices for step 3", which exist
The list of slices sent the chat slice to a section "Emoji" of
docs/design/gpui-spikes.md, which has none (the colour emoji gap is a
paragraph of spike 2). It now names the section "Open choices for step 3" and
the two open choices the chat slice touches there, emoji and links.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:45 +03:00
faumarayandClaude Sonnet 5.5 caf77561a9 about-assets.md: the Lucide 1.43 catalogue of gpui-kit-assets embedded in voelin-gpui
voelin-gpui embeds gpui-kit-assets' catalogue (Lucide 1.43.0, 1,818 icons,
beside 12 icons of the crate's own under its Apache-2.0 licence) behind the
client's own 1.48 set, and the notices named only the 1.48 set. The new line
has the same copyright holder, and the ISC and Feather MIT texts already
below are the catalogue's (its LICENSE-LUCIDE). THIRD_PARTY_NOTICES.md is
regenerated with scripts/notices.sh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:17 +03:00
faumarayandClaude Sonnet 5.5 5af85b4aa2 docs/design/gpui-spikes.md: the lock figures of the foundation, 292 entries with their two sources
The size paragraph said gpui-kit adds 279 entries (208 new names) to
Cargo.lock. The foundation's lock has 1,321 entries against main's 1,029: 292,
218 of them new names. 279 come from gpui-kit and 13 from voelin-gpui's
`gpui-pre` `test-support` dev-dependency, which ships in no binary (the lock
without that line has 1,308 entries).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:25:04 +03:00
faumarayandClaude Sonnet 5.5 ed49c283a2 voelin-platform: zbus on async-io alone in every binary (notify-rust z), and a test for the order of ashpd's callers
ashpd 0.13.13 keeps one session connection per process (a static in its
proxy.rs), and zbus 5.19 picks that connection's executor once, from
Handle::try_current() on the thread that builds it, when both its `tokio` and
`async-io` features are compiled in. The first ashpd caller therefore decided
the executor of every later portal call: a tokio caller first, then a caller
with no runtime (a GPUI foreground task), panics with "there is no reactor
running" (get_property("version") sets up zbus's property cache, which calls
tokio::task::spawn). The merged binary was safe only because GPUI's
colour-scheme call builds the connection before the engine's portal calls.

voelin-platform's notify-rust asks for `z` (async-io) in place of
`z-with-tokio`, and the stand-in portal's zbus dev-dependency for `async-io`
instead of `tokio`: a test binary with both features shows the panic even when
the binaries do not have it. `cargo tree -e features -i zbus` now names
`tokio` nowhere; Cargo.lock loses zbus's tokio edge and tokio's tracing edge
(THIRD_PARTY_NOTICES.md is unchanged).

tests/proxy.rs gets the gate's probe shape on a private dbus-run-session bus
(skipped with a printed reason where none can be made): a tokio caller first,
then a caller with no runtime. It fails with the panic on the tree before this
change, and still did with only notify-rust moved, which is why the
dev-dependency moved too.

The four records that described the move wrongly are corrected:
docs/design/gpui-spikes.md "Dependencies", the comment of
PortalCapture::start, voelin-media's Cargo.toml and CHANGELOG.md (whose
Slint-only sentence goes: the Slint app's zbus connections move to async-io
threads too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:24:19 +03:00
faumarayandClaude Sonnet 5.5 3f4dc700af voelin-gpui: the meter's /proc test waits for a CPU tick instead of burning 60 ms
this_process_can_be_read_on_linux burned CPU for 60 ms of wall time and
asserted that some thread group used a tick (10 ms) of it. On a busy machine
this thread gets less than a tick in 60 ms: with 5 busy loops on the test's
core, 39 of 40 runs failed at `!threads.is_empty()`. The test now burns CPU
until a second reading shows the process's tick count above the first and a
thread group above its own (a 30 s deadline only ends a hang, as
docs/testing/load.md asks), then asserts; 40 of 40 pass under the same
recipe (taskset to one core, 5 busy loops, 40 runs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:19:30 +03:00
faumarayandClaude Sonnet 5.5 7cabc2c13d docs/ui.md: which of the GPUI tests need a display
The Tests bullet said the tests need no display and then named
tests/launch_failure.rs, one case of which starts the binary on the test
display of VOELIN_X11_TEST_DISPLAY (skipped without it, like the X11 tests of
voelin-media and voelin-platform); the other case needs no display at all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 10:10:11 +03:00
faumarayandClaude Sonnet 5.5 d3fa8d85f0 docs: the spikes' README and report no longer put the repository on Rust 1.94
Since 5ce5c0d the repository is on 1.95.0, but spikes/gpui/README.md still
said no gpui-kit builds with "the repository's Rust 1.94" and the report's risk
table said "the client is on 1.94". The README now says the 1.94 the
repository used before 5ce5c0d (the E0658 demonstration with TOOLCHAIN=1.94
stays as the historical evidence), the risk row says the client moved to 1.95.0
in 5ce5c0d (seven lints fixed), and the report's "Settled for step 3" sentence
about the same failure names the 1.94 of before that commit too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:49 +03:00
faumarayandClaude Sonnet 5.5 6852204277 voelin-gpui: Later::run says what its answer promises
The doc said `false` "when the window is gone". The loop that drains the jobs
learns that the entity was released only when a job reaches it: the first job
sent after the release still answers `true` and is never run, and only the
next call is refused (a hotkey or decoder thread that calls run() after the
window went and before another job could so believe a job was queued that
never ran). The doc says that now ("false once a job has found the window
gone", true promises that the job was queued), and a test pins the order: the
job after the release is queued and never runs, the one after it is refused.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:21 +03:00
faumarayandClaude Sonnet 5.5 efc7db57a3 voelin-gpui: closing the window gives the engine time to send the session closes
The window's close sends CloseSession for every session (AppState::shutdown)
and ended the app straight into runtime.shutdown_timeout(2 s), which waits for
blocking tasks only and drops the engine's async tasks: the commands could go
with the runtime and leave ghost clients on the servers until they time out.
voelin-ui sleeps 500 ms in that case before shutting its runtime down
(app.rs after ui.run()); run() does the same now. shutdown() returns how many
sessions it told the engine to close, the close handler keeps that number for
run() (the App and its entities are gone once GPUI's loop has returned), and
run() waits CLOSE_GRACE only when it is not zero. A comment in run() tells the
slices that add another way to end the app to call shutdown() too.

The GPUI window cannot open a session in this slice, so the wait is not seen
end to end; the tests pin the count: with an engine a state holding a session
answers 1 and a state with none 0, without an engine 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:10 +03:00
faumarayandClaude Sonnet 5.5 a4694e944b voelin-gpui: a window that cannot open ends the app with the reason, not a hang
When open_main_window failed (no usable Vulkan or GL driver), run() stored the
error and called cx.quit() inside the launch callback. GPUI's Linux platform
calls that callback before it starts its event loop, and calloop's
EventLoop::run clears its stop signal on entry, so the quit was lost: the
binary stayed alive with no window and no message (reproduced on a private
Xvfb with VK_DRIVER_FILES, __EGL_VENDOR_LIBRARY_DIRS and LIBGL_DRIVERS_PATH
pointing nowhere: exit 124 under `timeout`, nothing in the log after "Creating
colormap"), and the `failure` that main was to print was never returned. The
quit is a foreground task now, which runs inside the loop: the same run exits
with status 1 and "cannot open the main window / Failed to create surface".

With no display server at all GPUI starts its headless platform, whose
open_window succeeds with a window that draws nothing, so the same silent hang
came from there; open_main_window refuses a compositor named "headless" with
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server".

tests/launch_failure.rs starts the built binary both ways (the driver case
under VOELIN_X11_TEST_DISPLAY, skipped where the machine's driver is found
anyway; the display case needs none) and fails when the process outlives two
minutes; with the old cx.quit() the driver test fails after 120 s, with the fix
both pass in a third of a second. docs/ui.md ("Running it") says what a missing
driver and a missing display look like; CHANGELOG.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:41:53 +03:00
faumarayandClaude Sonnet 5.5 97d51fb226 CI and docs: libxkbcommon-x11-dev and libxcb1-dev, which the GPUI front end links
The release binary of voelin-gpui links libxcb.so.1 and libxkbcommon-x11.so.0
(`readelf -d`: libxcb, libxkbcommon, libxkbcommon-x11, libasound, libm, libc)
and opens libwayland-client.so.0, libvulkan.so.1 and libEGL.so.1 by name
(`strings`). The development packages of the first two were in no package
list, so a workspace build on the Ubuntu runner (CI builds every member)
would have failed to link: .github/actions/system-deps, the CI example in
docs/ci.md, docker/linux.Dockerfile ("the same libraries as CI") and the apt
line of docs/building.md name libxkbcommon-x11-dev and libxcb1-dev now, and
building.md and docs/ui.md say what the GPUI front end links and what it
opens by name (an earlier sentence of mine had all of them opened by name).
Not run: no Ubuntu runner or image here; this machine builds with Nix's
libraries, where the headers come from the same projects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:10:37 +03:00
faumarayandClaude Sonnet 5.5 d4f9e59ed6 scripts/gpui-shot.sh: ImageMagick 6 (convert, identify) where magick is not there
Debian and Ubuntu ship ImageMagick 6, which has no `magick`; the script now
uses `convert` and `identify` when `magick` is missing, and its header names
what it needs (xdotool, xwd, ImageMagick). Both branches were run on Xvfb
:98 (the second with a PATH that has `convert` and `identify` only): the
swatch picture is 1440x960 and the window closes with exit code 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:47:36 +03:00
faumarayandClaude Sonnet 5.5 172d6247c6 docs: "The GPUI front end" in docs/ui.md, the spikes report's status and notes, README
docs/ui.md gains the section "The GPUI front end": what exists (the crate's
files and what each does), the root state and its three loops (the engine's
events through a foreground task, the one-second tick, Later for other
threads, and why Later exists: GPUI's AsyncApp is not Send), the tests and why
they use gpui-pre's test-support and not gpui-kit's, how to run it (what
GPUI needs at run time: Vulkan or OpenGL, lavapipe in software, a window
manager on X11), the development switches in a table, how the screenshots are
made (scripts/gpui-shot.sh, and the NixOS recipe over the spikes' headless
display) with the two swatch pictures, the theme in its two layers with the
mapping from the Voelin tokens to gpui-component's ThemeColor fields, the
mode, Inter and Lucide, and what is next: the plan's slices 1 to 9 with what
each takes from the Bridge, the conditions the spikes set (the emoji patch
before chat, a GPU run before the viewer, Wayland's preedit) and the steps
around them.

docs/design/gpui-spikes.md: the status paragraph says the foundation of step 3
landed (items 1 to 4 and 6 of its list; the shell is next) and points to
docs/ui.md; "Before step 3 can start" and "Dependencies" say the Rust move and
the ashpd move are done, with what zbus does with both features and the test
that calls ashpd with no tokio runtime; the size bullet gives what gpui-kit
adds to the root lock (279 entries, about 195 packages on Linux, two new
licences); a paragraph after the first slice's list says which items are done
and how.

README.md: the crate's bullet says what the window has so far.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:16:22 +03:00
faumarayandClaude Sonnet 5.5 a2fad4569a voelin-gpui: the backdrop's GPUI gradient in one place (Backdrop::to_gpui)
GPUI's gradient has two colour stops and the Slint backdrop three, so what
GPUI draws is the first and the last; that choice was written inline in the
swatch page. It is a method of the token now (theme/mod.rs), with a test that
it is the gradient of the first and the last stops and not of the middle one,
and the swatch calls it. No change on screen.

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (31 tests).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:15:31 +03:00
faumarayandClaude Sonnet 5.5 109e1d1839 voelin-gpui: the cost meter as a development switch (VOELIN_METER=1), logged once a second
meter.rs is spike_common::meter of the GPUI spikes
(spikes/gpui/common/src/meter.rs, docs/design/gpui-spikes.md) without the
measuring run's summary and exit: once a second, on a thread of its own, a
log line (target voelin_gpui::meter, level info) with the process's CPU in
percent of one core, the resident memory, the CPU of each group of threads
(a thread's name without its trailing number: `llvmpipe-12` is `llvmpipe`,
which tells the software renderer's share, work a GPU would take, from
GPUI's thread, the engine's runtime and the codecs; the busiest first, groups
under 0.5 % left out), the app's own counters per second and the voice
connections as a gauge:

  cpu 11.9% rss 250.4 MiB | threads llvmpipe 5.9 voelin-gpui 5.0 |
  engine_events 0.0/s ticks 1.0/s renders 1.0/s later_jobs 0.0/s | connections 0

The counters (`Counters`: engine events handled, ticks, renders, jobs run
through `Later`, connections up) are shared with the root state and the main
view, which count in `handle_event`, `tick`, the later task and `render`; the
numbers come from /proc/self (a note and a warning say so where there is none;
rustix's `param` for the page size and the clock tick, Linux only, no new
package: the lock gains the edge). The line is a pure function with a test,
as are the thread grouping and the stat parser (a name with spaces and
parentheses), and one test reads this process and checks it has threads and
memory. The root state's tests now also check the counters (events, the
connection gauge, three ticks, a job from another thread).

`VOELIN_METER=1` starts it (dev.rs parses it with the other switches).
Running the debug binary on the swatch page on Xvfb :97 logs the lines above
(about 12 % of a core when idle, the software renderer 6 to 11 % of it, one
frame a second); the window closes with exit code 0. The default log filter
now leaves out GPUI's "failed to load font .SystemUIFont" warning, which
every start printed (gpui-component asks for the platform UI font before the
theme names Inter; the text system falls back).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (30 tests), cargo deny, `scripts/notices.sh
--check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:12:56 +03:00
faumarayandClaude Sonnet 5.5 2690b8a802 voelin-gpui: VoelinTheme (every token of theme.slint, light and dark) written into gpui-component, Inter, the client's Lucide icons, the swatch page
Two layers, as the spikes' report settled:
1. `VoelinTheme`, a GPUI global (theme/tokens.rs): the 43 colour tokens of
   ui/theme.slint for light and dark (generated from the Slint file by a
   script, then checked by the test below), the backdrop gradient, and
   `Metrics`: the radii, spacing, type sizes, weights, control and shell
   sizes and the two durations at a text size factor (font-scale: the
   sidebar's `264 * max(1, scale)` and the top bar's `max(44, control + 8)`
   included).
2. gpui-component's `ThemeColor`, written on every change (theme/components.rs):
   the base of the report's table (background, foreground, border, input,
   ring, overlay; primary with hover, active and foreground from the client's
   accent; secondary and muted from surface-2 and its raised steps;
   gpui-component's "accent", which is a hover background, from surface-3;
   popover; list, table, sidebar, title and status bar, tabs, switch, slider,
   scrollbar, link, selection; danger, success, warning and info with a hover
   and active made by mixing and a text that is white or the window's ink,
   whichever contrasts more) and the 28 `button_*` fields a theme file would
   derive from them (without them the buttons keep the default theme's
   blue). The mixing, the WCAG contrast and `readable` are `Rgba` methods with
   tests. The window's background is bg-app; the backdrop and bg-rail stay in
   `VoelinTheme` (gpui-component has no rail, and GPUI's gradient has two
   stops against Slint's three: the swatch draws the first and the last and
   says so).
The mode (`Choice`: system, light, dark) follows the window's appearance in
`system` (`observe_window_appearance` calls `set_system_appearance`; a light
or dark choice ignores the window) and sets the platform's window appearance
where the platform draws the frame (macOS; a no-op elsewhere). The text size
factor rewrites the metrics, the theme's font size (font-body) and radii.

theme/slint_parity.rs reads ui/theme.slint at test time (`include_str!`) and
compares every declaration of the `Theme` global with tokens.rs by name: the
colours (dark and light), every length with the file's own arithmetic (a
small evaluator of `*`, `+`, `max()` and token references) at four text
sizes, the weights, durations, the font family and the backdrop's stops, and
fails on a name on one side only or a declaration kind it does not know. A
mutation check (accent, radius-md and the top bar's formula changed in
tokens.rs) failed the tests with the names of the tokens, then was reverted.

fonts.rs adds the five Inter TTFs of the Slint front end (`include_bytes!`)
to GPUI's text system; the theme names the family. build.rs turns the 147
Lucide 1.48 SVGs of crates/voelin-ui/ui/assets/icons into a sorted table of
`include_bytes!` (std only, no new dependency) that assets.rs serves as
gpui-component's `icons/<name>.svg` before gpui-kit-assets' Lucide 1.43
catalogue (1,830 paths, which answers the rest and, as it does, an error for
a path it lacks); a test checks that `mic.svg` is the client's, differs from
the catalogue's, and that other icons fall through.

Development switches (dev.rs): `VOELIN_OPEN=swatch`, `VOELIN_DEV_THEME=
dark|light|system`, `VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE` (the Slint
front end's names where they exist). swatch.rs is the page: the 43 colours in
the groups of docs/ui.md's "Theme tokens" table with name and value (a test
checks each token is in exactly one group), the backdrop, radii, spacing,
the type scale, buttons, switches and checkboxes of gpui-component and 16
icons; it scrolls when the window is smaller. scripts/gpui-shot.sh makes the
screenshot headless the way scripts/shots.sh does for Slint (xvfb-run, or
GPUI_SHOT_HEADLESS=1 under headless.sh on NixOS; Wayland, the session bus
and the XDG directories out of the environment), then closes the window with
Alt+F4 and reports how the app ended. docs/ui/gpui-swatch-dark.png and
-light.png are its output (Xvfb :97, openbox, lavapipe via wgpu's Vulkan
backend, the debug binary, 1440x960, truecolour: a 256-colour reduction would
change the tokens' values; the Slint pictures live in docs/screenshots/, the
task asked for docs/ui/).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets, the
build script included), `cargo test -p voelin-gpui` 26 tests, cargo deny,
`scripts/notices.sh --check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:07:10 +03:00
faumarayandClaude Sonnet 5.5 27a13fcc7c voelin-gpui: the root Entity<AppState>, the engine's events through a foreground task, the one-second tick, later()
crates/voelin-gpui/src/app.rs holds the root entity: the toolkit-free
voelin_ui_vm state (`AppState<Vec<ChatLine>>`) and `Social`, with
`events::handle` as the one dispatch of an engine event (the entry point
both front ends use; its Update's engine commands are sent, its warnings
logged, the rest belongs to the slices that draw it). Three loops, spawned by
`AppState::new` and ended when the entity is released:
- the engine's events: a foreground task awaits the tokio receiver of the
  hosted engine (no reactor needed, as the plan says), `this.update` and
  `cx.notify()`: spike 3's hotkey task;
- the tick: a loop of `background_executor().timer(1 s)`;
- `Later`, for other threads: GPUI's `AsyncApp` holds an Rc-based weak
  handle and is not Send (read in gpui-pre's async_context.rs), so a thread
  that wants to touch the entity holds a Send handle that queues a boxed
  closure; a third foreground task, which owns the cloned AsyncApp, runs it
  with the entity. This is the Slint front end's `later(|app| ...)`.
engine.rs repeats the ~25 lines of voelin-ui's `HostedEngine::start` (the
engine on a tokio runtime, its events forwarded into an unbounded channel):
that type lives in the Slint crate (crates/voelin-ui/src/app.rs), which this
crate cannot depend on and this task does not touch. dev.rs reads
VOELIN_WINDOW_SIZE. lib.rs `run()` logs through tracing (`VOELIN_LOG`, else
`RUST_LOG`, else a filter that shows GPUI's adapter line), starts the engine's
runtime, opens the window on the entity and, on close, tells the engine to
close the sessions and ends the app. view.rs shows the one line of state the
task asked for: version, voice connections up, engine events handled, seconds
up; each part moves by one of the loops.

Seven tests, none needing a display (GPUI's test platform): an injected
engine event (a voice state) reaches the entity and its status line, the
entity notifies its observers, the tick runs once per advanced second, a job
from another thread runs on the entity, and a real engine (HostedEngine on a
tokio runtime) delivers a real event (a setting changed by a command) to the
entity through the same task; the window-size switch parses and refuses
nonsense. The real-engine test calls `allow_parking`, as GPUI's test
scheduler calls a wake from a tokio thread a non-deterministic test
otherwise. The tests use `gpui-pre` (renamed `gpui`) with its `test-support`
as a dev-dependency, pinned `=0.3.10` beside gpui-kit's own pin: gpui-kit's
`test-support` feature names the optional `gpui-fast` backend in weak
features, which makes cargo lock gpui-fast and its tree and pins taffy to
0.15.0 for every build (reproduced in a scratch project: 793 packages
without the feature, 820 with it). The lock gains only gpui-pre's own
test-support crates (proptest and its few, futures-concurrency, postage);
THIRD_PARTY_NOTICES.md does not move (dev-dependencies are out of it) and
cargo deny passes.

Run on Xvfb :97 (headless.sh) with the debug binary: the window opens in
0.1 s, shows "Voelin 0.0.1-alpha · 0 connections · 1 engine event · 2 s up"
and, four seconds later, "... · 6 s up" (the one engine event is the real
engine's own at start); Alt+F4 ends the app with exit code 0 in 132 ms.
Checked on Rust 1.95.0: fmt and clippy -D warnings (all targets, --no-deps),
`cargo test -p voelin-gpui` (3 runs, 7 tests each), cargo deny.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:56:08 +03:00
faumarayandClaude Sonnet 5.5 8f234e0051 voelin-gpui: the GPUI front end's crate on gpui-kit 0.8.1, a window titled Voelin that opens and closes
The second front end of plan section 6 step 3: crates/voelin-gpui with
the binary voelin-gpui, in the workspace's members and default-members next
to voelin-ui (two binaries until parity; voelin-ui stays the app).
gpui-kit is a workspace dependency pinned `=0.8.1` (the version the three
spikes were rebuilt on in the commit before). The crate asks for gpui-kit
and the app's name and id from voelin-platform (APP_NAME as the window's
title, APP_ID as its app id); `run()` opens one window whose
`on_window_should_close` ends the app, and returns the error when the
window cannot be opened (no display).

Checked on Xvfb :97 (headless.sh: openbox, a private bus, lavapipe through
wgpu's Vulkan backend, state under .scratch): the debug binary opens a
window named "Voelin" (xdotool search) in 0.3 s and ends with exit code 0
when openbox sends the close request (Alt+F4).

Cargo.lock: 279 more package entries (208 new names; no existing version
moved, other versions of 61 names were added beside theirs): GPUI's
gpui-pre family, wgpu 30, gpui-component with its Markdown, HTML, chart and
table support, cosmic-text, the Linux platform crates. The root workspace
already carried Slint's and the codecs' dependencies, so this is 195 new
packages on Linux, not the ~1,000 of the spikes' lock (which has the root's
packages too). deny.toml and about.toml name the two licences no crate of
the tree had: 0BSD (enum-iterator and enum-iterator-derive, under
gpui-component) and CC0-1.0 (notify 8, the file watcher of gpui-component,
and tiny-keccak, under the X input method client of gpui-pre-linux); no
other licence, no advisory, no ban and no source is new (`cargo deny
--locked --workspace check`: advisories, bans, licenses and sources ok).
THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about
0.9.2, no warning; `--check` clean). There is no new clarification: cargo-about
finds every text.

Docs: CHANGELOG, docs/ui.md (the structure tree names the crate and the
intro the second front end), docs/building.md (the dependency list: Vulkan
or OpenGL at run time, what GPUI loads by name, a window manager on X11; no
new development package), README (the crate list and the run command) and
CLAUDE.md, which had no crate sentence (it only says "own crates"): it now
says there are two front ends on one engine and what they share.

Checked on Rust 1.95.0: cargo fmt and cargo clippy -D warnings --no-deps
over the own crates (all targets); cargo deny; scripts/notices.sh --check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:46:59 +03:00
faumarayandClaude Sonnet 5.5 6fc84e9e44 spikes/gpui: rebuilt on gpui-kit 0.8.1 (gpui-pre 0.3.10, wgpu 30), nothing regresses; the pin result in the report
0.8.1 came out on 2026-10-26, a day after the 0.8.0 the three spikes were
measured on. `=0.8.1` in spikes/gpui/Cargo.toml and `cargo update -p
gpui-kit --precise 0.8.1` move 40 packages of the lock (1,069 entries
before, 1,065 after): gpui-kit, gpui-base, gpui-component and
gpui-kit-assets to 0.8.1, the 19 gpui-pre crates to 0.3.10, wgpu 29 to 30
(naga 29 to 30), taffy 0.13 to 0.15. No source change: the spikes build as
they were, release, on Rust 1.95.0.

One run of each README's measurement command on Xvfb :96 (openbox, a
private bus, lavapipe through wgpu's Vulkan backend, state under .scratch)
with the machine at a load average of 64 to 80 (the 0.8.0 runs: 28 to 53):
- composer drive.sh 8 PASS, ime.sh 3 PASS, windows drive.sh 11 PASS, no FAIL;
  the composer's screenshot differs from the committed one in 579 of 900,000
  pixels;
- video: static 1440p 22.7 fps shown at 259 % CPU (11.4 % of CPU per fps,
  0.8.0: 11.7), raw 1440p60 13.4 fps at 174 % (13.0; 0.8.0: 12.5 to 13.1),
  memory flat with drop_image, +408 MiB in 10 s without it; windows-both
  123 % of a core, the preview shown 14.4 of 15 a second, memory flat.
The frame rates are lower than 0.8.0's because of the load; the cost of a
shown frame is the same. The report says plainly that the 42 to 49 fps raw
1440p figures were not reproduced on 0.8.1, only the cost per frame was.

So the pin is gpui-kit 0.8.1, exactly. docs/design/gpui-spikes.md ("The
version to pin", the status paragraph, the setup table) and the spikes'
README say so; its figures stay 0.8.0's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:36:31 +03:00
faumarayandClaude Sonnet 5.5 e325b65d42 ashpd on async-io in voelin-media (pipewire) and voelin-platform (portal)
GPUI's Linux backend enables ashpd's `async-io` feature, and ashpd 0.13.13
refuses `async-io` and `tokio` at once (compile_error! in its lib.rs), so
a binary could not hold the portals and gpui-kit. voelin-media's `pipewire`
feature (the screen-cast and camera portals) and voelin-platform's `portal`
feature (global shortcuts, file chooser, proxy resolver) now ask ashpd for
`async-io`; Cargo.lock loses ashpd's edge to tokio and nothing else (the
package set is the same: THIRD_PARTY_NOTICES.md is unchanged and
`scripts/notices.sh --check` clean).

What zbus 5.19 does with the features (read in its abstractions/mod.rs):
with both `async-io` and `tokio` compiled in it picks per connection, tokio
when a tokio runtime is current on the calling thread, else async-io with an
I/O thread of its own. The workspace has both on already (notify-rust asks
for zbus/tokio, secret-service and others for its defaults), so the engine's
portal calls, which run inside its tokio runtime, still use tokio; a caller
with no runtime (GPUI's foreground executor) gets the I/O thread. Built on
its own, voelin-media has `async-io` only.

The source needed no change beyond a doc comment (capture/portal.rs said
the connection needs a tokio runtime). tests/proxy.rs gains a second test on
the same stand-in portal: ashpd's ProxyResolver called from a thread with no
tokio runtime, polled by hand, gets the answer. Both tests run again under
`dbus-run-session` on a bus of their own (the harness takes the test's name).

Checked on Rust 1.95.0: fmt and clippy (-D warnings, --no-deps) of the own
crates; `cargo test -p voelin-platform -p voelin-media`: all pass, including
tests/proxy.rs (2 tests), the portal-less-bus tests of both crates run with
no session bus (`unavailable_without_session_bus`, the `proxy::tests` that
need none), and tests/pipewire_apps.rs against a private PipeWire and
WirePlumber (found on PATH, ran: 2 passed in 2.7 s). The live portal
(a desktop's screen-cast dialog, the shortcut binding) was not exercised:
no desktop session is used by these runs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:18:00 +03:00
faumarayandClaude Sonnet 5.5 5ce5c0db82 Rust 1.95: rust-toolchain.toml, the workspace rust-version and the gateway image; the lints 1.95 adds
gpui-kit (every gpui-pre 0.3.x) calls std::hint::cold_path, stable since
1.95.0, so the client moves from 1.94 to 1.95 before the GPUI front end
can build (docs/design/gpui-spikes.md, "Rust 1.95 or newer"). rustc 1.95.0
(59807616e 2026-04-14), cargo 1.95.0, clippy and rustfmt of the same
release were used.

rust-toolchain.toml and the workspace's rust-version say 1.95;
crates/voelin-gateway/Dockerfile builds from rust:1.95-bookworm (cargo
refuses a 1.94 image once rust-version is 1.95). docs/building.md names
the Rust version for a local build; docs/ci.md says a channel change in
rust-toolchain.toml is all the runner needs (they named no version
before).

Clippy of 1.95 adds `collapsible_match` for an `if` that is a match arm's
only statement, `unnecessary_sort_by` and `manual_checked_ops`; they
flagged seven spots in four crates, none a behaviour change:
- voelin-media capture::forward: a let-else instead of a match whose arm
  holds one `if`;
- voelin-media ffmpeg::sys: `sort_by_key` with `Reverse` (two places);
- voelin-media studio:📷 `checked_div` for the frame interval;
- voelin-stream peer and session: the condition in a local before the
  `if` (a guard would carry a side effect: `remove`);
- voelinctl engine and session: the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:00:40 +03:00
faumarayandClaude Fable 5.1 296664ffa9 Merge phase5/gpui-spikes: the three GPUI spikes (video frames in img(), the composer with preedit, a second window on the shared model) and docs/design/gpui-spikes.md: go for all three
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumarayandClaude Fable 5.1 df3b2074b9 spikes/gpui: voelin-model pinned at c5bb6b9 like the client's crates (one voelin_model in the graph after the keystore merge)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumaray 02b2b470fc Merge remote-tracking branch 'origin/main' into phase5/gpui-spikes 2026-10-27 04:59:04 +03:00
faumarayandClaude Fable 5.1 ee971f30bc docs/design/gpui-spikes.md: the matched --no-drop re-run claims no cause for its rate (review minor)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:59:04 +03:00
faumarayandClaude Sonnet 5.5 8c172f4dc5 spikes/gpui/README.md: the nightly clippy command; report: 9.6 as measured
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:54:24 +03:00
faumarayandClaude Sonnet 5.5 6f2c64aa63 docs/design/gpui-spikes.md: video headline labelled raw, quiet-window pipeline figure, the --no-drop XDamage row explained
The headline video figure (status table, the go paragraph, the software
bullet) is the raw source, frames from memory with no decoder: it now
says so. The pipeline rows (22.9 fps at 1080p, 9.6 at 1440p) were load
artifacts: the page now carries the reviewer's quiet-window run of
pipeline-1440p60 (40.8 fps shown, XDamage 41.3, encoded 50.4, decoded
49.5, process 1047 %, encoder 454 %, llvmpipe 476 %, memory flat, load
23.5 / 30.6; not repeated here, the load stayed above 40), says the
pipeline rows scale with free CPU (the in-process encoder takes 450 to
1000 %) and that the cases are bound by CPU contention, the encoder being
the largest user. The go verdict stays.

The XDamage exception of the --no-drop case is a measurement artifact,
not frames counted and not presented: measure.sh runs damage-count for
69 s with 10 s of warm-up while the case lasts 12 s with 2 s, so the mean
spreads two seconds of window over 59. Second by second the counts match
(13.8 against 13.6; the reviewer's run 5.2 against 5.1) and a re-run with
the counter set to the case's own length gave 6.8 against 7.0 (Xvfb :93,
lavapipe, load 43 / 47). The video README's case row says so. No code
change.

The status paragraph records this round in two sentences (gpui-kit 0.8.1
of 2026-10-26 still unmeasured).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:51:49 +03:00
faumarayandClaude Sonnet 5.5 24069ac170 spikes/gpui: clippy -D warnings clean on nightly (as_chunks, bounded range)
Nightly's clippy flagged the two chunks_exact(4) loops of
common/src/bgra.rs (chunks_exact_to_as_chunks): both now use
as_chunks::<4>() and as_chunks_mut::<4>() (stable since 1.88). Behind
them, because clippy stops at the first crate that fails, it flags the
raw source's `for n in 0u64..` in video/src/main.rs
(for_unbounded_range): now `0..=u64::MAX`, the same loop.

`cargo clippy --locked --all-targets -- -D warnings` is clean on 1.95.0
and on nightly 2026-10-24 (through shell.sh); the README and the
report's clippy sentence say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:45:53 +03:00
faumarayandClaude Fable 5.1 439a47f656 Merge phase4/keystore-task34: the key store follows task 34 (a sign-out keeps every key, only a forget deletes), VoelinProtocol crates pinned at c5bb6b9, the load-proof checkpoint tests
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:42:24 +03:00
faumaray 9c4bd29cb2 Merge remote-tracking branch 'origin/main' into phase4/keystore-task34
# Conflicts:
#	CHANGELOG.md
2026-10-27 04:34:14 +03:00
faumarayandClaude Fable 5.1 997c07b70e docs: the 17.7 row says where the one-second bound went (review minor of the keystore minors round)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:34:02 +03:00
faumarayandClaude Opus 5.5 5c36aae55e docs: the spikes' nightly clippy result as it is
The report and the spikes' README said the spikes pass clippy on 1.95.0
and on nightly; the final run's nightly clippy (1.101.0-nightly of
2026-10-23) has a lint 1.95 does not, chunks_exact_to_as_chunks, which
flags two chunks_exact(4) loops in spikes/gpui/common/src/bgra.rs. Both
now say so; the code is left as it is (clippy on 1.95.0, the pinned
toolchain of the spikes, is clean at every commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:24:09 +03:00
faumarayandClaude Opus 5.5 3167817b89 docs/design/gpui-spikes.md: the three GPUI spikes measured, go for all three
Plan section 6 step 1's report: the setup (Xvfb :91 with openbox, Mesa
lavapipe through wgpu's Vulkan backend, gpui-kit 0.8.0, Rust 1.95.0, the
load of each run), and per spike the figures and checks with a go/no-go
against the plan's criteria:

- video: img() with the port of video.rs' delivery holds 42 to 49 fps at
  1440p60 and 55 to 58 at 1080p60 on the software device, the static
  control 60 to 62; drop_image keeps the atlas flat (without it +1.9 GiB
  in 10 s); a new 1440p picture costs GPUI's thread 6 to 7 ms (a new atlas
  texture and two copies); a persistent texture needs a GPUI change; the
  Slint demo stream compared on the same display at its 720p30;
- composer, IME, chat lines: all checks pass, X11 preedit with fcitx5 and
  Pinyin works, Wayland preedit not exercised headless; colour emoji in
  U+1F600-U+1F640 need a one-line GPUI patch (tried in a scratch build);
  InteractiveText loses clicks shorter than a frame;
- second window: shared root entity, focus, fullscreen, close and the X11
  global hotkey all pass; the shared preview's cost.

Settled for step 3: gpui-kit =0.8.0 (0.8.1 noted), Rust 1.95 (the 1.94
error), ashpd on async-io, the wgpu renderer (not blade) on X11 and
Wayland, Inter and Lucide, the theme tokens against gpui-component's, the
first slice, the plan's risks restated, the open choices, and what this
attempt changed in the interrupted one's work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:18:23 +03:00
faumarayandClaude Opus 5.5 b6f8f16108 spikes/gpui: headless-wayland.sh stops its compositor
nixpkgs' sway wrapper runs sway under a dbus-run-session of its own when
no session bus is set, so the script's kill reached dbus-run-session and
every run left a headless sway behind. It now runs sway-unwrapped, which
is the process it kills, and clears sockets a dead compositor left in its
private runtime directory before it waits for the new one's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:12:16 +03:00
faumarayandClaude Opus 5.5 f9f95dbf0d spikes/gpui: the Slint app's logs stay out of the desktop's state directory
headless.sh and headless-wayland.sh set XDG_STATE_HOME to the run's state
directory as they set the other XDG directories: the Slint app (the
slint-720p30 case) keeps its log files there, and its runs had written
them to the desktop's ~/.local/state/voelin/logs.

measure.sh waits for the Slint app's window (up to 60 s; it took more than
20 s to appear on a busy machine, past the fixed 8 s the case waited) and
then measures it for the case's full length. The video README gives the
static cases and the Wayland run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:38:08 +03:00
faumarayandClaude Opus 5.5 1ffcf690cc spikes/gpui/windows: spike 3, a second window on the shared model
A main window and a Studio-like window (cx.open_window through
gpui_kit::open_window) both render views that observe one root entity: a
counter both change, the push-to-talk state, which window is active, and
the studio's preview. Closing the studio window docks it
(on_window_should_close), closing the main window ends the app, F11
toggles fullscreen, Ctrl+Tab activates the other window. The global
push-to-talk key is voelin-platform's X11 hotkey (XInput2 raw events),
read by a GPUI foreground task. The preview comes from voelin-media's
studio compositor and its preview tap, one BGRA RenderImage shown by both
windows, the replaced one dropped from every atlas. drive.sh runs the
scenario and its checks on the headless display.

From the interrupted attempt, changed here: the window's size after a
fullscreen toggle is logged once the window manager has set it (the
toggle's own bounds are the old ones) and checked (1000x900 back);
drive.sh says how long the app took to end; measure.sh (new) runs the
three cost cases into $OUT instead of the README's commands, which wrote
into the current directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 c81d4ea666 spikes/gpui/composer: spike 2, the composer, preedit and chat lines
gpui-component's Textarea as the composer (auto-grow, placeholder), emoji
from a picker of voelin-ui-vm's emoji archive inserted at the caret,
pictures and file paths pasted as attachments (Textarea::on_paste),
Ctrl+Enter bound to Send in the Input context after gpui-component's own
bindings. Sample messages go through voelin_ui_vm::chat::line and are drawn
as StyledText with one GPUI text run per TextRun inside InteractiveText,
links clickable (masked ones ask first). The preedit is GPUI's own (XIM on
X11, text-input-v3 on Wayland); the spike reads the marked range and
prints it. drive.sh runs the scenario on the headless display, ime.sh the
X11 preedit with fcitx5 and Pinyin.

From the interrupted attempt, changed here: runs instead of highlights, so
each run has its font (emoji runs in Noto Color Emoji, code in the theme's
monospace font: the row's font_family("monospace") resolved to no
monospace font); a sample line of the smileys DejaVu Sans also has; the
picker in the emoji font; the font probe (whose get_font_for_id printed
"?" for every fallback font) replaced by an emoji probe that counts the
glyphs GPUI draws in colour (ShapedGlyph::is_emoji), printed by drive.sh as
findings for the system's and a Noto-only font configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 fd421b9982 spikes/gpui/video: spike 1, decoded video as BGRA RenderImages in img()
video.rs' delivery (deliver, FrameSlot, Handoff, Buffers; video.rs:360-480)
ported to GPUI: the decoder hands over its newest frame only, a converter
thread turns it into an Arc<RenderImage> (BGRA, spike_common::bgra), the
window takes the newest from a Latest in render and drops the one it
replaces from every window's atlas (cx.drop_image). A RenderImage owns its
pixels with no way back to them, so Buffers' reuse cannot be ported.

Sources: --mode pipeline is LocalPreview with SourceId::Synthetic through
the real VP8 encoder and decoder, as Video::demo; --mode raw hands I420
frames from memory to the converter; --mode static (added in this attempt)
is the control: one picture, uploaded once, the window repainted every
frame. --convert rgba measures voelin-media's conversion in place,
--no-drop is the negative control for drop_image, --bench times RGBA
against BGRA. measure.sh runs every case on the headless display, with
damage-count beside it and the Slint app's demo stream for comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:30 +03:00
faumarayandClaude Opus 5.5 c9859bcfb4 spikes/gpui: the GPUI spikes' workspace, environment and meter
Plan section 6 step 1. A Cargo workspace of its own under spikes/gpui (own
lock, not a member of the root workspace, so the root's lock, deny policy,
notices and CI are untouched; it builds into the checkout's target/), on
gpui-kit pinned to =0.8.0. No gpui-kit release builds on Rust 1.94 (every
gpui-pre 0.3.x calls std::hint::cold_path, stable since 1.95), so the
workspace says rust-version 1.95.

- shell.sh: the toolchain (1.95.0, 1.94, stable or nightly, all from one
  pinned fenix), the native libraries, Mesa's lavapipe as the only Vulkan
  driver, Xvfb, openbox and the X tools, Noto Color Emoji and Noto Sans CJK.
- headless.sh: a private Xvfb display with openbox and a private session
  bus, never the desktop's; headless-wayland.sh: sway's headless backend.
- spike-common: CPU by thread group and memory from /proc once a second
  with the spike's counters (meter), proc-meter and damage-count for
  programs without a meter (the Slint app), Inter and the emoji/CJK fonts,
  the client's Lucide icons as GPUI assets, and the BGRA twin of
  voelin_media::convert::to_rgba.

From the interrupted 2026-10-25 attempt, kept; changed here: shell.sh takes
1.94 and nightly from the pinned fenix (the store paths it named were
garbage-collected), the README's headless-wayland.sh paragraph (sway, not
weston), its fmt command (-p, not --all), its toolchain and nixpkgs lines,
and the font docs (GPUI drops Noto Color Emoji from a fallback chain).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:20 +03:00
faumarayandClaude Fable 5.1 2e985d793c Merge phase5/ui-vm-2: the remaining Slint controllers split into toolkit-free logic (voelin-ui-vm) and Slint bind files, the engine-event transitions in vm::events::apply, the ui-vm gate follow-ups (plan section 6 step 2)
CI / Linux checks (push) Successful in 25m39s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:59:44 +03:00
faumarayandClaude Sonnet 5.5 f183b22b63 voelin-store: the writer of the blocked-checkpoint test paces itself by its own commits
The first version of this test (2cbb816) still failed under heavy load, with
the sign-out itself returning DatabaseBusy. The cause is the writer's fixed
pause of 5 ms: when disk pressure makes each of its commits take 100 ms and
more, it holds the writer lock nearly all the time, and the sign-out, whose
busy timeout is the default five seconds, never gets it between two commits.
(The commit message of 2cbb816 blamed the writer's synchronous = FULL; the
setting is right to mirror the app, but it was not the cause.)

Reproduced without load by delaying every pwrite64 of the process by 700 ms
(strace -f -e inject=pwrite64:delay_enter=700ms): the test of 2cbb816 fails
with DatabaseBusy from the sign-out in two runs of two, this version passes in
two of two. The lib test of 2cbb816 passes with the same delay and with fsync
delayed by 3 s as well.

Now the writer pauses ten times as long as its last write took (5 ms at least),
so its share of the lock stays under a tenth whatever the disk does, and the
sign-out starts only after the writer has written once (a thread of a busy
machine can start after the whole sign-out is over, which made "the writer
never ran" a failure of the machine). A drop guard ends the writer if an
assertion of the test fails first.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 10:54:10 +03:00
faumarayandClaude Fable 5.1 4491ecee25 Merge main (3930ef2) into phase5/ui-vm-2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Fable 5.1 785bbd050b docs: the three minors of the Opus gate of phase5/ui-vm-2
docs/ui.md: the app.rs row of the step-3 table points the toolbar and
tree refreshes at servers/bind.rs, where they live; app.rs only calls them.
voelin-ui-vm host.rs: the doc of Update::rest matches the events module
(the Studio's stream, a changed setting, the offline-message answers; the
watched and shared streams are state and go through the stream effects).
CHANGELOG: the two visible fixes of the branch are named instead of
"nothing changes on screen".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Sonnet 5.5 8c891a057e docs: session-seam 17.6 records the double listing in the trait's sign_out
When the device key's own row carries a device-only binding, the provided
KeyStore::sign_out of VoelinProtocol (c5bb6b9) lists the key twice in
SignOut.unbound: in its loop over the identities bound to the account and in the
Auto branch. The tests of this repository use contains and do not mind (a probe
counted two entries for the key with either value of bound_existing_key); the
fix is a follow-up for VoelinProtocol.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:16:21 +03:00
faumarayandClaude Sonnet 5.5 2df0b91edd CHANGELOG: the key store entry in the present tense
"The key store now keeps the device key when signing out ...", with the
sentence that nothing changes on screen yet kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:43 +03:00
faumarayandClaude Sonnet 5.5 9f720d75bd docs: rewrap the four lines of the key store text that passed 80 columns
Two in docs/architecture.md (the sign-out paragraph and item 2 of open
question 10) and two in docs/session-seam.md 17.6 (the voelin-store leak
bullet), refilled to the width of the files. The words are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:31 +03:00
faumarayandClaude Sonnet 5.5 2cbb816686 voelin-store: the two blocked-checkpoint tests no longer decide by the clock
a_reader_that_blocks_the_checkpoint_... and store::tests::a_blocked_checkpoint_...
bounded the wall clock of a checkpoint (1 s) and gave the concurrent writer a
busy timeout of 1 s. A checkpoint ends in two fsyncs, which take seconds under
disk pressure: the review's sequences failed 7 of 8 and 6 of 8 at I/O pressure
of 10 to 30 %, and dd conv=fsync loops beside 32 busy loops made the lib test
wait 6 s and the sign-out 5 s ("database is locked" for the writer,
DatabaseBusy for the sign-out, whose writer neighbour committed with
synchronous = FULL).

The integration test now asserts what it means without a time: the sign-out
finishes, the writer (set up as the app's connections are, synchronous =
NORMAL, a busy timeout of a minute) gets through without an error, and one
checkpoint is made for the four removals. It is renamed from "costs
milliseconds". The lib test sets the connection's busy timeout to an hour, calls
checkpoint_truncate once and requires that it came back while the reader still
held its snapshot (the reader lets go from a watchdog after 30 s, so a
checkpoint that does not give up fails the test instead of hanging it), that the
reader blocked it, and that the timeout is the hour again. With the line that
sets CHECKPOINT_WAIT removed the lib test fails after 30 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:14:22 +03:00
faumarayandClaude Sonnet 5.5 9e9db0e160 docs: CHANGELOG for the key store and the leak, and the old protocol revision named nowhere
CHANGELOG: one line under Changed for the sign-out that keeps the device key
and the identity text that errors no longer repeat.

docs/session-seam.md: the four places that named the old protocol revision (the
reading list of the design, slice 1, the conformance run, the lock merge of the
gate round) are records of that round; they now say "the pin of that round" and
name c5bb6b9 only where it is the revision the statement was checked at (the
suite has 17 cases in the same order at c5bb6b9 too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:51 +03:00
faumarayandClaude Sonnet 5.5 18b280df7e voelin-store: a damaged TeamSpeak identity row is reported by its kind of damage, never by its text
Store::identity and Store::identities read the stored JSON of a TeamSpeak
identity with `?`, so a row whose data was damaged outside the client came back
as Error::Json carrying serde_json's message, and that message quotes a value
it refuses: tsproto reports a key that does not import as an invalid value, the
key string and all. The error reaches status lines, events and logs.

identity_from_json classifies the error as voelin-core's ts::identity::from_json
does (voelin-core depends on voelin-store, so the classification is here too):
Error::Identity { damage: IdentityDamage, line, column } says malformed, cut
short, not an identity or unreadable, and where, and nothing of the text.
Error::Json stays for the bookmarks and settings, which hold no secret.

The key store was checked as the recorded leak (docs/session-seam.md 17.6)
names it, and does not leak: check_teamspeak (keystore.rs) drops the parse
error with `let Ok(..) else`, Columns::level uses `map_or`, and the warning of a
damaged binding names the row's kind and uid. A test pins that too.

tests/identity_text.rs damages a row six ways (a key that does not import, a
counter of the wrong type, syntax, a text cut inside its key, bytes that are no
UTF-8 as a BLOB and as TEXT) through a second connection, calls everything of
Store and SqliteKeyStore that reads or writes it, and looks through the errors
(text, Debug and sources) and every log line at TRACE (a capturing subscriber in
tests/support) for any 8 characters in a row of the row's data. A control shows
that serde's own message quotes the value and that the capture sees a warning.
With identity_from_json returning the old error the first test fails, naming
the quoted key; the key store test is a guard.

docs/session-seam.md 17.6: the leak bullet is closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:35 +03:00
faumarayandClaude Sonnet 5.5 412f909d18 docs: the key store keeps every key at sign-out; the three parts of open question 10 and the duties of the GPUI client (Phase 2 task 34)
docs/architecture.md, "Identities": the sign-out wording follows the trait of
c5bb6b9 (the device key stays, unbound, whether it predates the account or not;
the account record and the synced copies are what it deletes; the release is
the service's operation and the same local sign-out; the deletion of an account
releases every device key and the same sign-out is its local half), and records
the screens' duties as the GPUI client's: the sign-out dialog with "Forget this
device's identity" and an export first, the release in Settings -> Account, and
the delete-account dialog, which must warn that the account's servers become
unreachable and offer an export of the device keys first. The reasons of the
refusal of a synced device key and of the checkpoint are reworded to match
keystore.rs.

docs/session-seam.md 17.6: a bullet for the key store's follow-up, with what it
did and what it did not need (no release call, no "released" record).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:02:31 +03:00
faumarayandClaude Sonnet 5.5 ca142fd3f2 voelin-store: the local half of releasing a device key is the sign-out, and the store needs nothing more
AccountClient::release (voelin-account-client at c5bb6b9) asks the service to
release the key and then runs KeyStore::sign_out with DeviceKeyChoice::Auto, so
the unbind of one key that keeps its data is the sign-out's own step (and a put
of the blob without its binding for a single key). Open question 10 and
protocol 13.6 ask the client to remember nothing: the service holds the
registration of the key, and the client learns that a key is still registered
with an account it signed out of from the service's answer to a sign-in or a
sign-up (CONFLICT, field device). So there is no "released" record and no new
store call; keystore.rs says so, and says the same of the deletion of an
account, whose local half is this sign-out.

Two tests pin what the client relies on after a release: the key is kept byte
for byte and unbound, then is the device key of a record of another account,
and a sign-out of that account keeps it again (its copies go); and a release
whose local half was cut short is finished by a sign-out with Auto, and a
second one finds nothing to do.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:01:42 +03:00
faumarayandClaude Sonnet 5.5 c0e8a533a4 voelin-store: SqliteKeyStore follows task 34, a sign-out keeps every key and only a forget deletes one
The module documents of keystore.rs are rewritten to the rule of open question
10 (accounts design, answered 2026-10-24): a sign-out keeps the device key
unbound whether it predates the account or the client made it for the account
(bound_existing_key is the client's wording and no rule reads it), the
identities only this device holds are unbound and kept, and "Forget this
device's identity" is the only deletion of a key of the device: signed in it is
sign_out with DeviceKeyChoice::Forget(uid), signed out it is KeyStore::remove
(a TeamSpeak identity: Store::delete_identity). The store has no export call;
the docs say where the UI reads the bytes (voelin_key + to_pkcs8, Store::identity
+ ts::identity::export) before it forgets, which also serves the delete-account
dialog's export of the device keys.

What a sign-out still deletes is not a key of the device, and the docs now say
so truthfully: the synced copies of integration secrets (private keys, scrubbed
from the file and its log like any deleted key), the account record (no
secret), and with Forget the device key. That is why SignOutPass stays: the
trait's sign-out removes those rows, and the log is still truncated once after
the last step, not per row, and not at all when nothing was deleted.

The refusal of a synced device key stays and is reworded: the sign-out keeps the
device key, but its first step deletes every synced copy before it reads the
record, so a device key stored synced would be deleted all the same.

Tests (the turned-around ones are in the previous commit): the device key's
whole row is unchanged by a sign-out, with and without the flag; a key that
carries a device-only binding is unbound and nothing else of its row changes;
a sign-out scrubs what it deletes and leaves the kept keys in the file; the
blocked-checkpoint test counts exactly one blocked checkpoint for four
removals (Forget, so the removals are four as before), through a TRACE-level
capture in tests/support; a sign-out that deletes nothing does not checkpoint;
a key kept by a sign-out is exported, forgotten with no trace in the file or
the log, and restored from the export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:58:22 +03:00
faumarayandClaude Sonnet 5.5 4bd3d7a971 deps: voelin-identity, voelin-proto and voelin-model at VoelinProtocol c5bb6b9 (Phase 2 task 34)
The three protocol crates move together, as docs/building.md says: the
identity crate depends on voelin-proto of the same revision, so moving it
alone would put two voelin-proto packages in the lock.

c5bb6b9 is the protocol's main with task 34 (open question 10): the provided
KeyStore::sign_out keeps the device key whatever AccountRecord.bound_existing_key
says (only DeviceKeyChoice::Forget deletes it), and the crate gains Adoption,
Release and REVOCATION_KIND_RELEASED. Nothing in the workspace needed a source
change to compile (cargo check --workspace --all-targets --locked is clean on
1.94); the conformance Fixture of voelin-proto now holds an Arc<dyn Backend>,
and FakeHandle implements it, so the two callers build as they were. The
suite still has 17 cases, in the same order, so the two comments that named
the old revision name c5bb6b9.

Cargo.lock: the three source lines only. `cargo update -p ...` also flips
windows-sys 0.52 to 0.61 and itertools 0.14 to 0.13 in unrelated entries;
those are not taken, `--locked` accepts the file without them.
THIRD_PARTY_NOTICES.md regenerated (scripts/notices.sh): unchanged, the
workspace and git crates are not in it.

The voelin-store tests that pinned the old sign-out (a key made for the
account is deleted by Auto) are turned around here, in the same commit,
because they cannot pass with the new trait: the key stays, unbound, and only
Forget deletes it. The rest of the sign-out follow-up (the module documents,
the refusal wording, the new tests) is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:53:29 +03:00
faumarayandClaude Fable 5.1 3930ef2945 Merge phase5/test-hygiene: test hygiene after the runner-image round (DatabaseBusy twin, closed-port race, the load-only flakes, ts6_banners alone with its server, docs/testing/load.md)
CI / Linux checks (push) Failing after 5m13s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:12:04 +03:00
faumarayandClaude Fable 5.1 8614b120fe docs: load.md records the review's undecodable_video flake and the seven unformatted intermediate commits
The review's 100 whole-binary runs of the head saw
media::tests::undecodable_video_is_noticed_through_the_pipeline fail once
at load 106-146 (untouched by the round); it joins "Seen and left alone".
cargo fmt differed at seven intermediate commits, not six (the shell-only
5c029a9 sits on the unformatted tree); the orchestrator waives per-commit
rustfmt for them, fixed forward in 94195db, history not rewritten.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:11:47 +03:00
faumarayandClaude Sonnet 5.5 f791d3926f docs: testing/load.md names its own commits
The record's table said "this one" for the commit that adds the page; there
are two, the page and its record.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:19 +03:00
faumarayandClaude Sonnet 5.5 376925a96e docs: testing/load.md records the round, its commits and what ran
The record of the round at the top of the page, in the form of the earlier
rounds' records: the branch and its base, the fallback for the unregistered
mao-* agents, the commit table (which commits are the cut-off run's, which are
this attempt's, which are beyond the list), the two hunks dropped from the
cut-off run's tree, and a table of the checks that ran on the final tree. The
scope test's row gets the failures of the earlier tree that only had the first
half of its fix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:03 +03:00
faumarayandClaude Sonnet 5.5 d4ccb8c8b8 docs: testing/load.md, how to make a machine busy and what the load-only tests assert
The recipe of the round (32 busy loops beside many runs of a test binary, a
build before and one after run alternately), the rules the fixes followed, the
table of the tests that failed only under load with their counts before and
after, the account-change test of the seam follow-ups (not reproduced; the
timing of its steps against its deadlines, and the reading of the code that
found no race), the tests seen at heavier load and left alone, and the
engine stage of the live smoke (ts6_banners failed because the test shared the
TeamSpeak 6 server with the others; what the smoke still does not do
reliably). docs/ci.md points to it from the section on the job image.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 ad806606ac Say in the smoke script which of its checks still flake
After the roundtrip and ts6_banners fixes the smoke passed two of three runs
on the head of the branch; the third failed at the directory check of the
TeamSpeak 6 stage, `the directory did not list the stream`. The viewer of that
check ends when it has 30 frames and the script looks for the directory's
`"title"` line, which the viewer prints only if its own gateway session had
connected by then; in the failed run it was still `observe=Connecting`. The
fix is in voelinctl engine (end the viewer on both), not in a round about
tests, so the comment above directory_check records it, with the earlier
`expected output did not appear` of the gateway stage that was seen with the
same engine state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 f508e5bec4 Count frames, not a pause, in the automatic-bitrate test's "not per frame" check
Beyond the list of this round, found by its final whole-binary run: 1 of 150
runs of the voelin-core lib beside 32 busy loops failed in
an_automatic_bitrate_follows_the_stream, at the assertion that the sink is told
the layer's format once per change and not per frame (`left: 2, right: 1`), and
the unchanged test failed 2 of 900 runs of its own beside the same load.

The sink is told twice for the first picture, and the test counted in between:
Streamer::attach tells it the format from the size captured so far (when a
frame has been captured before the attach), and the encoder tells it again
before its first frame, because its record of what it told starts empty. The
test waited for the format, took the count, slept 200 ms and compared; on a
busy machine the encoder's first frame comes later than the 200 ms.

The test now waits until a frame has been handed over (the encoder tells before
it hands over, so both tellings are done), takes the count, waits for five more
frames, and compares: "per frame" is counted in frames. The deadline of 30 s
only ends a hang. 0 failures of 600 runs of the test beside 32 busy loops.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:59:07 +03:00
faumarayandClaude Sonnet 5.5 94195db16a Format four spots of the test changes of this round with rustfmt
cargo fmt on the own crates changed these four places of the commits before:
the match arm of ask_files_until, the closure of the features test, the count
closure of streamer_sends_opus and the call of preview_until in the studio
test. No change of meaning. Each of those commits passes clippy on its own;
rustfmt was not clean in them until this one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:42:19 +03:00
faumarayandClaude Sonnet 5.5 5c029a982a Start the smoke's action when its listener is on the server, not after 3 s
roundtrip started the listener in the background, waited a fixed 3 s and ran
the action (the poke, the private message, the avatar request, the file
upload). A dev server that is slow to let a client in (4 s and more, 13 s
seen, when the machine is busy) left the action running against a client that
was not on the server yet: `error: message: the client is not on the server`,
and `FAIL: private message: the action failed` (the action's client printed
`connected: 2 clients` and the listener's `connected: 1 clients` came after).
That is one of the places at which the earlier steps of the smoke flaked.

voelinctl engine prints `connected: N clients` once its client is on the
server and has seen the presence, for every action; roundtrip now waits for
that line in the listener's log (60 s at most, and not when the listener has
ended) and then 1 s more, for the others on the server to see the listener.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:30:02 +03:00
faumarayandClaude Sonnet 5.5 069fd2ac12 Run ts6_banners with the TeamSpeak 6 server to itself
The engine stage of the live smoke failed in every run that reached it, before
and after every recent branch, at crates/voelin-core/tests/live.rs
`disabled policy must prevent HTTP requests` (ts6_banners, left: 4, right: 0),
while the six tests of the file passed one after the other.

ts6_banners sets and unsets the TeamSpeak 6 server's banners, and it counts the
requests that reach an HTTP server of its own for the images it set, to show
that an engine whose policy is disabled makes none. The server tells every
client that connects while the banners are set where they are, and an engine
fetches what it is told (as it should): the other tests of the binary, which
cargo runs side by side, connect engines to the same server, and their
requests were counted as the engine under test's. Reproduced against the
development servers with the tests in pairs: ts6_banners alone passes (62 s),
with ts6_avatars, ts6_engine or ts6_channel_joins at the same time it fails
(`left: 2` or, in the join test's case, a later count, `left: 6, right: 4`),
and the TS3 and TS6 tests without it pass in any combination. So the test was
wrong, not the engine or the script's ordering: it needs the server to itself.

The TeamSpeak 6 tests that connect now hold a lock shared and ts6_banners
holds it exclusively, so it runs before or after them and not meanwhile. The
smoke is not run with --test-threads=1 for this: that would hide it, not
remove it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:29:42 +03:00
faumarayandClaude Sonnet 5.5 661a607a35 Make two more link and media tests independent of how long the machine takes
Beyond the list of this round, found by its load runs and rarer than the tests
of the list: in about 500 runs of the whole voelin-core lib beside 32 busy
loops, a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks failed 3 times
(the scope had 1 channel, not 5,003) and streamer_sends_opus 2 times (the
`video too` expectation). The fixes are of the mechanism the code shows; the
runs after them (docs/testing/load.md) are too few to count a rate that low.

a_scope_...: the connector waits 250 ms for a link's first snapshot after it
said it is connected, and the test made its 5,000 channels after saying it, so
a busy machine made the session without them. The channels are made first. The
scope is also sent whole only if the presence is in the host's state when it
is asked for, so the test now sends a voice packet of one of the presence's
clients and waits for it to come through: the link takes its events in order,
and a packet of a client comes through only once the presence is in.

streamer_sends_opus: it waited for ten frames of audio and then expected a
frame of video, but audio is made quickly and a busy machine can keep the
video encoder from its first frame for longer. It now waits for ten frames of
audio and one of video, whichever the encoders make first; its deadline, 30 s,
only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:27:19 +03:00
faumarayandClaude Sonnet 5.5 92d02b0e00 Wait for the studio's delivered count in the capture-backend test
Beyond the list of this round, found by its load runs: in 150 runs of the
whole voelin-media test binary beside 32 busy loops, 11 failed, 9 of them in
packets_reach_the_outputs_and_the_studio_is_a_capture_backend at
`assert!(studio.shared.delivered.load(..) > 0)` (the other 2 in
it_composes_into_the_preview_and_follows_commands, fixed in the commit before).

The studio counts a frame as delivered after it has handed it to the capture
sink (`sink.frame(..)`, then `delivered.fetch_add`), so a test that has just
received the frame can read the count before it is made. The test now waits
for the count to become non-zero after it has the frame; the wait for the
frame is 30 s instead of 5 s, and the wait for the count 30 s, which only end
a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:56 +03:00
faumarayandClaude Sonnet 5.5 9d04e0158a Wait for a preview frame of the size and scene asked for in the studio test
it_composes_into_the_preview_and_follows_commands took the first preview frame
after SetPreview and asserted its size. The studio composes from the moment it
starts, at the preview size and rate it has then (480x270, 15 fps), so the
first frame there is can be one of that size, composed before the command was
applied; on a busy machine it is. The 2 s waits for the new scene's colour
and the test's overall 5 s and 10 s limits measured the machine too.

preview_until now reads the preview until a frame that the test takes comes,
and looks at 20 frames at most: the preview keeps only the latest frame, so
few older ones are waiting or on their way, and the number of frames looked at
is the bound by the work. The wait for each frame, 30 s, only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 77304604fe Let the stream task say when it is done in the layer-format test
layer_formats_reach_the_live_stream sent the same layer format a second time
and then slept 200 ms before asserting that no keyframe was asked for, which
tests that the stream task had not got to the command within 200 ms. It is the
task that asks for a keyframe (when the layer's bitrate changes) and it takes
its commands in the order they are sent, from the sink and from the handle
through the same channel. The test now sends a command whose answer is an
error event (Kick of a viewer, 65535, that is none) and waits for that
event: it comes after everything the format set going, and nothing is left to
wait out. A keyframe request the viewer's side makes late is not covered, and
none was seen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 c5bb74ffcb Ask the file list one question at a time in the server-features test
the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list asked for
the lobby's file list every 20 ms until the answer was the one it wanted. The
bus holds 16 events, so on a busy machine the answers fell behind it (and
behind the host's work) and the one that counted was lost in the backlog, or
an answer to a question asked before the host narrowed what it offers was
taken for one asked after.

A helper, ask_files_until, now asks one question and reads the bus until that
question's answer comes, then asks the next only if the answer was not the one
wanted. Every question is answered before the next is asked, so those asked
after the update is pushed are the ones the update can refuse; nothing has to
be told apart by number, and nothing is waited out by the clock. The test
checks that the answer after the server lifted its list came from the host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 81c40a4b09 Wait for the states audio_sources_change_live asserts, and keep feeding the microphone
audio_sources_change_live failed 6 of 200 runs beside 32 busy loops, in two
ways. It waited for the sources' meters and then asserted their state and the
mixer's level and limiter, which are set at other times than the meters: the
state could still be Starting when the meters showed the tones. And its
microphone thread published 50 chunks of 20 ms, one second, and the source
takes what is published only from when it runs, which a busy machine delays
by any time, so the test then waited 5 s for a level that had gone by.

The first wait now includes the state, the mix and the limiter. The thread
publishes until the test has heard the tone (or, as a cap that ends a thread
whose test failed first, 120 s), and the second wait includes the window
source's error and the muted tone's own level, which the test asserted right
after it. The deadlines of the waits, 30 s, only end a hang; what is waited
for is a state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 25be4337a8 State what the preview's rates are, not what a busy machine reaches
The end of local_preview_decodes_the_pattern asked the rates of the second
since the first stats call to be 20 to 40 pictures and 100,000 to 5,000,000
bits a second. How many pictures a second the pipeline manages is a property
of the machine's load, and a second of sleep is longer than a second when the
machine is busy; neither is what the stats are about. What they promise is
that fps and bitrate are the counters' change over the time since the call
before.

The test now times its two stats calls and the sleep between them. The time
the stats measured lies between the two spans that the test measured around
it (from the end of the first call to the start of the second, and from the
start of the first to the end of the second), so the reported fps has to be
the pictures counted in that time, within the rounding of fps, and the
bitrate the bits counted in it, within the cut-off of bitrate. At least one
picture has to have come in the second.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 f9bfd5d305 Check the test pattern's structure, not its pixels within a tolerance
rectangle_span, the pixel check of local_preview_decodes_the_pattern and
test_pattern_through_stream_tasks, asked every pixel further than two columns
from the rectangle's edges to be within 24 per channel of the rectangle's
colour or of the background. The streamer's VP8 speed control lowers the
quality when the encoder falls behind, and a flat colour then moves by 30 and
more per channel (seen: [33, 31, 101] and [50, 33, 48] for the background
[24, 40, 72], [255, 85, 5] for the rectangle [240, 90, 30]), still nowhere
near the other colour. A tolerance of 40 was tried and reverted: it only moves
the load at which it fails.

A pixel is now whichever of the pattern's two colours it is nearer to, and
what the test is about is the row's structure: background, one run of the
rectangle, background. The first and last pixel that are the rectangle's give
the span; everything between them, but the two blurred columns at each end,
has to be the rectangle's too, and the callers still check the span's width
and that it moves. A stray rectangle-coloured pixel in the background
stretches the span over background and fails there.

Before, the two tests failed 4 and 2 of 100 runs each beside 32 busy loops; see
docs/testing/load.md for the runs after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:13 +03:00
faumarayandClaude Sonnet 5.5 0bc6abadfe Name the step in which the account-change test timed out
account_change_cancels_pending_handshake was seen to fail about once in 130
runs of the whole suite under load, and the failure was not kept. Its three
timeouts (5 s for the first handshake packet, 5 s for a packet from a new
socket after the account changed, 2 s for the connection to end after the
account source closed) were bare unwrap()s, so a failure said only that a
timeout had elapsed, at a line. Each now says which step it was.

No race was found, in the test or in the code it drives. The account receiver
has seen its version before the connection is made, so a change after the
first packet always restarts the connection; the restart opens a new socket,
so a packet from another port is a packet of the new connection; dropping the
sender makes changed() fail, which ends the loop with the reason the test
expects. The ways the test can fail are those three deadlines. With the steps
timed (a throw-away instrumented build, not committed), 300 runs of the test
alone, eight at a time beside 32 busy loops, all passed, and the steps took at
most 34 ms, 33 ms and 9 ms against deadlines of 5000, 5000 and 2000 ms. So
the failure needs a stall of seconds, which is the machine's and not a
property of the test; docs/testing/load.md has the numbers and what to do if
it is seen again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:12 +03:00
faumarayandClaude Fable 5.1 de89fddcb6 deps: crypto-bigint 0.7.7, ctutils 0.4.5, rustls-webpki 0.103.16, tokio 1.54.1, webpki-root-certs 1.0.11 (RUSTSEC-2026-0382, -0383, -0385, -0386, -0387); notices regenerated
CI / Linux checks (push) Successful in 37m31s
RUSTSEC-2026-0387 stays on the crypto-bigint 0.5 and 0.6 lines that the
tsclientlib fork pins (p256 0.13 in tsproto-types, crypto-bigint in tsproto);
ignored until 2026-12-20 with the fork's move to p256 0.14 as the follow-up.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:44:31 +03:00
faumarayandClaude Sonnet 5.5 e465a55b9e Give the fallback gateway test a port that stays refused
the_next_published_gateway_is_used_when_one_fails took its "port nothing
listens on" by binding a listener to port 0 and dropping it at once. A port
that is free only for a moment can be given to another socket before the
engine connects to it: the other tests of the binary bind port 0 for their
fake gateways and proxies, and the one that gets the port answers the
connection, so the test then passes over a gateway that is no longer closed,
or fails on the 650 ms deadline.

The test now binds a TCP socket and keeps it, without listening, for its
whole length: the port is taken, so nobody else gets it, and a connection to
it is refused at once. It checks that refusal before it relies on it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 ac957a0c87 Reopen the history database of the gateway test after the engine has closed it
history_on_open_paging_and_offline_messages drops its engine and opens the same
database again for the restart it tests, the same shape as the contacts test
that 0d67dd7 fixed: dropping an Engine does not close the history database, the
engine task ends later and closing the connection checkpoints the write-ahead
log under an exclusive lock, and a History::open meanwhile waits for that lock
only for the 5 s busy timeout, failing with DatabaseBusy on a loaded disk.

The test now waits until the -wal file is gone before it reopens. The helper
that does so (closed) moves from voice_features.rs to tests/common/mod.rs,
which both test binaries declare.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 35408a3dfe Require the portal proxy test's child to report one passed test
The test runs itself again under dbus-run-session and, on a zero exit, returned
without looking at what the child printed. A child that ran no test at all
(its --exact filter matching nothing, as after a rename of the test) also exits
0 and printed "running 0 tests ... 0 passed", so the wrapper passed having
checked nothing. A zero exit now has to come with libtest's "test result: ok.
1 passed;" in the child's output, else the wrapper fails with that output.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:20:03 +03:00
faumarayandClaude Sonnet 5.5 7e63092bcd Say in from_json's doc who reads the identity text through it
The doc said every reader of the TeamSpeak identity text refuses it through
from_json. Only voelin-core reads it through there: voelin-store parses the
same text on its own (keystore.rs check_teamspeak and level, store.rs list),
and drops or forwards serde's message by its own rules. The doc now names
voelin-core and says voelin-store parses it too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:19:48 +03:00
faumarayandClaude Fable 5.1 2ffe5ffb99 Merge phase5/tests-under-runner: the workspace suite green as root inside the runner image
CI / Linux checks (push) Failing after 35m27s
Every machine assumption of the tests fixed (root writes anywhere, no sound
card, no session bus, no GPU, no FFmpeg, no H.264 encoder, no display beyond
xvfb, no TeamSpeak servers, no DNS); a cancelled download's part file removed
after its task stopped (a real defect a test exposed). docs/ci.md: how to run
the suite the way CI runs it. Sonnet review accepted; its three docs minors
are in the last commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:09 +03:00
faumarayandClaude Fable 5.1 e807df40e5 docs: ci.md quotes the right git error, removes root's files, names the bare clone, follows main's loopback and D-Bus tests; .scratch/ ignored
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:08 +03:00
faumaray a8dbc5ba74 Merge remote-tracking branch 'origin/main' into phase5/tests-under-runner 2026-10-25 02:03:16 +03:00
faumarayandClaude Sonnet 5.5 6c8d4bbb61 Bring the status of docs/ui.md up to date with the merge of main 6e0df51
One paragraph: what the merge brought (the session seam, the CI deploy key, the
media codec test and the seam follow-ups, none of it in the UI crates), that the
.set_ counts of the table were counted again on the merged tree and stand, and
where the colour of a chat's avatar is chosen (servers::logic::conversation_tint,
pinned by a test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:37:10 +03:00
faumarayandClaude Sonnet 5.5 08a899cf01 Pin the colour of a chat's avatar with a test that fails when it falls back to black
The ui-vm gate's minor "server_tint falls back to black" was closed by a
fallback in App::conversation_item, `.unwrap_or_else(|| vm::avatar::tint(&title))`,
that no test could fail: replacing it with `.unwrap_or_default()` (opaque
black) left cargo test -p voelin-ui -p voelin-ui-vm green.

The choice of (kind, session) -> colour is now a pure function in
voelin-ui-vm, servers::logic::conversation_tint(state, kind, session, title),
and messages.rs calls it. A test pins the three cases: a server chat of a
server in the list takes the rail's colour, a server chat whose server is
gone takes the colour of its title, and a channel's or a person's chat (with
or without a known server) takes the colour of its title. The titles are
chosen so that the title's colour differs from the server's, and the test
asserts that. App::server_tint, whose only caller this was, is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:36:19 +03:00
faumarayandClaude Sonnet 5.5 9e7452ec2a Merge main (6e0df51) into phase5/ui-vm-2
Main gained phase0/ci-private-dependency (the CI deploy key and the checks
action), phase5/media-codec-test (a media test stated for machines without an
H.264 encoder) and phase4/seam-followups (five flaky tests fixed, the
identity-text leak closed, docs/session-seam.md 17.8 onwards). None of it
touches the UI crates: the merge is clean, with no conflict, and Cargo.lock
and THIRD_PARTY_NOTICES.md are unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:17:40 +03:00
faumarayandClaude Sonnet 5.5 1de2725f19 Remove a cancelled download's part file after its task has stopped
The download test, which 61458df of this branch made wait for the part file,
exposed a defect of the link: a download reports Started just before it opens its part file, and the
open ran on tokio's blocking pool. Link::cancel() aborted the task and removed
the part file at once; when the cancel came between Started and the end of the
open, there was no file yet to remove, the abort cannot stop an open that is
already on the blocking pool, and the open then made an empty `<name>.part`
next to the target after the transfer had been reported Cancelled. The user
sees a leftover file, and a later download with `resume` continues from it.

files::receive now makes the directory and opens the part file with std::fs in
one step (the same kind of small blocking call as Sink::offset and the removal
in cancel, which already ran on the loop), so an abort, which takes effect at
an await, cannot come in the middle of it. Link::cancel() keeps the task's
JoinHandle instead of its AbortHandle, aborts the task, and removes the part
file and reports Cancelled from a task of its own after the aborted one has
stopped: the file the task made is then there to be found, or the task never
got to make one. Cancelled is therefore reported after the removal and after
the task has stopped, where it was reported before both.

The test goes back to the shape it had before 61458df: it cancels as soon as
the transfer is Started (and now fails loudly if it never was). That shape
failed in 10 of 100 runs of the voelin-core lib tests three at a time with 16
busy loops beside them on a 32-core machine, and in the final runs of the CI
test step in the runner image of this task (the second of three); with this
change it failed in none of 200 such runs. The link and files tests pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:07:48 +03:00
faumarayandClaude Sonnet 5.5 443559aa79 Take the keyframe baseline of the layer-format test after the streamer has settled
stream::tests::layer_formats_reach_the_live_stream asserts that telling the
sink the same layer format twice asks for no second keyframe: it drains the
sink's keyframe requests, changes the format, waits for the request that
follows, tells the same format again and expects none within 200 ms. It failed
once ("nothing changed", stream.rs:1326) in the first of the three final runs of
the CI test step in the runner image of this task, with the machine busy with
another job.

Requests reach the sink from the stream going live, from the streamer's own
view of its viewer connecting (PeerEvent::Connected, a moment after the viewer
sees WatchState::Connected, which is all the test waited for), from the
viewer's picture requests, and from a changed layer. The test drained once,
right after the viewer's side was connected, so a request of one of the first
three that arrives later is taken for the one the changed format asked for, and
the real one then arrives after the "same again" and is counted as a change.
This could not be reproduced here (0 in 400 runs of the single test, 32 at a
time with 48 busy loops, nor in 200 runs of the lib tests); the change closes
those windows as far as they can be named: the test waits for the streamer's
own Connected (StreamViewers) as well, and drains until a moment longer than
the merge interval of requests (250 ms) passes with no request, before the
format is changed. The assertions are those of before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:15 +03:00
faumarayandClaude Sonnet 5.5 272de7a13d Read the streamer's stats until they show what the viewer already saw
Two voelin-core tests read Streamer::stats() once, at the moment a consumer had
seen the effect, and the stats lag behind it:

- stream::tests::test_pattern_through_stream_tasks asserted `video_frames >= 15`
  right after the viewer had decoded 15 pictures. The encoder counts a frame
  after the sink has taken it (`sink.send_video(..)`, then `fetch_add`), so the
  15th picture can be at the viewer first: video_frames was 14 with
  captured_frames 15 and the picture on screen.
- media::tests::an_automatic_bitrate_follows_the_stream asserted the layer's
  bitrate in the stats right after the sink had been told the layer's format;
  the stats had 0 (the layer's target is stored by the encoder thread, not by
  the call that tells the sink).

Both now poll for the value with a deadline (5 s, and 10 s as the test's other
waits), which is the same assertion without the order of two threads. Before,
on a 32-core machine with 32 busy loops beside the runs: the first failed on
that assertion in 7 of 150 runs of the stream tests six at a time, the second
in 19 of 120 runs of the voelin-core lib tests six at a time. After, in 200
runs of the lib tests three at a time with 16 busy loops beside them, neither
failed on these assertions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:03 +03:00
faumarayandClaude Sonnet 5.5 61458df625 Cancel the download test's transfer only once its part file is made
link::tests::a_file_is_downloaded_through_the_connection_the_link_opens waited
for the Started state and then cancelled, expecting the part file to be gone
100 ms later. The download reports Started just before it opens the part file
(files::download, then receive), and the open runs on tokio's blocking pool. A
cancel that arrives in between finds no part file to remove (link cancel()
removes it at once and reports Cancelled), the aborted task cannot stop the
open that is already going on, and the part file is made after the cancel:
`assert!(!part.exists())` failed. It did so in the second of the final runs of
the CI test step in the runner image of this task, and in 10 of 100 runs of
the voelin-core lib tests with three of them at a time and 16 busy loops
beside them on a 32-core machine (none in 200 such runs with this change).

The test now waits for the part file itself, which is what "the transfer
waits in the middle" means, and checks that Started was reported.

This is a real, if small, defect of the product that the test exposed: a
cancel in the moment between Started and the end of the open leaves an empty
`<name>.part` next to the target. It is not fixed here: closing it takes
reporting Started after the open (it also feeds the chat and the preview size
limit) or waiting for the aborted task before the part is removed, which is a
change of the transfer code and not of a test. Recorded in the report of this
branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:41:37 +03:00
faumarayandClaude Sonnet 5.5 637ee58979 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flakes this way (lines == []):
it failed in one of eight runs of the CI test step in the runner image of
this task (assertion `left == right` failed: [] left: 0 right: 1 at
session.rs:2541; it passed in the other seven). Several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs.

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one.

The same change is 4be37e1 on phase4/seam-followups (not merged yet; it
measured 1 failure in 300 runs of banner_tests before and 0 in 600 after),
taken here unchanged so that a CI run of this branch does not stop on it and
the two branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 20:08:50 +03:00
faumarayandClaude Sonnet 5.5 26ee8c38c1 Document the fields of the mirrored bridge structs and lift the exemption
The gate minor "field docs on the mirrored bridge structs" was answered with
`#![allow(missing_docs)]` on `bridge` and `studio_bridge`, and the crate's
comment said 400 or so fields. The two modules have 559 pub fields; 210
carried a comment of the .slint files and 349 (288 and 61) had none there.
Each of those is described now, from the code that fills it (the producers
in the view model and in voelin-ui, the settings keys' own documentation,
the gateway protocol's types), and the allow is gone: `#![warn(missing_docs)]`
holds for the whole crate and clippy -D warnings fails on a field without a
comment (checked by deleting one). docs/ui.md and lib.rs give the real
numbers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:56:38 +03:00
faumarayandClaude Sonnet 5.5 9aea876437 Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew fails. The test does not depend on the machine: it failed 9 times
in 300 runs of the single test on a developer machine, and once in the
offline run in the runner image of this task, a CI run that fails one time in
about thirty for it.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

The same change is 9254e08 on phase4/seam-followups (which also fixes four
other tests that fail on their own and is not merged yet): it is taken here
unchanged so that a CI run of this branch does not stop on it, and the two
branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:53:00 +03:00
faumarayandClaude Sonnet 5.5 370eaf94ed Point the references to the controllers the split removed at their folders
`servers.rs`, `chat.rs`, `streams.rs` and `settings_page.rs` of voelin-ui
are `servers/`, `chat/`, `streams/` and `settings_page/` since the split
(the Slint side in `bind.rs`, the decisions in voelin-ui-vm), and
`adopt_server_name` is in the view model's `events`. The comments of
`events.rs`, `app.rs`, `studio/bind.rs` and `dev/bind.rs`, and the
add-server section of docs/ui.md, named the old files. The "before" names in
the table of the `.set_` counts stay: they are the files as they were.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:44:14 +03:00
faumarayandClaude Sonnet 5.5 b439b9fbb2 Count the status line's calls in docs/ui.md as the files have them
Of the 230 `.set_` lines of the seven files at ad20979, 36 are calls of
`set_status(`, not 37: the 37th hit was `set_status_text`, the Bridge write
inside `set_status`, which is one of the ten direct writes already. Say so,
and give the share of Bridge writes (186 of 230) next to the two fractions.
`messages.rs` has 11 `.set_` calls since the offline message's text is taken
in by the view model (the row said 12).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:51 +03:00
faumarayandClaude Sonnet 5.5 f8447ec9f8 Test that a picture of pixels reaches Slint as wide, as high and in place
The length check of the pixels is in `Pixels::new`, but the Rgba arm of
`convert::image` had no test: a picture drawn with its width and height
swapped passed all 22 tests of voelin-ui. A 3 by 2 picture whose pixels
hold their own column and row is converted, and its Slint size and four of
its pixels are read back (the swap fails the test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:20 +03:00
faumarayandClaude Sonnet 5.5 56ce2cb739 Pin the notice kind names and the settings page title again
The social split deleted `notice_names_and_setting_pages` from voelin-ui
without moving it. The Slint side picks the bell's colours and icons by the
kind names ("poke", "mention", "event", "friend") and nothing but the one
"mention" assertion and the Keybinds search pinned them. The names of all
five kinds are tested next to `NoticeKind`, and the "Voice & Video" title
next to the list it is in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:39:49 +03:00
faumarayandClaude Sonnet 5.5 91d70702f3 Take the text of an offline message in before the redraw, not after it
The social split left the offline message's state change in the front end's
`rest` events, which `perform` handled after it drew the conversations:
`refresh_chats` drew the open message while `dm.mail` was still empty and
the inbox row was still unread, and nothing drew the page again. Before the
split `social_event` wrote both ahead of `social_refresh`.

`Event::OfflineMessage` is now taken in by `social::logic::event` like the
other offline events: the text is `Social::mail`, the inbox row turns read,
and a failure is the status line. `events::apply` no longer parks the event
in `rest`, so a tape test in `voelin-ui-vm` sees it (the mutation that
parks it fails the test). `perform` also handles what is left in `rest`
(a setting, the studio's stream, the request answers) before it draws, as
every such event ran before the redraw ahead of the split.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:33:29 +03:00
faumarayandClaude Sonnet 5.5 172bee5337 Say what the tests print when they skip only as precisely as the code does
The table of docs/ci.md quoted one skip message per row, but the tests print
several wordings per piece (for the H.264 encoder: "skipped: no H.264
encoder", "skipped: needs VP8 and H.264 encoders", "no h264_vaapi or H.264
decoder, skipped"; for FFmpeg: "FFmpeg not installed, skipped", "no FFmpeg with
libavformat, skipped", ...), and some live tests return without printing. The
rows now say a skipped line naming the piece, and keep an exact string only
where the code has exactly that one.

The row on DNS and the internet sat under a column headed "The image has no",
which read as if the job had no network; it has, for apt, rustup and crates.
The column is now headed "A test cannot count on" and the row says the tests
use no DNS or internet and names the #[ignore]d ones that would.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:42 +03:00
faumarayandClaude Sonnet 5.5 ac6937289d Name in docs/ci.md the job image the runner really registers
Runner setup told to register ubuntu-24.04:docker://ghcr.io/catthehacker/
ubuntu:act-24.04 while the new section on the tests says the test step runs in
docker.gitea.com/runner-images:ubuntu-24.04. The runner of this machine
(gitea-runner-performance, register script of its NixOS unit) is registered
with ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04, and
`docker ps` shows its CI tasks running that image, so the label line was the
stale one. It now names that image, the network list names its registry in
place of GHCR, and the tests section says it is the image of the
ubuntu-24.04 label.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Sonnet 5.5 cd08498092 Make the documented image run start cargo, and its VoelinProtocol mirror work
The docker run that docs/ci.md prints for the tests under the job image hung
for ever once the apt and rustup setup was done: bash -c execs its last
command, so xvfb-run became the container's process 1 and never started cargo
(probed: with the runner image and xvfb installed, xvfb-run -a as process 1
stays up with an idle Xvfb, and the same command under --init finishes). The
command now has --init. The runner is not affected: it starts its steps with
docker exec.

The hint for the private dependency is part of the block now, so the block
runs as printed: the bare clone is mounted at /protocol.git (it was never
mounted into the container before) and `git config` runs with -C /, because a
git worktree's .git file points outside the /src mount and git config in /src
exits 128 with "gitfile does not point to a valid repository".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Fable 5.1 6e0df5178e Merge phase4/seam-followups: the gate's identity-text minor, the H9 edge list, five flaky tests
CI / Linux checks (push) Failing after 27m35s
An unreadable TeamSpeak identity is refused without its key in the text (the
classification of from_blob shared as from_json); VoiceOptions fields and
Backends::set_account documented; docs/session-seam.md 17.6 holds the complete
engine/ts edge list for the second half; improve_level, the contacts database
reopen, the banner log subscriber, the two localhost tests and the portal proxy
test made deterministic. Sonnet review accepted; its five minors (two more
DatabaseBusy/port races in tests/gateway.rs, a 1-in-130 voice handshake flake,
the from_json doc, the proxy wrapper's success check) go to the next
test-hygiene round.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 17:32:58 +03:00
faumarayandClaude Sonnet 5.5 8541d7c9e5 Document what the Linux job image lacks and how the tests cope
The test step runs as root in docker.gitea.com/runner-images:ubuntu-24.04
with only the apt packages of the system-dependencies action. docs/ci.md now
says how to run the CI's test command in that image with --no-fail-fast, and
lists what the image has no (a regular user, sound card, PipeWire daemons, a
session bus, GPU and VA-API, FFmpeg, an H.264 encoder, Wayland, a browser, the
TeamSpeak dev servers) with what each kind of test does about it. It also
records that two voelin-core tests fail on a machine whose ::1 swallows
connections, whatever the change under test is.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 17:16:19 +03:00
faumarayandClaude Sonnet 5.5 2c9c739732 Make an_unwritable_path_fails_at_once hold for root
The test started a recording at /nonexistent-root-dir/x/clip.webm and expected
an error. Recorder::start creates the missing parent directories, which a
regular user cannot do below / but root can: under the runner image (Gitea
run 1091, docker.gitea.com/runner-images:ubuntu-24.04, root) the call
succeeded, created /nonexistent-root-dir and left a file behind.

The test now builds its unwritable paths in a temporary directory from things
that fail for every user: a path below a regular file (ENOTDIR, so
create_dir_all fails) and a path that names an existing directory (EISDIR, so
File::create fails). The unknown-container name is checked in the same place
and also asserts that no file was created. Reproduced in the runner image as
root with the old test failing and the new one passing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 16:42:41 +03:00
faumarayandClaude Fable 5.1 c91a3b719d Merge phase5/media-codec-test: peer_config_follows_codecs on a machine without an H.264 encoder
CI / Linux checks (push) Failing after 25m38s
The first CI run that could fetch the private dependency failed on this test
under the runner image. It now states preferred_codec's contract on any
machine. Reproduced and shown green inside docker.gitea.com/runner-images:ubuntu-24.04.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 15:34:27 +03:00
faumarayandClaude Sonnet 5.5 81def06144 Test that voice_options hands the version spec on as the spec
After the seam merge VoiceOptions::client_version is the spec string that the
engine resolves when it connects (docs/session-seam.md 17.3), and voice_options
only resolves it eagerly to tell the user at once. The test pins both: no spec
leaves None, a spec that resolves is passed on as written, one that does not
is refused with the message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:29:30 +03:00
faumarayandClaude Sonnet 5.5 f374f5797b Record the round after the gate in the design of the session seam
17.8: the commits of the follow-up round, the five flaky tests (all fixed, how
each was reproduced and what the evidence is, including the two that are
rewrites and the one that was never seen again), and what ran on both
toolchains: fmt and clippy per commit, the lib suite ten times in a row on
each with no exclusions, the integration tests, cargo doc, the workspace check
with the environment that made it build, and the smoke script before and after
on fresh stacks. The status line names the round.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:26:46 +03:00
faumarayandClaude Sonnet 5.5 d677273f06 Bring docs/ui.md up to date with the splits and what is left of step 2
The numbers of the .set_ table are counted with the command the text names, all
on one base (the files before this round's splits, ad20979) where the text
mixed the counts before and after the event move (chat.rs 38 or 33, servers.rs
37 or 32), and now include the social, dev and host files that the text left
out. Plan section 6 step 2 is stated as done, with what is left for the GPUI
step: the rest of app.rs, the small controllers, and the events page of
events.rs, which is no dispatch (the dispatch moved to voelin_ui_vm::events).
The two mirror modules' field docs are said to be exempted by the crate's lint
(349 fields), not documented. CHANGELOG.md's entry for voelin-ui-vm names the
areas that moved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
faumarayandClaude Sonnet 5.5 8aa5d6729b Write the user's gateway requests as a list, not an or-pattern
rustfmt 1.94 (the pinned toolchain) and the nightly rustfmt lay out the long
or-pattern of failure_text differently, so voelin-ui-vm, clean on both when it
was merged, was not any more. A list of the eleven requests is laid out the
same by both; the requests and the answer are the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
faumarayandClaude Sonnet 5.5 c35bbb5ba8 Run the portal proxy test on a bus of its own, or say it checked nothing
voelin-platform's tests/proxy.rs says to run it under dbus-run-session, and
without DBUS_SESSION_BUS_ADDRESS it returned at once. With one set it ran on
the desktop's bus and failed at "the portal leaves the bus": the test has its
stand-in release org.freedesktop.portal.Desktop, and the first call afterwards
starts the real xdg-desktop-portal, which the bus can start by name; it
answers instead of the "missing" the test expects for a minute. A private bus
from plain dbus-run-session starts it the same way (the test failed the same
three times under it here), so the documented way did not work on a desktop
that has the portal installed.

The test now runs itself again under dbus-run-session with a bus configuration
of its own, a session bus without service directories, so that nothing on it
can be started by name. Without dbus-run-session, or when the bus does not
come up, it says "skipped, nothing was checked" with the reason and passes;
when the test ran on its bus and failed, it fails with the output. The
stand-in and the assertions are the ones that were there.

On the bus with the default services the same inner test still fails as
before (checked by hand), and on the bus of its own it passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:32:53 +03:00
faumarayandClaude Sonnet 5.5 a90bb70ee6 Let the test SOCKS proxy dial localhost at the IPv4 loopback
web::tests::pictures_go_through_the_proxy_named_for_each_hop downloads
http://localhost:<port>/banner through a SOCKS5h proxy of its own and asserts
that the proxy was given the name "localhost:<port>". The test proxy then
connected to that name through the system's resolver, and on a machine that
resolves localhost to ::1 only (this one) the server, which listens on
127.0.0.1, was not reachable: the download timed out after 20 s.

The proxy still reports the name it was given, as SOCKS5h says, and dials
localhost at 127.0.0.1 like the server it stands in front of.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 e614a1c3f1 Probe localhost at the IPv4 loopback in the discovery test
discover::tests::without_records_the_gateway_itself_is_asked starts a server on
127.0.0.1 and has the discovery ask the gateway at "127.0.0.1",
"127.0.0.1:9987" and "localhost". The probe connected to the name through the
system's resolver, and on a machine that resolves localhost to ::1 only (this
one) nothing listens there: the third address found no gateway.

The test helper that makes the probe, probing, connects to localhost at
127.0.0.1 instead. What the test checks is that the gateway is asked at the
name localhost, not what the resolver makes of it, so it no longer depends on
the resolver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 4be37e1fd1 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flaked this way (lines == [],
once in a full run of slice 3); several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs. The old
helper failed 1 of 300 runs of banner_tests, and always on a single thread
that meets the callsite first (the new test below).

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one; the new helper failed 0 of 600
runs of the same tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:28:07 +03:00
faumarayandClaude Sonnet 5.5 0d67dd7433 Reopen the contacts database after the first engine has closed it
voice_features::contacts_are_kept_in_the_database dropped its engine and opened
the same database again at once. Dropping an Engine does not close the history
database: the engine task ends later, the history writer is joined there, and
closing the connection checkpoints the write-ahead log under an exclusive lock
with fsyncs. The second History::open waits for that lock only for the 5 s busy
timeout, and fails with DatabaseBusy when a loaded disk makes the close take
longer (seen as 3 failures in 8 runs, 10 in 24 with eight runs at a time).

The test now waits until the -wal file is gone, which SQLite does when the last
connection closes, before it reopens: the restart of a process, as the test
means it. With every fsync of the test process delayed by 6 s (strace -e
inject=fsync,fdatasync:delay_enter=6000000) the old test failed every time at
the reopen with DatabaseBusy, and the new one passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:24:30 +03:00
faumarayandClaude Sonnet 5.5 9254e08daa Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew failed: 8 failures in 300 runs of the single test before this
change, 0 in 300 after.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:21:22 +03:00
faumarayandClaude Sonnet 5.5 96ff0e0028 Write down the complete edge list between the engine and src/ts for H9
17.6 of docs/session-seam.md named two engine-to-ts edges; the Opus gate of the
merge found the rest. Each line was checked with rg and cargo tree:

- the engine into src/ts: Backends::default and register_teamspeak, the uid and
  id rule of the projection, gateway.rs from_blob/to_blob (H5), the public
  voelin_core::ts paths and their users in voelinctl and the UI crates, the
  API docs that link into ts, and the test-only edges;
- what a TeamSpeak connector in another crate cannot do with
  Backends::register (no LocalCtx, no StreamPort): streams across the crate
  boundary need H2 or a public extension trait;
- src/ts into engine-private items (link, stream, files, offline, the crate
  root, settings), with the conclusion that the "by git tag" step needs H1 and
  H2 or a shared vocabulary crate, else voelin-core and voelin-gateway-ts form
  a cycle;
- what else keeps tsclientlib and tsproto in voelin-core's tree, so that the
  exit check needs H5 too, and voelin-store, voelin-stream and
  voelin-gateway-proto lose the dependency;
- the split of stream.rs;
- the same key-quoting leak in voelin-store's Store::identity, not closed.

The H9 row of 11.2 points to the list and no longer says the exit check holds
after H1-H3 alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:20:02 +03:00
faumarayandClaude Sonnet 5.5 84f4a4835f Make cargo doc of voelin-ui-vm pass with -D warnings
RUSTDOCFLAGS=-D warnings failed with twelve errors, none of them new
behaviour: public docs linking to the private server_lines and PRESETS
(plain code spans now), Event::... links in state.rs that name voelin_core's
Event without importing it (voelin_core::Event::..), an unclosed <id> tag in
a bridge field comment (a code span), and three explicit link targets that
the label already resolves to.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:19:17 +03:00
faumarayandClaude Sonnet 5.5 371e4d77c8 Merge main (c60acf9, the session seam) into phase5/ui-vm-2
The engine of main runs on voelin_proto::link::Session; this branch had split
the Slint controllers into <area>/logic.rs (voelin-ui-vm) and <area>/bind.rs
(voelin-ui) before that merge and was never reviewed. One conflict, the one
the Opus gate of the seam merge predicted:

- crates/voelin-ui/src/servers.rs (modify/delete): this branch had split the
  file into servers/bind.rs and voelin-ui-vm's servers/logic.rs; main had
  changed the file for the seam (docs/session-seam.md 17.3). The file stays
  deleted and the changes of main are made where the code now is:
  servers/bind.rs sends ts::identity::to_blob(&identity) in ConnectVoice and in
  both ObserveGateway sends, builds voelin_core::QueryLogin {address,
  allowlisted: false} with voelin_core::QueryTransport for ObserveQuery, names
  ts::identity::DEFAULT_NICKNAME, and its tests import ts::identity::{Found,
  LaunchImport}; servers/logic.rs imports ts::identity::LaunchImport (and
  links ts::identity::import_new), and voice_options keeps the eager
  ts::versions::resolve for the message and assigns Some(spec.clone()) to
  VoiceOptions::client_version (the engine resolves the spec when it
  connects).

Cargo.lock merged without a conflict and differs from main's only by the edge
of voelin-ui-vm to roxmltree, which this branch added (d9de95b).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:18:43 +03:00
faumarayandClaude Sonnet 5.5 563482db72 Document VoiceOptions.nickname and server_password; correct Backends::set_account
Both fields were carried over from ConnectOptions without a doc: what the
nickname is on each kind of server and that an empty one falls back to the
link's nickname parameter; that the server password is Hello.password, falls
back to the link's password parameter and is not the channel's.

Backends::set_account said the connectors use the account (the QUIC
connector's certificate, the TeamSpeak connector's myTS ID proof). No connector
reads ConnectParams.account yet: the TeamSpeak one is given the myTeamSpeak
account through TsConnector's setters, and the QUIC connector does not exist.
The doc says so and names H4 as the step that moves the proof to this hook.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:17:16 +03:00
faumarayandClaude Sonnet 5.5 a856f90c6b Refuse an unreadable TeamSpeak identity without its key in the text
The Opus gate of the merge found that ts_session::inner_options put the raw
serde_json error into the refusal of an identity it cannot read, and tsproto's
key visitor reports a key that does not import as invalid_value(Unexpected::Str(
key), ..), so the private key string reached LinkEvent::Disconnected(Some(text)),
Event::Error and the UI status line.

The classification ts::identity::from_blob already had (malformed, cut short,
not an identity, unreadable, with line and column, never the value) is now
ts::identity::from_json, which takes the JSON text; from_blob and inner_options
both use it, so the refusal is worded in one place. A credential that is not
UTF-8 is refused as "it is not text".

Tests: identity::tests (a key that lost its last two characters: the JSON
reader's own message quotes it, from_json and from_blob do not; no 8-character
piece of the key), ts_session::tests (inner_options), link::tests (the
LinkEvent::Disconnected text through SessionLink with the real connector) and
session_fake (ConnectVoice through the engine: the Disconnected state, the
Error event and every event after it). All three connector-side tests fail with
the serde_json text put back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:16:06 +03:00
faumarayandClaude Sonnet 5.5 bf72d85a22 Split the development switches: the sample data into voelin-ui-vm
dev/logic.rs now has the sample of VOELIN_DEMO_UI as plain values and as
the events a server would send: the servers and their presence, the
pictures (PNG bytes the front end saves), the chats with their pins and
topics, the contacts, the private chats, the poke, the offline messages,
the gateway's events, the notices and the recordings, and the older pages
that answer scrolling up. The helpers that only look at the state (the
divider of VOELIN_OPEN=unread, the first locked channel) moved with it. The
Slint side (dev/bind.rs) keeps the switches, the window and the screenshot,
and feeds the sample through the app's own events; a test replays the
whole sample through events::handle and checks the state it leaves.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:57:42 +03:00
faumarayandClaude Sonnet 5.5 2d6cbf66af Split the social controller: the friends, the bell, the search and the social events into voelin-ui-vm
social/logic.rs now has the contacts as rows (contact_item, people), the
buttons of a contact and what they ask the window to do next, the bell
(notify, the rows, read, clear, open), the search with what each result
opens, and what an engine event does to the friends, the pokes, the offline
messages and the notices (event). events::handle runs that first, then
events::apply, so a front end has one entry point; Social<D> is the state
those keep, with what the messages page keeps as D for now. Refresh got
people, conversations and dm, the host got dm_shown and now_ms, and
Persist.Settings pages are told apart from the new notices. The Slint side
(social/bind.rs) writes the Bridge, shows the desktop toasts and navigates.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:41:29 +03:00
faumarayandClaude Sonnet 5.5 52e39f0b5a Split the settings page controller: the audio form, the switches and the volume dialog into voelin-ui-vm
settings_page/logic.rs now has what the page shows when it opens (the
device choices, the form, the push-to-talk and H.264 switches), what a
change of the form sends to the engine, the microphone test, the push-to-talk
key to register, the crash notice and the H.264 rows, and the client volume
dialog (what it fills from, what it plays and keeps, which client
VOELIN_OPEN=client opens). The audio settings and the clients' volumes are
kept through Persist::Audio and Persist::Playback. The Slint side
(settings_page/bind.rs) lists the devices, owns the hotkey, the codec and
the crash reports, and writes the Bridge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:09:37 +03:00
faumarayandClaude Sonnet 5.5 156df9d95b Split the servers controller: the rail, the card, the tree and the moves into voelin-ui-vm
servers/logic.rs now has what a server does to the state and says in plain
data: which server is shown and forgotten, how it is observed (a plan:
nothing, retry, gateway, query or discover), what finding the gateways
comes to, joining a channel (a move, the password question, or connecting
into it), the members' search, the voice view and the invite link, and the
rail, the server card and the channel tree as rows and values (rail,
toolbar, tree_view, server_tint). The Slint side (servers/bind.rs) keeps
the store, the secrets and the engine commands, and writes the Bridge and
the models from what the logic returns.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 12:57:24 +03:00
faumarayandClaude Sonnet 5.5 02a3b3eab0 Split the chat controller: the chat view, the user's moves and the lines into voelin-ui-vm
chat/logic.rs now has what the chat view shows (the strip, the lines with
their divider and downloads, the pins, the topics and the counts, as plain
data), the lines of a tab or of an open topic (lines_of, also for the Stream
Studio's chat, with the pokes of a private chat's peer), and what the user's
moves do: select and close a tab, send, ask for older messages, mark read,
react, pin, the topics, download, attach and upload. The Slint side
(chat/bind.rs) writes the Bridge and the models from it and calls the
transitions. Poke and its lines moved to voelin_ui_vm::social.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 07:05:58 +03:00
faumarayandClaude Sonnet 5.5 0d2ad3f250 Split the streams controller: the state, the events and the rows into voelin-ui-vm
What we share and what we watch are in the AppState now (Sharing, Watching),
with the transitions of the engine's stream events (apply handles them, the
Stream Studio's stream excepted), the user's choices (watch, leave, volume,
quality, the share dialog's plan, the capture that started) and the rows and
texts of the streams panel, the share card and the viewer, as plain data in
streams/logic.rs with tests of their own. The Slint side (streams/bind.rs)
writes the Bridge, owns the capture and the decoder, and attaches or drops
them as an update says (StreamEffects).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:48:18 +03:00
faumarayandClaude Sonnet 5.5 03d1c3bd07 Move the state transition of every engine event that the AppState holds into voelin-ui-vm
events::apply(state, host, event) changes the AppState for an engine Event and
returns an Update: the parts to draw again (Refresh, each once), the status
line, the engine commands, what to keep (Persist), pictures to decode again,
the password dialog, notices for the bell, the chats that changed, a stream to
watch. Host is what a transition asks while it runs (is the chat on screen,
the store's read markers, the preview limit); the Slint client answers it in
host.rs and carries the update out there, so App::handle_event is
social_event, apply_event and social_refresh. The chat transitions (tabs,
messages, what is read, pins and topics, files), the pictures linked in
chats, the server's name, icon and gateway, joining again and the password
prompt, the last place of voice and the stored volumes moved with it; Spot,
the notice types, own_uids and peer_name moved to the view model crate.

Update::rest hands back the events whose state is not in the AppState yet
(the streams we share and watch, the studio's stream, a setting that
changed); the friends, pokes and offline messages are still looked at by
social.rs before and after. The vm tests replay tapes of events against a
fake Host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:30:39 +03:00
faumarayandClaude Sonnet 5.5 0672b21758 Warn about undocumented public items of voelin-ui-vm
#![warn(missing_docs)] on the crate, with the fields and variants that had
no docs documented (BBCode styles and spans, settings, the tree's input) and
a targeted allow on the two mirror modules, bridge and studio_bridge, whose
fields are those of the Slint structs and are explained by the comments in
bridge.slint and studio-bridge.slint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 12b2773791 Say what docs/ui.md counts, with the true share and the studio's base
The table of controllers still to split now states its measure (every .set_
call, the status line's included), the share of Bridge writes as counted
(four fifths with the status line, two thirds without), the base counts
before the work on voelin-ui-vm (studio.rs 64, settings_pages.rs 52), why the
studio went before streams.rs, and what ImageSource::size() does now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 d9de95b985 Make a picture's size mean it shows, and keep pixels the size they say
ImageSource::size() read a raster file's header, so a cache file that was
cut short or garbled after the header counted as showable, where the Slint
version's decoded image was empty. A raster picture is now decoded to tell
(the first frame, with the limits the Slint side uses) and an SVG must parse
as XML with an svg root (roxmltree, already in the tree through the vector
renderer); the answer is kept per file stamp, and per key and content hash for
a downloaded picture, and decoding runs outside the lock. The size check of
the pixel count no longer overflows on a header that claims u32::MAX.

ImageSource::Rgba holds a Pixels value that can only be made with the right
length, so the Slint conversion cannot hand clone_from_slice bytes that do
not fit (it panics on that).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:52:16 +03:00
faumarayandClaude Sonnet 5.5 f92a14fc84 Fall back to the name's colour for a chat whose server is gone
server_tint answered opaque black for a server that is not in the list,
where the Slint version answered transparent. It now answers none, and the
direct-message list picks the colour of the chat's own title, as it does for
every chat that is not a server's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:31:35 +03:00
223 changed files with 56813 additions and 7311 deletions

No files matched your search

+29 -131
View File
@@ -1,135 +1,21 @@
name: Linux checks
description: Shared Linux validation for Gitea CI and release packaging.
inputs:
protocol-deploy-key:
description: >
Private half of the read-only deploy key registered on the private
Voelin/VoelinProtocol repository (the repository secret
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
visible inside a composite action). The action fails when it is empty.
required: true
description: >
Linux validation for Gitea CI: formatting, Clippy, the build, the tests, the
dependency policy, the third-party notices and the release tooling tests. It
runs after the job has fetched every dependency (the steps before it in
.gitea/workflows/ci.yml: system packages, the Rust toolchain and `cargo fetch`
with the read-only deploy key for the private VoelinProtocol repository) and
has deleted the key (docs/ci.md, "VoelinProtocol access"). This action has no
input and no secret, and every cargo command in it is --offline (or has
CARGO_NET_OFFLINE set where a script or a plugin starts cargo): it needs no key
and cannot use one, so the build scripts, procedural macros and tests it runs
hold none.
runs:
using: composite
steps:
# The workspace depends on the private VoelinProtocol repository over SSH
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
# in seconds and before anything runs cargo.
- name: Install the VoelinProtocol deploy key
# The key reaches this step through the environment only: never in the
# script text, never echoed, no `set -x`.
env:
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
run: |
set -euo pipefail
umask 077
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
exit 1
fi
for tool in ssh ssh-keygen; do
command -v "$tool" > /dev/null || {
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
exit 1
}
done
ssh_dir="$HOME/.ssh"
key_file="$ssh_dir/voelin_protocol"
mkdir -p "$ssh_dir"
chmod 700 "$ssh_dir"
# Whatever the secret store did to the line ends and the final newline,
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
unset PROTOCOL_DEPLOY_KEY
chmod 600 "$key_file"
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
rm -f "$key_file"
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
exit 1
fi
# The fingerprint of the public half, to compare with the deploy key in
# the VoelinProtocol settings.
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
# The reviewed host key from the repository, never one fetched now.
known_hosts="$ssh_dir/known_hosts"
touch "$known_hosts"
chmod 600 "$known_hosts"
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
exit 1
}
while IFS= read -r line; do
case "$line" in '' | '#'*) continue ;; esac
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
# Use this key, and only this one, for the Gitea server; fail rather than
# ask when its host key is unknown or changed. The block goes first: ssh
# takes the first value it finds for each option.
config="$ssh_dir/config"
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
touch "$config"
if ! grep -qxF -- "$marker" "$config"; then
{
cat << EOF
$marker
Host git.faumaray.com
User gitea
IdentityFile $key_file
IdentitiesOnly yes
UserKnownHostsFile $known_hosts
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 30
EOF
cat "$config"
} > "$config.new"
mv "$config.new" "$config"
fi
chmod 600 "$config"
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
# system git runs ssh, which reads the config above. `-F` names it
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
# in $HOME, and a job image may set the two apart.
{
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
echo "GIT_SSH_COMMAND=ssh -F '$config'"
} >> "$GITHUB_ENV"
shell: bash
- uses: ./.github/actions/system-deps
- name: Check read access to VoelinProtocol
# The first thing cargo does, with the same git and ssh configuration, so
# that a wrong key or a changed host key fails here with a clear message
# and not minutes later inside a cargo command.
run: |
set -euo pipefail
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "Voelin/VoelinProtocol is readable with the deploy key."
shell: bash
- name: Install pinned Rust toolchain
run: |
set -euo pipefail
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
export PATH="$CARGO_HOME/bin:$PATH"
if ! command -v rustup >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal --default-toolchain none
fi
if [[ -f "$CARGO_HOME/env" ]]; then
# shellcheck source=/dev/null
source "$CARGO_HOME/env"
fi
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
rustup toolchain install
shell: bash
- name: rustfmt (own crates)
env:
CARGO_NET_OFFLINE: "true"
run: |
set -euo pipefail
packages=$(scripts/own-crates.sh)
@@ -137,33 +23,45 @@ runs:
cargo fmt "${packages[@]}" --check
shell: bash
- name: clippy (own crates, deny warnings)
env:
CARGO_NET_OFFLINE: "true"
run: |
set -euo pipefail
packages=$(scripts/own-crates.sh)
read -r -a packages <<< "$packages"
cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings
cargo clippy "${packages[@]}" --all-targets --no-deps --locked --offline -- -D warnings
shell: bash
- name: clippy (workspace, report warnings)
run: cargo clippy --workspace --all-targets --locked
run: cargo clippy --workspace --all-targets --locked --offline
shell: bash
- name: Build
run: cargo build --workspace --all-targets --locked
run: cargo build --workspace --all-targets --locked --offline
shell: bash
- name: Test (X11 enabled)
run: |
# DISPLAY is assigned by xvfb-run, then expanded by the inner shell.
# shellcheck disable=SC2016
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked'
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked --offline'
shell: bash
- name: Install cargo-deny and cargo-about
# The only cargo commands here that go online: they download two tools from
# crates.io and build them. They read no manifest of this workspace and
# nothing in the job gives them a key.
run: |
cargo install cargo-deny --locked --version 0.20.2
cargo install cargo-about --locked --version 0.9.2 --features cli
shell: bash
- name: Dependency policy
# cargo-deny's own --offline would also stop it from fetching the RustSec
# advisory database, which the check needs (from github.com, no key).
# CARGO_NET_OFFLINE keeps only the `cargo metadata` it runs offline.
env:
CARGO_NET_OFFLINE: "true"
run: cargo deny --locked --workspace check
shell: bash
- name: Third-party notices
env:
CARGO_NET_OFFLINE: "true"
run: scripts/notices.sh --check
shell: bash
- name: Release tooling regressions
+4 -3
View File
@@ -4,7 +4,8 @@
#
# Committed, never fetched while a job runs, so a CI or release build trusts the
# key reviewed here and not whatever answers on the network at that moment.
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
# Read in place by ssh (-o UserKnownHostsFile, in the command line that the fetch
# step of .gitea/workflows/ci.yml gives git: nothing is appended to ~/.ssh) and
# COPYed by docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to
# re-check it and how to rotate it: docs/ci.md, "VoelinProtocol access".
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
+244 -9
View File
@@ -1,7 +1,22 @@
name: CI
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
# Off for pushes and pull requests: run by hand only.
# Runs on pushes to main and on pull requests (not when only docs or Markdown
# files change, apart from THIRD_PARTY_NOTICES.md), and by hand.
#
# The workspace depends on the private VoelinProtocol repository over SSH, so
# the job needs the read-only deploy key (the repository secret
# VOELIN_PROTOCOL_DEPLOY_KEY). The key exists for one step only: "Fetch the
# dependencies" runs `cargo fetch` with it, before any build script, procedural
# macro or test of the repository has run, and deletes it again. Everything after
# that (the composite action .gitea/actions/checks) runs `--offline` in a job that
# holds no key. docs/ci.md, "VoelinProtocol access", has the whole story; the
# order of the steps is part of it:
#
# 1. check that this job may hold the key (the runner, the pull request's head)
# 2. system packages and the Rust toolchain (no key yet)
# 3. install the key into a directory of its own, 4. fetch with it and delete it
# 5. delete it again whatever happened, 6. the checks, offline
on:
push:
branches: ["main"]
@@ -21,9 +36,8 @@ on:
env:
CARGO_TERM_COLOR: always
# Cargo fetches the private VoelinProtocol dependency with the system git and
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
# too; set here as well, it does not depend on the runner handing a composite
# action's GITHUB_ENV on to the later steps.
# ssh, whose command line the fetch step sets (docs/ci.md, "VoelinProtocol
# access"); Cargo's own git client could not use that key file.
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
jobs:
@@ -31,14 +45,235 @@ jobs:
name: Linux checks
runs-on: ubuntu-24.04
timeout-minutes: 180
env:
# 'yes' unless this run is a pull request whose head branch lives in
# another repository. For a pull request Gitea's event payload has
# github.event.pull_request.head.repo.full_name, the repository that holds
# the branch to be merged: this repository (equal to github.repository)
# for a branch pushed here, the fork's own name for a fork. Any other
# event (push, workflow_dispatch) has no pull request and the first
# operand is true at once. An absent or unequal name reads 'no', and the
# check below treats everything but 'yes' as no. The check asks the same
# question again in its script, from the head repository's name itself.
VOELIN_PR_HEAD_HERE: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && 'yes' || 'no' }}
defaults:
run:
shell: bash
steps:
- uses: https://github.com/actions/checkout@v4
# A runner prints the `env:` of a step in the job log when the step starts,
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
# there in clear (the deploy keys of all four repositories, 2026-10-27; they
# were rotated the next day). Both runners carry the same labels, so
# `runs-on` cannot keep the job off it. What the workflow can do is not to
# start the step that declares the secret on such a runner, and not to give
# the secret to a fork's pull request: this step decides, before any step
# names the secret, and writes the one positive flag that the key step asks
# for. Without the flag the job stops here: the key is not optional (nothing
# builds without voelin-identity), and a green job that checked nothing
# would be worse than a red one that says why.
- name: Check that this job may hold the VoelinProtocol deploy key
env:
# The oldest runner version known to mask a multi-line secret in the
# log. Lower it only after a canary secret has been shown masked on
# that runner (docs/ci.md, "VoelinProtocol access"). release.yml has
# the same line.
MIN_MASKING_RUNNER_VERSION: 3.1.0
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
run: |
set -euo pipefail
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
name="${RUNNER_NAME:-an unnamed runner}"
problems=()
masks=no
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
masks=yes
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
fi
fi
if [[ "$masks" != yes ]]; then
problems+=("the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner")
fi
# The pull request's head. The job-level expression has answered in
# VOELIN_PR_HEAD_HERE; the answer is asked for again here, from the
# head repository's name and the repository's, so that a mistake in
# one of the two places does not hand the key to a fork's code. A pull
# request (any event whose name starts with pull_request, or any event
# that carries a head repository) passes only with a head repository
# that is named and is this repository.
head_here=yes
[[ "${VOELIN_PR_HEAD_HERE:-}" == yes ]] || head_here=no
case "${GITHUB_EVENT_NAME:-}" in
pull_request*) pull_request=yes ;;
*) pull_request=no ;;
esac
[[ -z "${PR_HEAD_REPO:-}" ]] || pull_request=yes
if [[ "$pull_request" == yes ]]; then
if [[ -z "${PR_HEAD_REPO:-}" || "$PR_HEAD_REPO" != "${GITHUB_REPOSITORY:-}" ]]; then
head_here=no
fi
fi
if [[ "$head_here" == yes ]]; then
if [[ "$pull_request" == yes ]]; then
echo "Event ${GITHUB_EVENT_NAME:-unknown}: the pull request's head is in $PR_HEAD_REPO, which is this repository, not a fork."
else
echo "Event ${GITHUB_EVENT_NAME:-unknown}: no pull request, the code is this repository's own."
fi
else
problems+=("the pull request's head repository is '${PR_HEAD_REPO:-unknown}', and this repository is ${GITHUB_REPOSITORY:-unknown}, so it is a fork's pull request (or the event did not say where the head is), and the key is not given to a fork's code. Push the branch to ${GITHUB_REPOSITORY:-this repository} to have it checked")
fi
if ((${#problems[@]})); then
for problem in "${problems[@]}"; do
echo "::error::The VoelinProtocol deploy key is not given to this job: $problem." >&2
done
echo "::error::The job stops here: the workspace cannot be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
# Native libraries and tools (apt), the same action as GitHub CI. The job
# image has git and the OpenSSH client; the key step checks for ssh.
- uses: ./.github/actions/system-deps
- name: Install pinned Rust toolchain
run: |
set -euo pipefail
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
export PATH="$CARGO_HOME/bin:$PATH"
if ! command -v rustup >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal --default-toolchain none
fi
if [[ -f "$CARGO_HOME/env" ]]; then
# shellcheck source=/dev/null
source "$CARGO_HOME/env"
fi
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
rustup toolchain install
# The key, as late as it can be: after the packages and the toolchain have
# been installed, right before the one step that uses it.
- name: Install the VoelinProtocol deploy key
# Both lines below ask for the positive flag of the check above. On a
# runner that is not known to mask the secret (or whose expression context
# does not hold what an earlier step wrote to GITHUB_ENV) the flag reads
# empty: the step is not started, so it prints no header, and the
# expression is empty as well, in case a runner prints a header anyway.
# The key reaches the step through the environment only: never in the
# script text, never echoed, no `set -x`. A pull request from a fork gets
# no secrets from Gitea and fails the check above before it gets here.
if: env.VOELIN_KEY_ALLOWED == 'yes'
env:
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
run: |
set -euo pipefail
umask 077
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
for tool in ssh ssh-keygen; do
command -v "$tool" > /dev/null || {
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
exit 1
}
done
[[ -s "$GITHUB_WORKSPACE/.gitea/known_hosts" ]] || {
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
exit 1
}
# A directory of this job's own (mode 0700, a name that nothing else
# uses, so a host runner that keeps its temporary directory between
# jobs does not share it). On any way out of this step but the last
# line, the step removes it itself; the directory is left only for the
# fetch step, which removes it in turn. Its name goes to the later
# steps first, so that the cleanup step finds it even if this step is
# killed.
key_dir="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/voelin-protocol-key.XXXXXX")"
installed=
trap '[[ -n "$installed" ]] || rm -rf "$key_dir"' EXIT
echo "VOELIN_PROTOCOL_KEY_DIR=$key_dir" >> "$GITHUB_ENV"
key_file="$key_dir/id"
# Whatever the secret store did to the line ends and the final newline,
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
unset PROTOCOL_DEPLOY_KEY
chmod 600 "$key_file"
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
exit 1
fi
# The fingerprint of the public half, to compare with the deploy key in
# the VoelinProtocol settings.
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
echo "VOELIN_PROTOCOL_KEY=installed" >> "$GITHUB_ENV"
installed=1
# The only step that uses the key, and the only place that sets
# GIT_SSH_COMMAND: not in GITHUB_ENV, so no later step has it.
- name: Fetch the dependencies with the deploy key
run: |
set -euo pipefail
if [[ "${VOELIN_PROTOCOL_KEY:-}" != installed || -z "${VOELIN_PROTOCOL_KEY_DIR:-}" ]]; then
echo "::error::The deploy key was not installed by the step before (the check at the start of the job or the key step did not pass its flag on)." >&2
exit 1
fi
key_dir="$VOELIN_PROTOCOL_KEY_DIR"
key_file="$key_dir/id"
# On every way out of this step, a failed fetch included.
trap 'rm -rf "$key_dir"' EXIT
[[ -f "$key_file" ]] || { echo "::error::The deploy key file is missing." >&2; exit 1; }
# The system git runs this ssh command, so the key and the host key are
# named outright and nothing in ~/.ssh or /etc/ssh is read: -F /dev/null
# leaves out every ssh config file, -i with IdentitiesOnly and no agent
# offers this one key, and the only host key accepted is the reviewed
# line in .gitea/known_hosts, never one fetched now (a changed or unknown
# host key fails rather than asks). The paths are absolute: Cargo runs
# git in its own directory under CARGO_HOME, not in the checkout.
export GIT_TERMINAL_PROMPT=0
export GIT_SSH_COMMAND="ssh -F /dev/null -i '$key_file' -o IdentitiesOnly=yes -o IdentityAgent=none -o UserKnownHostsFile='$GITHUB_WORKSPACE/.gitea/known_hosts' -o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes -o BatchMode=yes -o ConnectTimeout=30"
# The first thing that touches the server with the key, so that a wrong
# key or a changed host key fails here with a clear message and not
# minutes later inside Cargo.
if ! timeout 120 git ls-remote --exit-code \
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "Voelin/VoelinProtocol is readable with the deploy key."
# Cargo reads the manifests and Cargo.lock and downloads every package
# of the lock file (all targets: cargo deny and cargo about, later, read
# the whole graph). It runs no build script, procedural macro or test
# of the repository. Nothing else in the job needs the key: every later
# cargo command is --offline.
cargo fetch --locked
unset GIT_SSH_COMMAND
rm -rf "$key_dir"
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
echo "The deploy key is removed from the job."
# Whatever happened to the two steps above (a failed fetch, a key that was
# installed and never fetched with, a cancelled job), the key is gone before
# the checks start. Idempotent: the fetch step has already removed it.
- name: Delete the deploy key
if: always()
run: |
set -euo pipefail
key_dir="${VOELIN_PROTOCOL_KEY_DIR:-}"
if [[ -n "$key_dir" && -e "$key_dir" ]]; then
rm -rf "$key_dir"
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
echo "The deploy key is removed from the job."
else
echo "No deploy key is left in the job."
fi
{
echo "VOELIN_PROTOCOL_KEY_DIR="
echo "VOELIN_PROTOCOL_KEY="
} >> "$GITHUB_ENV"
# Formatting, Clippy, build, tests, dependency policy, notices: all
# offline, in a job that holds no key (docs/ci.md, "VoelinProtocol access").
- uses: ./.gitea/actions/checks
with:
# A repository secret is not visible inside the composite action, so
# it is passed in. Pull requests from forks get no secrets: the
# action then fails at once with a message that says so.
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
+70 -12
View File
@@ -33,13 +33,56 @@ jobs:
# Remove only output owned by this workflow in its checkout.
rm -rf dist
# The workspace depends on the private VoelinProtocol repository over SSH
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
# this agent (`docker build --ssh default`): the key lives in the agent's
# memory, never on disk and never in an image layer. Stopped by the last
# step; the lifetime below ends the key anyway if the runner dies first.
- name: Start ssh-agent with the VoelinProtocol deploy key
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with an
# ssh-agent (`docker build --ssh default`): the key lives in the agent's
# memory, never on disk and never in an image layer, and only the
# `cargo fetch` of each Dockerfile is given the agent (the build that
# follows is --offline and has no ssh mount, so the build scripts and
# procedural macros run without the key). The agent is stopped by the step
# right after the last build, whatever the builds did; the lifetime below
# ends the key anyway if the runner dies first.
#
# A runner prints the `env:` of a step in the job log when the step starts,
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
# there in clear (2026-10-27; the keys were rotated the next day). It
# carries the same labels as the release runner, so `runs-on` cannot keep
# the job off it: this step decides, before any step names the secret, and
# writes the one positive flag that the agent step asks for. Without the
# flag the job stops here (no package can be built without voelin-identity).
# ci.yml has the same step, with the check of a pull request's head repository
# that a release (tags and manual runs only) does not need.
- name: Check that this runner may hold the VoelinProtocol deploy key
env:
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
# The oldest runner version known to mask a multi-line secret in the
# log. Lower it only after a canary secret has been shown masked on
# that runner (docs/ci.md, "VoelinProtocol access"). ci.yml has the
# same line.
MIN_MASKING_RUNNER_VERSION: 3.1.0
run: |
set -euo pipefail
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
name="${RUNNER_NAME:-an unnamed runner}"
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
exit 0
fi
fi
echo "::error::The VoelinProtocol deploy key is not given to this job: the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner." >&2
echo "::error::The job stops here: no package can be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
exit 1
- name: Start ssh-agent with the VoelinProtocol deploy key
# Both lines below ask for the positive flag of the check above: on a
# runner that is not known to mask the secret (or whose expression context
# does not hold what an earlier step wrote to GITHUB_ENV) the step is not
# started and the expression is empty as well, in case a runner prints a
# header anyway. The key reaches the step through the environment only:
# never in the script text, never echoed, no `set -x`.
if: env.VOELIN_KEY_ALLOWED == 'yes'
env:
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
run: |
set -euo pipefail
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
@@ -112,6 +155,27 @@ jobs:
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
mkdir -p dist/gateway
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
# Right after the builds, the only steps that use the agent, and whatever
# they did (a failed build, a cancelled job): the steps after this one
# (the artifact upload, the release draft with its token) have neither the
# key nor the socket.
- name: Stop the ssh-agent
if: always()
run: |
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
if ssh-agent -k > /dev/null; then
echo "The ssh-agent with the deploy key is stopped."
else
echo "::warning::ssh-agent -k failed; the agent ends by itself when its lifetime (nine hours) is over." >&2
fi
else
echo "No ssh-agent of this job is running."
fi
{
echo "SSH_AUTH_SOCK="
echo "SSH_AGENT_PID="
echo "VOELIN_AGENT_STARTED="
} >> "$GITHUB_ENV"
- name: Collect packages and checksums
run: |
set -euo pipefail
@@ -136,9 +200,3 @@ jobs:
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: scripts/gitea-release.sh dist/release
- name: Stop the ssh-agent
if: always()
run: |
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
ssh-agent -k > /dev/null || true
fi
+3 -2
View File
@@ -16,7 +16,8 @@ runs:
- name: apt packages
if: runner.os == 'Linux'
shell: bash
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
# by the GPUI front end), libvpx + dav1d
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
# (bindgen), Xvfb (X11 tests).
run: |
@@ -27,7 +28,7 @@ runs:
"${sudo[@]}" apt-get update
"${sudo[@]}" apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl git jq pkg-config python3 \
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
xvfb xauth
+2
View File
@@ -2,3 +2,5 @@
/dev/.state/
/dist/
/.cargo/
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
/.scratch/
+114 -7
View File
@@ -8,6 +8,69 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Added
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
window fed by the same engine and the same view models as the Slint app
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
radius, size and type token of the Slint app's `theme.slint`, light and dark
(a test reads the Slint file and fails when the two differ), written into
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
`scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a
second: the CPU by group of threads, the memory and its own counters. A
window that cannot open (no driver, no display server) ends the app with
the reason and exit status 1. The Slint app (`voelin`) is unchanged and
stays the app; both run on one engine until the GPUI one reaches parity
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
in software); no package ships it yet.
- The GPUI front end's desktop shell: the server rail, the top bar, the
sidebar and the main area, on the client's own database (the servers saved in
the Slint app are there, and the other way round). Add, edit, select and
remove a server, connect and disconnect voice, mute the microphone and the
sound, hold to talk and copy an invite link, as in the Slint app; the window's
title names the server on screen, and its size and whether it was maximized
are kept for the next run (setting `ui.window`; on X11 the window is
maximized once it is shown, not before the window manager has it, and a
resize made before it answers is kept). The chat and the other pages are the
next slices; the search and the settings buttons only log that.
`VOELIN_DEMO_UI=1` shows the Slint app's sample servers without sending or
keeping anything (docs/ui.md, "The desktop shell").
- The GPUI front end's channel tree and members panel. The server on screen's
channels nest in the sidebar with their spacers, icons, banners (under a veil
that keeps the names readable on any picture), locks and counts, and the
people in them with their badges and marks; a click selects a channel, a
double-click joins it (a locked one asks for its password: Enter joins, and
Escape closes the prompt), the chevron folds it, a right-click offers the
same, and what is folded and selected is kept for each server (setting
`ui.tree`). The panel on the right lists everyone on the server in sections,
with a search; a click on a person opens their card. A person who starts or
stops talking is marked in the tree (the ring on their avatar and the bars on
their row, as in the Slint app) and the members panel, which are redrawn for
it and nothing else of the window, and the pictures the engine writes again show
at once. `VOELIN_METER=1` counts the renders of each pane;
`VOELIN_DEMO_SERVER` and `VOELIN_DEMO_TALK` pick the sample server and make a
sample person talk (docs/ui.md, "The channel tree and the members").
- The GPUI front end's voice channel page and call bar. A server's Voice channel
button (or `VOELIN_OPEN=voice`) shows the channel we are in with its topic,
its banner and who is there: large avatars ringed green while they talk and
blue while they stream, with the marks of a microphone or sound that is off,
and under them the call bar (mute, deafen, share and the voice settings, which
only log until their pages come, and Leave). The smaller stage, one row of
small avatars centred while it fits and scrolling sideways when crowded, is
remembered and a window under 800 pixels tall always has it (the same setting
as the Slint app's); toggle icon buttons refresh their tooltips as soon as
their state flips. The sidebar's server card shows the server's banner, a
person's card has their volume and a mute for us, and the voice card says the
transmit mode when it is not push-to-talk. Hold to talk and the global
push-to-talk key (`Ctrl+Shift+T` by default, as in the Slint app, working
while another window has focus) track button and hotkey holds independently and
fail closed across voice drops (including drop and reconnect within one event
batch), window focus loss, leaving push-to-talk mode, switching or removing
servers, repeated portal activations across servers, desktop shortcut removal,
hotkey task exit, and window shutdown. A person's picture is round in its
avatar. `voelin-gpui` is still not the app (docs/ui.md, "The voice page and
the call bar").
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
@@ -69,13 +132,35 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The view models, the app's state and the decisions of the settings pages and
of the Stream Studio moved out of `voelin-ui` into a new crate,
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
the Bridge writes and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Nothing changes on screen. See
docs/ui.md, "Two crates".
- The desktop portals (screen capture and camera through PipeWire, the push to
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
have both. Every D-Bus connection of the apps, the desktop notifications'
included, now runs on an I/O thread of its own, whichever part of the app
asks first.
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
front end, which is being built, depends on a library that calls a function
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
builds from `rust:1.95-bookworm`.
- The key store now keeps the device key when signing out of an account,
unbound, whether it was in use before the account or was made for it; "Forget
this device's identity" is the only way a key is deleted. The identity store
also reports a damaged TeamSpeak identity by the kind of damage and never
repeats its key in an error. Nothing changes on screen yet: accounts and
sign-in are later steps.
- The view models, the app's state, the state change of every engine event and
the decisions of the settings pages, the Stream Studio, the streams, the chat,
the servers, the audio settings page, the friends and the development
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
depends on no UI toolkit (a second front end can use it); `voelin-ui`
converts its plain rows into Slint's and keeps the window, the Bridge writes
and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Two things change on screen: the chat of
a server that is gone takes the colour of its title instead of opaque
black, and a cached avatar file cut after a valid header shows the
initials instead of a broken picture. See docs/ui.md, "Two crates".
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
key, the signed-in account) with the account each belongs to, as a
`voelin-identity` key store, in two database migrations. Existing
@@ -183,6 +268,28 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
connections, so tsgw no longer earns a 600 second ban. It starts while
the TeamSpeak server is still down and connects once it is up, its
`/health` says what is missing, and it stops cleanly on SIGTERM.
- The client builds on VoelinProtocol's release `v0.2.0` (the tag, no longer a
commit) for `voelin-identity`, `voelin-proto` and `voelin-model`; nothing the
apps do changes. Two differences underneath: signing out of an account lists
a kept device key once (a key whose row carried a device-only binding was
listed twice), and the debug text of the protocol's messages (`Hello`,
`Welcome`, `Server`, `Channel`, `Member` and the others whose secrets
VoelinProtocol lists) shows `<redacted>` in place of a password or a token, so
a log line or a failed test that prints one does not show it.
- CI and the package builds give the VoelinProtocol deploy key only to the step
that fetches the sources. The CI job writes the key to a directory of its own
(no `~/.ssh` configuration), uses it for `cargo fetch` as `ssh -i` with the
committed host key, and deletes it right after and again in a step that always
runs; the formatting, Clippy, build, test and policy steps, which run the
repository's build scripts and tests, are `--offline` and run in a job without
the key. The Docker builds (Linux, Windows, Android and the gateway image)
fetch in a `RUN` with the ssh mount and build `--offline` without it, and the
release workflow stops its ssh-agent right after the last build. A job gives
the key only to a runner that reports version 3.1.0 or newer (the old runner
gitea-runner-docker v0.6.1 printed a multi-line secret in the job log; the
deploy key was replaced, id 7) and, on a pull request, only when its head
branch is in this repository; otherwise it stops with the reason. See
docs/ci.md, "VoelinProtocol access".
### Removed
+6
View File
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
project's own crates (`scripts/own-crates.sh`) green.
Two front ends run on one engine until the second reaches parity:
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
view models and the state, with no UI toolkit (`docs/ui.md`).
## Hosting: Gitea, not GitHub
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
Generated
+3683 -143
View File
File diff suppressed because it is too large. Load diff
+18 -7
View File
@@ -15,6 +15,7 @@ members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-gpui",
"crates/voelin-media",
"crates/voelin-observer",
"crates/voelin-platform",
@@ -36,6 +37,7 @@ default-members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-gpui",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
@@ -48,7 +50,7 @@ default-members = [
[workspace.package]
edition = "2024"
rust-version = "1.94"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
repository = "https://github.com/Faumaray/Voelin"
publish = false
@@ -57,14 +59,23 @@ publish = false
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
# the three crates below are at one revision (main c8e0e5a: the account-bound
# KeyStore of Phase 2 task 28, the account types of the session seam).
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
# VoelinProtocol checkout"). Pinned by the release tag (v0.2.0 is the first with the
# protocol crates; its README, "Releases", says how): the three crates below are at
# one tag, so the lock has one revision of each, and moving to a newer release means
# changing the `tag` of all three together (docs/building.md, "Depending on
# VoelinProtocol"). The account-bound KeyStore whose sign-out keeps every device key
# and the release of a device key, Phase 2 task 34, and the account types of the
# session seam are in it.
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# The UI-facing domain model and the client's replica of v1 entities.
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
# "The version to pin").
gpui-kit = "=0.8.1"
[workspace.lints.rust]
# deny, not forbid: generated code (Slint) needs a local allow.
+7
View File
@@ -48,6 +48,11 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
([docs/ui.md](docs/ui.md), "The GPUI front end")
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
clients through a TS6 server
@@ -79,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
```sh
# Desktop app
cargo run -p voelin-ui --bin voelin
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
cargo run -p voelin-gpui --release
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
docker compose -f dev/docker-compose.yml up -d
+3261 -45
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -11,6 +11,13 @@ archive in crates/voelin-ui-vm):
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
Contributors, under the ISC License; the icons derived from Feather are
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
client's own set above), Copyright (c) Lucide Icons and Contributors, under
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
the crates).
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
contributors, licensed under CC-BY 4.0
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
+4
View File
@@ -23,6 +23,10 @@ accepted = [
"LicenseRef-Slint-Royalty-free-2.0",
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
"bzip2-1.0.6",
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
# (notify 8, tiny-keccak); see deny.toml.
"0BSD",
"CC0-1.0",
]
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
+7 -2
View File
@@ -453,10 +453,15 @@ mod tests {
lookups
}
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
/// connected to through the system's resolver, except `localhost`: the
/// servers of the tests listen on 127.0.0.1, and some machines resolve
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
/// the name `localhost`, not what the resolver makes of it.)
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
});
lookups
}
+14 -11
View File
@@ -199,19 +199,22 @@ async fn receive<R: AsyncRead + Unpin>(
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
// The directory and the file are made in one step, without a pause in
// which the task could be stopped: a cancel stops the task, waits for
// it and then removes the part file, so what the task made must be
// there by then (a pending open on the blocking pool would not be).
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let mut file = tokio::fs::File::from_std(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.map_err(|e| format!("{}: {e}", part.display()))?,
);
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
+7 -3
View File
@@ -166,9 +166,13 @@ impl Backends {
self.register_local(Arc::new(connector));
}
/// The device's Voelin account, for the connectors that use it (the QUIC
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
/// None is the default: nothing uses an account yet.
/// The device's Voelin account, which every connect hands the connector as
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
/// connector takes the myTeamSpeak account it presents from its own setters
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
/// proof from those setters to this hook. None is the default.
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
self.account = agent;
}
+1 -1
View File
@@ -313,7 +313,7 @@ async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
assert_eq!(report.cases.len(), 17, "the suite of v0.2.0 has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
+8
View File
@@ -64,6 +64,10 @@ pub struct VoiceOptions {
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
/// client name on a TeamSpeak server (which may refuse or change it). When
/// it is empty, the `nickname` parameter of an `address` that is a
/// TeamSpeak link applies.
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
@@ -76,6 +80,10 @@ pub struct VoiceOptions {
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
/// The password of the server (`Hello.password`), for one that has a
/// password. When it is `None` or empty, the `password` parameter of an
/// `address` that is a TeamSpeak link applies. Not the password of
/// `channel` (that is `channel_password`).
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
+19 -13
View File
@@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
use voelin_audio::EncodedVoice;
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
@@ -325,7 +325,7 @@ async fn drive(
/// A transfer a user can cancel.
struct Running {
task: AbortHandle,
task: JoinHandle<()>,
part: Option<PathBuf>,
report: Report,
/// The server has opened it (a part file may exist).
@@ -1479,7 +1479,7 @@ impl Conn {
receive.await;
}
});
self.running(transfer, Running { task: task.abort_handle(), part, report, started });
self.running(transfer, Running { task, part, report, started });
}
fn upload(
@@ -1560,7 +1560,7 @@ impl Conn {
let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) };
files::upload_to(body, stored, from, size, offset, progress, task_report).await;
});
self.running(transfer, Running { task: task.abort_handle(), part: None, report, started });
self.running(transfer, Running { task, part: None, report, started });
}
fn running(&mut self, transfer: Option<TransferId>, running: Running) {
@@ -1572,15 +1572,21 @@ impl Conn {
fn cancel(&mut self, id: TransferId) {
match self.transfers.remove(&id) {
Some(running) if !running.task.is_finished() => {
running.task.abort();
// A part file exists once the server has opened the transfer.
if running.started.load(Ordering::Acquire)
&& let Some(part) = running.part
{
let _ = std::fs::remove_file(part);
}
(running.report)(TransferState::Cancelled);
Some(Running { task, part, report, started }) if !task.is_finished() => {
task.abort();
// The part file goes once the task has stopped, not at once: the task
// opens it in one step (files::download), so it is there or it never
// will be, and a removal that came before the open would leave it.
tokio::spawn(async move {
let _ = task.await;
// A part file exists once the server has opened the transfer.
if started.load(Ordering::Acquire)
&& let Some(part) = part
{
let _ = std::fs::remove_file(part);
}
report(TransferState::Cancelled);
});
}
_ => debug!(id, "cancel: no such transfer (finished?)"),
}
+98 -41
View File
@@ -607,6 +607,12 @@ async fn a_file_is_downloaded_through_the_connection_the_link_opens() {
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(
states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })),
"the transfer started: {:?}",
states.lock().unwrap()
);
// Cancelled the moment it is Started, when its part file may be opening.
rig.give(LinkCmd::CancelTransfer(3));
assert_eq!(final_state(&states).await, TransferState::Cancelled);
rig.quiet();
@@ -981,6 +987,32 @@ async fn a_connect_that_fails_is_a_disconnect_with_the_reason() {
);
}
/// An identity that cannot be read ends the connect with a disconnect whose
/// text says where it is wrong and holds none of the key: the JSON reader's
/// own message quotes a key that does not import, and the engine shows this
/// text as the error of the connection.
#[tokio::test(flavor = "multi_thread")]
async fn an_identity_that_cannot_be_read_is_a_disconnect_without_the_key() {
let (json, cut) = crate::ts::identity::json_with_a_cut_key();
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
let link = SessionLink::new(Backends::default());
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(options, LocalCtx::standalone().link, cmd_rx, event_tx);
let event = within("the end", events.recv()).await;
let LinkEvent::Disconnected(Some(text)) = event else {
panic!("a disconnect with the reason of the refusal")
};
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
crate::ts::identity::assert_holds_no_piece_of(&text, &cut);
}
// ---- the TeamSpeak side alone ---------------------------------------------------
/// A `LinkSession` over a recorder, made the way a connector makes it.
@@ -1930,20 +1962,38 @@ async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() {
const CHANNELS: u64 = 5_000;
let (conns, mut seen) = mpsc::unbounded_channel();
let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]);
let (mut params, _media) = connect_params("ts3server://fake.test?port=9987");
let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987");
params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() };
params.push_capacity = 1;
let connecting = tokio::spawn(connector.connect(params));
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(connected(everything())).unwrap();
// Made before the link is told it is connected: the connector waits only
// 250 ms for the first snapshot, and making 5,000 channels can take longer
// than that on a busy machine, which left the session without them.
let mut big = presence();
for id in 100..100 + CHANNELS {
let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() };
big.channels.insert(id, channel);
}
inner.events.send(connected(everything())).unwrap();
inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap();
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
let (session, mut pushes) = (connected.session, connected.pushes);
// The scope is sent whole only if the presence is in the host's state when
// it is asked for. The link takes its events in order, and a voice packet
// of one of the presence's clients comes through only once the presence
// is in: the packet says it is.
inner
.events
.send(LinkEvent::Audio(VoicePacket {
talker: TalkerId(8),
seq: 1,
codec: VoiceCodec::Voice,
whisper: false,
payload: OPUS_20_MS.to_vec(),
}))
.unwrap();
within("the voice", media.recv()).await;
let server = ScopeId::Server(1);
session.request(subscribe(server)).await.unwrap();
@@ -2152,12 +2202,48 @@ async fn event_of<T>(
.await
}
/// Asks for the file list of the lobby until the answer is one `wanted` takes,
/// one question at a time: the next goes out only when the last is answered.
/// Asked every few milliseconds instead, the answers fell behind the 16
/// events the bus holds (and the host's work), and the one that counted was
/// lost in the backlog.
async fn ask_files_until(
cmd_tx: &mpsc::UnboundedSender<LinkCmd>,
bus: &mut broadcast::Receiver<Event>,
request: &mut crate::files::RequestId,
wanted: impl Fn(&Result<Vec<FileEntry>, String>) -> bool,
) {
within("the file list to be answered as wanted", async {
loop {
*request += 1;
let dir = remote(10, None, "/");
cmd_tx.send(LinkCmd::ListFiles { request: *request, dir }).ok()?;
let result = loop {
match bus.recv().await {
Ok(Event::FileList { request: answered, result, .. })
if answered == *request =>
{
break result;
}
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => return None,
}
};
if wanted(&result) {
return Some(());
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await;
}
/// `Server.features` narrows what the host offers (protocol 1.3,
/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed.
#[tokio::test(flavor = "multi_thread")]
async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
use v1::entity::Kind;
use voelin_proto::test_util::{FakeConnector, eventually};
use voelin_proto::test_util::FakeConnector;
let connector = FakeConnector::new();
let host = connector.host();
@@ -2209,55 +2295,26 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
})
.count()
};
let ask = |request| {
let dir = remote(10, None, "/");
cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap();
};
let refusal = "not offered by this server: files";
let refused =
|event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal);
|result: &Result<Vec<FileEntry>, String>| matches!(result, Err(why) if why == refusal);
let mut request = 0;
// Refused here: nothing reaches the host.
ask(1);
loop {
let event = within("the refusal", async { bus.recv().await.ok() }).await;
if refused(&event) {
break;
}
}
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
assert_eq!(file_lists(), 0);
// The server lifts its list (an empty one keeps all the host's): files work.
put_server(&[]);
let mut request = 1;
eventually(WAIT, "a file list to reach the host", || {
request += 1;
ask(request);
file_lists() > 0
})
.await;
ask_files_until(&cmd_tx, &mut bus, &mut request, |result| !refused(result)).await;
assert!(file_lists() > 0, "the answer did not come from the host");
// The host narrows what it offers this user. A refusal counts only for a
// request made after the update: the earlier ones were answered by the host's
// wider set (or, before the server lifted its list, refused for that).
// The host narrows what it offers this user. Every question is answered
// before the next is asked, so those asked from here on are the ones the
// update can refuse; the earlier ones were answered by the host's wider set.
let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None };
handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap();
let after = request;
within("the narrower set to apply", async {
loop {
request += 1;
ask(request);
tokio::time::sleep(Duration::from_millis(20)).await;
while let Ok(event) = bus.try_recv() {
if matches!(&event, Event::FileList { request, .. } if *request > after)
&& refused(&event)
{
return Some(());
}
}
}
})
.await;
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
}
/// A port that is no port is refused in words, not dropped: the connection
+111 -38
View File
@@ -3257,9 +3257,13 @@ impl LocalPreview {
}
/// The first and last column of the rectangle in the middle row of a
/// decoded test pattern. Checks that pixels further than two columns from
/// its edges (which the codec blurs) have the colour of the rectangle or
/// the background.
/// decoded test pattern, after checking the row's structure: background, one
/// run of the rectangle, background. A pixel is whichever of the pattern's two
/// colours it is nearer to; it is not asked to be within some distance of one,
/// because an encoder that falls behind lowers its quality (the VP8 speed
/// control of the streamer does) and then moves a flat colour by 30 and more
/// per channel, still nowhere near the other colour. The two columns at each
/// edge, which the codec blurs, may be either.
#[cfg(all(test, feature = "media-desktop"))]
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
@@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
let i = ((y * picture.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
};
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
for x in 0..picture.width {
if x + 2 < a || x > b + 2 {
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
}
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
};
let rectangle = |x: u32| {
let p = pixel(x);
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
};
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
// One run: everything between its ends, but the blurred edges, is the
// rectangle's. Whatever is outside is the background by the choice of a and b.
for x in a + 2..=b.saturating_sub(2) {
assert!(
rectangle(x),
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
pixel(x)
);
}
(a, b)
}
@@ -3536,11 +3548,30 @@ mod tests {
};
told(30).await;
assert_eq!(streamer.bitrate_kbps(), 1105);
// Not per frame.
let count = lock(&sink.formats).len();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(lock(&sink.formats).len(), count);
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
// Not per frame. The sink is told when it is attached and again by the
// encoder before its first frame (the same format twice), so the count is
// taken once a frame has been handed over and compared after more have;
// the frames, not a pause, are what "per frame" counts.
let frames_by = |frames: u64| {
let streamer = &streamer;
async move {
let deadline = Instant::now() + Duration::from_secs(30);
while streamer.stats().layers[0].frames < frames {
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
};
frames_by(1).await;
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
frames_by(seen + 5).await;
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
// The stats follow the sink's being told, not the other way round.
let deadline = Instant::now() + Duration::from_secs(10);
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
streamer.reconfigure(&codecs, update).unwrap();
told(15).await;
@@ -3711,15 +3742,35 @@ mod tests {
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
}
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
let stats = preview.stats();
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
assert_eq!(stats.codec, Some(Codec::Vp8));
let (before_first, first) = (Instant::now(), preview.stats());
let after_first = Instant::now();
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
assert_eq!(first.codec, Some(Codec::Vp8));
assert_eq!(preview.streamer().backend(), "synthetic");
// Rates over the second since: the pattern's rate, its bitrate.
// The rates are the counters over the time since the call before. How
// long that was the test does not say (a busy machine stretches a second,
// and the rate of pictures it manages is not what is tested), but it lies
// between the two spans the test timed around it.
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = preview.stats();
assert!((20..=40).contains(&stats.fps), "{stats:?}");
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
let before_second = Instant::now();
let second = preview.stats();
let after_second = Instant::now();
let longest = after_second.duration_since(before_first).as_secs_f64();
let shortest = before_second.duration_since(after_first).as_secs_f64();
let frames = (second.decoded - first.decoded) as f64;
let bits = (second.bytes - first.bytes) as f64 * 8.0;
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
// (The pictures per second are rounded, the bits per second cut off.)
let fps = f64::from(second.fps);
assert!(
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
);
let bitrate = second.bitrate as f64;
assert!(
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
);
}
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
@@ -4143,7 +4194,8 @@ mod tests {
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
let deadline = Instant::now() + Duration::from_secs(5);
// What is waited for is a state; the deadline only ends a hang.
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let stats = streamer.stats();
if done(&stats) {
@@ -4153,15 +4205,18 @@ mod tests {
std::thread::sleep(Duration::from_millis(20));
}
};
// The SineSource tone is 0.05; the second at half gain.
// The SineSource tone is 0.05; the second at half gain. The sources are metered
// before the mixer has made anything of them: the mix and the state of the
// sources are waited for too, not taken to be there with the meters.
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
let stats = wait("both tones", &|s| {
let stats = wait("both tones, mixed", &|s| {
s.audio_sources.len() == 2
&& near(s.audio_sources[0].level.peak, 0.05)
&& near(s.audio_sources[1].level.peak, 0.025)
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
&& s.audio_level.peak > 0.05
&& s.audio_limiter == 1.0
});
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
let first = stats.audio_sources[0].id;
// Mute the first (kept: same id), drop the second, add the
@@ -4177,19 +4232,31 @@ mod tests {
streamer.reconfigure(&codecs, update).unwrap();
assert_eq!(streamer.audio_sources().len(), 3);
let publisher = tap::publisher_id();
let speak = std::thread::spawn(move || {
// 20 ms of a 0.2 tone every 20 ms, for a second.
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
for _ in 0..50 {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
let heard = Arc::new(AtomicBool::new(false));
let speak = std::thread::spawn({
let heard = heard.clone();
move || {
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
// source takes what is published only from when it runs, which a
// busy machine delays by any time (the cap ends a thread whose test
// failed first).
let cap = Instant::now() + Duration::from_secs(120);
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
}
}
});
let stats = wait("microphone in, tone muted", &|s| {
s.audio_sources.len() == 3
&& s.audio_sources[1].level.peak > 0.15
&& s.audio_level.peak > 0.15
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
// Muted, and still metered: the tone's own level is read again.
&& near(s.audio_sources[0].level.peak, 0.05)
});
heard.store(true, Ordering::Relaxed);
speak.join().unwrap();
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
assert!(stats.audio_sources[0].spec.muted);
@@ -4221,9 +4288,15 @@ mod tests {
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
let mut source = EncodedSource::new(streamer);
let mut frames = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
assert!(Instant::now() < deadline, "no audio");
// Ten frames of audio and one of video, whichever the encoders make first:
// 20 ms of audio is quickly made, and a busy machine can keep the video
// encoder from its first frame for longer than that. The deadline only ends
// a hang.
let deadline = Instant::now() + Duration::from_secs(30);
let count =
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
tokio::time::sleep(Duration::from_millis(20)).await;
source.poll_frames(Instant::now(), &mut frames);
}
+39 -6
View File
@@ -1295,9 +1295,21 @@ mod tests {
// Before the viewer asks: its offer is made after this.
sink.layer_format(0, format(60_000_000));
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
// Connected for the viewer and for the streamer, in either order: the
// streamer asks for a keyframe when its viewer connects, a moment after
// the viewer has seen the connection.
let (mut watching, mut served) = (false, false);
wait(&mut rx, |e| {
match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
watching = true;
}
Event::StreamViewers { session: 1, viewers } => {
served |= viewers.iter().any(|v| v.state == ViewerState::Connected);
}
_ => {}
}
(watching && served).then_some(())
})
.await;
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
@@ -1312,7 +1324,15 @@ mod tests {
sink.take_layer_keyframes(&mut layers);
layers.contains(0)
};
keyframes();
// What asked for a keyframe so far (going live, the viewer's connecting
// and its first picture request) is done when a moment longer than the
// merging interval of requests (250 ms) passes with none.
for _ in 0..50 {
tokio::time::sleep(Duration::from_millis(300)).await;
if !keyframes() {
break;
}
}
sink.layer_format(0, format(9_000_000));
timeout(Duration::from_secs(5), async {
while !keyframes() {
@@ -1322,7 +1342,11 @@ mod tests {
.await
.expect("the layer did not change");
sink.layer_format(0, format(9_000_000));
tokio::time::sleep(Duration::from_millis(200)).await;
// The stream task takes its commands in order: its answer to this one
// (an error, nobody is viewer 65535) comes after all that the format
// above set going, and nothing is left to wait out.
handles[0].send(StreamCmd::Kick { viewer: u16::MAX });
wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await;
assert!(!keyframes(), "nothing changed");
handles[0].send(StreamCmd::Stop);
}
@@ -1701,7 +1725,16 @@ mod tests {
let stats = pipeline.stats();
assert_eq!(stats.codec, Some(Codec::Vp8));
assert!(stats.error.is_none(), "{stats:?}");
let sent = streamer.stats();
// The encoder counts a frame once the sink has taken it, so the picture
// can be at the viewer before the count has moved.
let mut sent = streamer.stats();
for _ in 0..500 {
if sent.video_frames >= 15 && sent.audio_frames > 0 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
sent = streamer.stats();
}
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
handles[0].send(StreamCmd::Stop);
+64 -5
View File
@@ -255,8 +255,21 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
blob.kind
)));
}
serde_json::from_str(&blob.json).map_err(|e| {
// Where the JSON is wrong, not what it says: it holds a private key.
from_json(&blob.json)
}
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
/// store keeps; voelin-core reads that text only through here (voelin-store
/// parses it too, for its own checks of a stored row).
///
/// What does not read is refused in words that say how it is wrong
/// (malformed, cut short, not an identity, unreadable) and where (line and
/// column), and never what it holds: the text holds a private key, and the
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
/// key that does not import as an invalid value, the key string and all), so
/// that message is never shown, not in an error, an event or a log.
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
serde_json::from_str(json).map_err(|e| {
let what = match e.classify() {
serde_json::error::Category::Syntax => "malformed",
serde_json::error::Category::Eof => "cut short",
@@ -271,6 +284,27 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
})
}
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
#[cfg(test)]
pub(crate) fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
#[cfg(test)]
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
/// and every other tool reads.
pub fn export(nickname: &str, identity: &Identity) -> String {
@@ -615,18 +649,43 @@ mod tests {
}
}
/// The JSON reader's own message quotes a key that does not import, so the
/// refusal is worded by `from_json` and holds none of the key.
#[test]
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
let (json, cut) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
for error in [
from_json(&json).unwrap_err().to_string(),
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
] {
assert!(
error.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
assert_holds_no_piece_of(&error, &cut);
}
}
#[test]
fn improve_level_keeps_the_key() {
let identity = synthetic();
// A fresh identity stops at the first counter whose level is 8 or more,
// and about one in 32 has 13 or more already, which `improve_level`
// returns as it is: ask for more than this one has, whatever it has.
let target = identity.level() + 3;
let levels = std::sync::Mutex::new(Vec::new());
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
levels.lock().unwrap().push(l);
})
.unwrap();
assert!(better.level() >= 13);
assert!(better.level() >= target);
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
assert!(better.counter() > identity.counter());
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
// Cancelled: nothing.
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
// Already there: the same identity.
@@ -333,7 +333,7 @@ enum Expect {
}
use Expect::{NotRun, Passes, Skipped};
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
/// Every case of the suite of the protocol repository at `v0.2.0`, in its
/// order, with what a TeamSpeak session does with it. A case the suite gains
/// fails `the_suite_is_known` until it is listed here.
///
+36 -4
View File
@@ -43,7 +43,7 @@ use voelin_proto::link::{
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use super::{ConnectOptions, ServerLink, TsLink, versions};
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
use crate::BackendInfo;
use crate::link::{
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
@@ -82,9 +82,14 @@ fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOption
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
Some(serde_json::from_slice(blob).map_err(|e| {
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
})?)
// The refusal never quotes the JSON: it holds the private key, and the
// JSON reader's own message would show a key that does not import.
let json = std::str::from_utf8(blob).map_err(|_| {
SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is not text".into(),
)
})?;
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
}
_ => {
return Err(SessionError::Protocol(
@@ -754,6 +759,33 @@ mod tests {
assert!(!futures::executor::block_on(confirm));
}
/// An identity that cannot be read ends the connect with words that say
/// where it is wrong and hold none of the key: the JSON reader's own
/// message quotes a key that does not import, and this text reaches the
/// event bus and the status line.
#[test]
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
let (json, cut) = identity::json_with_a_cut_key();
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
identity::assert_holds_no_piece_of(&text, &cut);
// Not even text.
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
+9 -4
View File
@@ -1650,8 +1650,10 @@ mod account_tests {
events,
));
let mut packet = [0; 2048];
let (_, first) =
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet))
.await
.expect("the first handshake packet within 5 s")
.unwrap();
// A logout/clear notification must cancel the old socket and restart.
account.send_replace(None);
let second = timeout(Duration::from_secs(5), async {
@@ -1663,11 +1665,14 @@ mod account_tests {
}
})
.await
.unwrap();
.expect("a handshake packet from a new socket within 5 s of the account change");
assert_ne!(first, second);
// Losing the account authority fails closed immediately, not after connect timeout.
drop(account);
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
timeout(Duration::from_secs(2), task)
.await
.expect("the connection to end within 2 s of the account source closing")
.unwrap();
assert!(
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
);
+71 -10
View File
@@ -960,11 +960,27 @@ pub(crate) mod tests {
/// What `f` logs at info (and above) on this thread: each line its
/// message, then its fields (` name=value`).
///
/// One recording subscriber is installed for the whole test process, the
/// first time this is called, and each call records into a buffer of its
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
/// lines: while it is the only subscriber alive, a callsite that another
/// test's thread meets first is registered against that thread's own
/// default, which is none, and stays disabled for every thread, so the
/// lines of the test that reads them are gone
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
/// failed with no lines at all, once in about thirty runs of the suite).
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
use std::cell::RefCell;
use std::sync::Once;
use tracing::field::{Field, Visit};
use tracing::span;
struct Lines(Arc<Mutex<Vec<String>>>);
thread_local! {
/// The lines of the `info_lines` running on this thread, if any.
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
#[derive(Default)]
struct Line(String, String);
impl Visit for Line {
@@ -975,7 +991,8 @@ pub(crate) mod tests {
}
}
}
impl tracing::Subscriber for Lines {
struct Recorder;
impl tracing::Subscriber for Recorder {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
*metadata.level() <= tracing::Level::INFO
}
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut line = Line::default();
event.record(&mut line);
self.0.lock().unwrap().push(line.0 + &line.1);
LINES.with(|lines| {
if let Some(lines) = lines.borrow_mut().as_mut() {
let mut line = Line::default();
event.record(&mut line);
lines.push(line.0 + &line.1);
}
});
}
fn enter(&self, _: &span::Id) {}
fn exit(&self, _: &span::Id) {}
}
let lines = Arc::new(Mutex::new(Vec::new()));
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
let lines = lines.lock().unwrap().clone();
/// Ends the recording of this thread, also when `f` panics.
struct Recording;
impl Drop for Recording {
fn drop(&mut self) {
LINES.with(|lines| lines.borrow_mut().take());
}
}
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
tracing::subscriber::set_global_default(Recorder)
.expect("no other global tracing subscriber in the tests");
// Makes every callsite decide again with the subscriber in place, also
// one that a thread was registering while it was being installed
// (creating a `Dispatch` rebuilds the cached interest of all of them).
drop(tracing::Dispatch::new(Recorder));
});
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
let _recording = Recording;
let result = f();
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
(result, lines)
}
/// The lines of `info_lines` do not depend on which thread met a callsite
/// first: this one is met on another thread, which records nothing, before
/// the thread that reads the lines meets it.
#[test]
fn info_lines_see_a_callsite_another_thread_met_first() {
fn log() {
tracing::info!("met");
}
let ((), lines) = info_lines(|| {
std::thread::spawn(log).join().unwrap();
log();
});
assert_eq!(lines, ["met"]);
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
};
let mut port = [0u8; 2];
client.read_exact(&mut port).await.unwrap();
let target = format!("{host}:{}", u16::from_be_bytes(port));
let port = u16::from_be_bytes(port);
let target = format!("{host}:{port}");
targets.send(target.clone()).unwrap();
let mut server = TcpStream::connect(target).await.unwrap();
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
// `::1` only, and the servers of the tests listen on 127.0.0.1.
let dial =
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
let mut server = TcpStream::connect(dial).await.unwrap();
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
});
+28
View File
@@ -0,0 +1,28 @@
//! What more than one integration test of this crate needs (a test binary
//! that uses it declares `mod common;`).
use std::path::{Path, PathBuf};
use std::time::Duration;
/// Wait until nothing has the SQLite database at `path` open any more, as when
/// the process that had it has ended: SQLite deletes the write-ahead log
/// (`<path>-wal`) when the last connection closes.
///
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
/// is joined there, and closing the connection checkpoints the log under an
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
/// lock only as long as the busy timeout (5 s) and then fails with
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
/// 6 s it happens every time).
pub async fn closed(path: &Path) {
let mut wal = path.as_os_str().to_owned();
wal.push("-wal");
let wal = PathBuf::from(wal);
tokio::time::timeout(Duration::from_secs(120), async {
while wal.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the engine's database connection closed");
}
+14 -1
View File
@@ -24,6 +24,8 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
mod common;
const LOBBY: ChatTarget = ChatTarget::Channel(1);
const ME: &str = "me-uid";
@@ -529,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
history.flush();
drop((engine, history));
// Dropping the engine does not close the database yet (see `closed`).
common::closed(&path).await;
// After a restart, with the gateway down: the stored page, found by the
// gateway's URL, which is remembered with the server's id.
@@ -812,7 +816,16 @@ async fn not_found_proxy() -> String {
#[tokio::test(flavor = "multi_thread")]
async fn the_next_published_gateway_is_used_when_one_fails() {
let proxy = not_found_proxy().await;
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
// A port that is taken and never listened on: connecting is refused at once,
// and no other test of this process can be given it meanwhile (one that was
// only free for a moment could be, the listeners of the others bind port 0).
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
let closed = reserved.local_addr().unwrap().port();
assert!(
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
"something listens on port {closed}"
);
let gw = FakeGateway::start().await;
let path = temp_db("fallback");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
+17
View File
@@ -1,8 +1,10 @@
//! Engine against the development servers (dev/docker-compose.yml).
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use voelin_core::{
@@ -15,6 +17,17 @@ fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
/// unsets them there. While it does, whatever else connects to the server is
/// told the addresses of those banners, and an engine fetches what it is told
/// (as it should): the requests of such an engine reached the HTTP server of
/// `ts6_banners`, which counts the requests of the engine under test, and the
/// test failed on `disabled policy must prevent HTTP requests` in every run
/// that had the tests of this file run side by side (as they do). The tests
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
/// runs with the server to itself, and the others before or after it.
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for(
rx: &mut Receiver<Event>,
@@ -131,6 +144,7 @@ async fn ts6_engine() {
if !live() {
return;
}
let _server = TS6.read().await;
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
.await;
}
@@ -258,6 +272,7 @@ async fn ts6_channel_joins() {
if !live() {
return;
}
let _server = TS6.read().await;
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
}
@@ -329,6 +344,7 @@ async fn ts6_banners() {
if !live() {
return;
}
let _server = TS6.write().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let query_addr =
@@ -512,6 +528,7 @@ async fn ts6_avatars() {
if !live() {
return;
}
let _server = TS6.read().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
+52 -1
View File
@@ -10,7 +10,9 @@
//! dedup of a message that comes twice, history, transfers, offline messages,
//! the features of a host, a reconnect and the media of a session are the
//! engine's own behaviour; nothing here needs a TeamSpeak server or a
//! TeamSpeak type.
//! TeamSpeak type, except `a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`,
//! which runs the engine's own TeamSpeak connector up to its refusal of an
//! identity.
use std::path::PathBuf;
use std::sync::Arc;
@@ -163,6 +165,12 @@ impl Harness {
fn on(connector: FakeConnector) -> Self {
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
Self::with_backends(backends, connector)
}
/// The engine on `backends`; `connector` is the fake host the test may
/// have registered in them (a test that registers none leaves it unused).
fn with_backends(backends: Backends, connector: FakeConnector) -> Self {
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
@@ -1502,3 +1510,46 @@ async fn a_teamspeak_identity_without_json_is_refused_and_no_session_is_made() {
assert!(handle.close_reason().is_none());
assert_eq!(h.connector.connects().len(), 1);
}
/// A TeamSpeak identity whose key does not import ends the connect with words
/// that say where the JSON is wrong and never show the key: the JSON reader's
/// own message quotes it, and the text is the reason of the disconnect, the
/// `Error` event and the status line the UI makes of it. This is the one test
/// of the file that runs the engine's own TeamSpeak connector
/// (`Backends::default()`): the refusal is that connector's and comes before
/// any network.
#[tokio::test(flavor = "multi_thread")]
async fn a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key() {
let mut json = serde_json::to_value(tsclientlib::Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
// The key lost its last two characters.
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json.to_string()));
let mut h = Harness::with_backends(Backends::default(), FakeConnector::new());
h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
assert_eq!((state.own_channel, state.own_client), (None, None));
let error = h.error().await;
assert!(
error.starts_with(
"voice: the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
// Nothing the engine reported afterwards holds a piece of the key either.
let mut shown = vec![error];
while let Ok(Ok(event)) =
tokio::time::timeout(Duration::from_millis(300), h.events.recv()).await
{
shown.push(format!("{event:?}"));
}
for text in &shown {
for piece in cut.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
}
@@ -10,6 +10,10 @@ use voelin_core::settings::Settings;
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
use voelin_model::FileRef;
mod common;
use common::closed;
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
@@ -165,6 +169,7 @@ async fn contacts_are_kept_in_the_database() {
engine.history().flush();
}
// A new engine attaches the database later: the contacts come back.
closed(&path).await;
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
+9 -4
View File
@@ -9,7 +9,7 @@
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
FROM rust:1.94-bookworm AS build
FROM rust:1.95-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
# voelin-identity comes from the private VoelinProtocol repository, fetched
@@ -17,13 +17,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends cmake git libas
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# every cargo command needs this, although this crate does not use
# voelin-identity.
# the first cargo command needs this, although this crate does not use
# voelin-identity: the `cargo fetch` below, the only step that is given the agent.
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
# Only this step is given the agent, and it only fetches: no build script,
# procedural macro or test of the workspace runs in it. The build below has no
# ssh mount (so no agent socket and no key in reach of the code it compiles and
# runs) and is --offline, so it uses what this step fetched or fails.
RUN --mount=type=ssh,required=true \
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
cargo fetch --locked
RUN cargo build --release --locked --offline -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /tsgw /usr/local/bin/tsgw
+57
View File
@@ -0,0 +1,57 @@
[package]
name = "voelin-gpui"
version = "0.0.1-alpha"
description = "The GPUI front end of the desktop app, under construction: it runs on the same engine as the Slint front end (voelin-ui) until it reaches parity."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "voelin_gpui"
path = "src/lib.rs"
[[bin]]
name = "voelin-gpui"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
gpui-kit = { workspace = true }
# The engine's runtime and the channel of its events (a tokio receiver needs no
# reactor, so GPUI's executor can await it); `macros` for the hotkey task's
# `select!`.
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
# The TeamSpeak identity a connection is made with (the store hands it out).
tsclientlib = { path = "../proto/tsclientlib" }
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
# commit that moved voelin-media and voelin-platform to it) lets this binary
# hold both the portals and gpui-kit.
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
# The app's name and id, the hotkeys and portals of the slices to come.
voelin-platform = { path = "../voelin-platform" }
# The client's database (bookmarks, identities, settings, chat reads) and the
# secrets: the OS keyring, as the Slint front end keeps them.
voelin-store = { path = "../voelin-store", features = ["keyring"] }
# The view models and the state, shared with the Slint front end.
voelin-ui-vm = { path = "../voelin-ui-vm" }
# The meter reads /proc/self (CPU ticks per second, the page size).
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "1.1.5", features = ["param"] }
[dev-dependencies]
# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests
# need no display. gpui-kit's own `test-support` feature is not used: it names
# the optional `gpui-fast` backend in weak features, which puts gpui-fast and
# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit
# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does
# not resolve).
gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] }
[lints]
workspace = true
+34
View File
@@ -0,0 +1,34 @@
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
//! table written with `std`.
use std::fmt::Write as _;
use std::path::PathBuf;
fn main() {
let manifest =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let dir = manifest.join("../voelin-ui/ui/assets/icons");
println!("cargo:rerun-if-changed={}", dir.display());
let mut names: Vec<String> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.filter(|name| name.ends_with(".svg"))
.collect();
names.sort();
assert!(!names.is_empty(), "no icons in {}", dir.display());
let mut table = String::from(
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
);
for name in &names {
let path = dir.join(name);
let path = path.canonicalize().unwrap_or(path);
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
}
table.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
std::fs::write(out, table).expect("write icons.rs");
}
File diff suppressed because it is too large. Load diff
+85
View File
@@ -0,0 +1,85 @@
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
//! icons the client draws; anything else (the rest of gpui-kit-assets'
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
//! gpui-kit-assets.
use std::borrow::Cow;
use gpui_kit::{AssetSource, Result, SharedString};
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
/// The client's icons first, then gpui-kit-assets'.
#[derive(Clone, Copy, Debug, Default)]
pub struct Assets;
/// The client's icon of a file name (`mic.svg`), if it has one.
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
}
/// The names of the client's icons, sorted.
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
ICONS.iter().map(|(name, _)| *name)
}
/// The app's mark, the Slint front end's `logo.svg`.
const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg");
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
return Ok(Some(Cow::Borrowed(bytes)));
}
if path == "logo.svg" {
return Ok(Some(Cow::Borrowed(LOGO)));
}
gpui_kit::assets::AllAssets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
gpui_kit::assets::AllAssets.list(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_client_set_is_embedded_and_sorted() {
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
for (name, bytes) in ICONS {
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
}
}
#[test]
fn the_client_icon_answers_before_gpui_kit_assets() {
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
let ours = client_icon(name).unwrap();
let kit = gpui_kit::assets::AllAssets
.load(&format!("icons/{name}"))
.unwrap()
.expect("gpui-kit-assets has a mic too");
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
assert_eq!(&*served, ours);
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
}
#[test]
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
let only_in_kit = kit
.iter()
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
.expect("the catalogue has icons the client lacks");
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
// gpui-kit-assets answers a path it does not have with an error, so do we.
assert!(Assets.load("icons/no-such-icon.svg").is_err());
assert!(Assets.load("nothing/here").is_err());
}
}
+264
View File
@@ -0,0 +1,264 @@
//! What the window keeps besides the engine and the state, and opens at start
//! as the Slint front end's `run()` does (`crates/voelin-ui/src/app.rs`): the
//! client's database (the bookmarks, the identities, the chats' read marks),
//! the settings service on the same file, the secrets, and the identity a
//! connection is made with. The directory is the platform's data directory
//! (`voelin_platform::paths::data_dir`, which `VOELIN_DATA_DIR` overrides, so
//! that the two front ends share the store); everything below [`Backend::open`]
//! takes the directory, so that no test reaches the user's own.
//!
//! Left out against the Slint front end: importing the identities of the
//! official TeamSpeak clients at start (it reads the user's own files; the
//! slice with the identities page brings it), the crash reports and the
//! configuration of `--set` on the command line.
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result};
use tracing::warn;
use tsclientlib::Identity;
use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob};
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_TREE, UI_WINDOW, UiSettings,
};
/// The client's database, its settings and its secrets.
pub struct Backend {
/// The bookmarks, the identities and the chats' read marks.
pub store: Store,
/// The settings service, on the same file as the store (its own
/// connection); shared with the engine once [`Backend::attach`] ran.
pub prefs: Settings,
/// The servers' passwords.
pub secrets: Box<dyn Secrets>,
/// The identity of a server whose bookmark names none that exists, and
/// the store has no default for.
identity: Identity,
/// The database file, for the engine's chat history.
database: Option<PathBuf>,
}
/// What the store and the settings hold at start, for the state.
#[derive(Debug)]
pub struct Loaded {
/// The saved servers, in the rail's order.
pub bookmarks: Vec<Bookmark>,
/// The UI's own settings (the `ui` key).
pub settings: UiSettings,
/// The audio settings.
pub audio: AudioSettings,
/// The clients' local volumes.
pub playback: ClientPlaybackMap,
}
/// The data directory of this process: `VOELIN_DATA_DIR`, else the platform's.
pub fn data_dir() -> PathBuf {
voelin_platform::paths::data_dir()
}
/// The settings service on the client database in `dir`
/// ([`voelin_ui_vm::settings::open_settings`], which the Slint front end opens
/// the same way): the UI's keys and this front end's own, then a config file
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists) and
/// `VOELIN_SETTING_*` variables below the stored values. Without the database
/// the settings live in memory.
fn open_settings(dir: &Path) -> Settings {
voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
}
/// The keys that only this front end uses: where the window was
/// (`ui.window`) and what the channel trees remember (`ui.tree`).
fn register_own_keys(prefs: &Settings) {
prefs.register(&UI_WINDOW);
prefs.register(&UI_TREE);
}
impl Backend {
/// Open the database in `dir` (created if need be), its settings and the
/// default identity (made, and kept, when the store has none). `secrets`
/// are where passwords go.
pub fn open(dir: &Path, secrets: Box<dyn Secrets>) -> Result<Self> {
let database = dir.join("client.db");
let store = Store::open(&database).context("failed to open the client database")?;
let prefs = open_settings(dir);
let identity = match store.default_identity()? {
Some(entry) => store.identity(entry.id)?,
None => {
let identity = Identity::create();
store.add_identity(CREATED_IDENTITY, &identity, IdentityOrigin::Created)?;
identity
}
};
Ok(Self { store, prefs, secrets, identity, database: Some(database) })
}
/// A backend that stores nothing and keeps its secrets in memory, with a
/// fresh identity: the tests', and the sample data's.
pub fn in_memory() -> Result<Self> {
let prefs = Settings::in_memory();
voelin_ui_vm::settings::register_keys(&prefs);
register_own_keys(&prefs);
Ok(Self {
store: Store::open_in_memory()?,
prefs,
secrets: Box::new(MemorySecrets::default()),
identity: Identity::create(),
database: None,
})
}
/// What the store and the settings hold now.
pub fn load(&self) -> Loaded {
Loaded {
bookmarks: self.store.bookmarks().unwrap_or_else(|e| {
warn!(%e, "the bookmarks cannot be read");
Vec::new()
}),
settings: (*self.prefs.get_arc(&UI)).clone(),
audio: self.prefs.get(&AUDIO),
playback: self.prefs.get(&CLIENT_PLAYBACK),
}
}
/// Hand the engine what it keeps for the window: the chat history in the
/// same database (without it the engine keeps chats for this run only),
/// the settings service and the audio settings.
pub fn attach(&self, engine: &Engine) {
if let Some(database) = &self.database {
match History::open(database) {
Ok(history) => engine.send(Command::AttachHistory(history)),
Err(e) => warn!(%e, "chat history is not stored this time"),
}
}
engine.send(Command::AttachSettings(self.prefs.clone()));
engine.send(Command::SetAudioSettings(Box::new(self.prefs.get(&AUDIO))));
}
/// The identity a connection to the bookmark `bookmark` uses: its own if
/// it names one the store has, else the store's default, else the one made
/// at start ([`Store::identity_for`]).
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
self.store.identity_for(bookmark.and_then(|b| b.identity), &self.identity)
}
/// The identity of [`Backend::identity_for`] as the engine takes it, for a
/// bookmark that names the identity `named`.
pub fn identity_blob(&self, named: Option<i64>) -> IdentityBlob {
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
}
/// Write what the settings service holds to the database.
pub fn flush(&self) {
if let Err(e) = self.prefs.flush() {
warn!(%e, "could not store settings");
}
}
}
/// The secrets of this run: the OS keyring, and memory for what the keyring
/// refuses (no Secret Service on a headless Linux); the sample data's never
/// reach the keyring.
pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
if demo {
Box::new(MemorySecrets::default())
} else {
Box::new(voelin_store::FallbackSecrets::new("voelin"))
}
}
/// What the tests of this crate need to open a store of their own.
#[cfg(test)]
pub(crate) mod testing {
use std::path::PathBuf;
/// A directory of its own under the temporary one (`TMPDIR`), removed with
/// the guard: no test reaches the user's data directory.
pub(crate) struct TempDir(pub PathBuf);
impl TempDir {
/// An empty directory path named `name` and this process.
pub(crate) fn new(name: &str) -> Self {
let dir =
std::env::temp_dir().join(format!("voelin-gpui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[cfg(test)]
mod tests {
use voelin_ui_vm::settings::WindowState;
use super::testing::TempDir;
use super::*;
fn bookmark(name: &str, address: &str) -> Bookmark {
Bookmark { name: name.into(), address: address.into(), ..Default::default() }
}
/// What a run leaves in the directory is what the next one starts from: the
/// bookmarks, the identity (the same one, not a new one) and the settings.
#[test]
fn a_second_start_finds_what_the_first_kept() {
let dir = TempDir::new("backend");
let first = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
assert_eq!(first.load().bookmarks, Vec::new(), "a new store has no servers");
let id = first.store.add_bookmark(&bookmark("Nightfall", "ts.example")).unwrap();
let uid = first.identity_for(None).key().to_pub().get_uid();
let window = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false };
first.prefs.set(&UI_WINDOW, Some(window)).unwrap();
first.flush();
drop(first);
let second = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
let loaded = second.load();
assert_eq!(
loaded.bookmarks.iter().map(|b| (b.id, b.name.as_str())).collect::<Vec<_>>(),
[(id, "Nightfall")]
);
assert_eq!(second.identity_for(None).key().to_pub().get_uid(), uid, "the identity is kept");
assert_eq!(second.prefs.get(&UI_WINDOW), Some(window));
assert!(dir.0.join("client.db").is_file(), "the database is in the directory given");
}
/// A new server's nickname is the default identity's (one imported from
/// TeamSpeak keeps the nickname used there), not the name the app gave the
/// identity it made.
#[test]
fn a_new_servers_nickname_is_the_default_identitys_unless_the_app_named_it() {
use voelin_ui_vm::servers::sequence::default_nickname;
let backend = Backend::in_memory().unwrap();
let made = Identity::create();
backend.store.add_identity(CREATED_IDENTITY, &made, IdentityOrigin::Created).unwrap();
let nickname = default_nickname(&backend.store);
assert!(nickname != CREATED_IDENTITY && !nickname.trim().is_empty(), "{nickname}");
let imported =
backend.store.add_identity("Nova", &Identity::create(), IdentityOrigin::Imported);
backend.store.set_default_identity(imported.unwrap(), false).unwrap();
assert_eq!(default_nickname(&backend.store), "Nova");
}
#[test]
fn a_server_names_its_identity_and_the_default_serves_the_rest() {
let backend = Backend::in_memory().unwrap();
let (default, alt) = (Identity::create(), Identity::create());
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
backend.store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
let alt_id = backend.store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
assert_eq!(uid(&backend.identity_for(None)), uid(&default), "the first is the default");
let named = Bookmark { identity: Some(alt_id), ..bookmark("a", "a.test") };
assert_eq!(uid(&backend.identity_for(Some(&named))), uid(&alt));
let gone = Bookmark { identity: Some(alt_id + 100), ..bookmark("b", "b.test") };
assert_eq!(uid(&backend.identity_for(Some(&gone))), uid(&default));
}
}
+222
View File
@@ -0,0 +1,222 @@
//! The development switches of the GPUI front end, read from the
//! environment. They are the Slint front end's (docs/ui.md, "Development
//! switches and screenshots") where the GPUI one has the same thing to
//! switch, so that one recipe serves both; the rest are new.
//!
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
//! components, the icons) in place of the shell. The Slint front end's
//! other pages do not exist here yet; they are named in a warning and
//! skipped.
//! - `VOELIN_OPEN=voice` (`voice:compact`): the voice channel page on screen
//! once voice is connected, in place of the server page; `voice:compact`
//! with the smaller stage, which is not stored.
//! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through
//! the app's own events, with their pictures as files of a folder in the
//! temporary directory (removed when the window closes); nothing is sent to
//! the engine or kept in the store.
//! - `VOELIN_DEMO_SERVER=2`: with `VOELIN_DEMO_UI`, the sample server on
//! screen, counting from 0 (the first, which is connected and populated, is
//! the default; the second is observed, the third not connected).
//! - `VOELIN_DEMO_TALK=10`: with `VOELIN_DEMO_UI`, one of the sample people
//! starts and stops talking this many times a second, through the app's own
//! events (what the meter measures while someone talks).
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
//! one the settings give (`ui.theme`).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the
//! settings' (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size, in place of the
//! remembered one (`ui.window`), which it then leaves alone.
//! - `VOELIN_METER=1`: the cost meter, one log line a second
//! ([`crate::meter`]).
use crate::theme::Choice;
/// A page the window can be opened on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
/// The desktop shell.
Shell,
/// Every theme token, a few components and the icons.
Swatch,
}
/// What the environment switched.
#[derive(Clone, Debug, PartialEq)]
pub struct Switches {
/// The page to open on.
pub open: Page,
/// The voice channel page is asked for (`VOELIN_OPEN=voice`): it shows
/// once voice is connected.
pub voice: bool,
/// With the voice page, the smaller stage, as the switch says (it is not
/// stored, as the Slint front end's `voice:compact`).
pub voice_compact: bool,
/// Show the sample servers instead of the stored ones.
pub demo_ui: bool,
/// Write the sample servers' pictures to a folder of the temporary
/// directory and deliver them: what the binary does with the sample
/// servers, and what a test asks for by name (a test that does not leaves
/// nothing behind).
pub demo_pictures: bool,
/// The sample server to show, by its place in the list, when the switch
/// names one.
pub demo_server: Option<usize>,
/// How many times a second a sample person starts or stops talking (with
/// the sample servers), when the switch names a rate.
pub demo_talk: Option<f32>,
/// The theme mode, when the switch names one.
pub theme: Option<Choice>,
/// The text size factor, when the switch names one.
pub font_scale: Option<f32>,
/// The window's size in pixels, when the switch names one.
pub window: Option<(f32, f32)>,
/// Log the cost meter.
pub meter: bool,
}
impl Default for Switches {
fn default() -> Self {
Self {
open: Page::Shell,
voice: false,
voice_compact: false,
demo_ui: false,
demo_pictures: false,
demo_server: None,
demo_talk: None,
theme: None,
font_scale: None,
window: None,
meter: false,
}
}
}
impl Switches {
/// The switches of this process's environment.
pub fn from_env() -> Self {
Self::parse(|name| std::env::var(name).ok())
}
/// The switches `get` answers for; what it does not understand is logged
/// and left out.
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
let mut switches = Self::default();
if let Some(list) = get("VOELIN_OPEN") {
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
match what {
"swatch" => switches.open = Page::Swatch,
"voice" => switches.voice = true,
"voice:compact" => (switches.voice, switches.voice_compact) = (true, true),
other => tracing::warn!(
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)"
),
}
}
}
if let Some(name) = get("VOELIN_DEV_THEME") {
match Choice::parse(name.trim()) {
Some(choice) => switches.theme = Some(choice),
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
}
}
if let Some(text) = get("VOELIN_FONT_SCALE") {
match text.trim().parse::<f32>() {
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
}
}
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
match parse_size(&text) {
Some(size) => switches.window = Some(size),
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
if let Some(text) = get("VOELIN_DEMO_SERVER") {
match text.trim().parse::<usize>() {
Ok(place) if place < 3 => switches.demo_server = Some(place),
_ => tracing::warn!("VOELIN_DEMO_SERVER={text}: 0, 1 or 2 (a sample server)"),
}
}
if let Some(text) = get("VOELIN_DEMO_TALK") {
match text.trim().parse::<f32>() {
Ok(rate) if (0.1..=100.0).contains(&rate) => switches.demo_talk = Some(rate),
_ => tracing::warn!("VOELIN_DEMO_TALK={text}: a rate from 0.1 to 100 a second"),
}
}
let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0"));
switches.demo_ui = flag("VOELIN_DEMO_UI");
switches.demo_pictures = switches.demo_ui;
switches.meter = flag("VOELIN_METER");
switches
}
}
/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way.
fn parse_size(text: &str) -> Option<(f32, f32)> {
let (w, h) = text.trim().split_once('x')?;
let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32))
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
fn env(pairs: &[(&str, &str)]) -> Switches {
let map: HashMap<String, String> =
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
Switches::parse(|name| map.get(name).cloned())
}
#[test]
fn nothing_switched_is_the_shell_in_the_settings_theme() {
assert_eq!(env(&[]), Switches::default());
}
#[test]
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch,voice:compact"),
("VOELIN_DEMO_UI", "1"),
("VOELIN_DEMO_SERVER", "2"),
("VOELIN_DEMO_TALK", "10"),
("VOELIN_DEV_THEME", "light"),
("VOELIN_FONT_SCALE", "1.25"),
("VOELIN_WINDOW_SIZE", "1440x960"),
("VOELIN_METER", "1"),
]);
assert_eq!(s.open, Page::Swatch);
assert!(s.voice && s.voice_compact, "the voice page, with the smaller stage");
assert!(s.demo_ui && s.demo_pictures, "the sample servers come with their pictures");
assert_eq!(s.demo_server, Some(2));
assert_eq!(s.demo_talk, Some(10.0));
assert_eq!(s.theme, Some(Choice::Light));
assert_eq!(s.font_scale, Some(1.25));
assert_eq!(s.window, Some((1440.0, 960.0)));
assert!(s.meter);
}
#[test]
fn the_voice_page_alone_has_the_larger_stage() {
let s = env(&[("VOELIN_OPEN", "voice")]);
assert_eq!((s.open, s.voice, s.voice_compact), (Page::Shell, true, false));
}
#[test]
fn what_makes_no_sense_is_left_out() {
let s = env(&[
("VOELIN_OPEN", "settings:voice,home"),
("VOELIN_DEV_THEME", "blue"),
("VOELIN_FONT_SCALE", "9"),
("VOELIN_WINDOW_SIZE", "10x10"),
("VOELIN_DEMO_UI", "0"),
("VOELIN_DEMO_SERVER", "7"),
("VOELIN_DEMO_TALK", "fast"),
("VOELIN_METER", "0"),
]);
assert_eq!(s, Switches::default());
}
}
+64
View File
@@ -0,0 +1,64 @@
//! The engine this front end runs on, the same one the Slint front end
//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started
//! on a tokio runtime, its events forwarded into a channel the window reads.
//! The Slint crate cannot be a dependency here (it brings Slint in), so the
//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front
//! end is retired.
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::settings::Settings;
use voelin_core::{Backends, Engine, Event, History};
/// An engine owned by the caller of [`crate::run`].
pub struct HostedEngine {
/// The handle: commands go in through it.
pub engine: Engine,
/// The runtime the engine runs on; the window's helpers run there too.
pub runtime: Handle,
/// The engine's events for the window: first those that rebuild the
/// current state of every session, then new ones. Reading them needs no
/// reactor, so the window's foreground executor can await it.
pub events: mpsc::UnboundedReceiver<Event>,
}
impl HostedEngine {
/// A new engine on `runtime`, all of whose events go to the window.
pub fn start(runtime: &Runtime) -> Self {
Self::forward(runtime, runtime.block_on(async { Engine::start() }))
}
/// A new engine on `runtime` that connects with `backends` only, and keeps
/// nothing (settings and chat history in memory): the tests' (with
/// [`Backends::empty`] a connect ends at once, saying that no connector
/// serves the address, and touches neither the network nor the sound
/// devices).
pub fn start_with_backends(runtime: &Runtime, backends: Backends) -> Self {
Self::forward(
runtime,
runtime.block_on(async {
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends)
}),
)
}
/// Forward the events of `engine` into the channel the window reads.
fn forward(runtime: &Runtime, engine: Engine) -> Self {
let (tx, events) = mpsc::unbounded_channel();
let mut rx = engine.subscribe();
runtime.spawn(async move {
loop {
match rx.recv().await {
Ok(event) => {
if tx.send(event).is_err() {
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
});
Self { engine, runtime: runtime.handle().clone(), events }
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Inter, the UI font, as the Slint front end bundles it
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
//! come later (the chat slice; docs/design/gpui-spikes.md, "Open choices for step 3").
use std::borrow::Cow;
use gpui_kit::App;
/// The files of the family: regular, medium, semibold, bold, italic.
const INTER: [&[u8]; 5] = [
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
];
/// Add Inter to GPUI's text system.
pub fn load(cx: &mut App) {
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
if let Err(error) = cx.text_system().add_fonts(fonts) {
tracing::warn!(%error, "cannot add Inter to the text system");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_files_are_fonts() {
for bytes in INTER {
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
}
}
}
+361
View File
@@ -0,0 +1,361 @@
//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the
//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports
//! the key's presses and releases, whichever window has the focus.
//!
//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`),
//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the
//! engine's runtime and the front end's own way back to its state, and the
//! Slint crate cannot be a dependency (it brings Slint in); both go into one
//! place when the Slint front end is retired.
//!
//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on
//! it), not from a foreground task of GPUI: the portal's backend calls
//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which
//! panics where no tokio runtime is current, and GPUI's executor has none.
use std::future::Future;
use tokio::runtime::Handle;
use tokio::sync::mpsc;
use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
/// The id of the push-to-talk registration (the portal remembers the user's
/// choice by it).
const PTT_ID: &str = "push-to-talk";
/// The handle to the hotkey task.
pub struct GlobalPtt {
tx: mpsc::UnboundedSender<Option<String>>,
}
impl GlobalPtt {
/// Start the task on `runtime`. `status` gets a line that says how the key
/// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered),
/// `transmit` the key's state; both are called on the runtime, so they hand
/// over to GPUI's thread ([`crate::app::Later`]).
pub fn start(
runtime: &Handle,
status: impl Fn(String) + Send + 'static,
transmit: impl Fn(bool) + Send + 'static,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
runtime.spawn(run(rx, status, transmit));
Self { tx }
}
/// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered,
/// or nothing.
pub fn set(&self, key: Option<String>) {
let _ = self.tx.send(key);
}
}
/// A stream of press and release events for one registered hotkey (`None` once
/// the desktop removes it).
trait EventStream: Send {
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send;
}
impl EventStream for HotkeyEvents {
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send {
HotkeyEvents::recv(self)
}
}
/// Registers and unregisters the global push-to-talk hotkey with the platform
/// (or a test double).
trait Registrar: Send {
type Events: EventStream;
fn register(
&mut self,
key: String,
hotkey: Hotkey,
) -> impl Future<Output = Result<(Self::Events, String), String>> + Send;
fn unregister(&mut self) -> impl Future<Output = ()> + Send;
}
/// The real platform hotkey manager, opened lazily on the first registration.
struct PlatformRegistrar {
manager: Option<HotkeyManager>,
}
impl Registrar for PlatformRegistrar {
type Events = HotkeyEvents;
async fn register(
&mut self,
key: String,
hotkey: Hotkey,
) -> Result<(Self::Events, String), String> {
if self.manager.is_none() {
match HotkeyManager::new().await {
Ok(m) => self.manager = Some(m),
Err(e) => return Err(format!("Global hotkeys are not available: {e}")),
}
}
let Some(m) = &mut self.manager else {
return Err("Global hotkeys are not available.".into());
};
match m.register(PTT_ID, "Push to talk", hotkey).await {
Ok(registered) => {
let line = match m.backend() {
BackendKind::Portal => format!(
"Registered with the desktop: {}",
m.trigger_description(PTT_ID).unwrap_or(key)
),
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
BackendKind::WindowsHook => format!("Active: {hotkey}"),
};
Ok((registered, line))
}
Err(e) => Err(format!("Could not register {key}: {e}")),
}
}
async fn unregister(&mut self) {
if let Some(m) = &mut self.manager {
let _ = m.unregister(PTT_ID).await;
}
}
}
/// The next event of the registration, or never while there is none.
async fn next_event<E: EventStream>(events: &mut Option<E>) -> Option<HotkeyEvent> {
match events {
Some(events) => events.recv().await,
None => std::future::pending().await,
}
}
/// The task: a key to register (or none) arrives on `rx`, the registered key's
/// events are reported through `transmit`, and `status` says what happened.
async fn run(
rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await;
}
/// The event loop of [`run`], parameterised over `registrar` so the
/// fail-closed release paths are tested without a portal or display.
async fn run_loop<R: Registrar>(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
mut registrar: R,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
let mut events: Option<R::Events> = None;
loop {
tokio::select! {
key = rx.recv() => {
let Some(key) = key else {
// Fail closed on task exit: drop any hold that was still down.
transmit(false);
break;
};
events = None;
// Whatever was held no longer counts.
transmit(false);
registrar.unregister().await;
let Some(key) = key else {
status("Off.".into());
continue;
};
let hotkey: Hotkey = match key.parse() {
Ok(h) => h,
Err(e) => {
status(format!("{e}"));
continue;
}
};
match registrar.register(key, hotkey).await {
Ok((registered, line)) => {
events = Some(registered);
status(line);
}
Err(line) => status(line),
}
}
event = next_event(&mut events) => match event {
Some(HotkeyEvent::Pressed) => transmit(true),
Some(HotkeyEvent::Released) => transmit(false),
None => {
events = None;
// Fail closed if the desktop removes the shortcut mid-hold.
transmit(false);
status("The hotkey was removed by the desktop.".into());
}
},
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::*;
/// A channel-backed event stream for testing [`run_loop`] without a display.
struct FakeEvents(mpsc::UnboundedReceiver<HotkeyEvent>);
impl EventStream for FakeEvents {
async fn recv(&mut self) -> Option<HotkeyEvent> {
self.0.recv().await
}
}
/// A registrar that hands out a prepared [`FakeEvents`] stream once.
struct FakeRegistrar {
stream: Option<FakeEvents>,
}
impl Registrar for FakeRegistrar {
type Events = FakeEvents;
async fn register(
&mut self,
_key: String,
hotkey: Hotkey,
) -> Result<(Self::Events, String), String> {
let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?;
Ok((events, format!("Active: {hotkey} (test)")))
}
async fn unregister(&mut self) {}
}
/// Next recorded message from the task, bounded only against a hang.
async fn recv_log(rx: &mut mpsc::UnboundedReceiver<String>) -> String {
tokio::time::timeout(Duration::from_secs(30), rx.recv())
.await
.expect("hotkey loop timed out")
.expect("log channel closed unexpectedly")
}
/// A key that is not one is said so and registers nothing, and the held
/// state is let go first; no display or desktop is needed to say it.
#[test]
fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let (said, held) = (log.clone(), log.clone());
let ptt = GlobalPtt::start(
runtime.handle(),
move |line| said.lock().unwrap().push(format!("status: {line}")),
move |on| held.lock().unwrap().push(format!("transmit: {on}")),
);
ptt.set(Some("Ctrl+Hyper+Banana".into()));
ptt.set(None);
// The task answers in order: the last answer says the end of the list.
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while log.lock().unwrap().len() < 4 {
assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap());
std::thread::sleep(Duration::from_millis(5));
}
let log = log.lock().unwrap().clone();
assert_eq!(log[0], "transmit: false", "{log:?}");
assert!(log[1].starts_with("status: "), "the parse error: {log:?}");
assert_eq!(log[2], "transmit: false", "{log:?}");
assert_eq!(log[3], "status: Off.", "{log:?}");
drop(ptt);
runtime.shutdown_timeout(Duration::from_secs(2));
}
/// When the desktop removes the registered hotkey while it is pressed, the
/// loop releases transmit before reporting the removal.
#[test]
fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() {
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(async {
let (tx_key, rx_key) = mpsc::unbounded_channel();
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
let (said, held) = (tx_log.clone(), tx_log);
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
let task = tokio::spawn(run_loop(
rx_key,
registrar,
move |line| {
let _ = said.send(format!("status: {line}"));
},
move |on| {
let _ = held.send(format!("transmit: {on}"));
},
));
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
tx_evt.send(HotkeyEvent::Pressed).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
// Desktop removes the shortcut while held.
drop(tx_evt);
assert_eq!(
recv_log(&mut rx_log).await,
"transmit: false",
"transmit must fail closed before reporting removal"
);
assert_eq!(
recv_log(&mut rx_log).await,
"status: The hotkey was removed by the desktop."
);
drop(tx_key);
tokio::time::timeout(Duration::from_secs(30), task)
.await
.expect("task exit timed out")
.unwrap();
});
}
/// When the command channel closes (task exit) while the hotkey is pressed,
/// the loop releases transmit before exiting.
#[test]
fn closing_command_channel_mid_hold_releases_transmit_before_exiting() {
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(async {
let (tx_key, rx_key) = mpsc::unbounded_channel();
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
let (said, held) = (tx_log.clone(), tx_log);
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
let task = tokio::spawn(run_loop(
rx_key,
registrar,
move |line| {
let _ = said.send(format!("status: {line}"));
},
move |on| {
let _ = held.send(format!("transmit: {on}"));
},
));
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
tx_evt.send(HotkeyEvent::Pressed).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
// Keep the event stream open while the handle drops (task exit).
drop(tx_key);
tokio::time::timeout(Duration::from_secs(30), task)
.await
.expect("task exit timed out")
.unwrap();
assert_eq!(
rx_log.try_recv().ok().as_deref(),
Some("transmit: false"),
"closing rx mid-hold must release transmit before breaking"
);
drop(tx_evt);
});
}
}
+273
View File
@@ -0,0 +1,273 @@
//! The GPUI front end of the desktop app, under construction (plan section 6
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
//! reaches parity; both run on the same engine.
#![warn(missing_docs)]
pub mod app;
pub mod assets;
pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod hotkey;
pub mod meter;
pub mod pictures;
pub mod shell;
pub mod signals;
pub mod swatch;
pub mod theme;
pub mod view;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use gpui_kit::{
App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, point, px, size,
};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
use voelin_ui_vm::settings::WindowState;
use crate::app::{AppState, Setup, appearance};
use crate::assets::Assets;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::engine::HostedEngine;
use crate::meter::Counters;
use crate::theme::VoelinTheme;
use crate::view::MainView;
/// The smallest size the window can be given.
const MIN_SIZE: (f32, f32) = (640.0, 480.0);
/// The size of a window that has no remembered one.
const DEFAULT_SIZE: (f32, f32) = (1280.0, 800.0);
/// How long the engine gets, after the window closed, to act on the
/// `CloseSession` commands the close sent (the Slint front end waits as long):
/// its tasks run on the runtime, and shutting the runtime down drops them.
const CLOSE_GRACE: Duration = Duration::from_millis(500);
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
/// crate, this front end's information, and what GPUI says about the display
/// and the GPU adapter it picked (which device a run used). Two warnings are
/// left out because they are harmless: zbus's, as in the Slint front end (it
/// warns when a desktop portal's request object is gone before it reads its
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
/// asks for the platform's UI font, which Linux has no name for, before the
/// theme names Inter; the text system falls back).
const LOG_FILTER: &str =
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
/// GPUI logs through the `log` crate; the subscriber carries those records.
pub fn init_logging() {
let filter = EnvFilter::try_from_env("VOELIN_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
let _ = tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
.try_init();
}
/// Where the window opens: the size a development switch names, else the
/// remembered place if a screen still shows its corner (a monitor can have
/// gone since), else the middle of the screen at the default size. A place
/// that has no position (Wayland does not tell one) is the remembered size
/// in the middle. A window left maximized is asked for as maximized here, and
/// again by [`MainView`] once it is shown (an X11 window manager loses this
/// request: it manages a window only from its map).
fn window_bounds(switches: &Switches, remembered: Option<WindowState>, cx: &App) -> WindowBounds {
let sized = |(width, height): (f32, f32)| size(px(width), px(height));
if let Some(forced) = switches.window {
return WindowBounds::centered(sized(forced), cx);
}
let Some(state) = remembered else {
return WindowBounds::centered(sized(DEFAULT_SIZE), cx);
};
let remembered_size =
sized(((state.width as f32).max(MIN_SIZE.0), (state.height as f32).max(MIN_SIZE.1)));
let at = state.x.zip(state.y).map(|(x, y)| point(px(x as f32), px(y as f32)));
let bounds = match at {
Some(origin)
if cx.displays().iter().any(|display| {
display.bounds().intersects(&Bounds::new(origin, size(px(64.0), px(32.0))))
}) =>
{
Bounds::new(origin, remembered_size)
}
_ => Bounds::centered(None, remembered_size, cx),
};
if state.maximized { WindowBounds::Maximized(bounds) } else { WindowBounds::Windowed(bounds) }
}
/// The main window's options: titled with the app's name (and the server
/// shown), grouped by its id, opened where [`window_bounds`] says.
fn window_options(
switches: &Switches,
remembered: Option<WindowState>,
title: String,
cx: &App,
) -> WindowOptions {
WindowOptions {
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
window_bounds: Some(window_bounds(switches, remembered, cx)),
..Default::default()
}
}
/// Open the main window on the root state; closing it leaves the servers and
/// ends the app. `closed_sessions` is set to how many sessions the close told
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
// Without a display server GPUI falls back to a headless platform, which
// opens windows that draw nothing and runs until it is stopped.
if cx.compositor_name() == "headless" {
return Err(anyhow::anyhow!(
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
))
.context("cannot open the main window");
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let setup = Setup {
engine: Some(engine),
events,
counters: counters.clone(),
backend,
switches: switches.clone(),
};
move |cx| AppState::new(setup, cx)
});
// The global push-to-talk key, on the engine's runtime (docs/ui.md): once the
// state exists, and never from a test of the state.
app.update(cx, |app, _| app.start_global_ptt());
let options = {
let app = app.read(cx);
window_options(switches, app.remembered_window(), app.window_title(), cx)
};
let page = switches.open;
gpui_kit::open_window(options, cx, {
let app = app.clone();
move |window, cx| {
// The window's own appearance, which may differ from the system's before
// the window exists.
VoelinTheme::set_system_appearance(cx, window.appearance());
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
cx.quit();
true
}
});
cx.new(|cx| MainView::new(app, page, counters, window, cx))
}
})
.context("cannot open the main window")?;
Ok(())
}
/// Wait `grace` on `runtime`, so that the engine's tasks run (they send the
/// closes of the sessions) before the runtime drops them. The sleep is made
/// inside the runtime: a `Sleep` made outside it, as an argument of
/// `block_on`, panics ("there is no reactor running").
fn give_the_engine_time(runtime: &tokio::runtime::Runtime, grace: Duration) {
runtime.block_on(async move { tokio::time::sleep(grace).await });
}
/// Run the app on the current thread until its window closes.
pub fn run() -> Result<()> {
init_logging();
let switches = Switches::from_env();
tracing::info!(
version = env!("CARGO_PKG_VERSION"),
os = std::env::consts::OS,
"Voelin (GPUI) starting"
);
let counters = Counters::default();
if switches.meter {
meter::start(counters.clone());
}
// The engine runs on tokio threads of its own; the window is GPUI's.
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("cannot start the engine's runtime")?;
let hosted = HostedEngine::start(&runtime);
// The store and the settings, in the platform's data directory
// (`VOELIN_DATA_DIR` moves it: every run of this binary that is not the
// user's own sets it, and the XDG directories with it).
let backend = Backend::open(&backend::data_dir(), backend::default_secrets(switches.demo_ui))
.context("cannot open the client's store")?;
backend.attach(&hosted.engine);
let (theme, font_scale) = appearance(&backend.prefs, &switches);
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
let closed_sessions: Rc<Cell<usize>> = Rc::default();
gpui_kit::application().with_assets(Assets).run({
let failure = failure.clone();
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
shell::bind_keys(cx);
fonts::load(cx);
// The mode and the text size are the settings', or a development
// switch's.
VoelinTheme::init(cx, theme, cx.window_appearance(), font_scale);
if let Err(e) =
open_main_window(cx, &switches, hosted, backend, counters, closed_sessions)
{
*failure.borrow_mut() = Some(e);
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
// before it starts its event loop, and the loop forgets a stop
// asked for earlier (calloop clears its stop signal when it
// starts), so the process would stay with no window and no
// message. A task runs inside the loop.
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
}
}
});
// The close told the engine to close the sessions; give its tasks time to
// send that before the runtime drops them (`shutdown_timeout` waits for
// blocking tasks only), as the Slint front end does, or ghost clients stay
// on the servers until they time out. Any other way to end the app that
// the slices add must call `AppState::shutdown` too.
if closed_sessions.get() > 0 {
give_the_engine_time(&runtime, CLOSE_GRACE);
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
Some(e) => Err(e),
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The grace after a close with open sessions is a wait on the engine's
/// runtime from the GPUI thread, which is no runtime thread: it must not
/// panic, and it must wait. (The first end-to-end close against a server,
/// the first slice that opens a session, found the panic.)
#[test]
fn the_close_grace_waits_on_the_runtime_from_a_thread_that_is_none() {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let started = std::time::Instant::now();
give_the_engine_time(&runtime, Duration::from_millis(30));
assert!(started.elapsed() >= Duration::from_millis(30));
runtime.shutdown_timeout(Duration::from_secs(2));
}
}
+6
View File
@@ -0,0 +1,6 @@
//! `voelin-gpui`: the GPUI front end of the desktop app (docs/ui.md, "The
//! GPUI front end").
fn main() -> anyhow::Result<()> {
voelin_gpui::run()
}
+357
View File
@@ -0,0 +1,357 @@
//! What the app costs, once a second, in the log: the CPU of the process and
//! of each group of threads, the resident memory, and the app's own counters
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
//! it costs). It is `spike_common::meter` of the GPUI spikes
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
//! measuring run's summary and exit, writing log lines instead of JSON.
//!
//! CPU is in percent of one core (200 means two cores busy). Threads are
//! grouped by name without a trailing number (`llvmpipe-12` becomes
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
//! threads, work a GPU would take over) from GPUI's thread, the engine's
//! runtime and the codecs. The numbers come from `/proc/self`: on other
//! systems the meter says it cannot read them and stops.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// A number the app counts up (events handled, frames drawn) or sets (open
/// connections); the meter reports counters per second and gauges as they
/// are.
#[derive(Clone, Default, Debug)]
pub struct Counter(Arc<AtomicU64>);
impl Counter {
/// Add one.
pub fn incr(&self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
/// Set (gauges).
pub fn set(&self, value: u64) {
self.0.store(value, Ordering::Relaxed);
}
/// The current value.
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// How many times each pane of the window was rendered (per second). A pane
/// is an entity of its own that the window draws again only when it was
/// notified (`Entity::cached`), or when something below it was; the figures
/// say which panes a change of the state cost.
#[derive(Clone, Default, Debug)]
pub struct Panes {
/// The server rail.
pub rail: Counter,
/// The top bar.
pub topbar: Counter,
/// The sidebar (the server card, the voice and user cards; the tree is
/// inside it).
pub sidebar: Counter,
/// The channel tree.
pub tree: Counter,
/// The main area.
pub main: Counter,
/// The members panel.
pub members: Counter,
/// The voice channel page.
pub voice: Counter,
}
impl Panes {
/// The counters with the names the meter reports them under.
pub fn named(&self) -> [(&'static str, Counter); 7] {
[
("rail", self.rail.clone()),
("topbar", self.topbar.clone()),
("sidebar", self.sidebar.clone()),
("tree", self.tree.clone()),
("main", self.main.clone()),
("members", self.members.clone()),
("voice", self.voice.clone()),
]
}
}
/// The app's own numbers the meter reports besides the process's.
#[derive(Clone, Default, Debug)]
pub struct Counters {
/// Engine events handled by the root state (per second).
pub engine_events: Counter,
/// One-second ticks of the root state (per second: 1).
pub ticks: Counter,
/// Windows drawn (frames, per second).
pub renders: Counter,
/// Renders of each pane of the window (per second).
pub panes: Panes,
/// Jobs other threads handed to the foreground through
/// [`crate::app::Later`] (per second).
pub later_jobs: Counter,
/// Voice connections that are up (a gauge).
pub connections: Counter,
}
/// CPU ticks of the process and of each thread group, and the resident
/// memory, at one moment.
#[derive(Clone, Debug)]
pub struct Snapshot {
at: Instant,
process: u64,
threads: BTreeMap<String, u64>,
rss_bytes: u64,
}
/// The size of a page of memory, for `statm`'s page counts.
#[cfg(target_os = "linux")]
fn page_size() -> u64 {
rustix::param::page_size() as u64
}
/// The size of a page of memory (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn page_size() -> u64 {
4096
}
/// The unit of the CPU times in `stat`.
#[cfg(target_os = "linux")]
fn clock_ticks_per_second() -> u64 {
rustix::param::clock_ticks_per_second()
}
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn clock_ticks_per_second() -> u64 {
100
}
/// `utime + stime` and the name of a `/proc/.../stat` line.
fn ticks_of(stat: &str) -> Option<(String, u64)> {
let open = stat.find('(')?;
let close = stat.rfind(')')?;
let name = stat.get(open + 1..close)?.to_owned();
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
let utime: u64 = fields.get(11)?.parse().ok()?;
let stime: u64 = fields.get(12)?.parse().ok()?;
Some((name, utime + stime))
}
/// A thread's group: its name without a trailing number or separator.
pub fn group_of(name: &str) -> String {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
}
impl Snapshot {
/// Read `/proc/self` now; `None` where there is none.
pub fn now() -> Option<Self> {
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
let mut threads = BTreeMap::new();
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
for entry in dir.flatten() {
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
if let Some((name, ticks)) = ticks_of(&stat) {
*threads.entry(group_of(&name)).or_insert(0) += ticks;
}
}
}
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
.ok()
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
.map_or(0, |pages| pages * page_size());
Some(Self { at: Instant::now(), process, threads, rss_bytes })
}
/// Resident memory in MiB.
pub fn rss_mib(&self) -> f64 {
self.rss_bytes as f64 / (1024.0 * 1024.0)
}
}
/// CPU in percent of one core between two snapshots: the process's and each
/// thread group's that used any (groups that exited in between count from
/// zero).
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
let hz = clock_ticks_per_second() as f64;
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
let process = pct(b.process.saturating_sub(a.process));
let threads = b
.threads
.iter()
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
.filter(|(_, p)| *p > 0.0)
.collect();
(process, threads)
}
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
pub fn line(
cpu: f64,
rss_mib: f64,
threads: &BTreeMap<String, f64>,
rates: &[(&str, f64)],
gauges: &[(&str, u64)],
) -> String {
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
// The busiest groups first; a thread group under 0.5 % is noise.
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
if !busy.is_empty() {
text.push_str(" | threads");
for (name, pct) in busy {
let _ = write!(text, " {name} {pct:.1}");
}
}
text.push_str(" |");
for (name, rate) in rates {
let _ = write!(text, " {name} {rate:.1}/s");
}
if !gauges.is_empty() {
text.push_str(" |");
for (name, value) in gauges {
let _ = write!(text, " {name} {value}");
}
}
text
}
/// Start the meter on a thread of its own: once a second, a log line (target
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
/// `counters`' rates. It ends with the process.
pub fn start(counters: Counters) {
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
let Some(mut last) = Snapshot::now() else {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated: Vec<(&str, Counter)> = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
]
.into_iter()
.chain(counters.panes.named())
.chain([("later_jobs", counters.later_jobs.clone())])
.collect();
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
loop {
std::thread::sleep(Duration::from_secs(1));
let Some(now) = Snapshot::now() else { return };
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
let (cpu, threads) = cpu_between(&last, &now);
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
let rates: Vec<(&str, f64)> = rated
.iter()
.zip(counts.iter().zip(&last_counts))
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
.collect();
let gauges = [("connections", counters.connections.get())];
tracing::info!(
target: "voelin_gpui::meter",
"{}",
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
);
last = now;
last_counts = counts;
}
});
if let Err(error) = spawned {
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_panes_are_counted_by_name() {
let panes = Panes::default();
panes.members.incr();
let named = panes.named();
let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect();
assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]);
let seen: Vec<u64> = named.iter().map(|(_, counter)| counter.get()).collect();
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
}
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
assert_eq!(group_of("voelin-meter"), "voelin-meter");
assert_eq!(group_of("1234"), "1234");
}
#[test]
fn stat_lines_parse_with_spaces_in_names() {
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
}
#[test]
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
let threads = BTreeMap::from([
("main".to_owned(), 5.04),
("llvmpipe".to_owned(), 310.0),
("idle".to_owned(), 0.2),
]);
let text = line(
317.0,
210.44,
&threads,
&[("engine_events", 0.0), ("renders", 59.96)],
&[("connections", 1)],
);
assert_eq!(
text,
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
);
}
#[test]
fn this_process_can_be_read_on_linux() {
if !cfg!(target_os = "linux") {
return;
}
let a = Snapshot::now().expect("/proc/self");
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
// machine this thread gets a tick's worth of CPU only after a long wall
// time: burn CPU until a second reading shows the process's ticks above
// the first, and in a thread group (the process's total and a thread's
// own are rounded separately). The deadline only ends a hang
// (docs/testing/load.md); it never decides the result.
let deadline = Instant::now() + Duration::from_secs(30);
let (b, cpu) = loop {
let burn = Instant::now();
let mut x = 0u64;
while burn.elapsed() < Duration::from_millis(2) {
x = x.wrapping_mul(31).wrapping_add(7);
}
std::hint::black_box(x);
let b = Snapshot::now().expect("/proc/self");
let (cpu, threads) = cpu_between(&a, &b);
if b.process > a.process && !threads.is_empty() {
break (b, cpu);
}
assert!(
Instant::now() < deadline,
"no CPU tick showed in 30 s: {} -> {}",
a.process,
b.process
);
};
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
}
}
+205
View File
@@ -0,0 +1,205 @@
//! Pictures of the engine's cache on screen.
//!
//! The engine writes a picture that arrives again into the same file in its
//! cache (an avatar or a server icon that changed), and GPUI's `img(path)`
//! keeps what it decoded in the asset cache under the path alone, so the new
//! picture would never show. Here the key of a decoded picture is the file
//! and what the file was when the reference to it was made
//! ([`PictureKey`]: the path and the [`Stamp`] of `voelin_ui_vm::image`, its
//! length and time), so a reference made after the file changed is another
//! picture: it is decoded, and the lists that show it compare unequal and
//! draw the row again. What a changed file left in the cache (the decoded
//! copy under the old key, and the texture the atlas made of it) is dropped
//! when the engine says the file was written again
//! ([`forget_stale`], for `Update::reloaded`).
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::Arc;
use gpui_kit::{
App, Asset, Global, ImageAssetLoader, ImageCacheError, ImageSource, Img, RenderImage, Resource,
img,
};
use voelin_ui_vm::image::{ImageRef, ImageSource as Picture, Stamp};
/// What identifies a decoded picture: the file in the engine's cache and what
/// it was when the picture was referred to.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PictureKey {
path: Arc<Path>,
stamp: Stamp,
}
impl PictureKey {
/// The key of a reference to a file of the cache; none for no picture, a
/// picture that cannot be shown (missing or damaged: the reference's
/// size is none) and the pictures that are not files, which the slices
/// that decode them show.
pub fn of(image: &ImageRef) -> Option<Self> {
match &**image {
Picture::File { path, stamp } if image.size().width > 0 => {
Some(Self { path: Arc::from(path.as_path()), stamp: *stamp })
}
_ => None,
}
}
/// The file.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Decodes the file of a [`PictureKey`] as `img(path)` does, keeping the
/// result under the whole key.
enum PictureLoader {}
impl Asset for PictureLoader {
type Source = PictureKey;
type Output = Result<Arc<RenderImage>, ImageCacheError>;
fn load(
source: PictureKey,
cx: &mut App,
) -> impl Future<Output = Self::Output> + Send + 'static {
<ImageAssetLoader as Asset>::load(Resource::Path(source.path), cx)
}
}
/// The keys that were drawn, by file: what [`forget_stale`] has to look at.
#[derive(Default)]
struct Drawn(HashMap<Arc<Path>, Vec<PictureKey>>);
impl Global for Drawn {}
/// Note that `key` is being drawn.
fn note(key: &PictureKey, cx: &mut App) {
let known = cx.has_global::<Drawn>()
&& cx.global::<Drawn>().0.get(key.path()).is_some_and(|keys| keys.contains(key));
if !known {
cx.default_global::<Drawn>().0.entry(key.path.clone()).or_default().push(key.clone());
}
}
/// The picture at `key` as an image element: decoded once per key, and again
/// when the file is another by the stamp. Give it a size and an object fit.
pub fn picture(key: PictureKey) -> Img {
img(ImageSource::Custom(Arc::new(move |window, cx| {
note(&key, cx);
window.use_asset::<PictureLoader>(&key, cx)
})))
}
/// The engine wrote the file at `path` again: drop what was decoded of it
/// under a stamp it no longer has, and the textures the atlas made of that.
/// The picture under the stamp it has now (a reference made after the write)
/// is kept; one that is made from the old file is drawn again when it is next
/// asked for.
pub fn forget_stale(path: &Path, cx: &mut App) {
if !cx.has_global::<Drawn>() {
return;
}
let now = Stamp::of(path);
let stale: Vec<PictureKey> = {
let Some(keys) = cx.global_mut::<Drawn>().0.get_mut(path) else { return };
let (stale, kept) = std::mem::take(keys).into_iter().partition(|key| key.stamp != now);
*keys = kept;
stale
};
for key in stale {
if let Some(Ok(image)) = cx.fetch_asset::<PictureLoader>(&key) {
cx.drop_image(image, None);
}
cx.remove_asset::<PictureLoader>(&key);
}
}
/// Whether the decoded copy of `key` is in the asset cache (the tests ask).
#[cfg(test)]
pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool {
cx.has_asset::<PictureLoader>(key)
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use voelin_ui_vm::image::ImageSource as Source;
use super::*;
use crate::backend::testing::TempDir;
/// A PNG of `width` by 2 pixels.
fn png(width: u32) -> Vec<u8> {
voelin_ui_vm::dev::logic::demo_picture(width, 2, 1)
}
/// The key of a picture follows the file: a reference made after the
/// engine wrote the file again is another picture, one made before still
/// refers to the old, and what is not a file of the cache has none.
#[test]
fn the_key_of_a_picture_changes_when_the_file_does() {
let dir = TempDir::new("picture-key");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let first = Source::file(&path);
let key = PictureKey::of(&first).expect("a picture in the cache");
assert_eq!(key.path(), path);
assert_eq!(PictureKey::of(&Source::file(&path)), Some(key.clone()), "same file, same key");
std::fs::write(&path, png(7)).unwrap();
let second = PictureKey::of(&Source::file(&path)).unwrap();
assert_ne!(second, key, "the file was written again");
assert_eq!(PictureKey::of(&first), Some(key), "a reference made before keeps its own");
assert_eq!(PictureKey::of(&Source::none()), None);
assert_eq!(PictureKey::of(&Source::file(dir.0.join("missing"))), None);
std::fs::write(dir.0.join("damaged"), b"not a picture").unwrap();
assert_eq!(PictureKey::of(&Source::file(dir.0.join("damaged"))), None);
assert_eq!(PictureKey::of(&Source::rgba(1, 1, vec![0; 4])), None, "not a file");
}
/// A picture rewritten into the same file is decoded again under its new
/// key, and what was decoded of the old one is dropped when the engine says
/// the file was written again; the key of the file as it is stays.
#[gpui::test]
fn a_picture_written_again_is_decoded_again_and_the_old_copy_goes(cx: &mut TestAppContext) {
let dir = TempDir::new("picture-reload");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let old = PictureKey::of(&Source::file(&path)).unwrap();
let width = |cx: &mut TestAppContext, key: &PictureKey| {
cx.update(|cx| match cx.fetch_asset::<PictureLoader>(key) {
Some(Ok(image)) => Some(image.size(0).width.0),
_ => None,
})
};
cx.update(|cx| note(&old, cx));
assert_eq!(width(cx, &old), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &old), Some(3));
// The engine writes the file again, and the window draws the picture
// under the key of the file as it is now, before it is told so.
std::fs::write(&path, png(7)).unwrap();
let new = PictureKey::of(&Source::file(&path)).unwrap();
cx.update(|cx| note(&new, cx));
assert_eq!(width(cx, &new), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &new), Some(7), "the new bytes, not the old ones");
assert_eq!(width(cx, &old), Some(3), "the old copy is still there");
cx.update(|cx| forget_stale(&path, cx));
assert!(!cx.update(|cx| cx.has_asset::<PictureLoader>(&old)), "the old copy is dropped");
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)), "the current key is kept");
assert_eq!(width(cx, &new), Some(7));
// Nothing more to forget; a file nobody drew is nothing to forget.
cx.update(|cx| forget_stale(&path, cx));
cx.update(|cx| forget_stale(&dir.0.join("never-drawn"), cx));
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)));
}
}
+206
View File
@@ -0,0 +1,206 @@
//! What the user can ask of the shell, as GPUI actions: the callbacks of the
//! Slint front end's `bind/servers.rs` that the desktop shell has (the first
//! eleven below), and the shell's own affordances. A click dispatches the
//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view
//! ([`crate::view::MainView`]) handles it, and the handler asks the root state
//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings
//! and menus come to the same handlers later.
//!
//! The voice page and the call bar add `show_voice_view`, the page's own
//! buttons (the smaller stage, Leave) and the two affordances of the call bar
//! whose pages come with later slices (Share, the voice settings), which are
//! logged.
//!
//! The channel tree and the members panel add `join_channel`,
//! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and
//! `open_client` (the last one only logs: the client's volume dialog is a
//! dialog of its own slice). The callbacks of `bind/servers.rs` that are
//! still not here belong to the slices after: `client_audio_changed` to the
//! dialogs (the member card has the volume and the mute of a person,
//! [`SetMemberVolume`] and [`SetMemberMuted`]), and `copied` (the toast that
//! follows a copy) to whichever copies: [`Invite`] sets it itself.
use gpui_kit::{Action, actions};
actions!(
voelin,
[
/// `connect_voice`: connect the server on screen with voice, into its default channel.
ConnectVoice,
/// `disconnect_voice`: leave voice on the server on screen.
DisconnectVoice,
/// `invite`: copy a link to the voice channel we are in.
Invite,
/// `save_bookmark`: save the server form (the form's own Save button).
SaveServer,
/// `save_and_connect`: save the server form, then connect.
SaveAndConnect,
/// Open the empty server form (the rail's plus button).
AddServer,
/// Close the server form without saving.
CancelServerForm,
/// The top bar's search box: the search comes with its slice, today it is logged.
OpenSearch,
/// The settings buttons: the settings come with their slice, today it is logged.
OpenSettings,
/// `join_with_password`: the password prompt's Join, with what it holds.
SubmitChannelPassword,
/// Close the password prompt without joining.
CancelChannelPassword,
/// The voice page's Leave (`Nav.show-voice(false)` then `disconnect_voice`).
LeaveVoice,
/// The voice page's Smaller stage / Larger stage (`ui.voice_compact`).
ToggleVoiceCompact,
/// The call bar's Share: the share menu comes with the stream slices, today it is logged.
OpenShare,
/// The call bar's voice settings: the settings come with their slice, today it is logged.
OpenVoiceSettings,
]
);
/// `show_voice_view`: the voice channel page on (the main area) or off (back to
/// the server page, where the chat will be).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ShowVoiceView {
/// Shown from now on.
pub on: bool,
}
/// The member card's volume slider: the person's playback volume, in percent
/// (`member_volume` of the Slint card).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberVolume {
/// The client's id on the server.
pub client: u16,
/// 0 to 200.
pub percent: f32,
}
/// The member card's Mute for me: stop playing the person (local only).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberMuted {
/// The client's id on the server.
pub client: u16,
/// Muted from now on.
pub muted: bool,
}
/// `select_server`: show a server (and observe it).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectServer {
/// The bookmark's id.
pub id: i64,
}
/// `edit_bookmark`: open the server form with a saved server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditServer {
/// The bookmark's id.
pub id: i64,
}
/// `delete_bookmark`: remove a server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct DeleteServer {
/// The bookmark's id.
pub id: i64,
}
/// `set_input_muted`: mute or unmute our microphone.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetInputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `set_output_muted`: mute or unmute the sound.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetOutputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `push_to_talk`: transmit while the hold-to-talk button is held.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct PushToTalk {
/// Transmitting from now on.
pub on: bool,
}
/// `join_channel`: join a channel of the server on screen (a double-click on
/// its row, the context menu's Join).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct JoinChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// A click on a channel's row: select it (the Slint tree opens the channel's
/// chat, which comes with the chat slice).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// `toggle_collapse`: fold or unfold a channel of the tree.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ToggleChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Edit channel: the channel editor is a slice of its own,
/// today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Move to my channel: moving another client needs a command
/// the engine does not have yet, so today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct MoveClient {
/// The client's id on the server.
pub client: u16,
}
/// `open_client`: a click on a person in the tree opens their volume dialog,
/// which is a dialog of its own slice: today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenClient {
/// The client's id on the server.
pub client: u16,
}
/// `search_members`: the members panel's search text.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SearchMembers {
/// What the box holds; empty shows everyone.
pub text: String,
}
/// `open_member`: open the card of a person over the members panel; -1 closes it.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenMember {
/// The client's id on the server, or -1.
pub client: i32,
}
+502
View File
@@ -0,0 +1,502 @@
//! The channel tree of the sidebar (`ChannelTree` of `screens/channels.slint`):
//! the channels of the server on screen with the people in them, nested, with
//! their spacers, pictures, passwords and counts, and the person's marks.
//!
//! A cached pane ([`gpui_kit::Entity::cached`], which needs the size the
//! sidebar gives it) over a virtual list ([`gpui_kit::list`]: only the rows in
//! view are built, the rows differ in height) that follows [`TreeModel`]: the
//! model says which rows changed ([`TreeEvent::Rows`]) and the pane tells its
//! list, so a person who joins is a row inserted and the scroll stays where it
//! was. The pane reads nothing but its own fields while it renders, so
//! nothing but its own notify draws it again. A click selects a channel, a
//! double-click joins it, the chevron folds it, a right-click offers the
//! same; a click on a person is logged (their volume dialog is a slice of
//! its own).
use std::sync::Arc;
use gpui_kit::component::menu::ContextMenuExt as _;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ListAlignment,
ListState, ObjectFit, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, div,
list, px,
};
use voelin_ui_vm::bridge::TreeItem;
use voelin_ui_vm::tree::ChannelId;
use super::actions::{
EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel,
};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture, speaking_bars};
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::theme::{VoelinTheme, hsla};
/// How far each level of the tree is indented.
const INDENT: f32 = 14.0;
/// How opaque the hover and selection tints of a row with a banner are over
/// the banner and its veil: the hover is `channels.slint`'s (`Theme.surface-3.
/// transparentize(0.5)`), the selection, which Slint has no state for, is a
/// stronger one of the same colour.
const BANNER_HOVER: f32 = 0.5;
const BANNER_SELECTED: f32 = 0.75;
/// The channel tree.
pub struct ChannelTree {
rows: Arc<Vec<TreeItem>>,
selected: Option<ChannelId>,
emptiness: Emptiness,
list: ListState,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscription: Subscription,
}
impl ChannelTree {
/// A tree that follows `model`.
pub fn new(model: &Entity<TreeModel>, counters: Counters, cx: &mut Context<Self>) -> Self {
let (rows, selected, emptiness) = {
let model = model.read(cx);
(model.rows().clone(), model.selected(), model.emptiness())
};
let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::Rows(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Selection => this.selected = model.read(cx).selected(),
// The count of people is the members panel's.
TreeEvent::Lists => {
let emptiness = model.read(cx).emptiness();
if emptiness == this.emptiness {
return;
}
this.emptiness = emptiness;
}
TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return,
}
cx.notify();
});
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
selected,
emptiness,
measured_at: 0.0,
counters,
_subscription: subscription,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[TreeItem] {
&self.rows
}
/// The channel it shows selected.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why it shows no rows, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (a
/// channel row and a person's differ).
fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc<Vec<TreeItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut channels: Vec<bool> = self.rows.iter().map(|row| row.is_channel).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if channels[i] != new[i].is_channel {
self.list.splice(i..i + 1, 1);
}
channels[i] = new[i].is_channel;
}
Change::Remove(i) => {
channels.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
channels.insert(i, new[i].is_channel);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The row at `ix`, for the list.
fn row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
match self.rows.get(ix) {
Some(item) if item.is_channel => {
channel_row(&theme, item, self.selected == Some(item.id as ChannelId))
}
Some(item) => client_row(&theme, item),
None => div().into_any_element(),
}
}
}
/// The words of a tree with no rows.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::NoServer => "No server yet.",
Emptiness::Loading => "Loading the channels…",
// The tree is not searched, so it is never `NoMatch` (the members
// panel's, `TreeModel::people_emptiness`): the model gives it
// `Emptiness::of`, which does not say it.
Emptiness::Connect | Emptiness::NoMatch => "Connect to see the channels.",
}
}
/// The chevron of a channel, which folds it.
fn chevron(item: &TreeItem, covered: bool, theme: &VoelinTheme) -> impl IntoElement {
let c = &theme.colors;
let id = item.id as ChannelId;
div()
.id(("tree-toggle", id))
.debug_selector(move || format!("tree-toggle-{id}"))
.w(px(18.0))
.h(px(18.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.on_click(move |_, window, cx| {
cx.stop_propagation();
window.dispatch_action(Box::new(ToggleChannel { channel: id }), cx);
})
.child(icon(
if item.collapsed { "chevron-right" } else { "chevron-down" },
14.0,
if covered { c.text } else { c.text_muted },
))
}
/// One channel: its icon (or a speaker, or a lock), its name as the server
/// set it out, how many are in it, and the chevron.
fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as ChannelId;
let indent = item.depth as f32 * INDENT;
let banner = PictureKey::of(&item.banner);
let covered = banner.is_some();
let strong = item.own || covered;
let (hover, accent_soft, accent, selected_fill) =
(hsla(c.surface_3), hsla(c.accent_soft), hsla(c.accent), hsla(c.surface_3));
let own = item.own;
let has_icon = PictureKey::of(&item.icon).is_some();
let name_color = if strong { c.text } else { c.text_secondary };
let weight = if strong { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM };
let name = div()
.flex_1()
.min_w_0()
.text_size(px(m.font_body))
.font_weight(weight)
.text_color(hsla(name_color))
.when(item.spacer == 2, |name| name.text_center())
.when(item.spacer == 3, |name| name.text_right())
// A line is cut where the row ends; it does not widen the list.
.when(item.spacer == 4, |name| name.overflow_hidden().whitespace_nowrap())
.when(item.spacer != 4, |name| name.truncate())
.child(item.name.to_string());
let counted = item.spacer == 0 && (item.members > 0 || item.max_members >= 0);
let count = if item.max_members >= 0 {
format!("{}/{}", item.members, item.max_members)
} else {
item.members.to_string()
};
let group = SharedString::from(format!("tree-row-{id}"));
let row = div()
.id(("tree-channel", id))
.debug_selector(move || format!("tree-channel-{id}"))
.group(group.clone())
.relative()
.w_full()
.h(px(34.0 * m.font_scale))
.flex_none()
.overflow_hidden()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(own, |row| row.bg(accent_soft).border_1().border_color(accent))
.when(!own && selected, |row| row.bg(selected_fill))
.when(!own && !selected, |row| row.hover(move |style| style.bg(hover)))
// Artwork behind the same compact row as its title, from the indent on,
// under a veil of the surface colour that keeps the text readable over
// any picture, and under the tints of the row: our own channel's, the
// selected one and the one the pointer is over. The artwork covers the
// row's own background (which only the indent shows), so the tints
// are translucent children above the veil, as `channels.slint` does
// for the hover.
.when_some(banner, |row, key| {
let tint = || {
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
};
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id(("tree-scrim", id))
.debug_selector(move || format!("tree-scrim-{id}"))
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.bg(banner_scrim(theme)),
)
.when(own, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
.bg(accent_soft.opacity(0.65)),
)
})
.when(!own && selected, |row| {
row.child(
tint()
.debug_selector(move || format!("tree-selected-{id}"))
.bg(selected_fill.opacity(BANNER_SELECTED)),
)
})
.when(!own && !selected, |row| {
row.child(
tint().group_hover(group, move |style| style.bg(hover.opacity(BANNER_HOVER))),
)
})
})
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent))
.pr(px(m.space_3))
.gap(px(m.space_2))
// A centred spacer is balanced against the chevron.
.when(item.spacer == 2, |row| row.child(div().w(px(18.0)).flex_none()))
.when(item.spacer == 0, |row| match small_picture(&item.icon, 16.0) {
Some(picture) => row.child(picture),
None => row.child(icon(
if item.locked { "lock" } else { "volume-2" },
18.0,
if strong { c.text } else { c.icon },
)),
})
.child(name)
.when(item.locked && (has_icon || item.spacer != 0), |row| {
row.child(icon("lock", 14.0, if covered { c.text } else { c.icon }))
})
.when(counted, |row| {
row.child(
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(own, |count| count.child(icon("users", 14.0, c.text_secondary)))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(if strong { c.text } else { c.text_muted }))
.child(count),
),
)
})
.child(chevron(item, covered, theme))
.on_click(move |event, window, cx| {
if event.click_count() >= 2 {
window.dispatch_action(Box::new(JoinChannel { channel: id }), cx);
} else {
window.dispatch_action(Box::new(SelectChannel { channel: id }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Join channel", Box::new(JoinChannel { channel: id }))
.menu("Fold or unfold", Box::new(ToggleChannel { channel: id }))
.separator()
.menu("Edit channel…", Box::new(EditChannel { channel: id }))
});
row.into_any_element()
}
/// One person: their avatar, name and badges, and the marks of what they do.
fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as u64;
let indent = item.depth as f32 * INDENT;
let (hover, myself) = (hsla(c.surface_3), item.myself);
let name_color = if item.away {
c.text_muted
} else if myself {
c.accent_text
} else {
c.text_secondary
};
let mark = |name: &'static str, color| icon(name, 14.0, color);
div()
.id(("tree-client", id))
.debug_selector(move || format!("tree-client-{id}"))
.w_full()
.h(px(30.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(move |style| style.bg(hover))
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent + 12.0))
.pr(px(m.space_3))
.gap(px(m.space_3))
.child(
Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint)
.image(item.avatar.clone())
.speaking(item.talking),
)
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_body))
.font_weight(if myself { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
// Badges after the name, then the free room.
.child(
div().flex_1().min_w_0().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|badge| small_picture(badge, 14.0)),
),
)
// The Slint bars move; these stand still (nothing here draws the window
// anew with the clock).
.when(item.talking, |row| {
row.child(
div()
.debug_selector(move || format!("tree-speaking-{id}"))
.flex_none()
.child(speaking_bars(theme, 14.0)),
)
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.local_muted, |row| row.child(mark("volume-x", c.warning)))
.when(!item.local_muted && item.local_volume != 100, |row| {
row.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", item.local_volume)),
)
})
.when(item.muted, |row| row.child(mark("mic-off", c.danger)))
.when(item.sound_off, |row| row.child(mark("headphone-off", c.danger)))
.when(item.away, |row| {
row.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child("away"))
})
.children(
[&item.icon, &item.icon_2, &item.icon_3]
.into_iter()
.filter_map(|i| small_picture(i, 16.0)),
)
.on_click(move |_, window, cx| {
if !myself {
window.dispatch_action(Box::new(OpenClient { client: id as u16 }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Show the card", Box::new(OpenMember { client: id as i32 }))
.menu("Volume…", Box::new(OpenClient { client: id as u16 }))
.separator()
.menu("Move to my channel", Box::new(MoveClient { client: id as u16 }))
})
.into_any_element()
}
impl Render for ChannelTree {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.tree.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
// A new text size makes the rows another height.
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
div()
.id("sidebar-channels")
.debug_selector(|| "sidebar-channels".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.px(px(m.space_2))
.child(
div()
.min_h(px(24.0))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_secondary))
.child(icon("volume-2", m.icon_sm, c.text_secondary))
.child("Channels"),
)
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("tree-empty")
.debug_selector(|| "tree-empty".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.row(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The server form: where a server is added or edited (the server dialog of
//! the Slint front end, `bookmark_form` / `save_bookmark` /
//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs
//! come with their slice; until then the form takes the place of the main
//! area, with gpui-component's text inputs: the address (the only thing a
//! server needs), a name (empty: the server's own), the nickname and the
//! server's password.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Window, div, px,
};
use voelin_ui_vm::bridge::BookmarkForm;
use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer};
use super::widgets::{panel, tagged};
use crate::theme::{VoelinTheme, hsla};
/// The form.
pub struct ServerForm {
id: i64,
connected: bool,
address: Entity<InputState>,
name: Entity<InputState>,
nickname: Entity<InputState>,
password: Entity<InputState>,
confirm_remove: bool,
}
impl ServerForm {
/// A form filled in with `form` (id -1: a new server). The address has the
/// focus; Enter in any field saves.
pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context<Self>) -> Self {
let field = |window: &mut Window,
cx: &mut Context<Self>,
placeholder: &str,
value: &str,
masked: bool| {
let input = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(SharedString::from(placeholder.to_owned()))
.default_value(SharedString::from(value.to_owned()))
.masked(masked)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
window.dispatch_action(Box::new(SaveServer), cx);
}
})
.detach();
input
};
let address =
field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false);
let name = field(window, cx, "Optional: the server tells its own", &form.name, false);
let nickname = field(window, cx, "The name others see", &form.nickname, false);
let password = field(window, cx, "Optional", &form.server_password, true);
address.update(cx, |input, cx| input.focus(window, cx));
Self {
id: i64::from(form.id),
connected: form.connected,
address,
name,
nickname,
password,
confirm_remove: false,
}
}
/// The bookmark this form edits; -1 for a new server.
pub fn id(&self) -> i64 {
self.id
}
/// The form as the fields hold it now, for `AppState::save_bookmark`.
pub fn to_form(&self, cx: &App) -> BookmarkForm {
let text = |input: &Entity<InputState>| input.read(cx).value().to_string();
BookmarkForm {
id: self.id as i32,
name: text(&self.name).into(),
address: text(&self.address).into(),
nickname: text(&self.nickname).into(),
server_password: text(&self.password).into(),
connected: self.connected,
..Default::default()
}
}
/// Put `text` in the address field (a link that fills the form comes with
/// its slice; the tests type here).
pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) {
self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
fn labelled(
theme: &VoelinTheme,
label: &'static str,
input: &Entity<InputState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(label),
)
.child(Input::new(input))
}
impl Render for ServerForm {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let new = self.id < 0;
let id = self.id;
let confirm = self.confirm_remove;
panel(&theme)
.id("server-form")
.debug_selector(|| "server-form".into())
.flex_1()
.min_w_0()
.h_full()
.items_center()
.justify_center()
.child(
div()
.w_full()
.max_w(px(440.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(if new { "Add a server" } else { "Edit the server" }),
)
.child(labelled(&theme, "Address", &self.address))
.child(labelled(&theme, "Name", &self.name))
.child(labelled(&theme, "Nickname", &self.nickname))
.child(labelled(&theme, "Server password", &self.password))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(tagged(
"form-save",
Button::new("form-save").primary().label("Save").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveServer), cx)
},
),
))
.when(!self.connected, |row| {
row.child(tagged(
"form-connect",
Button::new("form-connect").label("Save and connect").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveAndConnect), cx)
},
),
))
})
.child(tagged(
"form-cancel",
Button::new("form-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelServerForm), cx)
},
),
))
.when(!new, |row| {
row.child(div().flex_1()).child(tagged(
"form-remove",
Button::new("form-remove")
.danger()
.label(if confirm {
"Click again to remove"
} else {
"Remove"
})
.on_click(cx.listener(move |this, _, window, cx| {
if this.confirm_remove {
window.dispatch_action(
Box::new(DeleteServer { id }),
cx,
);
} else {
this.confirm_remove = true;
cx.notify();
}
})),
))
}),
),
)
}
}
+234
View File
@@ -0,0 +1,234 @@
//! The main area. Until the voice page, the chat and the rest come, it is the
//! empty page: the "no server selected" state with the way to add one, and for
//! a server on screen its name, address and state with the buttons that
//! connect, disconnect and edit it. An entity of its own, drawn as a cached
//! pane: it listens to the servers' signal and tells the window only when
//! what it shows changed.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer, ShowVoiceView};
use super::widgets::{Avatar, Presence, icon, panel, tagged};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the main area shows.
#[derive(Clone, Debug, PartialEq)]
pub enum MainState {
/// No server is on screen.
NoServer,
/// A server is.
Server(ServerItem),
}
impl MainState {
/// The main area for the state.
pub fn of(app: &AppState) -> Self {
let current = app.vm.current;
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| Some(i64::from(item.id)) == current)
.map_or(Self::NoServer, Self::Server)
}
}
/// The words for a server's state.
fn state_words(status: &str) -> &'static str {
match status {
"connected" => "Connected with voice",
"connecting" => "Connecting…",
"observing" => "Observed without joining",
_ => "Not connected",
}
}
/// The main area.
pub struct MainPanel {
state: MainState,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MainPanel {
/// A main area that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (state, counters, signals) = {
let shown = app.read(cx);
(MainState::of(shown), shown.counters().clone(), shown.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let state = MainState::of(app.read(cx));
if state != this.state {
this.state = state;
cx.notify();
}
});
Self { state, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn state(&self) -> &MainState {
&self.state
}
}
impl Render for MainPanel {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.main.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let body = match &self.state {
MainState::NoServer => div()
.id("main-empty")
.debug_selector(|| "main-empty".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
div()
.size(px(72.0))
.rounded(px(m.radius_xl))
.bg(hsla(c.surface_2))
.border_1()
.border_color(hsla(c.border))
.flex()
.items_center()
.justify_center()
.child(icon("server", 32.0, c.text_muted)),
)
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child("No server selected"),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Pick a server in the list, or add one to start talking."),
)
.child(tagged(
"main-add",
Button::new("main-add")
.primary()
.label("Add a server")
.on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)),
)),
MainState::Server(item) => {
let id = i64::from(item.id);
let connected = item.status.as_ref() == "connected";
let connecting = item.status.as_ref() == "connecting";
div()
.id("main-server")
.debug_selector(|| "main-server".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.child(
div()
.max_w(px(480.0))
.truncate()
.text_size(px(m.font_2xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div()
.text_size(px(m.font_body))
.text_color(hsla(c.text_secondary))
.child(item.address.to_string()),
)
.child(
div()
.id("main-server-state")
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(state_words(&item.status)),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Its chat comes with a later slice."),
)
.child(
div()
.flex()
.flex_row()
.gap(px(m.space_3))
.when(connected || connecting, |row| {
row.child(tagged(
"main-disconnect",
Button::new("main-disconnect")
.danger()
.label("Disconnect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
))
})
.when(!connected && !connecting, |row| {
row.child(tagged(
"main-connect",
Button::new("main-connect")
.primary()
.label("Connect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ConnectVoice), cx);
}),
))
})
.when(connected, |row| {
row.child(tagged(
"main-voice",
Button::new("main-voice")
.primary()
.label("Voice channel")
.on_click(|_, window, cx| {
window.dispatch_action(
Box::new(ShowVoiceView { on: true }),
cx,
);
}),
))
})
.child(tagged(
"main-edit",
Button::new("main-edit").label("Edit").on_click(
move |_, window, cx| {
window.dispatch_action(Box::new(EditServer { id }), cx);
},
),
)),
)
}
};
// The root of a cached pane takes the size its place gives it: laid out
// on its own, `flex_1` would be as wide as its contents.
panel(&theme).id("main").size_full().items_center().justify_center().child(body)
}
}
+768
View File
@@ -0,0 +1,768 @@
//! The members panel (`MembersPanel` and `MemberCardPopup` of
//! `screens/members.slint`): everyone on the server in sections (those
//! streaming first, then each server group), a search, and the card of one
//! person over the panel.
//!
//! [`MembersPane`] is a cached pane over a virtual list that follows
//! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations
//! the list applies). A talker redraws it, with the tree: a person's row has
//! the speaking ring, "Speaking" and the bars, and no other pane of the window
//! is told. [`MemberCardView`] is the card, a card over the window with a scrim
//! that a click outside closes; it has the volume and the mute of the person for
//! us (`SetMemberVolume`, `SetMemberMuted`), and its other buttons (a message, a
//! poke, friends, blocking) come with the slices that have those dialogs.
use std::sync::Arc;
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::slider::{Slider, SliderEvent, SliderState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ListAlignment, ListState, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, list, px,
};
use voelin_ui_vm::bridge::{MemberCard, MemberItem};
use voelin_ui_vm::list::Changes;
use super::actions::{OpenMember, SearchMembers, SetMemberMuted, SetMemberVolume};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{
Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars,
};
use crate::meter::Counters;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// The colour of the shield of a moderator's role.
const ROLE: Rgba = Rgba(0xc06c_ffff);
/// The members panel.
pub struct MembersPane {
rows: Arc<Vec<MemberItem>>,
total: i32,
emptiness: Emptiness,
/// The person whose card is open.
open: Option<i32>,
list: ListState,
search: Entity<InputState>,
searching: bool,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MembersPane {
/// A panel that follows `model`.
pub fn new(
model: &Entity<TreeModel>,
counters: Counters,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let (rows, total, emptiness, open) = {
let model = model.read(cx);
(
model.people().clone(),
model.total(),
model.people_emptiness(),
model.card().map(|c| c.id),
)
};
let search = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Search members…"))
});
let subscriptions = vec![
cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Lists => {
let model = model.read(cx);
let now = (model.total(), model.people_emptiness());
if now == (this.total, this.emptiness) {
return;
}
(this.total, this.emptiness) = now;
}
TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id),
TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return,
}
cx.notify();
}),
cx.subscribe_in(&search, window, |_, input, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::Change) {
let text = input.read(cx).value().to_string();
window.dispatch_action(Box::new(SearchMembers { text }), cx);
}
}),
];
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
total,
emptiness,
open,
search,
searching: false,
measured_at: 0.0,
counters,
_subscriptions: subscriptions,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[MemberItem] {
&self.rows
}
/// The person whose card is open, as the panel marks them.
pub fn open(&self) -> Option<i32> {
self.open
}
/// Why it shows no one, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Whether the search box is shown.
pub fn searching(&self) -> bool {
self.searching
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (the
/// first row of a section has the heading above it).
fn apply(&mut self, changes: &Changes, new: Arc<Vec<MemberItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut headed: Vec<bool> = self.rows.iter().map(|row| row.first_in_group).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if headed[i] != new[i].first_in_group {
self.list.splice(i..i + 1, 1);
}
headed[i] = new[i].first_in_group;
}
Change::Remove(i) => {
headed.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
headed.insert(i, new[i].first_in_group);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The search box was opened or closed: closing it shows everyone again.
fn toggle_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.searching = !self.searching;
if self.searching {
self.search.update(cx, |input, cx| input.focus(window, cx));
} else {
self.search.update(cx, |input, cx| input.set_value("", window, cx));
window.dispatch_action(Box::new(SearchMembers { text: String::new() }), cx);
}
cx.notify();
}
/// The entry at `ix` for the list: the heading of its section if it opens
/// one, then the person.
fn entry(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
let Some(item) = self.rows.get(ix) else { return div().into_any_element() };
let m = &theme.metrics;
div()
.w_full()
.px(px(m.space_3))
.flex()
.flex_col()
.when(item.first_in_group, |entry| entry.child(group_header(&theme, item)))
.child(member_row(&theme, item, self.open == Some(item.id)))
.into_any_element()
}
}
/// The words of a panel with nobody in it.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::Loading => "Loading who is here…",
Emptiness::NoMatch => "Nobody matches.",
Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.",
}
}
/// The heading above the first person of a section: "Moderator — 3".
fn group_header(theme: &VoelinTheme, item: &MemberItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let words = if item.group_count > 0 {
format!("{} — {}", item.group, item.group_count)
} else {
item.group.to_string()
};
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pt(px(m.space_5))
.pb(px(m.space_2))
.pl(px(m.space_2))
.children(small_picture(&item.group_icon, 16.0))
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(words),
)
}
/// One person: avatar, name with their badges and role, what they are doing.
fn member_row(theme: &VoelinTheme, item: &MemberItem, open: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id;
let hover = hsla(c.surface_3);
let presence = if item.away {
Presence::Idle
} else if item.sound_off {
Presence::Dnd
} else {
Presence::Online
};
let name_color = if item.myself {
c.accent_text
} else if !item.role.is_empty() {
c.name_text
} else {
c.text
};
let crowns = div()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(item.admin, |row| row.child(icon("crown", 14.0, c.gold)))
.when(item.priority, |row| row.child(icon("star", 14.0, c.accent_text)))
.when(item.commander, |row| row.child(icon("flag", 14.0, c.info)))
.when(item.recording, |row| row.child(icon("circle-dot", 14.0, c.danger)));
let badges = div().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|b| small_picture(b, 14.0)),
);
div()
.id(("member", id as u64))
.debug_selector(move || format!("member-{id}"))
.w_full()
.h(px(52.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(open, |row| row.bg(hsla(c.accent_soft)))
.when(!open, |row| row.hover(move |style| style.bg(hover)))
.when(item.away, |row| row.opacity(0.6))
.flex()
.flex_row()
.items_center()
.px(px(m.space_2))
.gap(px(m.space_3))
.child(
Avatar::new(("member-avatar", id as u64), 40.0, &item.initials, item.tint)
.image(item.avatar.clone())
.presence(presence)
.speaking(item.talking),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
.child(crowns)
.child(badges),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if item.talking {
c.success
} else {
c.text_muted
}))
.child(item.status.to_string()),
)
.when(item.talking, |row| row.child(speaking_bars(theme, 12.0)))
.when(item.streaming, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
),
)
.when(!item.role.is_empty(), |row| {
row.child(icon("shield-check", 18.0, ROLE)).child(chip(
theme,
item.role.to_string(),
None,
None,
))
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.muted, |row| row.child(icon("mic-off", 16.0, c.danger)))
.when(item.sound_off, |row| row.child(icon("headphone-off", 16.0, c.danger)))
// A hand, as TeamSpeak asks for talk power; the card has the number.
.when(item.cannot_talk, |row| {
row.child(
div()
.id(("member-hand", id as u64))
.tooltip(|window, cx| {
gpui_kit::component::tooltip::Tooltip::new("Needs talk power to speak")
.build(window, cx)
})
.child(icon("hand", 16.0, c.text_muted)),
)
})
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: id }), cx)
})
.into_any_element()
}
impl Render for MembersPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.members.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
let searching = self.searching;
let this = cx.entity();
let search_button = IconButton::new("members-search", "search", "Search members")
.size(32.0)
.checked(searching)
.on_click(move |_, window, cx| {
this.update(cx, |pane, cx| pane.toggle_search(window, cx));
});
div()
.id("members")
.debug_selector(|| "members".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_4))
.pb(px(m.space_2))
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pl(px(m.space_5))
.pr(px(m.space_3))
.child(
div()
.id("members-title")
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text))
.child(format!("Members — {}", self.total)),
)
.child(search_button),
)
.when(searching, |pane| {
pane.child(
div()
.id("members-search-box")
.debug_selector(|| "members-search-box".into())
.px(px(m.space_4))
.child(Input::new(&self.search)),
)
})
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("members-empty")
.debug_selector(|| "members-empty".into())
.px(px(m.space_5))
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.entry(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
/// The card over a member row, over the window: a scrim that a click outside
/// the card closes, and the card with what is known of the person, and the
/// volume and the mute of their voice for us (the Slint card's Volume rows).
pub struct MemberCardView {
card: Option<MemberCard>,
/// How wide the members panel is: the card stands beside it.
panel_width: f32,
/// The volume slider, in percent (0 to 200, as the Slint card's).
slider: Entity<SliderState>,
_subscriptions: Vec<Subscription>,
}
/// The loudest the card's slider plays a person, in percent.
const LOUDEST: f32 = 200.0;
impl MemberCardView {
/// A card that follows `model`, beside a panel `panel_width` pixels wide.
pub fn new(
model: &Entity<TreeModel>,
panel_width: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let card = model.read(cx).card().cloned();
let slider = cx.new(|_| {
SliderState::new()
.min(0.0)
.max(LOUDEST)
.step(5.0)
.default_value(card.as_ref().map_or(100.0, |card| card.volume))
});
let subscriptions = vec![
cx.subscribe_in(
model,
window,
|this: &mut Self, model, event: &TreeEvent, window, cx| {
if matches!(event, TreeEvent::Card) {
this.card = model.read(cx).card().cloned();
// The slider shows the person's volume as it is now (a change
// the slider itself made comes back the same).
if let Some(card) = &this.card {
let volume = card.volume.clamp(0.0, LOUDEST);
this.slider
.update(cx, |slider, cx| slider.set_value(volume, window, cx));
}
cx.notify();
}
},
),
cx.subscribe_in(
&slider,
window,
|this: &mut Self, _, event: &SliderEvent, window, cx| {
if let (SliderEvent::Change(value), Some(card)) = (event, &this.card) {
let client = u16::try_from(card.id).unwrap_or_default();
let percent = value.end();
window.dispatch_action(Box::new(SetMemberVolume { client, percent }), cx);
}
},
),
];
Self { card, panel_width, slider, _subscriptions: subscriptions }
}
/// The card that is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
}
/// The heading of a part of the card: "Groups", "Badges".
fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.text_size(px(m.font_xs))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_muted))
.child(text)
}
/// The card's Volume rows: what the person is played at, a mute for us and
/// the slider. Both need a person the server gave a unique id (the choice is
/// kept by it), as the Slint card's do.
fn volume(
theme: &VoelinTheme,
person: &MemberCard,
slider: &Entity<SliderState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let client = u16::try_from(person.id).unwrap_or_default();
let (muted, known) = (person.muted, person.known);
div()
.id("member-volume")
.debug_selector(|| "member-volume".into())
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_3))
.border_t_1()
.border_color(hsla(c.border_popup))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.flex_1()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child("Volume"),
)
.child(
div()
.id("member-volume-percent")
.debug_selector(|| "member-volume-percent".into())
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", person.volume.round() as i32)),
),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
IconButton::new(
"member-mute",
if muted { "volume-x" } else { "volume-2" },
if muted { "Unmute for me" } else { "Mute for me" },
)
.size(30.0)
.danger()
.checked(muted)
.enabled(known)
.on_click(move |_, window, cx| {
window
.dispatch_action(Box::new(SetMemberMuted { client, muted: !muted }), cx)
}),
)
.child(
div()
.id("member-slider")
.debug_selector(|| "member-slider".into())
.flex_1()
.child(Slider::new(slider).disabled(!known || muted)),
),
)
}
impl Render for MemberCardView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(person) = self.card.clone() else { return div().into_any_element() };
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let facts = div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(m.space_2))
.when(person.talk_power > 0, |row| {
row.child(chip(
&theme,
format!("talk power {}", person.talk_power),
Some("mic"),
None,
))
})
.when(!person.country.is_empty(), |row| {
row.child(chip(&theme, person.country.to_string(), Some("globe"), None))
});
let body = div()
.id("member-card")
.debug_selector(|| "member-card".into())
.w(px(300.0))
.flex()
.flex_col()
.gap(px(m.space_3))
.p(px(m.space_4))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
// Clicks inside stay inside.
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
Avatar::new("member-card-avatar", 52.0, &person.initials, person.tint)
.image(person.avatar.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(person.name.to_string()),
)
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(person.status.to_string()),
),
)
.child(IconButton::new("member-card-close", "x", "Close").size(26.0).on_click(
|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
},
)),
)
.when(!person.description.is_empty(), |card| {
card.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(person.description.to_string()),
)
})
.when(!person.groups.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Groups"))
.children(person.groups.iter().map(|group| {
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(group.to_string())
})),
)
})
.when(!person.badges.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Badges"))
.child(div().flex().flex_row().flex_wrap().gap(px(m.space_2)).children(
person.badges.iter().enumerate().map(|(i, badge)| {
let description = badge.description.clone();
div()
.id(("member-badge", i as u64))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(
description.to_string(),
)
.build(window, cx)
})
.child(chip(
&theme,
badge.name.to_string(),
None,
small_picture(&badge.icon, 14.0),
))
}),
)),
)
})
.child(facts)
.child(volume(&theme, &person, &self.slider));
// The card stands beside the panel, near the top.
div()
.id("member-card-scrim")
.debug_selector(|| "member-card-scrim".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(hsla(c.scrim_light))
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
})
.flex()
.flex_row()
.justify_end()
.items_start()
.pt(px(120.0))
.pr(px(self.panel_width + 24.0))
.child(body)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// What an empty panel says for each reason it can be empty.
#[test]
fn an_empty_panel_says_why() {
assert_eq!(empty_words(Emptiness::NoServer), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Connect), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Loading), "Loading who is here…");
assert_eq!(empty_words(Emptiness::NoMatch), "Nobody matches.");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and
//! the server callbacks of `bind/servers.rs`): the server rail, the top bar,
//! the sidebar, the main area, the voice channel page that takes its place
//! while voice is on screen, the server form and the toast, each an entity
//! that listens to the per-area signals of the root state
//! ([`crate::signals`]) and tells the window only when what it shows changed,
//! and the actions the user's moves are ([`actions`]). The rail, the top bar,
//! the main area and the voice page are embedded cached (they have a size of
//! their own), so gpui-pre 0.3.10 renders them again only when they were told
//! something changed; [`crate::view::MainView`] puts them in the window.
pub mod actions;
mod channels;
mod form;
mod main_panel;
mod members;
mod password;
mod rail;
mod sidebar;
mod toast;
mod topbar;
mod tree_model;
mod voice;
pub mod widgets;
pub use channels::ChannelTree;
pub use form::ServerForm;
pub use main_panel::{MainPanel, MainState};
pub use members::{MemberCardView, MembersPane};
pub use password::ChannelPassword;
/// Bind the shell's keys (Escape in the password prompt): once, after the
/// widget library's own are (`gpui_kit::init`).
pub fn bind_keys(cx: &mut gpui_kit::App) {
password::bind_keys(cx);
}
pub use rail::{RailView, ServerRail};
pub use sidebar::{Sidebar, SidebarView};
pub use toast::{TOAST_TIME, Toast};
pub use topbar::TopBar;
pub use tree_model::{Emptiness, TreeEvent, TreeModel};
pub use voice::{SHORT_WINDOW, VoiceHead, VoicePage};
+171
View File
@@ -0,0 +1,171 @@
//! The password prompt of a locked channel (`ChannelPasswordDialog` of
//! `screens/dialogs.slint`): what the transitions ask for with
//! `Update::password` when a channel with a password is joined and the one
//! given this connection (if any) is not at hand, or was refused. It is a
//! card over the window with a scrim; until the dialogs slice makes every
//! dialog one, it is this view's own. As in the Slint dialog, Join (and Enter)
//! do nothing while the field is empty, and Escape closes the prompt.
//!
//! Escape is a key binding of the prompt's key context ([`bind_keys`]) that
//! dispatches [`CancelChannelPassword`], and the prompt is a focus target of
//! its own (its scrim, which the card is on): a click on the card, off the
//! field, takes the focus from the field, and a click outside any focus target
//! would hand it to the window's root, which the prompt is not under, so
//! without a target the context would not be on the dispatch path and Escape
//! would do nothing. With the field focused its own Escape (which has nothing
//! to undo in a password) passes the key on, and the binding closes the prompt.
use gpui_kit::component::Disableable as _;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FocusHandle, FontWeight, InteractiveElement as _,
IntoElement, KeyBinding, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use voelin_ui_vm::host::PasswordPrompt;
use super::actions::{CancelChannelPassword, SubmitChannelPassword};
use super::widgets::tagged;
use crate::theme::{VoelinTheme, hsla};
/// The key context of the prompt.
const CONTEXT: &str = "ChannelPassword";
/// The keys of the prompt: Escape closes it. Bound once, at start, with the
/// widget library's own.
pub fn bind_keys(cx: &mut App) {
cx.bind_keys([KeyBinding::new("escape", CancelChannelPassword, Some(CONTEXT))]);
}
/// The prompt for the password of one channel.
pub struct ChannelPassword {
channel: String,
wrong: bool,
input: Entity<InputState>,
/// What the prompt's scrim holds the focus with, so that Escape reaches the
/// prompt wherever in it the last click was.
focus: FocusHandle,
}
impl ChannelPassword {
/// A prompt for what `ask` names, with the field focused: Enter joins.
pub fn new(ask: &PasswordPrompt, window: &mut Window, cx: &mut Context<Self>) -> Self {
let input = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Password")).masked(true)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| match event {
InputEvent::PressEnter { .. } => {
window.dispatch_action(Box::new(SubmitChannelPassword), cx);
}
// Join is there while there is something to join with.
InputEvent::Change => cx.notify(),
_ => {}
})
.detach();
input.update(cx, |input, cx| input.focus(window, cx));
Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() }
}
/// The channel it asks for.
pub fn channel(&self) -> &str {
&self.channel
}
/// Whether it says that the last password was refused.
pub fn wrong(&self) -> bool {
self.wrong
}
/// What the field holds. The prompt joins only with something in it.
pub fn text(&self, cx: &App) -> String {
self.input.read(cx).value().to_string()
}
/// Type `text` in the field (the tests type here).
pub fn set_text(&self, text: &str, window: &mut Window, cx: &mut App) {
self.input.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
impl Render for ChannelPassword {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let empty = self.text(cx).is_empty();
div()
.id("password-prompt")
.debug_selector(|| "password-prompt".into())
.key_context(CONTEXT)
.track_focus(&self.focus)
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.flex()
.items_center()
.justify_center()
.bg(hsla(c.scrim))
// A click outside the card closes the prompt.
.on_click(|_, window, cx| window.dispatch_action(Box::new(CancelChannelPassword), cx))
.child(
div()
.id("password-card")
.debug_selector(|| "password-card".into())
.w(px(380.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(format!("{} has a password", self.channel)),
)
.when(self.wrong, |card| {
card.child(
div()
.id("password-wrong")
.debug_selector(|| "password-wrong".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.danger))
.child("That password was not accepted. Try again."),
)
})
.child(Input::new(&self.input))
.child(
div()
.flex()
.flex_row()
.justify_end()
.gap(px(m.space_3))
.child(tagged(
"password-cancel",
Button::new("password-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelChannelPassword), cx)
},
),
))
.child(tagged(
"password-join",
Button::new("password-join")
.primary()
.label("Join")
.disabled(empty)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(SubmitChannelPassword), cx)
}),
)),
),
)
}
}
+250
View File
@@ -0,0 +1,250 @@
//! The server rail: the saved servers as avatars with their state, the
//! selection, the add-server button and the settings button (`ServerRail` of
//! `ui/shells/desktop.slint`). An entity of its own, drawn as a cached pane:
//! it listens to the servers' signal ([`crate::signals`]) and tells the window
//! only when the servers it lists changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, EditServer, OpenSettings, SelectServer};
use super::widgets::{Avatar, IconButton, Presence};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the rail shows: the servers in order, and which is on screen.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RailView {
/// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them.
pub servers: Vec<ServerItem>,
/// The bookmark on screen.
pub current: Option<i64>,
}
impl RailView {
/// The rail for the state.
pub fn of(app: &AppState) -> Self {
Self {
servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)),
current: app.vm.current,
}
}
}
/// The rail.
pub struct ServerRail {
view: RailView,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl ServerRail {
/// A rail that follows the servers of `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(RailView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let view = RailView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn view(&self) -> &RailView {
&self.view
}
}
/// One server of the rail: the selection pill, the ring of the one on screen,
/// the avatar with its state, the unread count and the live mark.
fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> {
let (c, m) = (&theme.colors, &theme.metrics);
let id = i64::from(item.id);
let group = format!("rail-server-{id}");
let name = item.name.to_string();
let tooltip = format!("{name}\n{}", item.address);
let pill = div()
.absolute()
.left(px(0.0))
.w(px(4.0))
.h(px(if selected { 36.0 } else { 0.0 }))
.rounded(px(2.0))
.bg(hsla(c.text))
.when(!selected, |pill| {
let group = group.clone();
pill.group_hover(group, |style| style.h(px(18.0)))
});
div()
.id(("rail-server", id as u64))
.group(group)
.relative()
.w_full()
.h(px(56.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.debug_selector(|| format!("rail-server-{id}"))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx)
})
.on_click(move |event, window, cx| {
// A second click on the server is the Slint rail's double click.
if event.click_count() >= 2 {
window.dispatch_action(Box::new(EditServer { id }), cx);
} else {
window.dispatch_action(Box::new(SelectServer { id }), cx);
}
})
.child(pill)
.when(selected, |row| {
row.child(
div()
.absolute()
.size(px(52.0))
.rounded(px(m.radius_lg + 2.0))
.border_2()
.border_color(hsla(c.accent))
.bg(hsla(c.glow.with_alpha(0x66))),
)
})
.child(
Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.when(item.unread > 0, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.left(px(50.0))
.min_w(px(18.0))
.h(px(18.0))
.px(px(5.0))
.rounded(px(9.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail))
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(c.on_accent))
.child(item.unread.to_string()),
)
})
.when(item.live && item.unread == 0, |row| {
row.child(
div()
.absolute()
.top(px(4.0))
.left(px(52.0))
.size(px(12.0))
.rounded(px(6.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail)),
)
})
}
impl Render for ServerRail {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.rail.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let current = self.view.current;
let servers: Vec<_> = self
.view
.servers
.iter()
.map(|item| server(&theme, item, current == Some(i64::from(item.id))))
.collect();
div()
.id("rail")
.w(px(m.rail_width))
.h_full()
.flex_none()
.flex()
.flex_col()
.items_center()
.py(px(m.space_3))
.gap(px(m.space_2))
.bg(hsla(c.bg_rail.with_alpha(230)))
.border_r_1()
.border_color(hsla(c.border))
// The app's mark. (Home, which the Slint rail opens from it, comes
// with its slice.)
.child(
div()
.size(px(48.0))
.flex_none()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.flex()
.items_center()
.justify_center()
.child(gpui_kit::img("logo.svg").size(px(30.0))),
)
.child(
div()
.w(px(32.0))
.h(px(2.0))
.my(px(m.space_2))
.rounded(px(1.0))
.bg(hsla(c.border_strong)),
)
.child(
div()
.id("rail-servers")
.flex_1()
.min_h_0()
.w_full()
.overflow_y_scroll()
.flex()
.flex_col()
.items_center()
.gap(px(m.space_2))
.children(servers)
.child(
div().pt(px(m.space_2)).child(
IconButton::new("rail-add", "plus", "Add a server")
.size(46.0)
.round()
.filled()
.tint(c.success)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(AddServer), cx);
}),
),
),
)
.child(
IconButton::new("rail-settings", "settings", "Settings")
.size(46.0)
.round()
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenSettings), cx);
}),
)
}
}
+494
View File
@@ -0,0 +1,494 @@
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen (its card has the server's
//! banner behind it, under the same veil as the tree's rows), its channel tree
//! ([`super::ChannelTree`], a cached pane of its own), the voice card while
//! voice is connecting or connected, and the user's own card with the voice
//! buttons. An entity of its own: it listens to the servers' and the toolbar's
//! signals and tells the window only when what it shows changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, StyledImage as _, Subscription, Window, div, px,
};
use voelin_core::TransmitMode;
use voelin_ui_vm::Rgb;
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::channels::ChannelTree;
use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the sidebar shows.
#[derive(Clone, Debug, PartialEq)]
pub struct SidebarView {
/// The server on screen, as the rail has it.
pub server: Option<ServerItem>,
/// "9 online · 7 channels" once its presence is known, else empty.
pub stats: String,
/// The server's banner, behind its card; empty without one.
pub server_banner: ImageRef,
/// Our nickname there; empty without a server.
pub nickname: String,
/// The channel we are in; empty while connecting.
pub own_channel: String,
/// Our picture on the server.
pub own_avatar: ImageRef,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice goes out.
pub transmitting: bool,
/// The transmit mode is push-to-talk, so the card has a hold-to-talk button.
pub hold_to_talk: bool,
/// How our voice is sent, as the audio settings say: the card has the
/// button for push-to-talk and says the mode otherwise.
pub transmit: TransmitMode,
}
impl SidebarView {
/// The sidebar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark));
let server = app.vm.current.and_then(|id| {
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| i64::from(item.id) == id)
});
Self {
server,
stats: card.server_stats,
server_banner: card.server_banner,
nickname: card.nickname,
own_channel: card.own_channel,
own_avatar: card.own_avatar,
voice_connected: card.voice_connected,
voice_connecting: card.voice_connecting,
observing: card.observing,
input_muted: card.input_muted,
output_muted: card.output_muted,
transmitting: card.transmitting,
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
transmit: app.vm.audio.transmit,
}
}
}
/// The sidebar.
pub struct Sidebar {
view: SidebarView,
/// The channel tree, a pane of its own between the server card and the
/// voice card.
tree: Entity<ChannelTree>,
/// The hold-to-talk button is held down.
holding: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl Sidebar {
/// A sidebar that follows the server on screen and the voice state in
/// `app`, with `tree` between its cards.
pub fn new(app: &Entity<AppState>, tree: Entity<ChannelTree>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(SidebarView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let state = app.read(cx);
let view = SidebarView::of(state);
// The button goes away when voice leaves `Connected`, transmit
// leaves push-to-talk, or another server is shown; and a drop
// and reconnect inside one batch ends the hold in `AppState`
// while `view.voice_connected` stays true. Keep `holding` in
// sync with the root state's own button hold (this observer
// only sets its own fields).
let same_server =
view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id);
let held_here = view
.server
.as_ref()
.is_some_and(|s| state.button_held() == Some(i64::from(s.id)));
if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here {
this.holding = false;
}
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, tree, holding: false, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn view(&self) -> &SidebarView {
&self.view
}
/// Whether the hold-to-talk button is currently held down.
#[cfg(test)]
pub(crate) fn is_holding(&self) -> bool {
self.holding
}
/// Let go of the hold-to-talk button if it is held (the window lost the
/// focus: the release will not come to it): whether it was held. The caller
/// tells the session.
pub fn release(&mut self) -> bool {
std::mem::take(&mut self.holding)
}
/// The hold-to-talk button was released, if it was held.
fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if std::mem::take(&mut self.holding) {
window.dispatch_action(Box::new(PushToTalk { on: false }), cx);
}
}
}
/// The server's name, its icon and how many are there, over its banner when it
/// has one (`ServerHeader` of `channels.slint`: the picture covers the card,
/// the surface veil of `banner-picture.slint` lies over it, and the stats read
/// in the text colour instead of the secondary one).
fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() };
let banner = PictureKey::of(&view.server_banner);
let ink = if banner.is_some() { c.text } else { c.text_muted };
card(theme, 0xff)
.id("sidebar-server")
.debug_selector(|| "sidebar-server".into())
.relative()
.overflow_hidden()
.p(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.when_some(banner, |card, key| {
card.child(
div()
.id("sidebar-server-banner")
.debug_selector(|| "sidebar-server-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
// The picture covers the card and is cropped to it, not past
// its border.
.overflow_hidden()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(div().absolute().top(px(0.0)).left(px(0.0)).size_full().bg(banner_scrim(theme)))
})
.child(
Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint)
.image(item.icon.clone())
.square(),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats),
),
)
}
/// How our voice is sent, in words, for the modes that have no button.
fn transmit_words(mode: TransmitMode) -> &'static str {
match mode {
TransmitMode::PushToTalk => "Push to talk",
TransmitMode::VoiceActivation => "Voice activity",
TransmitMode::Continuous => "Open microphone",
}
}
/// "Voice Connected" and our channel, disconnect, and Hold to talk in the
/// push-to-talk mode (the other modes say themselves).
fn voice_card(
theme: &VoelinTheme,
view: &SidebarView,
cx: &mut Context<Sidebar>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (dot, words) = if view.voice_connected {
(c.success, "Voice Connected")
} else {
(c.warning, "Connecting…")
};
let talking = view.transmitting;
card(theme, 0xff)
.id("sidebar-voice")
.debug_selector(|| "sidebar-voice".into())
.p(px(m.space_3))
.flex()
.flex_col()
.gap(px(m.space_3))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(dot))
.child(words),
)
.when(!view.own_channel.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(view.own_channel.clone()),
)
}),
)
.when(view.voice_connected && !view.own_channel.is_empty(), |row| {
row.child(
IconButton::new("voice-invite", "link", "Copy an invite to this channel")
.size(32.0)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx);
}),
)
})
.child(
IconButton::new("voice-disconnect", "phone-off", "Disconnect")
.size(32.0)
.tint(c.danger)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
),
)
.when(view.voice_connected && !view.hold_to_talk, |card| {
card.child(
div()
.id("transmit-mode")
.debug_selector(|| "transmit-mode".into())
.h(px(m.control_height_sm))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.child(icon("mic", m.icon_sm, c.text_muted))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(transmit_words(view.transmit)),
),
)
})
.when(view.voice_connected && view.hold_to_talk, |card| {
card.child(
div()
.id("hold-to-talk")
.debug_selector(|| "hold-to-talk".into())
.h(px(m.control_height))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(if talking { c.success } else { c.border }))
.bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 }))
.cursor_pointer()
.hover(move |style| {
style.bg(hsla(if talking { c.success } else { c.surface_3 }))
})
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
this.holding = true;
window.dispatch_action(Box::new(PushToTalk { on: true }), cx);
}),
)
// Let go on the button or off it: the end of what was started.
.on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go))
.on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go))
.child(icon(
"mic",
m.icon_sm,
if talking { c.on_accent } else { c.text_secondary },
))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(if talking { c.on_accent } else { c.text_secondary }))
.child(if talking { "Talking…" } else { "Hold to talk" }),
),
)
})
}
/// Who we are, and the buttons for the microphone and the sound.
fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (words, presence) = if view.voice_connected {
("Online", Presence::Online)
} else if view.observing {
("Observing", Presence::Info)
} else {
("Offline", Presence::Offline)
};
let name = if view.nickname.is_empty() {
voelin_platform::APP_NAME.to_owned()
} else {
view.nickname.clone()
};
let (input_muted, output_muted) = (view.input_muted, view.output_muted);
card(theme, 0xb3)
.id("sidebar-user")
.debug_selector(|| "sidebar-user".into())
.min_h(px(60.0))
.p(px(m.space_2))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.id("sidebar-profile")
.flex_1()
.min_w_0()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_2))
.py(px(m.space_2))
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(|style| style.bg(hsla(c.surface_3)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
.child(
Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff))
.image(view.own_avatar.clone())
.presence(presence)
.speaking(view.transmitting),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(name),
)
.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(words),
),
),
)
.child(
IconButton::new(
"user-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.danger()
.checked(input_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx);
}),
)
.child(
IconButton::new(
"user-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.danger()
.checked(output_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx);
}),
)
}
/// The initials of a nickname, for the avatar.
fn name_initials(name: &str) -> String {
voelin_ui_vm::avatar::initials(name)
}
impl Render for Sidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.sidebar.incr();
let theme = VoelinTheme::global(cx).clone();
let m = &theme.metrics;
let view = &self.view;
panel(&theme)
.id("sidebar")
.w(px(m.sidebar_width))
.h_full()
.flex_none()
.p(px(m.space_3))
.gap(px(m.space_3))
.when_some(view.server.as_ref(), |sidebar, item| {
sidebar.child(server_card(&theme, view, item))
})
// The tree has the room the cards leave, whatever their height.
.child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full()))
.when(view.voice_connected || view.voice_connecting, |sidebar| {
sidebar.child(voice_card(&theme, view, cx))
})
.child(user_card(&theme, view))
}
}
+88
View File
@@ -0,0 +1,88 @@
//! The status line as a toast: what the last move did ("Connecting to
//! ts.example…", why a server was not saved), shown at the bottom of the
//! window for a few seconds. It watches the root state's status line and its
//! generation, so that the same words said twice are two toasts.
use std::time::Duration;
use gpui_kit::{
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _,
Subscription, Window, div, px,
};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// How long a toast stays.
pub const TOAST_TIME: Duration = Duration::from_secs(5);
/// The toast.
pub struct Toast {
text: String,
generation: u64,
_subscription: Subscription,
}
impl Toast {
/// A toast that follows `app`'s status line from now on (what it said
/// before is not shown).
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let generation = app.read(cx).status_generation;
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (generation, text) = {
let app = app.read(cx);
(app.status_generation, app.vm.status.clone())
};
if generation == this.generation {
return;
}
this.generation = generation;
this.text = text;
cx.notify();
if this.text.is_empty() {
return;
}
cx.spawn(async move |this, cx| {
cx.background_executor().timer(TOAST_TIME).await;
let _ = this.update(cx, |this, cx| {
if this.generation == generation && !this.text.is_empty() {
this.text.clear();
cx.notify();
}
});
})
.detach();
});
Self { text: String::new(), generation, _subscription: subscription }
}
/// What it shows now; empty when nothing is.
pub fn text(&self) -> &str {
&self.text
}
}
impl Render for Toast {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let toast =
div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center();
if self.text.is_empty() {
return toast;
}
toast.child(
div()
.max_w(px(560.0))
.px(px(m.space_5))
.py(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.text_size(px(m.font_body))
.text_color(hsla(c.text))
.child(self.text.clone()),
)
}
}
+119
View File
@@ -0,0 +1,119 @@
//! The bar at the top of the window: the page's title, the search box and the
//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes
//! with the notifications). The search and the settings are affordances until
//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]).
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use super::actions::{OpenSearch, OpenSettings};
use super::widgets::{IconButton, icon};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// The page title: the server on screen, else the app's name.
pub fn title(app: &AppState) -> String {
match app.current_bookmark() {
Some(bookmark) => bookmark.name.clone(),
None => voelin_platform::APP_NAME.to_owned(),
}
}
/// The top bar.
pub struct TopBar {
title: String,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl TopBar {
/// A top bar that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (shown, counters, signals) = {
let state = app.read(cx);
(title(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let shown = title(app.read(cx));
if shown != this.title {
this.title = shown;
cx.notify();
}
});
Self { title: shown, counters, _subscriptions: subscriptions }
}
/// The title it shows now.
pub fn title(&self) -> &str {
&self.title
}
}
impl Render for TopBar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.topbar.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("topbar")
.w_full()
.h(px(m.topbar_height))
.flex_none()
.flex()
.flex_row()
.items_center()
// The main panel starts where the sidebar and the gaps around it end.
.pl(px(m.sidebar_width + 2.0 * m.space_3))
.pr(px(m.space_4))
.gap(px(m.space_4))
.child(
div()
.id("topbar-title")
.max_w(px(280.0 * m.font_scale.max(1.0)))
.flex_none()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(self.title.clone()),
)
.child(
div().flex_1().min_w_0().flex().justify_center().child(
div()
.id("topbar-search")
.w_full()
.max_w(px(680.0))
.h(px(m.control_height))
.px(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.cursor_text()
.hover(|style| style.border_color(hsla(c.border_strong)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx))
.child(icon("search", m.icon_sm, c.text_muted))
.child(
div()
.flex_1()
.truncate()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Search servers, channels, people or settings…"),
),
),
)
.child(
IconButton::new("topbar-settings", "settings", "Settings")
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)),
)
}
}
+319
View File
@@ -0,0 +1,319 @@
//! The narrow entity behind the channel tree and the members panel: what
//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between
//! one change and the next so that the two panes can be told what changed.
//!
//! It listens to the tree, toolbar and member-card signals
//! ([`crate::signals`]), builds the rows once for both panes, compares them
//! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the
//! Slint front end applies to its `VecModel`) and emits what differs
//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the
//! operations to its list state, so a person who joins is a row that is
//! inserted, not a list that starts again at the top. A change that moves none
//! of what a pane shows emits nothing.
//!
//! The people of our voice channel (`TreeView::members`, the voice page's
//! rows) come out of the same build as the other two lists: the model keeps
//! them and emits them when they differ ([`TreeEvent::Voice`]), so the voice
//! page needs no build of its own.
//!
//! **The tree marks who is talking**, as the Slint tree does (the ring on the
//! avatar and the speaking bars on the row): someone who starts or stops
//! talking changes one row of the tree and one of the members panel, so each
//! of the two panes is drawn again once for it, and no other pane is
//! (docs/ui.md, "What a change costs").
use std::sync::Arc;
use gpui_kit::{App, Context, Entity, EventEmitter, Subscription};
use voelin_core::{ObserveState, VoiceState};
use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem};
use voelin_ui_vm::list::{Changes, diff};
use voelin_ui_vm::servers::logic;
use voelin_ui_vm::tree::{ChannelId, member_card};
use crate::app::{AppState, VmState};
use crate::signals::Area;
/// Why a list has no rows, which the pane says in words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Emptiness {
/// No server is on screen.
NoServer,
/// The server is observed or being connected to, and its presence is on
/// the way.
Loading,
/// Nothing is known of the server until it is connected.
Connect,
/// The server has people and the members' search matches none of them (the
/// members panel's only: the tree is not searched).
NoMatch,
}
impl Emptiness {
/// Why the lists of the server on screen are empty: never
/// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s.
pub fn of(vm: &VmState) -> Self {
match vm.current {
None => Self::NoServer,
Some(id) => match vm.sessions.get(&id) {
Some(view)
if view.state.observe != ObserveState::Off
|| view.state.voice == VoiceState::Connecting =>
{
Self::Loading
}
_ => Self::Connect,
},
}
}
/// Why the members panel is empty: as [`Emptiness::of`], except that a
/// search that leaves nobody of the `total` on the server (`shown` rows
/// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here"
/// would be false.
pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self {
if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() {
Self::NoMatch
} else {
Self::of(vm)
}
}
}
/// What changed in the model, as the panes need it.
///
/// The list events carry the rows their operations lead to. A model that
/// refreshed twice before the first event is delivered (an observer that
/// changes the state inside a flush makes it) holds the second rows by the
/// time a pane hears of the first operations, and operations applied to rows
/// they were not made for index past their end. A pane applies them to the
/// rows it has and keeps the rows the event carries, so the events, in the
/// order they are delivered, lead from the rows the pane started with to the
/// model's last.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeEvent {
/// The tree's rows: the operations from the rows the pane has to the rows
/// carried (the model's [`TreeModel::rows`] when it made them).
Rows(Changes, Arc<Vec<TreeItem>>),
/// The members panel's rows: the operations from the rows the pane has to
/// the rows carried (the model's [`TreeModel::people`] when it made them).
People(Changes, Arc<Vec<MemberItem>>),
/// The people of our voice channel, the voice page's rows, as they are
/// now (the whole list: the page lays its people out in a wrapping row, not
/// a virtual list, and takes them as they come).
Voice(Arc<Vec<MemberItem>>),
/// The card over a member row opened, changed or closed
/// ([`TreeModel::card`]).
Card,
/// The selected channel ([`TreeModel::selected`]).
Selection,
/// Why the lists are empty, or how many people there are
/// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`],
/// [`TreeModel::total`]).
Lists,
}
/// The areas the model listens to.
const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard];
/// How many times each of [`AREAS`] was raised.
fn generations(app: &Entity<AppState>, cx: &App) -> [u64; 3] {
let signals = app.read(cx).signals();
AREAS.map(|area| signals.of(area).read(cx).generation())
}
/// The rows of the tree and of the members panel, the member card and the
/// selection of the server on screen.
pub struct TreeModel {
app: Entity<AppState>,
/// The generations of its signals it last built the rows at: a batch that
/// raises several of them (a picture that arrives raises three) has them
/// all raised before the first is heard, so the first refresh builds the
/// rows and the others find nothing new.
seen: [u64; 3],
refreshes: u64,
rows: Arc<Vec<TreeItem>>,
people: Arc<Vec<MemberItem>>,
voice: Arc<Vec<MemberItem>>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
_subscriptions: Vec<Subscription>,
}
impl EventEmitter<TreeEvent> for TreeModel {}
/// Check that `changes` lead from a list of `old` rows to one of `new` rows
/// (debug builds): a pane that applies operations to rows they were not made
/// for finds the counts out of step, where a release build would index past
/// the end or leave its list state out of step with its rows.
pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) {
debug_assert_eq!(
old + changes.inserted(),
new + changes.removed(),
"{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \
for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \
inside a flush)"
);
}
/// Everything the model keeps, as the state gives it now.
struct Snapshot {
rows: Vec<TreeItem>,
people: Vec<MemberItem>,
voice: Vec<MemberItem>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
}
impl Snapshot {
fn of(app: &AppState) -> Self {
let vm = &app.vm;
let view = vm.current.and_then(|id| vm.sessions.get(&id));
let (rows, people, voice, total) = match logic::tree_view(vm, false) {
Some(tree) => (tree.rows, tree.server_members, tree.members, tree.member_total),
None => (Vec::new(), Vec::new(), Vec::new(), 0),
};
Self {
people_emptiness: Emptiness::of_people(vm, people.len(), total),
rows,
people,
voice,
total,
card: view
.and_then(|view| view.member_card.map(|id| (view, id)))
.and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)),
selected: app.selected_channel(),
emptiness: Emptiness::of(vm),
}
}
}
impl TreeModel {
/// A model of what `app` shows now, following its tree signals.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (snapshot, signals) = {
let state = app.read(cx);
(Snapshot::of(state), state.signals().clone())
};
let subscriptions =
signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx));
Self {
app: app.clone(),
seen: generations(app, cx),
refreshes: 0,
rows: Arc::new(snapshot.rows),
people: Arc::new(snapshot.people),
voice: Arc::new(snapshot.voice),
total: snapshot.total,
card: snapshot.card,
selected: snapshot.selected,
emptiness: snapshot.emptiness,
people_emptiness: snapshot.people_emptiness,
_subscriptions: subscriptions,
}
}
/// The rows of the channel tree: channels with the clients in them.
pub fn rows(&self) -> &Arc<Vec<TreeItem>> {
&self.rows
}
/// The rows of the members panel: everyone on the server, in sections.
pub fn people(&self) -> &Arc<Vec<MemberItem>> {
&self.people
}
/// The people of our voice channel, in the voice page's order (empty while
/// voice is not connected).
pub fn voice(&self) -> &Arc<Vec<MemberItem>> {
&self.voice
}
/// How many are on the server (the query clients not counted).
pub fn total(&self) -> i32 {
self.total
}
/// The card over a member row, when one is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
/// The channel selected in the tree.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why the tree is empty, were it.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Why the members panel is empty, were it: the same as
/// [`TreeModel::emptiness`], or that the search matches nobody.
pub fn people_emptiness(&self) -> Emptiness {
self.people_emptiness
}
/// How many times the rows were built again since the model was made: one
/// for each batch of changes, not one for each signal it raised.
pub fn refreshes(&self) -> u64 {
self.refreshes
}
/// Build the rows again, and tell the panes what differs. Nothing, when
/// none of the signals was raised since the last time.
fn refresh(&mut self, cx: &mut Context<Self>) {
let now = generations(&self.app, cx);
if now == self.seen {
return;
}
self.seen = now;
self.refreshes += 1;
let new = Snapshot::of(self.app.read(cx));
let rows = diff(&self.rows, &new.rows);
let people = diff(&self.people, &new.people);
if !rows.is_empty() {
self.rows = Arc::new(new.rows);
}
if !people.is_empty() {
self.people = Arc::new(new.people);
}
let voice = *self.voice != new.voice;
if voice {
self.voice = Arc::new(new.voice);
}
let lists = (self.emptiness, self.people_emptiness, self.total)
!= (new.emptiness, new.people_emptiness, new.total);
(self.emptiness, self.people_emptiness, self.total) =
(new.emptiness, new.people_emptiness, new.total);
let card = self.card != new.card;
self.card = new.card;
let selection = self.selected != new.selected;
self.selected = new.selected;
if !rows.is_empty() {
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
}
if !people.is_empty() {
cx.emit(TreeEvent::People(people, self.people.clone()));
}
if voice {
cx.emit(TreeEvent::Voice(self.voice.clone()));
}
if lists {
cx.emit(TreeEvent::Lists);
}
if card {
cx.emit(TreeEvent::Card);
}
if selection {
cx.emit(TreeEvent::Selection);
}
}
}
+657
View File
@@ -0,0 +1,657 @@
//! The voice channel page (`VoiceView` of `screens/voice.slint`, with its
//! `Participant` of `voice-parts.slint` and the `CallBar`): the channel we are
//! in, who is there and who talks, and the call's controls under them.
//!
//! [`VoicePage`] is a cached pane of its own, a sibling of the server page
//! ([`super::MainPanel`]) that [`crate::view::MainView`] puts in the main
//! area in its place while the page is asked for and voice is connected
//! ([`crate::app::AppState::voice_page_shown`]). It takes its people from the
//! tree model ([`TreeEvent::Voice`]: the rows `TreeView::members` gave the one
//! build the tree and the members panel come from, so the page builds nothing
//! of its own) and the header and the call bar from the servers' and the
//! toolbar's signals, compares what it would show with what it showed, and
//! tells the window only when they differ. A person who starts or stops
//! talking, or mutes, is one row of the page and one render of this pane.
//!
//! The larger stage lays the people out as large avatars in a wrapping row;
//! the smaller stage (`ui.voice_compact`, and always in a window under 800
//! pixels tall) is one row of small avatars that scrolls sideways. The streams
//! of the Slint page come with the stream slices and its chat with the chat's.
use std::sync::Arc;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ObjectFit,
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, StyledImage as _,
Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::MemberItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
Invite, LeaveVoice, OpenMember, OpenShare, OpenVoiceSettings, SetInputMuted, SetOutputMuted,
ShowVoiceView, ToggleVoiceCompact,
};
use super::tree_model::{TreeEvent, TreeModel};
use super::widgets::{Avatar, IconButton, banner_scrim, icon, live_badge, panel, speaking_bars_in};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A window under this tall (pixels) has the smaller stage whatever the
/// setting says (`Nav.short` of the Slint front end).
pub const SHORT_WINDOW: f32 = 800.0;
/// What the page's header and call bar show, from the state.
#[derive(Clone, Debug, PartialEq)]
pub struct VoiceHead {
/// The channel we are in, as the tree shows it.
pub channel: String,
/// Its topic.
pub topic: String,
/// Its banner, empty without one.
pub banner: ImageRef,
/// Its client limit, -1 without one.
pub limit: i32,
/// Voice is connected.
pub connected: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// The server can stream (TeamSpeak 6 with voice): the call bar has Share.
pub can_share: bool,
}
impl VoiceHead {
/// The header and the call bar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |_| ImageRef::default());
let can_share = app
.vm
.current
.and_then(|id| app.vm.sessions.get(&id))
.is_some_and(|view| view.streams_available());
Self {
channel: card.own_channel,
topic: card.own_channel_topic,
banner: card.own_channel_banner,
limit: card.own_channel_limit,
connected: card.voice_connected,
input_muted: card.input_muted,
output_muted: card.output_muted,
can_share,
}
}
}
/// The voice channel page.
pub struct VoicePage {
head: VoiceHead,
people: Arc<Vec<MemberItem>>,
/// The smaller stage by choice.
compact: bool,
/// The window is too short for the larger stage.
short: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl VoicePage {
/// A page that follows `app` for the header and the call bar and `model` for
/// the people, on the stage the setting says (`compact`) in a window that is
/// `short` or not.
pub fn new(
app: &Entity<AppState>,
model: &Entity<TreeModel>,
compact: bool,
short: bool,
cx: &mut Context<Self>,
) -> Self {
let (head, counters, signals) = {
let state = app.read(cx);
(VoiceHead::of(state), state.counters().clone(), state.signals().clone())
};
let mut subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let head = VoiceHead::of(app.read(cx));
if head != this.head {
this.head = head;
cx.notify();
}
});
subscriptions.push(cx.subscribe(model, |this: &mut Self, _, event: &TreeEvent, cx| {
if let TreeEvent::Voice(people) = event {
this.people = people.clone();
cx.notify();
}
}));
let people = model.read(cx).voice().clone();
Self { head, people, compact, short, counters, _subscriptions: subscriptions }
}
/// What the header and the call bar show.
pub fn head(&self) -> &VoiceHead {
&self.head
}
/// The people it shows.
pub fn people(&self) -> &[MemberItem] {
&self.people
}
/// Whether the page is on the smaller stage now: chosen, or the window is too
/// short for the larger.
pub fn compact_shown(&self) -> bool {
self.compact || self.short
}
/// Whether the window is too short for the larger stage (the stage button is
/// off then).
pub fn short(&self) -> bool {
self.short
}
/// The setting `ui.voice_compact` is `compact`: tells the window if the stage
/// changes.
pub fn set_compact(&mut self, compact: bool, cx: &mut Context<Self>) {
if self.compact != compact {
self.compact = compact;
cx.notify();
}
}
/// The window is `short` (under [`SHORT_WINDOW`] tall) or not.
pub fn set_short(&mut self, short: bool, cx: &mut Context<Self>) {
if self.short != short {
self.short = short;
cx.notify();
}
}
}
/// The ring around a person's avatar: green while they talk, blue while they
/// stream (3 pixels, 2 on the smaller stage), else the quiet border of the
/// larger stage (2 pixels; the smaller has none).
fn ring(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> (u8, Rgba) {
let c = &theme.colors;
let loud = if compact { 2 } else { 3 };
if person.talking {
(loud, c.success)
} else if person.streaming {
(loud, c.accent)
} else {
(if compact { 0 } else { 2 }, c.border_strong)
}
}
/// What the corner of a person's avatar says: the bars while they talk, else
/// that their sound or their microphone is off.
fn corner(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> Option<AnyElement> {
let (c, bars) = (&theme.colors, if compact { 12.0 } else { 14.0 });
let size = if compact { 22.0 } else { 26.0 };
if !(person.talking || person.muted || person.sound_off) {
return None;
}
let (face, inside) = if person.talking {
if compact {
(c.accent, speaking_bars_in(theme, bars, c.on_accent).into_any_element())
} else {
(c.surface, speaking_bars_in(theme, bars, c.success).into_any_element())
}
} else {
let name = if person.sound_off { "headphone-off" } else { "mic-off" };
(c.surface, icon(name, if compact { 12.0 } else { 15.0 }, c.danger).into_any_element())
};
let (id, talking) = (person.id, person.talking);
let inset = if compact { 0.0 } else { 2.0 };
Some(
div()
.absolute()
.right(px(inset))
.bottom(px(inset))
.debug_selector(move || {
format!("voice-{}-{id}", if talking { "speaking" } else { "off" })
})
.size(px(size))
.rounded(px(size / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(face))
.flex()
.items_center()
.justify_center()
.child(inside)
.into_any_element(),
)
}
/// One person: an avatar with its ring, the mark in its corner, the name with
/// the crown of an admin, and what they do. A click opens their card.
fn participant(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let size = if compact { 54.0 } else { 80.0 };
let width = if compact { 68.0 } else { 120.0 };
let outer = size + 8.0;
let id = person.id;
let (ring_width, ring_color) = ring(theme, person, compact);
let client = u16::try_from(id).unwrap_or_default();
let name_width = width - if person.admin { 16.0 } else { 0.0 };
let words = if person.talking {
"Speaking"
} else if person.streaming {
"Streaming"
} else if person.away {
"Away"
} else {
""
};
let mut face = div()
.relative()
.size(px(outer))
.flex_none()
.rounded(px(outer / 2.0))
.border_color(hsla(ring_color))
.flex()
.items_center()
.justify_center();
face = match ring_width {
3 => face.border_3(),
2 => face.border_2(),
_ => face,
};
let mut face = face.child(
Avatar::new(("voice-avatar", id as u64), size, &person.initials, person.tint)
.image(person.avatar.clone()),
);
if let Some(mark) = corner(theme, person, compact) {
face = face.child(mark);
}
div()
.id(("voice-member", id as u64))
.debug_selector(move || format!("voice-member-{id}"))
.w(px(width))
.flex_none()
.flex()
.flex_col()
.items_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.cursor_pointer()
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: i32::from(client) }), cx)
})
.child(face)
.child(
div()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.child(
div()
.max_w(px(name_width))
.truncate()
.text_size(px(if compact { m.font_sm } else { m.font_md }))
.font_weight(if compact { FontWeight::NORMAL } else { FontWeight::MEDIUM })
.text_color(hsla(if person.myself { c.accent_text } else { c.text }))
.child(person.name.to_string()),
)
.when(person.admin, |row| {
row.child(icon("crown", if compact { 13.0 } else { 15.0 }, c.gold))
}),
)
.when(!compact, |column| {
column.child(
div()
.h(px(m.font_sm + 4.0))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.when(person.talking, |row| row.child(speaking_bars_in(theme, 12.0, c.success)))
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if person.talking {
c.success
} else {
c.text_secondary
}))
.child(words),
)
.when(person.streaming && !person.talking, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
)
})
.when(compact && person.streaming, |column| column.child(live_badge(theme)))
.into_any_element()
}
/// The channel's name, its topic and how many are in voice, over its banner.
fn header(
theme: &VoelinTheme,
head: &VoiceHead,
people: usize,
page: &VoicePage,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let banner = PictureKey::of(&head.banner);
let ink = if banner.is_some() { c.text } else { c.text_secondary };
let compact = page.compact_shown();
let count = if head.limit >= 0 {
format!("{people} in voice / {} total", head.limit)
} else {
format!("{people} in voice")
};
let stage = if page.short() {
"The window is too short for the larger stage"
} else if compact {
"Larger stage"
} else {
"Smaller stage"
};
div()
.id("voice-header")
.debug_selector(|| "voice-header".into())
.relative()
.w_full()
.flex_none()
.overflow_hidden()
.when_some(banner, |header, key| {
header
.child(
div()
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id("voice-banner")
.debug_selector(|| "voice-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(banner_scrim(theme)),
)
})
.child(
div()
.relative()
.flex()
.flex_row()
.gap(px(m.space_5))
.pl(px(m.space_7))
.pr(px(m.space_5))
.pt(px(m.space_5))
.pb(px(m.space_3))
.child(div().pt(px(m.space_1)).child(icon("volume-2", 40.0, c.text_secondary)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(m.space_1))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
div()
.id("voice-channel")
.debug_selector(|| "voice-channel".into())
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_3xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(head.channel.clone()),
)
.child(
IconButton::new(
"voice-invite",
"user-plus",
"Copy invite link",
)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx)
}),
)
.child(
IconButton::new(
"voice-stage",
if compact { "chevron-down" } else { "chevron-up" },
stage,
)
.enabled(!page.short())
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ToggleVoiceCompact), cx)
}),
)
.child(
IconButton::new(
"voice-chat-only",
"message-square",
"Chat only",
)
.on_click(|_, window, cx| {
window.dispatch_action(
Box::new(ShowVoiceView { on: false }),
cx,
)
}),
),
)
.when(!head.topic.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_md))
.text_color(hsla(ink))
.child(head.topic.clone()),
)
})
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(icon("users", 16.0, c.text_secondary))
.child(
div()
.id("voice-count")
.debug_selector(|| "voice-count".into())
.text_size(px(m.font_body))
.text_color(hsla(ink))
.child(count),
),
),
),
)
}
/// Mute, deafen, share, the voice settings and Leave, under the people.
fn call_bar(theme: &VoelinTheme, head: &VoiceHead) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (input_muted, output_muted) = (head.input_muted, head.output_muted);
let leave = c.danger;
div()
.id("voice-callbar")
.debug_selector(|| "voice-callbar".into())
.w_full()
.flex_none()
.flex()
.flex_row()
.justify_center()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_6))
.pb(px(m.space_3))
.child(
IconButton::new(
"call-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(input_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx)
}),
)
.child(
IconButton::new(
"call-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(output_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx)
}),
)
.when(head.can_share, |bar| {
bar.child(
IconButton::new("call-share", "monitor-up", "Share or go live")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenShare), cx)),
)
})
.child(
IconButton::new("call-settings", "settings", "Voice Settings")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenVoiceSettings), cx)),
)
.child(
div()
.id("call-leave")
.debug_selector(|| "call-leave".into())
.h(px(m.control_height))
.px(px(m.space_5))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(leave.with_alpha(0x73)))
.bg(hsla(c.danger_soft))
.cursor_pointer()
.hover(move |style| style.bg(hsla(c.danger_soft.mix(leave, 0.25))))
.on_click(|_, window, cx| window.dispatch_action(Box::new(LeaveVoice), cx))
.child(icon("phone-off", m.icon_md, leave))
.child(
div()
.text_size(px(m.font_body))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(leave))
.child("Leave"),
),
)
}
impl Render for VoicePage {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.voice.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let compact = self.compact_shown();
let stage = if compact {
// One row, scrolling sideways when there are many; centred while it fits.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
.h(px(112.0))
.flex_none()
.overflow_x_scroll()
.flex()
.flex_row()
.child(
div()
.h_full()
.flex_none()
.mx_auto()
.flex()
.flex_row()
.gap(px(m.space_3))
.px(px(m.space_6))
.pt(px(m.space_2))
.children(
self.people.iter().map(|person| participant(&theme, person, true)),
),
)
} else {
// Centred, wrapping into more rows when there are many.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
// Rows taller than the page scroll; the header and the call bar keep
// their places.
.flex_shrink(1.0)
.min_h_0()
.overflow_y_scroll()
.flex()
.flex_row()
.flex_wrap()
.justify_center()
.gap_x(px(m.space_6))
.gap_y(px(m.space_4))
.px(px(m.space_6))
.pt(px(m.space_3))
.pb(px(m.space_4))
.children(self.people.iter().map(|person| participant(&theme, person, false)))
};
// A cached pane's root takes the size its place gives it.
panel(&theme)
.id("voice-page")
.debug_selector(|| "voice-page".into())
.size_full()
.child(header(&theme, &self.head, self.people.len(), self))
.child(stage)
.child(call_bar(&theme, &self.head))
.child(
div()
.flex_1()
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("The channel's chat comes with a later slice."),
)
}
}
+563
View File
@@ -0,0 +1,563 @@
//! The few pieces the shell is made of, drawn from the theme's tokens
//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a
//! person, the icon button, the panel and the Lucide icon. They are the GPUI
//! counterparts of `ui/components/avatar.slint`, `button.slint` and
//! `shells/common.slint`'s `Panel`.
use std::sync::Arc;
use gpui_kit::{
AnyElement, App, Background, ClickEvent, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _,
Window, div, linear_color_stop, linear_gradient, px, svg,
};
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
use voelin_ui_vm::Rgb;
use voelin_ui_vm::avatar::first_letter;
use voelin_ui_vm::image::ImageRef;
use crate::pictures::{PictureKey, picture};
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A Lucide icon of the client's set, `size` pixels square, in `color`.
pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement {
svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color))
}
/// What the dot on an avatar says (`Status` of `avatar.slint`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
/// No dot.
None,
/// Connected with voice.
Online,
/// Connecting.
Idle,
/// Observed invisibly.
Info,
/// Not connected.
Offline,
/// Their sound is off (a person who does not hear).
Dnd,
}
impl Presence {
/// The dot of a server's state as the engine names it
/// (`voelin_ui_vm::servers::status`): connected is online, observing is
/// blue, connecting is idle, offline has none.
pub fn of_server(status: &str) -> Self {
match status {
"connected" => Self::Online,
"observing" => Self::Info,
"connecting" => Self::Idle,
_ => Self::None,
}
}
/// The dot's colour.
fn color(self, theme: &VoelinTheme) -> Option<Rgba> {
let c = &theme.colors;
match self {
Self::None => None,
Self::Online => Some(c.success),
Self::Idle => Some(c.idle),
Self::Info => Some(c.info),
Self::Offline => Some(c.offline),
Self::Dnd => Some(c.dnd),
}
}
}
/// The colour a server or person is drawn in.
pub fn tint(color: Rgb) -> Rgba {
Rgba(color.0 << 8 | 0xff)
}
/// How opaque the veil over a banner is at its left edge and at its right
/// (`components/banner-picture.slint`: `transparentize(0.26)` and `(0.34)`).
const BANNER_VEIL: (f32, f32) = (0.74, 0.66);
/// The veil over a banner picture: the surface colour, left to right from 74 %
/// to 66 % opaque. A row's text (`text`) keeps more than 4.5 to 1 against it
/// whatever the picture, even white behind the dark theme's light text or
/// black behind the light theme's dark text. It lies over the picture and
/// under the row's own tint.
pub fn banner_scrim(theme: &VoelinTheme) -> Background {
let surface = hsla(theme.colors.surface);
linear_gradient(
90.0,
linear_color_stop(surface.opacity(BANNER_VEIL.0), 0.0),
linear_color_stop(surface.opacity(BANNER_VEIL.1), 1.0),
)
}
/// Under this size (pixels) an avatar shows one letter, larger (`avatar.slint`).
const SMALL_AVATAR: f32 = 28.0;
/// What an avatar of `size` pixels writes on its colour, and how large:
/// the initials at 0.38 of the size, but only the first letter at half of it
/// under 28 pixels, where two letters at 0.38 are a few pixels high and cramped
/// (`avatar.slint`'s `small`, with `Images.first-letter`).
fn initials_for(initials: &str, size: f32) -> (SharedString, f32) {
if size < SMALL_AVATAR {
(first_letter(initials).into(), size * 0.5)
} else {
(initials.to_owned().into(), size * 0.38)
}
}
/// An avatar: the picture when there is one (a file of the engine's cache),
/// else the initials on `tint` (one letter under 28 pixels), square with
/// rounded corners for a server and round for a person, with a presence dot and
/// a green ring while the person's voice goes out. The picture is keyed by the
/// file and its stamp ([`crate::pictures`]), so a picture the engine writes
/// again shows. Pictures other than files of the cache are drawn as initials
/// until the slices that decode them (the chat's).
#[derive(IntoElement)]
pub struct Avatar {
id: ElementId,
size: f32,
initials: SharedString,
tint: Rgb,
image: ImageRef,
square: bool,
presence: Presence,
speaking: bool,
}
impl Avatar {
/// An avatar of `size` pixels with these initials on `tint`.
pub fn new(id: impl Into<ElementId>, size: f32, initials: &str, tint: Rgb) -> Self {
Self {
id: id.into(),
size,
initials: initials.to_owned().into(),
tint,
image: ImageRef::default(),
square: false,
presence: Presence::None,
speaking: false,
}
}
/// Draw this picture when it is a file of the cache.
pub fn image(mut self, image: ImageRef) -> Self {
self.image = image;
self
}
/// A server's rounded square, not a person's circle.
pub fn square(mut self) -> Self {
self.square = true;
self
}
/// The dot at the corner.
pub fn presence(mut self, presence: Presence) -> Self {
self.presence = presence;
self
}
/// The green ring.
pub fn speaking(mut self, speaking: bool) -> Self {
self.speaking = speaking;
self
}
}
impl RenderOnce for Avatar {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
let key = PictureKey::of(&self.image);
let face = div()
.size(px(self.size))
.flex_none()
.rounded(px(radius))
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match key {
// The picture rounds its own corners: a parent's `overflow_hidden`
// clips to a rectangle.
Some(key) => face
.child(picture(key).size_full().rounded(px(radius)).object_fit(ObjectFit::Cover)),
None => {
let (letters, size) = initials_for(&self.initials, self.size);
face.child(
div()
.text_size(px(size))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child(letters),
)
}
};
let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none();
if self.speaking {
avatar = avatar.child(
div()
.absolute()
.top(px(-3.0))
.left(px(-3.0))
.size(px(self.size + 6.0))
.rounded(px(radius + 3.0))
.border_2()
.border_color(hsla(c.success)),
);
}
avatar = avatar.child(face);
if let Some(color) = self.presence.color(theme) {
let dot = (self.size * 0.3).max(10.0);
avatar = avatar.child(
div()
.absolute()
.top(px(self.size - dot + 1.0))
.left(px(self.size - dot + 1.0))
.size(px(dot))
.rounded(px(dot / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(color)),
);
}
avatar
}
}
type Handler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
/// A button that is an icon: 36 pixels (or `size`) square, round or with
/// rounded corners, with a tooltip. Without a handler or disabled it draws
/// dimmed and does nothing, and keeps its tooltip.
#[derive(IntoElement)]
pub struct IconButton {
id: ElementId,
icon: &'static str,
label: SharedString,
size: f32,
tint: Option<Rgba>,
danger: bool,
round: bool,
filled: bool,
checked: bool,
enabled: bool,
on_click: Option<Handler>,
}
impl IconButton {
/// The Lucide icon `icon` (a file name without `.svg`), named `label` for
/// the tooltip.
pub fn new(
id: impl Into<ElementId>,
icon: &'static str,
label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
icon,
label: label.into(),
size: 34.0,
tint: None,
danger: false,
round: false,
filled: false,
checked: false,
enabled: true,
on_click: None,
}
}
/// The button's side in pixels.
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
/// The icon's colour, instead of the theme's icon colour.
pub fn tint(mut self, tint: Rgba) -> Self {
self.tint = Some(tint);
self
}
/// A button that turns danger-coloured when checked (mute).
pub fn danger(mut self) -> Self {
self.danger = true;
self
}
/// A circle.
pub fn round(mut self) -> Self {
self.round = true;
self
}
/// A button with a border and a face of its own (the rail's plus).
pub fn filled(mut self) -> Self {
self.filled = true;
self
}
/// Whether it is on.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Whether it can be used.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// What a click does.
pub fn on_click(
mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Box::new(handler));
self
}
}
impl RenderOnce for IconButton {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let (face, ink, hover) = match (self.checked, self.danger, self.filled) {
(true, true, _) => (c.danger_soft, c.danger, c.danger_soft),
(true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover),
(false, _, true) => {
let ink = self.tint.unwrap_or(c.icon);
(c.surface_2, ink, ink.with_alpha(0x33))
}
(false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3),
};
let radius = if self.round { self.size / 2.0 } else { m.radius_md };
let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) };
let label = self.label.clone();
let selector = self.id.to_string();
#[cfg(test)]
let tooltip_selector = selector.clone();
// Key the element by both its id and its label so GPUI drops stale
// hover/tooltip state when a toggle button's label changes, while
// keeping the debug selector stable for tests.
let id = ElementId::NamedChild(Arc::new(self.id), self.label);
let mut button = div()
.id(id)
.debug_selector(move || selector)
.size(px(self.size))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(radius))
.bg(hsla(face))
.child(icon(self.icon, icon_size, ink));
if self.filled {
button = button.border_1().border_color(hsla(ink));
}
// The tooltip is there while the button is off too: it says why (the voice
// page's stage button in a window too short for the larger stage).
button = button.tooltip(move |window, cx| {
#[cfg(test)]
tests::record_tooltip(&tooltip_selector, &label);
gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
});
if !self.enabled {
return button.opacity(0.4).into_any_element();
}
button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover)));
match self.on_click {
Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)),
None => button,
}
.into_any_element()
}
}
/// A rounded panel of the frame (sidebar, main area): `surface` a little
/// see-through over the backdrop, a border, clipped.
pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
}
/// What a card of the sidebar is drawn on.
pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2.with_alpha(alpha)))
}
/// `element` in a box of its own that tests find by `selector` (a debug
/// selector costs nothing in a build without debug assertions): for the
/// components of gpui-component, which have none of their own.
pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement {
div().flex_none().debug_selector(|| selector.into()).child(element)
}
/// A picture of the cache in its own colours, `size` pixels square (a group's
/// or a client's icon, a badge); none when it is no picture that shows.
pub fn small_picture(image: &ImageRef, size: f32) -> Option<AnyElement> {
let key = PictureKey::of(image)?;
Some(
picture(key)
.w(px(size))
.h(px(size))
.flex_none()
.object_fit(ObjectFit::Contain)
.into_any_element(),
)
}
/// The red LIVE tag.
pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(18.0))
.px(px(5.0))
.flex_none()
.flex()
.items_center()
.rounded(px(m.radius_xs))
.bg(hsla(c.live))
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child("LIVE")
}
/// Three bars: someone speaks. (The Slint bars move; these stand still, as
/// nothing here may draw the window anew with the clock.)
pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement {
speaking_bars_in(theme, size, theme.colors.success)
}
/// The speaking bars in `color`, for a ground the green does not stand out on
/// (the accent of the voice page's corner badge).
pub fn speaking_bars_in(_theme: &VoelinTheme, size: f32, color: Rgba) -> impl IntoElement {
let bar = move |height: f32| {
div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color))
};
div()
.w(px(size))
.h(px(size))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_between()
.child(bar(1.0))
.child(bar(0.6))
.child(bar(0.8))
}
/// A small rounded label: a role, a fact (talk power, a country), a badge.
/// `picture` is a badge's own picture, `icon` a Lucide icon in the label's
/// colour.
pub fn chip(
theme: &VoelinTheme,
text: impl Into<SharedString>,
icon_name: Option<&'static str>,
picture: Option<AnyElement>,
) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(22.0))
.px(px(m.space_3))
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.rounded(px(m.radius_pill))
.border_1()
.border_color(hsla(c.border_strong))
.bg(hsla(c.surface_3))
.text_size(px(m.font_xs))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.children(icon_name.map(|name| icon(name, 12.0, c.text_secondary).into_any_element()))
.children(picture)
.child(text.into())
}
/// Tooltips built by [`IconButton`] since the last call, as `(selector, label)`.
#[cfg(test)]
pub(crate) fn take_tooltips() -> Vec<(String, String)> {
tests::TOOLTIPS.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use super::*;
use crate::theme::Choice;
thread_local! {
pub(super) static TOOLTIPS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn record_tooltip(selector: &str, label: &str) {
TOOLTIPS.with(|log| log.borrow_mut().push((selector.to_owned(), label.to_owned())));
}
#[test]
fn two_letters_are_written_large_enough_and_one_letter_under_28_pixels() {
// The tree's 22 pixel avatars: one letter, half the size.
assert_eq!(initials_for("DE", 22.0), (SharedString::from("D"), 11.0));
assert_eq!(initials_for("GP", 27.9).0, SharedString::from("G"));
// 28 pixels and up: the initials at 0.38 of the size.
let (letters, size) = initials_for("NS", 28.0);
assert_eq!((letters, size), (SharedString::from("NS"), 28.0 * 0.38));
assert_eq!(initials_for("NS", 46.0).0, SharedString::from("NS"));
// What the engine gave when there is none, and a letter with a mark.
assert_eq!(initials_for("", 22.0).0, SharedString::from(""));
assert_eq!(initials_for("A\u{308}B", 22.0).0, SharedString::from("A\u{308}"));
}
#[test]
fn the_banner_veil_keeps_the_text_readable_over_any_picture() {
for choice in [Choice::Dark, Choice::Light] {
let theme = VoelinTheme::new(choice, choice == Choice::Dark, 1.0);
let c = &theme.colors;
// The weakest end of the veil, over the two pictures that are the
// worst for light and dark text.
for picture in [Rgba(0x0000_00ff), Rgba(0xffff_ffff)] {
let seen = c.surface.mix(picture, 1.0 - BANNER_VEIL.1);
assert!(
c.text.contrast(seen) > 4.5,
"{choice:?}: text on {picture:?} under the veil is {}",
c.text.contrast(seen)
);
}
// Left to right, from the stronger end to the weaker, in the surface's colour.
let surface = hsla(c.surface);
assert_eq!(
banner_scrim(&theme),
linear_gradient(
90.0,
linear_color_stop(surface.opacity(0.74), 0.0),
linear_color_stop(surface.opacity(0.66), 1.0),
)
);
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Per-area signals: `Update.refresh` of the transitions
//! ([`voelin_ui_vm::host::Refresh`]) turned into what the window's parts
//! listen to.
//!
//! The Slint front end draws again what a transition's `refresh` flags name.
//! Here a part of the window is an entity, and gpui-pre 0.3.10 draws a part
//! again when its entity is notified, so each area has an entity of its own,
//! a [`Signal`] with a generation, that the root state raises for the flags
//! of an update ([`Signals::raise`]) and that the parts observe
//! ([`Signals::watch`]): a change of the channel tree notifies the tree's
//! listeners, and the rail, the top bar and the main area are not asked
//! whether anything changed for them. A part still compares what it would show
//! with what it showed before it tells the window, for the many events that
//! set a flag and change nothing it shows.
//!
//! Only the flags of areas this front end has parts for are signals; the
//! others (`chat`, `streams`, ...) are dropped until their slices come, as
//! `perform` dropped all of them before.
use gpui_kit::{App, AppContext as _, Context, Entity, Subscription};
use voelin_ui_vm::host::Refresh;
use crate::app::AppState;
/// An area of the window that a change of the state can concern.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Area {
/// The servers: the rail, the top bar's title, the main area, the server
/// card (`Refresh::servers`).
Servers,
/// The voice and user cards of the sidebar (`Refresh::toolbar`).
Toolbar,
/// The channel tree and the members panel (`Refresh::tree`).
Tree,
/// The card over a member row (`Refresh::member_card`).
MemberCard,
}
impl Area {
/// Every area.
pub const ALL: [Area; 4] = [Area::Servers, Area::Toolbar, Area::Tree, Area::MemberCard];
}
/// The entity of an area: it has nothing but a count of how many times it was
/// raised, so that what observes it is told.
#[derive(Debug, Default)]
pub struct Signal {
generation: u64,
}
impl Signal {
/// How many times it was raised.
pub fn generation(&self) -> u64 {
self.generation
}
}
/// The signals of the areas, owned by the root state.
#[derive(Clone, Debug)]
pub struct Signals {
servers: Entity<Signal>,
toolbar: Entity<Signal>,
tree: Entity<Signal>,
member_card: Entity<Signal>,
}
impl Signals {
/// One signal per area, made in the entity `cx` belongs to.
pub fn new<T: 'static>(cx: &mut Context<T>) -> Self {
Self {
servers: cx.new(|_| Signal::default()),
toolbar: cx.new(|_| Signal::default()),
tree: cx.new(|_| Signal::default()),
member_card: cx.new(|_| Signal::default()),
}
}
/// The signal of an area.
pub fn of(&self, area: Area) -> &Entity<Signal> {
match area {
Area::Servers => &self.servers,
Area::Toolbar => &self.toolbar,
Area::Tree => &self.tree,
Area::MemberCard => &self.member_card,
}
}
/// The areas an update's flags name.
pub fn areas(refresh: &Refresh) -> Vec<Area> {
[
(refresh.servers, Area::Servers),
(refresh.toolbar, Area::Toolbar),
(refresh.tree, Area::Tree),
(refresh.member_card, Area::MemberCard),
]
.into_iter()
.filter_map(|(flagged, area)| flagged.then_some(area))
.collect()
}
/// Raise one area: whatever observes it is told.
pub fn raise_area(&self, area: Area, cx: &mut App) {
self.of(area).update(cx, |signal, cx| {
signal.generation += 1;
cx.notify();
});
}
/// Raise the areas `refresh` names, each once however many flags a batch
/// of events merged into it.
pub fn raise(&self, refresh: &Refresh, cx: &mut App) {
for area in Self::areas(refresh) {
self.raise_area(area, cx);
}
}
/// Run `on` whenever one of `areas` is raised, with the root state; the
/// subscriptions end with the part that holds them. `on` reads the state
/// outside of the part's render: a part that read the root entity while it
/// renders would be drawn again with every change of the root, which is
/// what the signals are for not doing.
pub fn watch<T: 'static>(
&self,
app: &Entity<AppState>,
areas: &[Area],
cx: &mut Context<T>,
on: impl Fn(&mut T, &Entity<AppState>, &mut Context<T>) + Clone + 'static,
) -> Vec<Subscription> {
areas
.iter()
.map(|&area| {
let (app, on) = (app.clone(), on.clone());
cx.observe(self.of(area), move |this, _, cx| on(this, &app, cx))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_flags_of_an_update_name_the_areas_this_front_end_has() {
assert!(Signals::areas(&Refresh::default()).is_empty());
let refresh = Refresh { tree: true, servers: true, chat: true, ..Default::default() };
assert_eq!(Signals::areas(&refresh), [Area::Servers, Area::Tree], "chat has no part yet");
assert_eq!(Signals::areas(&Refresh::ALL), Area::ALL);
}
}
+389
View File
@@ -0,0 +1,389 @@
//! The swatch page: every colour token of the theme with its name and value,
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
//! from the second layer of the theme) and the client's icons, in the mode
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
//! of a theme change, and what the screenshots in docs/ui/ show.
use std::collections::HashMap;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::checkbox::Checkbox;
use gpui_kit::component::switch::Switch;
use gpui_kit::{
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
StatefulInteractiveElement as _, Styled as _, div, px, svg,
};
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
pub const GROUPS: [(&str, &[&str]); 6] = [
(
"Backgrounds",
&[
"bg-app",
"bg-rail",
"surface",
"surface-2",
"surface-3",
"surface-4",
"scrim",
"scrim-light",
"overlay",
],
),
("Lines", &["border", "border-strong", "border-popup", "glow"]),
(
"Accent",
&[
"accent",
"accent-hover",
"accent-pressed",
"accent-soft",
"accent-soft-hover",
"accent-text",
"name-text",
"on-accent",
],
),
(
"States",
&[
"live",
"live-soft",
"danger",
"danger-soft",
"success",
"success-soft",
"warning",
"warning-soft",
"idle",
"dnd",
"offline",
"gold",
"info",
],
),
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
];
/// Icons shown, by the name of the client's file.
const ICONS: [&str; 16] = [
"mic.svg",
"mic-off.svg",
"headphones.svg",
"volume-2.svg",
"settings.svg",
"search.svg",
"bell.svg",
"users.svg",
"message-square.svg",
"monitor-up.svg",
"hash.svg",
"lock.svg",
"crown.svg",
"plus.svg",
"x.svg",
"check.svg",
];
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
let m = &theme.metrics;
div()
.text_size(px(m.font_md))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(theme.colors.text))
.child(text.to_owned())
}
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.w(px(100.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.h(px(24.0))
.rounded(px(m.radius_xs))
.border_1()
.border_color(hsla(c.border_strong))
.bg(hsla(color)),
)
.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_secondary))
.child(name.to_owned()),
)
.child(
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
)
}
fn colours(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
let mut column = div().flex().flex_col().gap(px(m.space_4));
for (group, names) in GROUPS {
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
for name in names {
row = row.child(chip(theme, name, by_name[name]));
}
column = column.child(
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
);
}
column
}
fn radii(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut row = div().flex().flex_row().gap(px(m.space_4));
for (name, radius) in [
("xs", m.radius_xs),
("sm", m.radius_sm),
("md", m.radius_md),
("lg", m.radius_lg),
("xl", m.radius_xl),
("pill", m.radius_pill),
] {
row = row.child(
div()
.flex()
.flex_col()
.items_center()
.gap(px(m.space_2))
.child(
div()
.size(px(40.0))
.rounded(px(radius))
.bg(hsla(c.surface_4))
.border_1()
.border_color(hsla(c.border_popup)),
)
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
}
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut rows = div().flex().flex_col().gap(px(m.space_1));
for (name, space) in [
("space-1", m.space_1),
("space-2", m.space_2),
("space-3", m.space_3),
("space-4", m.space_4),
("space-5", m.space_5),
("space-6", m.space_6),
("space-7", m.space_7),
("space-8", m.space_8),
] {
rows = rows.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
div()
.w(px(56.0))
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(name),
)
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{space} px")),
),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
}
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut rows = div().flex().flex_col();
for (name, size, weight) in [
("font-3xl", m.font_3xl, FontWeight::BOLD),
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
("font-lg", m.font_lg, FontWeight::MEDIUM),
("font-md", m.font_md, FontWeight::MEDIUM),
("font-body", m.font_body, FontWeight::NORMAL),
("font-sm", m.font_sm, FontWeight::NORMAL),
("font-xs", m.font_xs, FontWeight::NORMAL),
] {
rows = rows.child(
div()
.text_size(px(size))
.font_weight(weight)
.text_color(hsla(c.text))
.child(format!("{name} {size}: Raid tonight at 21:00")),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
}
fn components(theme: &VoelinTheme) -> impl IntoElement {
let m = &theme.metrics;
div()
.flex()
.flex_col()
.gap(px(m.space_3))
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(m.space_3))
.child(Button::new("primary").primary().label("Primary"))
.child(Button::new("secondary").label("Secondary"))
.child(Button::new("danger").danger().label("Danger"))
.child(Button::new("success").success().label("Success"))
.child(Button::new("warning").warning().label("Warning"))
.child(Button::new("info").info().label("Info")),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_5))
.child(Switch::new("on").checked(true))
.child(Switch::new("off").checked(false))
.child(Checkbox::new("checked").checked(true).label("Checked"))
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
)
}
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
let [first, _, last] = b.stops;
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
div()
.h(px(36.0))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border))
.bg(b.to_gpui())
.px(px(m.space_3))
.py(px(m.space_2))
.text_size(px(m.font_xs))
.text_color(hsla(c.text_secondary))
.child(format!(
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
b.angle,
first.0,
last.0,
b.stops[1].0,
(b.stops[1].1 * 100.0).round()
)),
)
}
fn icons(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
for name in ICONS {
row = row.child(
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
);
}
div()
.flex()
.flex_col()
.gap(px(m.space_3))
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
.child(row)
}
/// The page: the colours on the left, the rest on the right; it scrolls when
/// the window is smaller than it.
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("swatch")
.size_full()
.overflow_y_scroll()
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_6))
.bg(hsla(c.bg_app))
.child(
div()
.flex()
.flex_row()
.items_baseline()
.gap(px(m.space_4))
.child(
div()
.text_size(px(m.font_2xl))
.font_weight(FontWeight::BOLD)
.text_color(hsla(c.text))
.child("Voelin theme"),
)
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
format!(
"{} (setting {}), text size {}",
if theme.is_dark() { "dark" } else { "light" },
theme.choice().name(),
m.font_scale
),
)),
)
.child(
div()
.flex()
.flex_row()
.gap(px(m.space_8))
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
.child(
div()
.w(px(600.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.child(backdrop(theme))
.child(radii(theme))
.child(spacing(theme))
.child(type_scale(theme))
.child(components(theme))
.child(icons(theme)),
),
)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use super::*;
use crate::assets::client_icon;
use crate::theme::Palette;
#[test]
fn every_colour_token_is_in_exactly_one_group() {
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
let unique: BTreeSet<&str> = shown.iter().copied().collect();
assert_eq!(shown.len(), unique.len(), "a token in two groups");
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
assert_eq!(unique, tokens);
}
#[test]
fn the_icons_shown_are_the_clients() {
for name in ICONS {
assert!(client_icon(name).is_some(), "{name}");
}
}
}
+278
View File
@@ -0,0 +1,278 @@
//! The second layer of the theme: the colours gpui-component's widgets read,
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
//! for the list, one for the table, one for each kind of button); the
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
//! What has no counterpart stays as the registered theme of the mode has it
//! (charts' bullish and bearish colours, the cyan and magenta of the base
//! palette).
//!
//! gpui-component's "accent" is a hover background, not a brand colour: the
//! client's `accent` is its `primary`.
use gpui_kit::Hsla;
use gpui_kit::component::ThemeColor;
use super::tokens::{Palette, Rgba};
/// A palette colour as GPUI's.
pub fn hsla(color: Rgba) -> Hsla {
gpui_kit::rgba(color.0).into()
}
/// Of `base`, the colours a status button needs: hover, active, and a text
/// that reads on it (white or the window's ink, whichever contrasts more).
struct Status {
base: Hsla,
hover: Hsla,
active: Hsla,
foreground: Hsla,
}
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
Status {
base: hsla(base),
hover: hsla(base.mix(toward_hover, 0.14)),
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
foreground: hsla(base.readable(ink)),
}
}
/// Write the palette's colours into `colors`, over what the registered theme
/// of the mode left there. Every field that gpui-component's themes derive
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
/// too, so that none keeps the default theme's blue.
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
let c = colors;
let h = hsla;
let clear = Hsla::transparent_black();
// The window and its text.
c.background = h(p.bg_app);
c.foreground = h(p.text);
c.border = h(p.border);
c.input = h(p.border_strong);
c.ring = h(p.glow);
c.overlay = h(p.scrim);
c.window_border = h(p.border);
c.caret = h(p.text);
c.selection = h(p.accent_soft);
c.drag_border = h(p.accent);
c.drop_target = h(p.accent_soft);
// Links: one colour for all three states, as the client has one.
c.link = h(p.accent_text);
c.link_hover = h(p.accent_text);
c.link_active = h(p.accent_text);
// The brand colour, and gpui-component's hover "accent".
c.primary = h(p.accent);
c.primary_hover = h(p.accent_hover);
c.primary_active = h(p.accent_pressed);
c.primary_foreground = h(p.on_accent);
c.accent = h(p.surface_3);
c.accent_foreground = h(p.text);
// Cards, inputs, menus, popovers.
c.secondary = h(p.surface_2);
c.secondary_hover = h(p.surface_3);
c.secondary_active = h(p.surface_4);
c.secondary_foreground = h(p.text);
c.muted = h(p.surface_2);
c.muted_foreground = h(p.text_muted);
c.popover = h(p.surface_3);
c.popover_foreground = h(p.text);
c.group_box = h(p.surface_2);
c.group_box_foreground = h(p.text);
c.accordion = h(p.surface_2);
c.description_list_label = h(p.surface_2);
c.description_list_label_foreground = h(p.text_secondary);
// The status colours, with the text that reads on each.
let [danger, success, warning, info] =
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
(danger.base, danger.hover, danger.active, danger.foreground);
(c.success, c.success_hover, c.success_active, c.success_foreground) =
(success.base, success.hover, success.active, success.foreground);
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
(warning.base, warning.hover, warning.active, warning.foreground);
(c.info, c.info_hover, c.info_active, c.info_foreground) =
(info.base, info.hover, info.active, info.foreground);
// Lists and tables: rows on the panel, hovered rows raised, the selected
// row the soft accent with the accent's edge.
c.list = h(p.surface);
c.list_hover = h(p.surface_3);
c.list_active = h(p.accent_soft);
c.list_active_border = h(p.accent);
c.list_even = h(p.surface);
c.list_head = h(p.surface_2);
c.table = h(p.surface);
c.table_hover = h(p.surface_3);
c.table_active = h(p.accent_soft);
c.table_active_border = h(p.accent);
c.table_even = h(p.surface);
c.table_head = h(p.surface_2);
c.table_head_foreground = h(p.text_secondary);
c.table_foot = h(p.surface_2);
c.table_foot_foreground = h(p.text_secondary);
c.table_row_border = h(p.border);
// The panels around the content: the sidebar, the title and status bars.
c.sidebar = h(p.surface);
c.sidebar_foreground = h(p.text);
c.sidebar_border = h(p.border);
c.sidebar_accent = h(p.surface_3);
c.sidebar_accent_foreground = h(p.text);
c.sidebar_primary = h(p.accent);
c.sidebar_primary_foreground = h(p.on_accent);
c.title_bar = h(p.surface);
c.title_bar_border = h(p.border);
c.status_bar = h(p.surface);
c.status_bar_border = h(p.border);
// Small widgets.
c.scrollbar = clear;
c.scrollbar_thumb = h(p.border_strong);
c.scrollbar_thumb_hover = h(p.text_muted);
c.slider_bar = h(p.accent);
c.slider_thumb = h(p.on_accent);
c.switch = h(p.surface_4);
c.switch_thumb = h(p.on_accent);
c.progress_bar = h(p.accent);
c.skeleton = h(p.surface_3);
c.tab = clear;
c.tab_active = h(p.surface_2);
c.tab_active_foreground = h(p.text);
c.tab_bar = h(p.surface);
c.tab_bar_segmented = h(p.surface_2);
c.tab_foreground = h(p.text_secondary);
// The base palette and the charts: the client's state colours.
c.red = h(p.danger);
c.red_light = h(p.danger_soft);
c.green = h(p.success);
c.green_light = h(p.success_soft);
c.yellow = h(p.warning);
c.yellow_light = h(p.warning_soft);
c.blue = h(p.info);
c.blue_light = h(p.accent_soft);
c.chart_1 = h(p.accent);
c.chart_2 = h(p.success);
c.chart_3 = h(p.warning);
c.chart_4 = h(p.danger);
c.chart_5 = h(p.info);
// The buttons: what a theme file leaves out they take from the colours
// above, so they are written from them here.
c.button = c.secondary;
c.button_hover = c.secondary_hover;
c.button_active = c.secondary_active;
c.button_foreground = c.secondary_foreground;
c.button_primary = c.primary;
c.button_primary_hover = c.primary_hover;
c.button_primary_active = c.primary_active;
c.button_primary_foreground = c.primary_foreground;
c.button_secondary = c.secondary;
c.button_secondary_hover = c.secondary_hover;
c.button_secondary_active = c.secondary_active;
c.button_secondary_foreground = c.secondary_foreground;
c.button_danger = c.danger;
c.button_danger_hover = c.danger_hover;
c.button_danger_active = c.danger_active;
c.button_danger_foreground = c.danger_foreground;
c.button_success = c.success;
c.button_success_hover = c.success_hover;
c.button_success_active = c.success_active;
c.button_success_foreground = c.success_foreground;
c.button_warning = c.warning;
c.button_warning_hover = c.warning_hover;
c.button_warning_active = c.warning_active;
c.button_warning_foreground = c.warning_foreground;
c.button_info = c.info;
c.button_info_hover = c.info_hover;
c.button_info_active = c.info_active;
c.button_info_foreground = c.info_foreground;
}
#[cfg(test)]
mod tests {
use super::*;
fn written(dark: bool) -> (Palette, ThemeColor) {
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
let mut colors = ThemeColor::default();
write(&palette, dark, &mut colors);
(palette, colors)
}
#[test]
fn the_client_tokens_land_where_the_table_says() {
for dark in [true, false] {
let (p, c) = written(dark);
assert_eq!(c.background, hsla(p.bg_app));
assert_eq!(c.foreground, hsla(p.text));
assert_eq!(c.primary, hsla(p.accent));
assert_eq!(c.primary_hover, hsla(p.accent_hover));
assert_eq!(c.primary_active, hsla(p.accent_pressed));
assert_eq!(c.primary_foreground, hsla(p.on_accent));
assert_eq!(
c.accent,
hsla(p.surface_3),
"gpui-component's accent is a hover background"
);
assert_eq!(c.secondary, hsla(p.surface_2));
assert_eq!(c.secondary_active, hsla(p.surface_4));
assert_eq!(c.border, hsla(p.border));
assert_eq!(c.input, hsla(p.border_strong));
assert_eq!(c.ring, hsla(p.glow));
assert_eq!(c.overlay, hsla(p.scrim));
assert_eq!(c.list_active, hsla(p.accent_soft));
assert_eq!(c.link, hsla(p.accent_text));
assert_eq!(c.muted_foreground, hsla(p.text_muted));
assert_eq!(c.sidebar, hsla(p.surface));
assert_eq!(c.danger, hsla(p.danger));
assert_eq!(c.success, hsla(p.success));
}
}
#[test]
fn the_buttons_follow_the_colours_they_fall_back_to() {
let (_, c) = written(true);
assert_eq!(c.button_primary, c.primary);
assert_eq!(c.button_primary_hover, c.primary_hover);
assert_eq!(c.button_danger_foreground, c.danger_foreground);
assert_eq!(c.button, c.secondary);
assert_eq!(c.button_info_active, c.info_active);
}
#[test]
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
for base in [p.danger, p.success, p.warning, p.info] {
let s = status(base, p.bg_app, dark);
let chosen = base.readable(p.bg_app);
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
assert_eq!(s.foreground, hsla(chosen));
assert_ne!(s.hover, s.base);
assert_ne!(s.active, s.base);
}
}
}
#[test]
fn mixing_and_contrast_do_what_they_say() {
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
assert_eq!(black.mix(white, 0.0), black);
assert_eq!(black.mix(white, 1.0), white);
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
assert!((black.contrast(white) - 21.0).abs() < 0.01);
assert_eq!(black.readable(black), white);
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
}
}
+293
View File
@@ -0,0 +1,293 @@
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
//!
//! 1. [`VoelinTheme`], a GPUI global with every token of
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
//! elements (the server rail, presence dots, meters, the backdrop) read it.
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
//! menus, dialogs) read, written from the first on every change
//! ([`components`]), so that they look like ours.
//!
//! The mode is the client's `ui.theme`: `system` follows the window's
//! appearance (and its changes), `light` and `dark` do not.
mod components;
#[cfg(test)]
mod slint_parity;
pub mod tokens;
pub use components::hsla;
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{App, Background, Global, WindowAppearance, linear_color_stop, linear_gradient, px};
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
impl Backdrop {
/// What GPUI draws: its gradient has two colour stops, so the first and the
/// last of the three; the middle one is not drawn.
pub fn to_gpui(&self) -> Background {
let [first, _, last] = self.stops;
linear_gradient(
self.angle,
linear_color_stop(hsla(first.0), first.1),
linear_color_stop(hsla(last.0), last.1),
)
}
}
/// The theme mode setting (`ui.theme` of the Slint front end).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Choice {
/// Follow the window's appearance.
System,
/// Always light.
Light,
/// Always dark.
Dark,
}
impl Choice {
/// `system`, `light` or `dark`.
pub fn parse(text: &str) -> Option<Self> {
match text {
"system" => Some(Self::System),
"light" => Some(Self::Light),
"dark" => Some(Self::Dark),
_ => None,
}
}
/// The setting's value.
pub fn name(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
/// Whether the theme is dark, given whether the window's appearance is.
pub fn resolve(self, system_dark: bool) -> bool {
match self {
Self::System => system_dark,
Self::Light => false,
Self::Dark => true,
}
}
}
/// Whether a window's appearance is a dark one.
pub fn is_dark(appearance: WindowAppearance) -> bool {
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
}
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
/// global.
#[derive(Clone, Debug)]
pub struct VoelinTheme {
choice: Choice,
dark: bool,
/// The colours of the resolved mode.
pub colors: Palette,
/// The window's backdrop gradient of the resolved mode.
pub backdrop: Backdrop,
/// The sizes, radii, type and durations at the text size factor.
pub metrics: Metrics,
}
impl Global for VoelinTheme {}
impl VoelinTheme {
/// The tokens for a mode (resolved against `system_dark`) and a text size
/// factor.
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
let dark = choice.resolve(system_dark);
Self {
choice,
dark,
colors: if dark { Palette::DARK } else { Palette::LIGHT },
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
metrics: Metrics::new(font_scale),
}
}
/// The theme mode that was set.
pub fn choice(&self) -> Choice {
self.choice
}
/// Whether the colours are the dark ones.
pub fn is_dark(&self) -> bool {
self.dark
}
/// Install the theme as the global and write it into gpui-component, which
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
/// the system's before there is a window).
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
Self::apply(cx);
}
/// The theme global.
pub fn global(cx: &App) -> &Self {
cx.global::<Self>()
}
/// Change the mode (a setting changed), given the window's appearance now.
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
let (scale, current) = {
let this = Self::global(cx);
(this.metrics.font_scale, this.choice)
};
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
return;
}
cx.set_global(Self::new(choice, is_dark(appearance), scale));
Self::apply(cx);
}
/// The window's appearance changed; it matters only in `system` mode.
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
let this = Self::global(cx);
if this.choice == Choice::System && this.dark != is_dark(appearance) {
let (choice, scale) = (this.choice, this.metrics.font_scale);
cx.set_global(Self::new(choice, is_dark(appearance), scale));
Self::apply(cx);
}
}
/// The text size factor changed (`ui.font_scale`).
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
let this = Self::global(cx);
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
return;
}
// `dark` is what the mode resolved to: for every mode, resolving it again
// against it gives the same.
let (choice, dark) = (this.choice, this.dark);
cx.set_global(Self::new(choice, dark, font_scale));
Self::apply(cx);
}
/// Write the global into gpui-component's theme: the mode, the colours of
/// the second layer, the font, the base size and the radii.
fn apply(cx: &mut App) {
let this = Self::global(cx).clone();
// The registered theme of the mode first (it sets whatever the second
// layer leaves alone), then our colours over it in a second update, as
// `Theme::update` says a mode change must be.
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
Theme::update(cx, |theme| {
components::write(&this.colors, this.dark, &mut theme.colors);
theme.font_family = FONT_FAMILY.into();
theme.font_size = px(this.metrics.font_body);
theme.radius = px(this.metrics.radius_sm);
theme.radius_lg = px(this.metrics.radius_lg);
});
// Where the platform draws the window's frame itself (macOS), it follows
// the mode; elsewhere this does nothing.
cx.set_window_appearance(match this.choice {
Choice::System => None,
Choice::Light => Some(WindowAppearance::Light),
Choice::Dark => Some(WindowAppearance::Dark),
});
}
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use gpui_kit::component::ActiveTheme as _;
use super::*;
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
cx.update(|cx| {
gpui_kit::init(cx);
VoelinTheme::init(cx, choice, appearance, 1.0);
});
}
#[test]
fn the_mode_resolves_against_the_window() {
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
for choice in [Choice::System, Choice::Light, Choice::Dark] {
assert_eq!(Choice::parse(choice.name()), Some(choice));
}
assert_eq!(Choice::parse("blue"), None);
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
}
#[test]
fn the_backdrop_draws_the_first_and_the_last_of_its_three_stops() {
let b = Backdrop::DARK;
let [first, middle, last] = b.stops;
assert_eq!(
b.to_gpui(),
linear_gradient(
160.0,
linear_color_stop(hsla(first.0), 0.0),
linear_color_stop(hsla(last.0), 1.0)
)
);
assert_ne!(
b.to_gpui(),
linear_gradient(
160.0,
linear_color_stop(hsla(first.0), 0.0),
linear_color_stop(hsla(middle.0), 1.0)
),
"the middle stop is not the end one"
);
}
#[gpui::test]
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
start(cx, Choice::Dark, WindowAppearance::Light);
cx.update(|cx| {
let theme = cx.theme();
assert!(theme.is_dark());
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
assert_eq!(theme.font_family.as_ref(), "Inter");
assert_eq!(theme.font_size, px(14.0));
assert_eq!(theme.radius, px(6.0));
assert_eq!(theme.radius_lg, px(12.0));
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
});
}
#[gpui::test]
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
start(cx, Choice::System, WindowAppearance::Light);
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
}
#[gpui::test]
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
start(cx, Choice::Dark, WindowAppearance::Dark);
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
cx.update(|cx| {
let theme = VoelinTheme::global(cx);
assert!(theme.is_dark(), "the mode stays");
assert_eq!(theme.metrics.font_body, 17.5);
assert_eq!(theme.metrics.control_height, 45.0);
assert_eq!(cx.theme().font_size, px(17.5));
});
}
}
@@ -0,0 +1,318 @@
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
//! read and every token in it is compared with the Rust value of the same
//! name, light and dark and at four text sizes; a token on one side only, a
//! value that differs, or a declaration of a kind this test does not know
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
//! `font-family`) fails it. While both front ends live, a token changed in
//! one place and not the other is caught here.
use std::collections::{BTreeMap, BTreeSet};
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
/// What `theme.slint` declares: the kind and the expression of each property
/// of the `Theme` global, in file order.
fn declarations() -> Vec<(String, String, String)> {
declarations_of(SLINT)
}
/// The same for the text of a `.slint` file (the tests below also read
/// altered copies of `theme.slint`).
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
let without_comments: String = source
.lines()
.map(|line| line.split("//").next().unwrap_or(""))
.collect::<Vec<_>>()
.join("\n");
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
let mut found = Vec::new();
for statement in body.split(';') {
let statement = statement.trim();
let Some(rest) = ["in-out property", "out property", "in property"]
.iter()
.find_map(|prefix| statement.strip_prefix(prefix))
else {
continue;
};
let (kind, rest) =
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
// One line, single spaces: `backdrop` is written over several.
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
}
found
}
/// `#rgb`-style literal as `Rgba`.
fn colour(text: &str) -> Rgba {
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
match hex.len() {
6 => Rgba(value << 8 | 0xff),
8 => Rgba(value),
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
}
}
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
fn by_mode(expr: &str) -> (String, String) {
let Some(rest) = expr.strip_prefix("dark ?") else {
return (expr.to_owned(), expr.to_owned());
};
let mut depth = 0;
for (i, c) in rest.char_indices() {
match c {
'(' => depth += 1,
')' => depth -= 1,
':' if depth == 0 => {
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
}
_ => {}
}
}
panic!("no `:` in {expr:?}");
}
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
/// `*`, `+`, `max(a, b)` and parentheses.
struct Eval<'a> {
tokens: Vec<String>,
at: usize,
env: &'a BTreeMap<String, String>,
scale: f64,
}
impl<'a> Eval<'a> {
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
let mut tokens = Vec::new();
let mut word = String::new();
for c in expr.chars() {
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
word.push(c);
} else {
if !word.is_empty() {
tokens.push(std::mem::take(&mut word));
}
if !c.is_whitespace() {
tokens.push(c.to_string());
}
}
}
if !word.is_empty() {
tokens.push(word);
}
let mut eval = Eval { tokens, at: 0, env, scale };
let value = eval.sum();
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
value
}
fn peek(&self) -> Option<&str> {
self.tokens.get(self.at).map(String::as_str)
}
fn take(&mut self) -> String {
self.at += 1;
self.tokens[self.at - 1].clone()
}
fn sum(&mut self) -> f64 {
let mut value = self.product();
while self.peek() == Some("+") {
self.take();
value += self.product();
}
value
}
fn product(&mut self) -> f64 {
let mut value = self.factor();
while self.peek() == Some("*") {
self.take();
value *= self.factor();
}
value
}
fn factor(&mut self) -> f64 {
let token = self.take();
if token == "(" {
let value = self.sum();
assert_eq!(self.take(), ")");
return value;
}
if token == "max" {
assert_eq!(self.take(), "(");
let a = self.sum();
assert_eq!(self.take(), ",");
let b = self.sum();
assert_eq!(self.take(), ")");
return a.max(b);
}
if token == "font-scale" {
return self.scale;
}
if token.starts_with(|c: char| c.is_ascii_digit()) {
let number: String =
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
}
let expr =
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
Eval::run(&expr, self.env, self.scale)
}
}
/// The names `theme.slint` declares that are state, not tokens: the mode and
/// what it resolves to, and the text size factor (the factor is a parameter
/// of [`Metrics`]).
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
#[test]
fn every_colour_is_the_same_in_both_files() {
let slint: Vec<(String, String, String)> =
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &slint {
let (d, l) = by_mode(expr);
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
names.insert(name.as_str());
}
let ours: BTreeSet<&str> = dark.keys().copied().collect();
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
}
#[test]
fn every_length_weight_and_duration_is_the_same_in_both_files() {
let all = declarations();
let env: BTreeMap<String, String> =
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
let numeric: Vec<&(String, String, String)> = all
.iter()
.filter(|(name, kind, _)| {
matches!(kind.as_str(), "length" | "int" | "duration")
&& !STATE.contains(&name.as_str())
})
.collect();
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &numeric {
let slint = Eval::run(expr, &env, f64::from(scale));
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
assert!(
(slint - ours).abs() < 1e-3,
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
);
names.insert(name.as_str());
}
let rust: BTreeSet<&str> = ours.keys().copied().collect();
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
}
}
#[test]
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
let all = declarations();
let get = |name: &str| {
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
};
let gradient = |text: &str| -> Backdrop {
let inner = text
.trim()
.strip_prefix("@linear-gradient(")
.and_then(|t| t.strip_suffix(')'))
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
let mut parts = inner.split(',').map(str::trim);
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
let stops: Vec<(Rgba, f32)> = parts
.map(|stop| {
let (colour_text, position) = stop.split_once(' ').unwrap();
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
(colour(colour_text), percent / 100.0)
})
.collect();
Backdrop { angle, stops: stops.try_into().expect("three stops") }
};
let (dark, light) = by_mode(&get("backdrop"));
assert_eq!(gradient(&dark), Backdrop::DARK);
assert_eq!(gradient(&light), Backdrop::LIGHT);
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
}
/// What the declarations hold that no comparison above covers, one sentence
/// each; empty when there is none: a kind of declaration this test does not
/// know, a brush other than `backdrop` or a string other than `mode` and
/// `font-family` (the two comparisons of those go by name, so a second one
/// would pass unseen), a state name that is no longer declared.
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
let mut problems = Vec::new();
let kinds: BTreeSet<&str> = declared
.iter()
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
.map(|(_, kind, _)| kind.as_str())
.collect();
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
if kinds != known {
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
}
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
let found: BTreeSet<&str> = declared
.iter()
.filter(|(_, declared_kind, _)| declared_kind == kind)
.map(|(name, _, _)| name.as_str())
.collect();
let expected: BTreeSet<&str> = expected.iter().copied().collect();
for name in found.symmetric_difference(&expected) {
problems.push(format!(
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
));
}
}
for name in STATE {
if !declared.iter().any(|(declared, _, _)| declared == name) {
problems.push(format!("{name} is not declared"));
}
}
problems
}
#[test]
fn the_file_declares_nothing_this_test_does_not_know() {
let problems = unknown_to_this_test(&declarations());
assert!(problems.is_empty(), "{problems:#?}");
}
/// `theme.slint` with one more declaration in its `Theme` global.
fn with_declaration(declaration: &str) -> String {
let opening = "export global Theme {";
assert!(SLINT.contains(opening));
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
}
#[test]
fn a_second_brush_or_string_is_not_passed_unseen() {
// Mutants of the Slint file: a token on one side only.
for (declaration, name) in [
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
("out property <string> font-mono: \"Mono\";", "font-mono"),
] {
let mutant = declarations_of(&with_declaration(declaration));
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
let problems = unknown_to_this_test(&mutant);
assert!(
problems.iter().any(|problem| problem.contains(name)),
"{name} goes unnoticed: {problems:#?}"
);
}
// And the file as it is has neither.
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
}
+372
View File
@@ -0,0 +1,372 @@
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
//! the original while the Slint front end lives; the test in
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
//! formula here differs from it, so the two cannot drift apart.
use std::fmt;
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
/// is opaque).
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgba(pub u32);
impl fmt::Debug for Rgba {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for Rgba {
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.alpha() == 255 {
write!(f, "#{:06x}", self.0 >> 8)
} else {
write!(f, "#{:08x}", self.0)
}
}
}
impl Rgba {
/// Transparent black, for the widgets that draw nothing.
pub const TRANSPARENT: Self = Self(0);
/// The opacity, 0 to 255.
pub fn alpha(self) -> u8 {
(self.0 & 0xff) as u8
}
/// The same colour with another opacity.
pub fn with_alpha(self, alpha: u8) -> Self {
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
}
/// The channels, 0 to 1.
pub fn channels(self) -> [f32; 3] {
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
}
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
/// from `self`.
pub fn mix(self, other: Self, amount: f32) -> Self {
let (a, b) = (self.channels(), other.channels());
let channel =
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
}
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
pub fn luminance(self) -> f32 {
let [r, g, b] = self
.channels()
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
0.2126 * r + 0.7152 * g + 0.0722 * b
}
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
pub fn contrast(self, other: Self) -> f32 {
let (a, b) = (self.luminance(), other.luminance());
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
/// Of white and `ink`, the one that reads better on `self`.
pub fn readable(self, ink: Self) -> Self {
let white = Self(0xffff_ffff);
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
}
}
macro_rules! palette {
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
/// Every colour token of `theme.slint` for one mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Palette {
$(
#[doc = concat!("`", $name, "` of `theme.slint`.")]
pub $field: Rgba,
)*
}
impl Palette {
/// The dark palette.
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
/// The light palette.
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
/// Every colour by the name it has in `theme.slint`, in its order.
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
vec![$(($name, self.$field),)*]
}
}
};
}
palette! {
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
surface "surface": 0x0b1330ff, 0xf7f9feff;
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
scrim "scrim": 0x02050fc0, 0x0b132b80;
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
overlay "overlay": 0x060a18c8, 0x0b1330b0;
border "border": 0x1b2750ff, 0xd3dceeff;
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
accent "accent": 0x2d6bffff, 0x2458e6ff;
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
on_accent "on-accent": 0xffffffff, 0xffffffff;
glow "glow": 0x3f7bff90, 0x2458e660;
live "live": 0xff2d55ff, 0xe0203fff;
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
danger "danger": 0xff4d5eff, 0xd92c3cff;
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
success "success": 0x22d36bff, 0x16a557ff;
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
warning "warning": 0xf5b301ff, 0xb77f00ff;
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
idle "idle": 0xf5b301ff, 0xc98b00ff;
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
gold "gold": 0xffc233ff, 0xd99a00ff;
info "info": 0x3fb3ffff, 0x1180d6ff;
text "text": 0xeef2ffff, 0x0e1733ff;
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
icon "icon": 0xb9c4e2ff, 0x43506fff;
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
}
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
/// (`Backdrop::to_gpui`, in the theme module) is the first and the last; the
/// middle one stays here for a front end that can use it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Backdrop {
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
pub angle: f32,
/// Three stops: colour and position (0 to 1).
pub stops: [(Rgba, f32); 3],
}
impl Backdrop {
/// The dark backdrop.
pub const DARK: Self = Self {
angle: 160.0,
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
};
/// The light backdrop.
pub const LIGHT: Self = Self {
angle: 160.0,
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
};
}
/// The family of the UI font (`font-family` of `theme.slint`).
pub const FONT_FAMILY: &str = "Inter";
/// Every size, radius, weight and duration token of `theme.slint` for one
/// text size factor: lengths in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Metrics {
/// `font-scale`: multiplies every type size and the sizes that follow text.
pub font_scale: f32,
/// `radius-xs`.
pub radius_xs: f32,
/// `radius-sm`.
pub radius_sm: f32,
/// `radius-md`.
pub radius_md: f32,
/// `radius-lg`.
pub radius_lg: f32,
/// `radius-xl`.
pub radius_xl: f32,
/// `radius-pill`.
pub radius_pill: f32,
/// `space-1`.
pub space_1: f32,
/// `space-2`.
pub space_2: f32,
/// `space-3`.
pub space_3: f32,
/// `space-4`.
pub space_4: f32,
/// `space-5`.
pub space_5: f32,
/// `space-6`.
pub space_6: f32,
/// `space-7`.
pub space_7: f32,
/// `space-8`.
pub space_8: f32,
/// `font-xs` (scaled).
pub font_xs: f32,
/// `font-sm` (scaled).
pub font_sm: f32,
/// `font-body` (scaled).
pub font_body: f32,
/// `font-md` (scaled).
pub font_md: f32,
/// `font-lg` (scaled).
pub font_lg: f32,
/// `font-xl` (scaled).
pub font_xl: f32,
/// `font-2xl` (scaled).
pub font_2xl: f32,
/// `font-3xl` (scaled).
pub font_3xl: f32,
/// `weight-regular`.
pub weight_regular: u16,
/// `weight-medium`.
pub weight_medium: u16,
/// `weight-semibold`.
pub weight_semibold: u16,
/// `weight-bold`.
pub weight_bold: u16,
/// `row-height` (scaled).
pub row_height: f32,
/// `control-height` (scaled).
pub control_height: f32,
/// `control-height-sm` (scaled).
pub control_height_sm: f32,
/// `icon-sm`.
pub icon_sm: f32,
/// `icon-md`.
pub icon_md: f32,
/// `icon-lg`.
pub icon_lg: f32,
/// `glow-width`: the ring around focused and selected items.
pub glow_width: f32,
/// `rail-width`.
pub rail_width: f32,
/// `sidebar-width`: 264 and more with large text.
pub sidebar_width: f32,
/// `topbar-height`: 44, taller when large text makes the controls taller.
pub topbar_height: f32,
/// `right-panel-min`.
pub right_panel_min: f32,
/// `fast`, in milliseconds.
pub fast_ms: u32,
/// `normal`, in milliseconds.
pub normal_ms: u32,
}
impl Metrics {
/// The tokens at a text size factor (1 is the default).
pub fn new(font_scale: f32) -> Self {
let s = font_scale;
let control_height = 36.0 * s;
let space_3 = 8.0;
Self {
font_scale,
radius_xs: 4.0,
radius_sm: 6.0,
radius_md: 8.0,
radius_lg: 12.0,
radius_xl: 16.0,
radius_pill: 999.0,
space_1: 2.0,
space_2: 4.0,
space_3,
space_4: 12.0,
space_5: 16.0,
space_6: 20.0,
space_7: 24.0,
space_8: 32.0,
font_xs: 11.0 * s,
font_sm: 12.0 * s,
font_body: 14.0 * s,
font_md: 15.0 * s,
font_lg: 17.0 * s,
font_xl: 20.0 * s,
font_2xl: 24.0 * s,
font_3xl: 30.0 * s,
weight_regular: 400,
weight_medium: 500,
weight_semibold: 600,
weight_bold: 700,
row_height: 32.0 * s,
control_height,
control_height_sm: 28.0 * s,
icon_sm: 16.0,
icon_md: 20.0,
icon_lg: 24.0,
glow_width: 2.0,
rail_width: 72.0,
sidebar_width: 264.0 * s.max(1.0),
topbar_height: 44.0_f32.max(control_height + space_3),
right_panel_min: 220.0,
fast_ms: 120,
normal_ms: 200,
}
}
/// Every number token by the name it has in `theme.slint`, in its order:
/// lengths in pixels, weights as they are, durations in milliseconds.
pub fn entries(&self) -> Vec<(&'static str, f64)> {
let m = self;
[
("radius-xs", m.radius_xs),
("radius-sm", m.radius_sm),
("radius-md", m.radius_md),
("radius-lg", m.radius_lg),
("radius-xl", m.radius_xl),
("radius-pill", m.radius_pill),
("space-1", m.space_1),
("space-2", m.space_2),
("space-3", m.space_3),
("space-4", m.space_4),
("space-5", m.space_5),
("space-6", m.space_6),
("space-7", m.space_7),
("space-8", m.space_8),
("font-xs", m.font_xs),
("font-sm", m.font_sm),
("font-body", m.font_body),
("font-md", m.font_md),
("font-lg", m.font_lg),
("font-xl", m.font_xl),
("font-2xl", m.font_2xl),
("font-3xl", m.font_3xl),
("row-height", m.row_height),
("control-height", m.control_height),
("control-height-sm", m.control_height_sm),
("icon-sm", m.icon_sm),
("icon-md", m.icon_md),
("icon-lg", m.icon_lg),
("glow-width", m.glow_width),
("rail-width", m.rail_width),
("sidebar-width", m.sidebar_width),
("topbar-height", m.topbar_height),
("right-panel-min", m.right_panel_min),
]
.into_iter()
.map(|(name, value)| (name, f64::from(value)))
.chain([
("weight-regular", f64::from(m.weight_regular)),
("weight-medium", f64::from(m.weight_medium)),
("weight-semibold", f64::from(m.weight_semibold)),
("weight-bold", f64::from(m.weight_bold)),
("fast", f64::from(m.fast_ms)),
("normal", f64::from(m.normal_ms)),
])
.collect()
}
}
impl Default for Metrics {
fn default() -> Self {
Self::new(1.0)
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+154
View File
@@ -0,0 +1,154 @@
//! The binary's failure path, end to end: when the main window cannot be
//! opened (no display server, no Vulkan or GL driver), `voelin-gpui` prints
//! why and exits with status 1 instead of staying alive with no window and no
//! message.
//!
//! It has to start the real binary. GPUI's Linux platform runs the launch
//! callback before it starts its event loop, and the loop forgets a quit asked
//! for before it started, so a failure handled by quitting inside the
//! callback hung the process; the test platform of the unit tests has no such
//! loop and cannot show it.
//!
//! The no-driver test needs a test X server in `VOELIN_X11_TEST_DISPLAY` (an
//! Xvfb, as CI has; never the desktop's display) and is skipped without one.
#![cfg(target_os = "linux")]
use std::fs;
use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Where the drivers are not: the Vulkan loader, EGL's vendor library
/// directory and Mesa's driver directory all point here.
const NOWHERE: &str = "/nonexistent-voelin-gpui-test";
/// Loaded machines are slow, so the wait is generous; a run that works takes a
/// second or two.
const WAIT: Duration = Duration::from_secs(120);
/// The scratch directory of one run, removed at the end.
struct Scratch(PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// How a run of the binary went.
enum Outcome {
/// It ended, with this status and this much of the log.
Ended(ExitStatus, String),
/// It picked a GPU: the window can open, so nothing failed.
Opened,
/// It was still running after [`WAIT`] with no GPU picked.
Hung(String),
}
/// Run the binary with the drivers hidden (`hide_drivers`) on `display`
/// (none: no display server at all) and wait for it to end, to pick a GPU or
/// to run out of time. Nothing of the user's state, display or session bus is
/// in its environment.
fn run_binary(name: &str, display: Option<&str>, hide_drivers: bool) -> Outcome {
let scratch = Scratch(
Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())),
);
let home = scratch.0.join("home");
let runtime = scratch.0.join("runtime");
fs::create_dir_all(&runtime).unwrap();
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap();
let log = scratch.0.join("stderr.log");
let mut command = Command::new(env!("CARGO_BIN_EXE_voelin-gpui"));
command
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
.env_remove("WAYLAND_SOCKET")
.env_remove("XDG_SESSION_TYPE")
.env_remove("DBUS_SESSION_BUS_ADDRESS")
.env_remove("RUST_LOG")
.env("HOME", &home)
.env("XDG_RUNTIME_DIR", &runtime)
.env("XDG_CONFIG_HOME", home.join("config"))
.env("XDG_DATA_HOME", home.join("data"))
.env("XDG_STATE_HOME", home.join("state"))
.env("XDG_CACHE_HOME", home.join("cache"))
.env("VOELIN_DATA_DIR", home.join("voelin"))
// The log line that tells a GPU was picked.
.env("VOELIN_LOG", "warn,voelin_gpui=info,gpui_wgpu=info")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(fs::File::create(&log).unwrap());
if let Some(display) = display {
command.env("DISPLAY", display);
}
if hide_drivers {
command
.env("VK_DRIVER_FILES", format!("{NOWHERE}/vulkan.json"))
.env("VK_ICD_FILENAMES", format!("{NOWHERE}/vulkan.json"))
.env("__EGL_VENDOR_LIBRARY_DIRS", NOWHERE)
.env("__EGL_VENDOR_LIBRARY_FILENAMES", format!("{NOWHERE}/egl.json"))
.env("LIBGL_DRIVERS_PATH", NOWHERE);
}
let mut child = command.spawn().unwrap();
let deadline = Instant::now() + WAIT;
loop {
if let Some(status) = child.try_wait().unwrap() {
return Outcome::Ended(status, fs::read_to_string(&log).unwrap_or_default());
}
let seen = fs::read_to_string(&log).unwrap_or_default();
let outcome = if seen.contains("Selected GPU adapter") {
Outcome::Opened
} else if Instant::now() > deadline {
Outcome::Hung(seen)
} else {
std::thread::sleep(Duration::from_millis(50));
continue;
};
let _ = child.kill();
let _ = child.wait();
return outcome;
}
}
#[test]
fn a_window_that_cannot_open_for_want_of_a_driver_ends_the_binary_with_an_error() {
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
else {
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
return;
};
match run_binary("no-driver", Some(&display), true) {
Outcome::Ended(status, seen) => {
assert_eq!(status.code(), Some(1), "{seen}");
assert!(seen.contains("cannot open the main window"), "{seen}");
}
Outcome::Opened => eprintln!(
"skipped: this machine's driver was found in spite of the environment, \
so the window can open"
),
Outcome::Hung(seen) => panic!(
"still running after {WAIT:?} with no window and no GPU: a quit asked for in the \
launch callback is lost\n{seen}"
),
}
}
#[test]
fn without_a_display_server_the_binary_ends_with_an_error() {
match run_binary("no-display", None, false) {
Outcome::Ended(status, seen) => {
assert_eq!(status.code(), Some(1), "{seen}");
assert!(seen.contains("cannot open the main window"), "{seen}");
assert!(seen.contains("no display"), "{seen}");
}
Outcome::Opened => panic!("a GPU was picked without a display server"),
Outcome::Hung(seen) => panic!(
"still running after {WAIT:?} with no window: GPUI's headless platform keeps \
the app alive\n{seen}"
),
}
}
+7 -1
View File
@@ -69,7 +69,13 @@ tracing = "0.1.44"
yuv = "0.8.19"
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
# `async-io`, not `tokio`: GPUI's Linux backend enables ashpd's `async-io`, ashpd
# refuses both at once, and a front end holds the portals and GPUI in one binary.
# zbus then runs every connection on an I/O thread of its own, whichever thread
# builds it: no crate of the workspace turns zbus's `tokio` feature on (with it
# zbus would pick tokio for a connection made inside a tokio runtime, and ashpd
# shares one connection per process with every later caller).
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "async-io"], optional = true }
memmap2 = { version = "0.9.11", optional = true }
pipewire = { version = "0.10.1", optional = true }
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
+7 -7
View File
@@ -279,14 +279,14 @@ impl FrameSink for QueueSink {
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
loop {
match frames.recv_timeout(Duration::from_millis(100)) {
Some(frame) => {
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
break;
}
let Some(frame) = frames.recv_timeout(Duration::from_millis(100)) else {
if frames.is_closed() {
break;
}
None if frames.is_closed() => break,
None => {}
continue;
};
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
break;
}
}
})?;
+3 -1
View File
@@ -181,7 +181,9 @@ impl ScreenCapture for PortalCapture {
}
/// Asks the user through the portal dialog (unless a restore token
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
/// applies). Any executor will do: ashpd runs on zbus's `async-io` in every
/// binary of the workspace (no crate turns zbus's `tokio` feature on), whose
/// connection has an I/O thread of its own, whichever thread builds it.
fn start(
&mut self,
source: &SourceId,
+2 -2
View File
@@ -446,7 +446,7 @@ fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
found.into_iter().map(|(_, p)| p).collect()
}
@@ -466,7 +466,7 @@ fn ldconfig(base: &str) -> Vec<PathBuf> {
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
found.into_iter().map(|(_, p)| p).collect()
}
+2 -2
View File
@@ -603,8 +603,8 @@ mod v4l2 {
// Seconds per frame; a stepwise range starts with its smallest
// interval, which is the highest rate.
let (num, den) = (entry.interval[0], entry.interval[1]);
if num > 0 {
best = best.max(den / num);
if let Some(rate) = den.checked_div(num) {
best = best.max(rate);
}
if entry.type_ != FRMIVAL_DISCRETE {
break;
+36 -19
View File
@@ -1180,19 +1180,32 @@ mod tests {
scenes
}
/// The first preview frame that `wanted` takes. The preview keeps the latest
/// frame only, so few older ones are waiting or on their way: the number of
/// frames looked at is the bound (the work), and the wait for each, which a
/// busy machine can stretch, only ends a hang.
fn preview_until(
preview: &Handoff<VideoFrame>,
wanted: impl Fn(&VideoFrame) -> bool,
) -> Arc<VideoFrame> {
for _ in 0..20 {
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
if wanted(&frame) {
return frame;
}
}
panic!("the preview never showed what was asked for");
}
#[tokio::test]
async fn it_composes_into_the_preview_and_follows_commands() {
let studio = Studio::start(one_colour_scene()).await.unwrap();
let preview = studio.preview();
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
let started = Instant::now();
let frame = loop {
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
};
assert_eq!((frame.width, frame.height), (32, 24));
// The studio composes from the moment it starts, at the size and rate the
// preview has then (480x270, 15 fps): a frame of that size can be the
// first one there is.
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
@@ -1211,15 +1224,12 @@ mod tests {
.unwrap();
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
assert_eq!(studio.status().active_scene, break_id);
// The new scene's source draws.
let frame = loop {
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
if p.data[..3] == [1, 2, 3] {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
};
// The new scene's source draws, from the first frame composed after the
// command.
let frame = preview_until(
&preview,
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
);
drop(frame);
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
@@ -1402,9 +1412,16 @@ mod tests {
assert_eq!((listed[0].width, listed[0].height), (64, 48));
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
let mut frames = frames;
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
// (The wait only ends a hang.)
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
assert_eq!((frame.width, frame.height), (64, 48));
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
// A frame is counted once it has been handed over, so the count can still be
// behind when the frame is in the hands of the test.
let deadline = Instant::now() + Duration::from_secs(30);
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
assert!(Instant::now() < deadline, "the frame handed over was never counted");
std::thread::sleep(Duration::from_millis(5));
}
capture.stop();
std::fs::remove_dir_all(&dir).ok();
}
@@ -350,7 +350,22 @@ mod tests {
#[test]
fn an_unwritable_path_fails_at_once() {
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
let dir = dir("unwritable");
// A path below a regular file fails for every user, root included
// (ENOTDIR). A directory that is merely missing would be created, and
// a read-only one is written to by root.
let file = dir.join("not-a-directory");
std::fs::write(&file, b"x").unwrap();
assert!(Recorder::start(file.join("x").join("clip.webm"), 0, 2).is_err());
// The directory is there and the file cannot be created because the
// path names a directory (EISDIR, again for every user).
let named_like_a_file = dir.join("clip.webm");
std::fs::create_dir(&named_like_a_file).unwrap();
assert!(Recorder::start(&named_like_a_file, 0, 2).is_err());
// A name that asks for no known container is refused before any file
// is created.
assert!(Recorder::start(dir.join("clip.mp4"), 0, 2).is_err());
assert!(!dir.join("clip.mp4").exists());
std::fs::remove_dir_all(&dir).ok();
}
}
+9 -4
View File
@@ -24,9 +24,11 @@ tokio = { version = "1", features = ["rt", "sync", "time"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
# `async-io`, not `tokio`, as in voelin-media: GPUI enables ashpd's `async-io` and
# ashpd refuses both features at once.
ashpd = { version = "0.13", default-features = false, features = ["async-io", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
notify-rust = { version = "4.18", default-features = false, features = ["z"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
[target.'cfg(windows)'.dependencies]
@@ -46,8 +48,11 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
# A stand-in desktop portal on a private session bus (tests/proxy.rs); the
# zbus ashpd uses.
zbus = { version = "5", default-features = false, features = ["tokio"] }
# zbus ashpd uses, on `async-io` like every other zbus in the workspace: a
# `tokio` here would put the executor choice of ashpd's connection (zbus picks
# tokio when a tokio runtime is current where it builds the connection) into
# the tests alone, and tests/proxy.rs checks that the choice does not matter.
zbus = { version = "5", default-features = false, features = ["async-io"] }
[lints]
workspace = true
+172 -7
View File
@@ -1,8 +1,15 @@
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
//! session bus. Run it on a private bus:
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
//! without a session bus it checks nothing. Its own test binary: answers
//! are kept process-wide.
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
//! own that starts no services: on a desktop's bus the real portal is running
//! or startable, and when the stand-in leaves the bus (as the test has it do)
//! the real one is started and answers instead. Without `dbus-run-session`,
//! or a bus daemon for it, the test says so and checks nothing. Its own test
//! binary: answers are kept process-wide.
//!
//! The second and third tests call ashpd from a thread with no tokio runtime,
//! as GPUI's executor would: ashpd runs on zbus's `async-io`, whichever thread
//! built its connection (the third lets a tokio caller build it first;
//! docs/design/gpui-spikes.md, "Dependencies").
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
@@ -11,6 +18,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
use voelin_platform::proxy::proxy_for;
/// Set for the run on the bus of its own.
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
/// others.
struct Resolver {
@@ -34,10 +44,72 @@ impl Resolver {
}
}
/// The configuration of the bus of its own: a session bus without the service
/// directories, so that nothing on it can be started by name. Its socket is
/// made in `dir`.
fn bus_config(dir: &std::path::Path) -> String {
format!(
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:tmpdir={}</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
"#,
dir.display()
)
}
/// Run the test `name` again under `dbus-run-session` on a bus of its own, and
/// say nothing was checked when that bus cannot be had.
fn on_a_bus_of_its_own(name: &str) {
let dir = std::env::temp_dir();
let config = dir.join(format!("voelin-proxy-test-bus-{}-{name}.conf", std::process::id()));
std::fs::write(&config, bus_config(&dir)).unwrap();
let run = std::process::Command::new("dbus-run-session")
.arg(format!("--config-file={}", config.display()))
.arg("--")
.arg(std::env::current_exe().unwrap())
.args(["--exact", name, "--nocapture", "--test-threads=1"])
.env(ON_ITS_OWN_BUS, "1")
.output();
let _ = std::fs::remove_file(&config);
let run = match run {
Ok(run) => run,
Err(e) => {
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
return;
}
};
let text =
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
if run.status.success() {
// A child that ran no test (its filter matched nothing) exits 0 as well.
assert!(
text.contains("test result: ok. 1 passed;"),
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
);
return;
}
// The test ran and failed, or the bus never came up.
assert!(
!text.contains("running 1 test"),
"the test failed on its own bus ({}):\n{text}",
run.status
);
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
}
#[tokio::test]
async fn the_portal_names_the_proxy() {
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
eprintln!("no session bus: run under dbus-run-session");
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own("the_portal_names_the_proxy");
return;
}
let lookups = Arc::new(AtomicU32::new(0));
@@ -66,3 +138,96 @@ async fn the_portal_names_the_proxy() {
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
}
/// Run `future` on the calling thread, which parks while it waits: an executor
/// of no runtime at all, as a GPUI foreground task is to ashpd.
fn block_on<F: std::future::Future>(future: F) -> F::Output {
struct Unpark(std::thread::Thread);
impl std::task::Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current())));
let mut cx = std::task::Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
return output;
}
std::thread::park();
}
}
/// The stand-in portal on the bus of its own, served from the calling task.
async fn stand_in_portal(lookups: &Arc<AtomicU32>) -> zbus::Connection {
zbus::connection::Builder::session()
.unwrap()
.name("org.freedesktop.portal.Desktop")
.unwrap()
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
.unwrap()
.build()
.await
.unwrap()
}
/// A lookup through ashpd, from the calling task.
async fn lookup() -> Vec<ashpd::Uri> {
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
resolver.lookup(&uri).await.unwrap()
}
/// A lookup through ashpd from a thread of its own with no runtime, blocking
/// the caller's task for it (the pool's threads, `spawn_blocking`, have the
/// runtime in reach). The stand-in portal runs on the test's runtime: keep it
/// free while waiting.
async fn lookup_without_a_runtime() -> Vec<String> {
let caller = std::thread::spawn(|| {
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
block_on(lookup()).iter().map(|uri| uri.as_str().to_owned()).collect::<Vec<_>>()
});
tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap()
}
/// ashpd with `async-io`: a caller outside any tokio runtime gets its answer,
/// the connection's I/O running on zbus's own thread.
#[tokio::test(flavor = "multi_thread")]
async fn the_portal_answers_a_caller_without_a_runtime() {
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime";
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own(TEST);
return;
}
let lookups = Arc::new(AtomicU32::new(0));
let _portal = stand_in_portal(&lookups).await;
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
assert_eq!(lookups.load(Ordering::SeqCst), 1);
}
/// ashpd keeps one session connection for the process, and zbus picks the
/// executor of a connection once, when it builds it: tokio if a tokio runtime
/// is current on that thread and zbus has its `tokio` feature on, its own
/// `async-io` thread otherwise. If the engine's runtime made the connection
/// first, a later caller with no runtime (a GPUI foreground task) would find a
/// tokio connection with no reactor to run on and panic ("there is no reactor
/// running" in zbus's property cache). With zbus on `async-io` alone in every
/// binary (notify-rust without `z-with-tokio`, no zbus `tokio` here either)
/// the order does not matter.
#[tokio::test(flavor = "multi_thread")]
async fn the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller() {
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller";
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own(TEST);
return;
}
let lookups = Arc::new(AtomicU32::new(0));
let _portal = stand_in_portal(&lookups).await;
// The tokio caller first: it builds the process's session connection.
let answer: Vec<_> = lookup().await.iter().map(|uri| uri.as_str().to_owned()).collect();
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
// Then the caller with no runtime, on the same connection.
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
}
+123 -38
View File
@@ -35,44 +35,119 @@
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
//! record and the device key with [`KeyStore::get`]: one damaged row, the
//! record's own included, would otherwise keep a sign-out from ever finishing,
//! and with it the deletion of the key the user asked to forget. Unbound is the
//! reading that never deletes on a guess: a sign-out neither deletes such a row
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
//! four good binding columns. A `data` column that is not text (a BLOB, or text
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
//! that a record that cannot be read is deleted by the sign-out, as the trait
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
//! and with it the deletion of the synced copies and of the record, and the
//! forgetting of the key the user asked to forget. Unbound is the reading that
//! never deletes on a guess: a sign-out neither deletes such a row as a synced
//! copy nor writes it, it stays as it is until a `put` of it writes four good
//! binding columns. A `data` column that is not text (a BLOB, or text of bytes
//! that are no UTF-8) is read as text with the odd bytes replaced, so that a
//! record that cannot be read is deleted by the sign-out, as the trait says,
//! instead of its read failing. A [`KeyStore::put`] of the text that
//! [`KeyStore::get`] returned for such a row is taken for the data that is
//! there: it changes the binding and keeps the stored bytes, where any other
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
//! out with a warning.
//!
//! # Signing out keeps every key
//!
//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since
//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts
//! design, answered by the owner on 2026-10-24) it keeps every key of the
//! device. The device key stays, unbound and byte for byte, whether it was in
//! use before the account existed or the client made it for the account:
//! `AccountRecord::bound_existing_key` only records which, for the client's
//! wording, and no rule reads it. At every host without accounts that the user
//! reached with it, either key is the user's identity, and deleting it would
//! lose their servers, roles and memberships there. The identities that only
//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user
//! kept local) are unbound and kept as well.
//!
//! What a sign-out deletes is not a key of the device: the synced copies of
//! integration secrets, which the account service holds and every device can
//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted
//! like one, see below), and the account record, which holds no secret. A
//! sign-out does not release the device key at the account service either: the
//! key stays registered with the account there. The release is its own
//! operation, see below.
//!
//! # Releasing a device key
//!
//! The release of the device key from its account (part 2 of open question 10)
//! is the account service's operation followed by a local unbind, and the unbind
//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls
//! `POST /v1/devices/<own>/release` after a password check, and then runs
//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key,
//! unbound. So the store needs nothing of its own for it: no call that unbinds
//! one key (a [`KeyStore::put`] of the blob without its binding does that, and
//! keeps the data, as the sign-out does), and no record that the key was
//! released. The accounts design asks the client to remember nothing of the
//! kind: the service holds the registration of the key (after a release it is
//! registered with no account, after a sign-out with the account that was
//! signed out of), and the client learns which at the next sign-in or sign-up,
//! from the service's answer (`CONFLICT`, field `device`), not from a note kept
//! here. The deletion of the account (`AccountClient::delete_account`) is the
//! same: the service writes a DEVICE and a RELEASED entry for every device key
//! of the account, and the local half is this sign-out, which keeps this
//! device's key.
//!
//! # Forgetting the device's identity
//!
//! "Forget this device's identity" is the user's explicit choice and the only
//! deletion of a key of the device; the UI offers to export the key first and
//! asks before it deletes.
//!
//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of
//! the device key. The caller names the key, because the key goes before the
//! record is read: a record that cannot be read does not keep it.
//! - Signed out, or with a key that no account ever bound, it is
//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is
//! [`Store::delete_identity`]. Neither looks at an account record, so a UI
//! that forgets the device key of the account it is signed in to does it
//! through the sign-out, not through `remove`.
//!
//! The store has no call that exports, because it would only wrap what the
//! caller can read before it deletes: a Voelin key is
//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that
//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is
//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by
//! `voelin_core::ts::identity::export` or `write_export`. The same two calls,
//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes
//! the account: it offers an export of the device keys before the service is
//! asked.
//!
//! # Deleted keys leave no trace
//!
//! The rows are private keys, so a removed row is not left behind in the file:
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
//! [`Store::delete_identity`] does, so that the frame of the log that held the
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
//! `remove`, truncates the log once, after its last step, not after each
//! removal. The checkpoint waits for another connection for a moment at most
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
//! and then the removal still succeeds and a warning says that the deleted
//! bytes may stay in the log file, until a later checkpoint truncates the log,
//! later writes overwrite those frames, or the last connection to the database
//! closes and the log is deleted.
//! page with the key is gone too. A forgotten key needs exactly that. So does
//! the one deletion a sign-out still makes of a key: a synced copy of a
//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out
//! deletes with `remove` on a `SignOutPass` and truncates the log once, after
//! its last step, not after each removal; one that deletes nothing (the record
//! was gone, no copies) truncates nothing. The checkpoint waits for another
//! connection for a moment at most (`Store::truncate_wal`): one that keeps
//! reading an old snapshot blocks it, and then the removal still succeeds and a
//! warning says that the deleted bytes may stay in the log file, until a later
//! checkpoint truncates the log, later writes overwrite those frames, or the
//! last connection to the database closes and the log is deleted.
//!
//! The device key is never a synced copy. The account record names the Voelin key
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
//! every identity bound with `synced = true` in its first step, before it reads
//! the record, so a key stored that way would be deleted whatever the record
//! says (a key that predates the account is to be kept). The store therefore
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
//! with `synced = true` while an account record names its uid as the device, or
//! while a record cannot be read, because then it cannot tell; and a put of an
//! # The device key is never a synced copy
//!
//! A sign-out keeps the device key, but its first step deletes every identity
//! bound with `synced = true`, before it reads the account record that names
//! the device key. A device key stored that way would be deleted by that step,
//! whether it predates the account or not, which is what the rule that a
//! sign-out keeps every device key forbids. The store therefore refuses, with an
//! error that says why, a [`KeyStore::put`] of a `voelin` blob with
//! `synced = true` while an account record names its uid as the device, or while
//! a record cannot be read, because then it cannot tell; and a put of an
//! account record that names a key which is stored as a synced copy. A binding
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
//! follows the record. The check and the write are done under the store's lock;
//! a second process writing the same file at the same moment is not covered.
//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps
//! it. The check and the write are done under the store's lock; a second
//! process writing the same file at the same moment is not covered.
//!
//! A TeamSpeak blob that is refused says why in words that carry none of its
//! input: its `data` is the identity's private key, and an error reaches log
@@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities
/// access to the TeamSpeak methods of the same connection.
///
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
/// `voelin-identity` defines them, on top of the five methods here; the
/// sign-out only truncates the write-ahead log once, at its end.
/// `voelin-identity` defines them, on top of the five methods here: a sign-out
/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the
/// device key), and only truncates the write-ahead log once, at its end, when
/// it deleted something.
pub struct SqliteKeyStore {
store: Mutex<Store>,
}
@@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore {
/// The trait's sign-out, with the log truncated once after its last step
/// instead of after each of its removals: it removes up to a handful of
/// rows, and a checkpoint that another connection blocks costs a moment
/// rows (the synced copies, the account record and, with
/// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and
/// a checkpoint that another connection blocks costs a moment
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
/// the checkpoint to this method.
/// the checkpoint to this method. A sign-out that deleted nothing does not
/// checkpoint.
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
let outcome = KeyStore::sign_out(&pass, account, device_key);
@@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
/// rows, but `remove` only notes that it deleted something, so that the sign-out
/// truncates the log once at its end.
/// truncates the log once at its end. What a sign-out removes is the synced
/// copies of integration secrets, the account record and, when the user chose
/// to forget it, the device key; unbinding goes through `put`, which deletes
/// nothing.
struct SignOutPass<'a> {
store: &'a SqliteKeyStore,
/// Whether a row was deleted.
@@ -470,26 +553,28 @@ enum Refused {
/// `uid` is unique across kinds in this table.
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
UidHeld { uid: String, kind: String },
/// The Voelin key is the device key of an account record. A sign-out
/// deletes a synced copy without reading the record, so the key the record
/// says to keep would be deleted.
/// The Voelin key is the device key of an account record. A sign-out keeps
/// the device key, but it deletes a synced copy without reading the record,
/// so a device key stored as one would be deleted all the same.
#[error(
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
reads the record, so it would delete the device key that it keeps"
)]
SyncedDeviceKey { uid: String, record: String },
/// An account record cannot be read, so the store cannot tell whether the
/// Voelin key is its device key.
#[error(
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
record {record:?} cannot be read, so it may name this key as the device key"
record {record:?} cannot be read, so it may name this key as the device key, which a \
sign-out keeps but would delete as a synced copy"
)]
UnreadableRecord { uid: String, record: String },
/// The device key of the record is stored as a synced copy already.
#[error(
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
says"
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
reads the record, so it would delete the device key that it keeps"
)]
RecordNamesSyncedKey { record: String, device: String },
}
+37 -1
View File
@@ -27,18 +27,54 @@ pub use chat::{
pub use contacts::{Contact, ContactSeen, Relation};
pub use keystore::SqliteKeyStore;
#[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets;
pub use secrets::{FallbackSecrets, KeyringSecrets};
pub use secrets::{MemorySecrets, Secrets};
pub use store::{
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
};
/// How the JSON of a stored TeamSpeak identity is wrong: the category of the
/// reader's complaint and nothing of the text, which holds a private key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IdentityDamage {
/// The text is not JSON.
Malformed,
/// The text ends before the JSON does.
CutShort,
/// The JSON is not that of an identity: a field is missing or of another
/// type, or the key does not import.
NotAnIdentity,
/// The text could not be read.
Unreadable,
}
impl std::fmt::Display for IdentityDamage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Malformed => "malformed",
Self::CutShort => "cut short",
Self::NotAnIdentity => "not an identity",
Self::Unreadable => "unreadable",
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("database: {0}")]
Db(#[from] rusqlite::Error),
#[error("serialization: {0}")]
Json(#[from] serde_json::Error),
/// The JSON of a stored TeamSpeak identity cannot be read, which only damage
/// outside the client can cause. It says how the text is wrong and where, and
/// never what it holds: the text is a private key, and the message of the
/// JSON reader quotes the value it refuses (`tsproto` reports a key that does
/// not import as an invalid value, the key string and all), so that message is
/// not kept, not here and not in a log line.
#[error(
"the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}"
)]
Identity { damage: IdentityDamage, line: usize, column: usize },
#[error("{0} {1} not found")]
NotFound(&'static str, i64),
#[error("secret store: {0}")]
+41
View File
@@ -74,6 +74,47 @@ impl Secrets for KeyringSecrets {
}
}
/// The keyring first, memory when the keyring cannot keep a secret (no Secret
/// Service on a headless Linux): what the desktop front ends keep the servers'
/// passwords in. A secret the keyring refused is kept for this run only.
#[cfg(feature = "keyring")]
pub struct FallbackSecrets {
keyring: KeyringSecrets,
memory: MemorySecrets,
}
#[cfg(feature = "keyring")]
impl FallbackSecrets {
/// Secrets in the keyring entries of `service` (the app's name), with
/// memory behind them.
pub fn new(service: impl Into<String>) -> Self {
Self { keyring: KeyringSecrets::new(service), memory: MemorySecrets::default() }
}
}
#[cfg(feature = "keyring")]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> Result<()> {
if let Err(error) = self.keyring.set(key, value) {
tracing::warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
+93 -11
View File
@@ -8,7 +8,7 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tsclientlib::Identity;
use crate::{Error, Result};
use crate::{Error, IdentityDamage, Result};
/// A schema migration: SQL, or code for what SQL alone cannot do.
enum Migration {
@@ -244,6 +244,28 @@ impl Bookmark {
/// waits.
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
/// The TeamSpeak identity in the JSON of a stored row.
///
/// A text that does not read (it could only have been damaged outside the
/// client: [`Store::add_identity`] writes what `serde_json` makes of an
/// identity) is refused with [`Error::Identity`], which says how it is wrong and
/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json`
/// does for the text it is handed. The reader's own message is dropped: it
/// quotes a value it refuses, and `tsproto` reports a key that does not import
/// as an invalid value, the key string and all, which would reach a status line
/// or a log.
fn identity_from_json(json: &str) -> Result<Identity> {
serde_json::from_str(json).map_err(|error| {
let damage = match error.classify() {
serde_json::error::Category::Syntax => IdentityDamage::Malformed,
serde_json::error::Category::Eof => IdentityDamage::CutShort,
serde_json::error::Category::Data => IdentityDamage::NotAnIdentity,
serde_json::error::Category::Io => IdentityDamage::Unreadable,
};
Error::Identity { damage, line: error.line(), column: error.column() }
})
}
pub struct Store {
pub(crate) db: Connection,
}
@@ -348,7 +370,7 @@ impl Store {
})?;
rows.map(|row| {
let (id, name, uid, data, origin, is_default) = row?;
let identity: Identity = serde_json::from_str(&data)?;
let identity = identity_from_json(&data)?;
let origin = IdentityOrigin::parse(&origin);
Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default })
})
@@ -385,6 +407,24 @@ impl Store {
Ok(())
}
/// The identity entry a connection uses: `named` (the identity a
/// bookmark names) if the store still has it, else the default identity's.
/// None when the store has no identity.
pub fn identity_id_for(&self, named: Option<i64>) -> Option<i64> {
let entries = self.identities().unwrap_or_default();
named
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| entries.iter().find(|e| e.is_default).or(entries.first()).map(|e| e.id))
}
/// The identity a connection uses ([`Store::identity_id_for`]); `fallback`
/// when the store has none it can read.
pub fn identity_for(&self, named: Option<i64>, fallback: &Identity) -> Identity {
self.identity_id_for(named)
.and_then(|id| self.identity(id).ok())
.unwrap_or_else(|| fallback.clone())
}
pub fn identity(&self, id: i64) -> Result<Identity> {
let data: Option<String> = self
.db
@@ -395,7 +435,7 @@ impl Store {
)
.optional()?;
let data = data.ok_or(Error::NotFound("identity", id))?;
Ok(serde_json::from_str(&data)?)
identity_from_json(&data)
}
/// Store an identity again, e.g. after its security level was improved.
@@ -630,23 +670,43 @@ mod tests {
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
// A value that is not the default, so that restoring a constant would show.
// A value that is not the default, so that restoring a constant would
// show, and one so long that a checkpoint that waited as long as the
// connection allows would not come back by itself.
const HOUR_MS: i64 = 3_600_000;
let timeout = |store: &Store| -> i64 {
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
};
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
let started = std::time::Instant::now();
store.truncate_wal();
let elapsed = started.elapsed();
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
store.db.busy_timeout(Duration::from_secs(3600)).unwrap();
// "Briefly" is not a time: a checkpoint ends in two fsyncs, which take
// seconds under disk pressure (it took 6 s here beside `dd conv=fsync`
// loops), and only a checkpoint that comes back while the reader still
// holds its snapshot has not waited for it. So the reader lets go from
// another thread after 30 s, which ends a checkpoint that does not give
// up with a failure here and not with an hour's wait.
let (back, hear) = std::sync::mpsc::channel::<()>();
let watchdog = std::thread::spawn(move || {
let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok();
if !in_time {
reader.execute_batch("COMMIT").unwrap();
}
(reader, in_time)
});
// One attempt, which the reader blocks (`1`).
let blocked = store.checkpoint_truncate();
back.send(()).ok();
let (reader, in_time) = watchdog.join().unwrap();
assert!(in_time, "the checkpoint waited for the reader instead of giving up");
assert_eq!(blocked.unwrap(), 1, "the reader should block the reset");
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
assert_eq!(timeout(&store), 2345);
assert_eq!(timeout(&store), HOUR_MS);
// Without the reader the same call resets the log.
reader.execute_batch("COMMIT").unwrap();
store.truncate_wal();
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
assert_eq!(timeout(&store), 2345);
assert_eq!(timeout(&store), HOUR_MS);
drop(reader);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
@@ -676,6 +736,28 @@ mod tests {
assert_eq!(store.default_identity().unwrap().unwrap().id, made);
}
/// A bookmark's own identity if the store has it, else the default one,
/// else the fallback.
#[test]
fn a_connection_uses_the_named_identity_else_the_default_else_the_fallback() {
let store = Store::open_in_memory().unwrap();
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
let fallback = Identity::create();
assert_eq!(store.identity_id_for(Some(1)), None);
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&fallback), "no identity at all");
let (default, alt) = (Identity::create(), Identity::create());
let default_id = store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
let alt_id = store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&default), "the default");
assert_eq!(store.identity_id_for(Some(alt_id)), Some(alt_id));
assert_eq!(uid(&store.identity_for(Some(alt_id), &fallback)), uid(&alt), "the named one");
let gone = alt_id + 100;
assert_eq!(store.identity_id_for(Some(gone)), Some(default_id), "one that is gone");
assert_eq!(uid(&store.identity_for(Some(gone), &fallback)), uid(&default));
store.set_default_identity(alt_id, false).unwrap();
assert_eq!(store.identity_id_for(None), Some(alt_id), "the default moved");
}
/// A database of version 3 learns where its identities came from: the
/// first one, named `Default`, is the one the app made; the others were
/// imported; the first stays the default.
+330
View File
@@ -0,0 +1,330 @@
//! A damaged identity row: what the store returns and logs about it says how
//! the row is wrong and never what it holds.
//!
//! The `data` of a TeamSpeak row is the JSON of a private key. Only something
//! outside the client can damage it, but when that happens the error of the
//! JSON reader quotes the value it refuses (`tsproto` reports a key that does
//! not import as an invalid value, the key string and all), and an error
//! reaches a status line, an event or a log. `Store::identity` and
//! `Store::identities` used to return that error as it was.
//!
//! Every case here damages a row of a database file through a second
//! connection, calls everything of the store that reads or writes the row, and
//! looks through the errors (their text, their `Debug` text and their sources)
//! and the logs at TRACE for any 8 characters in a row of what the row held.
use rusqlite::types::Value;
use rusqlite::{Connection, params};
use tsclientlib::Identity;
use voelin_identity::{
AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK,
KeyStore, Uid, account_uid,
};
use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store};
mod support;
/// A directory of its own that is removed again.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir()
.join(format!("voelin-identity-text-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn db(&self) -> std::path::PathBuf {
self.0.join("client.db")
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Letters and digits that no message of this crate, of `serde_json` or of
/// SQLite is made of in a run of eight.
const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga";
const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za";
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that
/// string: the reader quotes it in its message.
fn json_with_a_counter_of_the_wrong_type() -> String {
let mut json = serde_json::to_value(Identity::create()).unwrap();
json["counter"] = SECRET.into();
json.to_string()
}
/// The JSON of a fresh identity cut in the middle of its key, and the key.
fn json_cut_inside_its_key() -> (String, String) {
let json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let text = json.to_string();
let cut = text.find(&key).unwrap() + key.len() / 2;
(text[..cut].to_owned(), key)
}
/// How a row's `data` is damaged: what is stored, as which storage class, and
/// the text of it that must never be repeated.
struct Damage {
label: &'static str,
value: Value,
/// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB.
as_text: bool,
secret: String,
/// What the store says of it, when it reads it as JSON.
damage: Option<IdentityDamage>,
}
fn damages() -> Vec<Damage> {
let (cut, cut_key) = json_with_a_cut_key();
let (cut_short, whole_key) = json_cut_inside_its_key();
let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes();
not_utf8.push(0xff);
vec![
Damage {
label: "a key that does not import",
value: Value::Text(cut),
as_text: false,
secret: cut_key,
damage: Some(IdentityDamage::NotAnIdentity),
},
Damage {
label: "a field of the wrong type",
value: Value::Text(json_with_a_counter_of_the_wrong_type()),
as_text: false,
secret: SECRET.to_owned(),
damage: Some(IdentityDamage::NotAnIdentity),
},
Damage {
label: "syntax",
value: Value::Text(format!("not json: {SECRET}")),
as_text: false,
secret: SECRET.to_owned(),
damage: Some(IdentityDamage::Malformed),
},
Damage {
label: "cut short",
value: Value::Text(cut_short),
as_text: false,
secret: whole_key,
damage: Some(IdentityDamage::CutShort),
},
Damage {
label: "bytes that are no UTF-8, stored as a BLOB",
value: Value::Blob(not_utf8.clone()),
as_text: false,
secret: SECRET.to_owned(),
damage: None,
},
Damage {
label: "bytes that are no UTF-8, stored as TEXT",
value: Value::Blob(not_utf8),
as_text: true,
secret: SECRET.to_owned(),
damage: None,
},
]
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data");
}
}
/// The texts an error shows to a caller: how it reads, its `Debug` text and
/// those of everything it was caused by.
fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec<String> {
let mut texts = vec![error.to_string(), format!("{error:?}")];
let mut source = error.source();
while let Some(cause) = source {
texts.push(cause.to_string());
texts.push(format!("{cause:?}"));
source = cause.source();
}
texts
}
fn binding() -> AccountBinding {
let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16]));
AccountBinding {
account,
integration: Some(IntegrationId::from_bytes([7; 16])),
rev: 3,
synced: false,
}
}
/// A database file with one TeamSpeak identity, its `data` replaced by `damage`
/// through a second connection. Returns the id and uid of the row.
fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) {
let store = Store::open(&scratch.db()).unwrap();
let identity = Identity::create();
let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap();
let uid = identity.key().to_pub().get_uid();
drop(store);
let db = Connection::open(scratch.db()).unwrap();
let sql = if damage.as_text {
"UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2"
} else {
"UPDATE identities SET data = ?1 WHERE id = ?2"
};
assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1);
(id, uid)
}
#[test]
fn the_json_readers_own_message_quotes_what_it_refuses() {
// Without this the cases below could not fail: serde's message for a key
// that does not import and for a field of the wrong type repeats the value.
let (json, cut_key) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}");
let typed = json_with_a_counter_of_the_wrong_type();
let raw = serde_json::from_str::<Identity>(&typed).unwrap_err().to_string();
assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}");
}
#[test]
fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() {
for damage in damages() {
let scratch = Scratch::new("store");
let (id, _) = damaged_database(&scratch, &damage);
let label = damage.label;
let store = Store::open(&scratch.db()).unwrap();
let ((one, all, default), lines) = support::at_trace(|| {
(
store.identity(id).unwrap_err(),
store.identities().unwrap_err(),
store.default_identity().unwrap_err(),
)
});
for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] {
for text in texts_of(error) {
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}"));
}
if let Some(expected) = damage.damage {
// The kind of damage and where, in the store's own words.
match error {
Error::Identity { damage, line, column } => {
assert_eq!(*damage, expected, "{label}: {call}");
assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}");
let shown = error.to_string();
assert!(
shown.starts_with(&format!(
"the stored TeamSpeak identity cannot be read: {expected} at line 1, column "
)),
"{label}: {call}: {shown}"
);
}
other => panic!("{label}: {call}: {other:?}"),
}
}
}
for line in &lines {
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
}
}
}
#[test]
fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() {
for damage in damages() {
let scratch = Scratch::new("keystore");
let (_id, uid) = damaged_database(&scratch, &damage);
let label = damage.label;
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
// Everything that reads or writes the row, in the order a sign-out would,
// with the errors and the logs of all of it kept.
let (results, lines) = support::at_trace(|| {
let mut errors: Vec<Box<dyn std::error::Error + Send + Sync>> = Vec::new();
let mut note = |result: Result<(), voelin_identity::KeyStoreError>| {
if let Err(error) = result {
errors.push(Box::new(error));
}
};
let listed = store.list().unwrap();
let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed");
assert_eq!(entry.level, 0, "{label}: damage reads as level 0");
// What `get` hands out is the data itself; a `put` of it rebinds the row.
let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read");
note(store.put(&blob.clone().with_binding(binding())));
// Other data over the row is checked and refused, and the refusal does
// not repeat it.
let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#);
note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other)));
note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET)));
// The sign-out that unbinds it, and the delete that removes it.
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
store.remove(KIND_TEAMSPEAK, &uid).unwrap();
errors
});
assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}");
for error in &results {
for text in texts_of(error.as_ref()) {
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal"));
assert_holds_no_piece_of(
&text,
SECRET,
&format!("{label}: a refusal of other data"),
);
assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data"));
}
}
for line in &lines {
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data"));
}
}
}
#[test]
fn the_capture_sees_what_the_store_logs() {
// A control for the cases above: a row whose binding columns are damaged is
// listed with a warning that names it, and the capture takes it in at TRACE.
let scratch = Scratch::new("control");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#));
store.put(&blob).unwrap();
let db = Connection::open(scratch.db()).unwrap();
assert_eq!(
db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(),
1
);
let (listed, lines) = support::at_trace(|| store.list().unwrap());
assert_eq!(listed.len(), 1);
let warning = lines
.iter()
.find(|line| line.contains("the binding columns of an identity cannot be read"))
.unwrap_or_else(|| panic!("no warning in {lines:?}"));
assert!(warning.starts_with("WARN "), "{warning}");
assert!(warning.contains("future:one"), "{warning}");
// And it does not carry the row's data either.
for line in &lines {
assert_holds_no_piece_of(line, SECRET, "a log line");
}
}
+417 -71
View File
@@ -31,6 +31,8 @@ use voelin_identity::{
};
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
mod support;
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
/// identity of tsproto's own `identity_tests`.
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
@@ -789,6 +791,11 @@ fn pair(blob: &IdentityBlob) -> (String, String) {
(blob.kind.clone(), blob.uid.clone())
}
/// How many times a sign-out's list names the identity `key` (by kind and uid).
fn times_listed(infos: &[IdentityInfo], key: &IdentityInfo) -> usize {
infos.iter().filter(|info| info.kind == key.kind && info.uid == key.uid).count()
}
/// The record of the install replaced by damaged JSON.
fn damage_the_record(store: &SqliteKeyStore, json: &str) {
let mut damaged = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap();
@@ -803,8 +810,9 @@ fn the_record_fixture_is_what_the_protocol_writes() {
}
#[test]
fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
// The device key was made for the account: signing out deletes it.
fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() {
// The device key was made for the account: signing out keeps it all the
// same, unbound (open question 10 of the accounts design).
let Install { store, synced, device_only, local } = signed_in_install(false);
let mine = binding().account;
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
@@ -815,19 +823,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
store.put_voelin_key(&other_key).unwrap();
let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap();
let mut expected_removed = vec![
(KIND_ACCOUNT.to_owned(), record().blob_uid()),
pair(&synced),
(KIND_VOELIN.to_owned(), key().uid().to_base32()),
];
let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
expected_removed.sort();
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
assert_eq!(
sorted(done.unbound.clone()),
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
"{done:?}"
);
// What is left: the device secret unbound and byte for byte as it was, the
// local and the other account's identities as they were, the other key.
// What is left: the device key, the device secret unbound and byte for
// byte as it was, the local and the other account's identities as they
// were, the other key.
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid());
assert_eq!(store.account_record().unwrap(), None);
let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
assert_eq!(kept, device_only.clone().with_binding(None));
@@ -835,11 +844,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local);
assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob);
assert!(store.voelin_key(&other_key.uid()).unwrap().is_some());
assert_eq!(store.list().unwrap().len(), 4);
assert_eq!(store.list().unwrap().len(), 5);
// Signing out again finds nothing to do.
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
assert_eq!(store.list().unwrap().len(), 4);
assert_eq!(store.list().unwrap().len(), 5);
// Another account's sign-out acts on that account's identities only.
assert_eq!(
store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed,
@@ -892,17 +901,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() {
}
#[test]
fn signing_out_deletes_a_device_key_the_client_made_for_the_account() {
fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() {
// Open question 10 of the accounts design (answered 2026-10-24): a key that
// the client made for the account is the user's identity at every host
// without accounts that the user reached with it as well, so `Auto` keeps
// it like a key that predates the account. Only `Forget` deletes it.
let Install { store, device_only, local, .. } = signed_in_install(false);
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
let signature = key().sign(b"the same key, signed before and after");
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.contains(&device_key_info()), "{done:?}");
assert!(!done.unbound.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
assert_eq!(key_after, key_before, "the stored blob is untouched");
assert_eq!(key_after.binding, None);
let mut left = sorted(store.list().unwrap());
left.sort();
let mut expected = vec![pair(&device_only), pair(&local)];
let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)];
expected.sort();
assert_eq!(left, expected, "the device secret and the local one");
assert_eq!(left, expected, "the key, the device secret and the local one");
// The flag changes nothing: a key that predates the account gets the same
// treatment. (The other identities of the two installs are fresh ones, so
// the reports differ in them.)
let existing = signed_in_install(true);
let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(again.unbound.contains(&device_key_info()), "{again:?}");
assert!(!again.removed.contains(&device_key_info()), "{again:?}");
assert_eq!(again.removed.len(), done.removed.len());
assert_eq!(again.unbound.len(), done.unbound.len());
}
#[test]
@@ -1282,16 +1312,10 @@ impl OnFile {
/// What a sign-out of `choice` must have done, whatever else was damaged:
/// the record and the synced copy are gone, the device-only secret is
/// unbound and the local identity is as it was; the device key is deleted
/// when the user forgot it or the client made it for the account, and
/// reported as kept and unbound otherwise.
fn assert_signed_out(
&self,
done: &SignOut,
bound_existing_key: bool,
choice: DeviceKeyChoice,
label: &str,
) {
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key;
/// when the user forgot it, and reported as kept and unbound otherwise,
/// whether it predates the account or not.
fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) {
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_));
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)];
let mut unbound = vec![pair(&self.device_only)];
let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32());
@@ -1335,7 +1359,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [
fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
// The record carries no binding, so damage in those columns says nothing
// about the record: it is read, and the sign-out does what it always does.
// `Forget` deletes the key it names; `Auto` follows the record.
// `Forget` deletes the key it names; `Auto` keeps it.
for bound_existing_key in [true, false] {
for damage in RECORD_ROW_DAMAGE {
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
@@ -1346,7 +1370,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
.store
.sign_out(&binding().account, choice)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, bound_existing_key, choice, &label);
install.assert_signed_out(&done, choice, &label);
}
}
}
@@ -1354,8 +1378,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
#[test]
fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
// With `Auto` and a key that predates the account, the trait reads the key
// to report it as kept. Damage in its binding columns must not fail that.
// With `Auto` the trait reads the key to report it as kept, whether it
// predates the account or not. Damage in its binding columns must not fail
// that.
for bound_existing_key in [true, false] {
for damage in [
"UPDATE identities SET synced = 2 WHERE kind = 'voelin'",
@@ -1369,12 +1394,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
.store
.sign_out(&binding().account, DeviceKeyChoice::Auto)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label);
if bound_existing_key {
// The key was kept, as it was stored.
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label);
// The key was kept, as it was stored.
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
}
@@ -1423,7 +1446,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record()
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}");
let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap();
assert_eq!(secret.binding, None, "{label}");
// `Auto` cannot find the key the record named, and keeps it.
// `Auto` keeps the key, as it always does; `Forget` deleted it first.
let forgot = matches!(choice, DeviceKeyChoice::Forget(_));
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}");
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
@@ -1623,14 +1646,13 @@ fn key_text(json: &str, field: &str) -> String {
}
#[test]
fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
// The device key the client made for the account goes with `Auto`, and a
// key that predates the account goes when the user forgets it. Either way
// its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the
// free pages of `client.db` or in a frame of `client.db-wal`.
for (bound_existing_key, choice) in
[(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))]
{
fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
// The device key goes when the user forgets it, whether it predates the
// account or the client made it for the account. Its PKCS#8 text, and a
// synced TeamSpeak copy's key, must not stay in the free pages of
// `client.db` or in a frame of `client.db-wal`.
for bound_existing_key in [true, false] {
let choice = DeviceKeyChoice::Forget(key().uid());
let scratch = Scratch::new("scrub-signout");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
@@ -1697,13 +1719,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
}
#[test]
fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() {
fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() {
// A connection that keeps a read snapshot (a long query of the UI, a backup)
// keeps the checkpoint that truncates the log from finishing. The sign-out
// still deletes and warns that the bytes may stay in the log, and it waits
// for the checkpoint a moment, not for the busy timeout of five seconds once
// per removed row. While the checkpoint waits it holds the writer lock of the
// log, so a second connection that writes meanwhile must get through.
// still deletes and warns that the bytes may stay in the log, and it makes
// one checkpoint for all its removals, not one per removed row. While the
// checkpoint waits it holds the writer lock of the log, so a second
// connection that writes meanwhile must get through.
//
// No clock decides anything here. A checkpoint ends in two fsyncs, and under
// disk pressure (a build or a copy writing beside the tests) they take
// seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O
// pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A
// bound on the sign-out or a short busy timeout on the writer failed this
// test with "database is locked" for a checkpoint that was only slow. That a
// checkpoint gives up on a reader after a moment and does not wait out the
// connection's busy timeout is pinned where that timeout can be set to an
// hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`.
let scratch = Scratch::new("blocked-checkpoint");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
@@ -1718,37 +1750,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 4);
/// Stops the writer when dropped, so that a failed assertion of the test does
/// not leave the scope waiting for it.
struct StopsTheWriter<'a>(&'a AtomicBool);
impl Drop for StopsTheWriter<'_> {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
let stop = AtomicBool::new(false);
let (done, elapsed, writes, errors) = std::thread::scope(|scope| {
let written = AtomicUsize::new(0);
let (done, elapsed, errors, lines) = std::thread::scope(|scope| {
let _stops = StopsTheWriter(&stop);
let writer = scope.spawn(|| {
// Its own connection, which gives up on a lock after one second.
// Its own connection, set up as the app's are (`Store::open`: the log
// and `synchronous = NORMAL`, so that a commit does not wait for the
// disk), with a busy timeout that a slow checkpoint does not reach.
let db = Connection::open(scratch.db()).unwrap();
db.busy_timeout(Duration::from_secs(1)).unwrap();
db.pragma_update(None, "synchronous", "NORMAL").unwrap();
db.busy_timeout(Duration::from_secs(60)).unwrap();
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
let (mut writes, mut errors) = (0, Vec::new());
let mut errors = Vec::new();
while !stop.load(Ordering::Relaxed) {
match db.execute(sql, [writes.to_string()]) {
Ok(_) => writes += 1,
let began = Instant::now();
match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) {
Ok(_) => {
written.fetch_add(1, Ordering::Relaxed);
}
Err(error) => errors.push(error.to_string()),
}
std::thread::sleep(Duration::from_millis(5));
// It pauses ten times as long as the write took, and 5 ms at least.
// Under disk pressure a commit takes 100 ms and more, and a writer
// that paused 5 ms after each would hold the writer lock nearly all
// the time and keep the sign-out, whose busy timeout is the default
// five seconds, from getting it (`DatabaseBusy`).
let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5));
while Instant::now() < wake && !stop.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(1));
}
}
(writes, errors)
errors
});
// The sign-out starts when the writer is up and has written, not when
// the thread was spawned: a thread of a busy machine can start late.
let deadline = Instant::now() + Duration::from_secs(60);
while written.load(Ordering::Relaxed) == 0 {
assert!(Instant::now() < deadline, "the writer never ran");
std::thread::sleep(Duration::from_millis(1));
}
let started = Instant::now();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
let (done, lines) = support::at_trace(|| {
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid()))
});
let elapsed = started.elapsed();
stop.store(true, Ordering::Relaxed);
let (writes, errors) = writer.join().unwrap();
(done.unwrap(), elapsed, writes, errors)
let errors = writer.join().unwrap();
(done.unwrap(), elapsed, errors, lines)
});
// Four removals: the two copies, the device key the client made, the record.
// Four removals: the two copies, the device key the user forgot, the record.
assert_eq!(done.removed.len(), 4, "{done:?}");
assert!(store.list().unwrap().is_empty());
assert!(writes > 0, "the writer never ran");
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}");
// One checkpoint for the four removals: each one that is blocked says so.
let blocked = support::blocked_checkpoints(&lines);
assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})");
// Nothing is lost by the wait: once the reader is gone, the next removal
// truncates the log.
@@ -1758,6 +1824,286 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
}
// ------------------------- the keys a sign-out keeps, and the one the user forgets
//
// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps
// every device key, and "Forget this device's identity" is the only deletion.
/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name.
fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> {
db.query_row(
"SELECT * FROM identities WHERE kind = ?1 AND uid = ?2",
params![kind, uid],
|row| {
let names: Vec<String> =
row.as_ref().column_names().iter().map(|n| n.to_string()).collect();
names
.into_iter()
.enumerate()
.map(|(index, name)| Ok((name, row.get(index)?)))
.collect::<rusqlite::Result<Vec<_>>>()
},
)
.unwrap()
}
#[test]
fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() {
// Whether it predates the account or the client made it for the account, no
// column of its row changes: the key never carried a binding, and a sign-out
// writes nothing to it.
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
assert!(before.len() >= 8, "{before:?}");
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}");
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
#[test]
fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() {
// The store accepts a binding with `synced = false` on the device key (a
// binding with `synced = true` is refused, see the last section). A sign-out
// unbinds it and keeps it: the four binding columns are the only ones that
// change.
const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"];
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let device_only = AccountBinding { synced: false, ..binding() };
install
.store
.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only))
.unwrap();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
let bound = |row: &[(String, rusqlite::types::Value)]| {
row.iter().any(|(name, value)| {
name == "account" && !matches!(value, rusqlite::types::Value::Null)
})
};
assert!(bound(&before), "the setup binds the key");
// It is listed once, as kept: VoelinProtocol before v0.2.0 listed a key whose
// row carried the binding twice in `unbound`.
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(
times_listed(&done.unbound, &device_key_info()),
1,
"{bound_existing_key}: {done:?}"
);
assert_eq!(
times_listed(&done.removed, &device_key_info()),
0,
"{bound_existing_key}: {done:?}"
);
let after = named_row(&db, KIND_VOELIN, &uid);
assert!(!bound(&after), "{bound_existing_key}: unbound");
assert_eq!(before.len(), after.len());
for ((name, was), (_, is)) in before.iter().zip(&after) {
if !BINDING_COLUMNS.contains(&name.as_str()) {
assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column");
}
}
let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap();
assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap());
assert!(install.store.bound_to(&binding().account).unwrap().is_empty());
}
}
#[test]
fn a_device_key_that_carries_a_binding_is_listed_once_as_deleted_when_it_is_forgotten() {
// The same row, named by `Forget`: the sign-out unbinds it in its loop over
// the account's identities and deletes it after. It is listed once, as
// deleted; VoelinProtocol before v0.2.0 also left it in `unbound`.
for bound_existing_key in [true, false] {
let Install { store, .. } = signed_in_install(bound_existing_key);
let device_only = AccountBinding { synced: false, ..binding() };
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
let done =
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())).unwrap();
assert_eq!(
times_listed(&done.removed, &device_key_info()),
1,
"{bound_existing_key}: {done:?}"
);
assert_eq!(
times_listed(&done.unbound, &device_key_info()),
0,
"{bound_existing_key}: {done:?}"
);
assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "the key is deleted");
assert_eq!(store.account_record().unwrap(), None);
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
}
}
#[test]
fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() {
// What a sign-out still deletes is a synced copy (a private key, which
// the service holds again) and the record: those are gone from the file and
// its log. The device key and the device-only secret are kept, so their text
// is still there.
let scratch = Scratch::new("scrub-keeps");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
let device_text = key_text(&device.json, "pkcs8");
let (synced_text, device_only_text) =
(key_text(&synced.json, "key"), key_text(&device_only.json, "key"));
for blob in [&device, &synced, &device_only] {
store.put(blob).unwrap();
}
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
let neighbour = Store::open(&scratch.db()).unwrap();
let before = RawFiles::read(&scratch);
assert!(before.holds(&device_text) && before.holds(&synced_text));
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy");
assert!(after.holds(&device_text), "the device key is kept");
assert!(after.holds(&device_only_text), "the device-only secret is kept");
assert!(after.wal.is_empty(), "the log is truncated");
drop(neighbour);
}
#[test]
fn a_sign_out_that_deletes_nothing_does_not_checkpoint() {
// With no record and no synced copy a sign-out only unbinds. The checkpoint
// belongs to deletions: with a reader that blocks it, a deletion says so, and
// the sign-out does not.
let scratch = Scratch::new("no-deletion");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
store.put(&device_only).unwrap();
let reader = Connection::open(scratch.db()).unwrap();
reader.execute_batch("BEGIN").unwrap();
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 1);
let (done, lines) =
support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap());
assert!(done.removed.is_empty(), "{done:?}");
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}");
// The same reader does block the checkpoint of a deletion, so the count above
// would have shown one.
store.put_voelin_key(&key()).unwrap();
let (removed, lines) =
support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
assert!(removed);
assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}");
reader.execute_batch("COMMIT").unwrap();
}
#[test]
fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() {
// The flow of "Forget this device's identity" after a sign-out: the key is
// still there, unbound; the UI exports it, then deletes it. The export is
// what `voelin_key` and `to_pkcs8` give, and it restores the key.
let scratch = Scratch::new("export-forget");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let uid = key().uid();
let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap();
let text = key_text(&stored.json, "pkcs8");
let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap();
assert!(RawFiles::read(&scratch).holds(&text));
assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap());
assert!(store.voelin_key(&uid).unwrap().is_none());
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left");
assert!(after.wal.is_empty(), "the log is truncated");
// The export brings the same key back.
let restored = IdentityKey::from_pkcs8(&exported).unwrap();
assert_eq!(restored.uid(), uid);
assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key"));
store.put_voelin_key(&restored).unwrap();
assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored);
}
// ------------------------------------------ releasing the device key from its account
//
// `AccountClient::release` asks the service to release the key and then runs the
// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so
// the store's part is the sign-out of the tests above, and the key has to be
// usable for another account afterwards.
#[test]
fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() {
let Install { store, .. } = signed_in_install(false);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let signature = key().sign(b"the same key, before and after the release");
// The service released the key; the device finishes with a local sign-out.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
assert_eq!(store.account_record().unwrap(), None);
// The key is registered with no account and signs up for another one: its
// record names the same key, and a copy of the new account's material is
// bound to it.
let other_id = AccountId::from_bytes([42; 16]);
let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() };
store.put_account_record(&other).unwrap();
assert_eq!(store.account_record().unwrap(), Some(other.clone()));
let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() };
let other_copy = fresh_teamspeak(other_binding);
store.put(&other_copy).unwrap();
// Signing out of the new account keeps the key again, and the copy goes.
let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, before and after the release"), signature);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
}
#[test]
fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() {
// The service released the device and the call was dropped before the local
// sign-out took the slot: the record and the copies are still here, and the
// key is still the record's device key. A sign-out with `Auto` finishes it
// and keeps the key; running it again finds nothing to do.
let Install { store, synced, device_only, .. } = signed_in_install(true);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.contains(&info_of(&synced)), "{done:?}");
assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}");
assert_eq!(store.account_record().unwrap(), None);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before);
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
}
// -------------------------------------- the device key is never a synced copy
//
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its
@@ -1798,15 +2144,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() {
assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0);
// A binding that is not synced is a device-only secret: accepted, and a
// sign-out unbinds it and keeps it (or deletes it, as the record says).
// sign-out unbinds it and keeps it.
let device_only = AccountBinding { synced: false, ..binding() };
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
store.put(&before).unwrap();
// So the sign-out still does what the record says with the key.
// So the sign-out keeps the key, whether it predates the account or not.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}");
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key);
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
}
}
+87
View File
@@ -0,0 +1,87 @@
//! Helpers the integration tests of this crate share.
// Each integration test crate of this directory uses some of these helpers.
#![allow(dead_code)]
use std::fmt::{self, Write as _};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use tracing::field::{Field, Visit};
use tracing::level_filters::LevelFilter;
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};
/// A subscriber that keeps every event and span it sees as one line of text
/// each: level, target and every field with its `Debug` text, as a log line
/// would show them.
struct Capture {
lines: Arc<Mutex<Vec<String>>>,
spans: AtomicU64,
}
impl Capture {
fn push(&self, line: String) {
self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line);
}
}
/// The fields of an event or a span as ` name=value` text.
struct Fields<'a>(&'a mut String);
impl Visit for Fields<'_> {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
let _ = write!(self.0, " {}={value:?}", field.name());
}
}
impl Subscriber for Capture {
fn enabled(&self, _: &Metadata<'_>) -> bool {
true
}
fn max_level_hint(&self) -> Option<LevelFilter> {
Some(LevelFilter::TRACE)
}
fn new_span(&self, attributes: &Attributes<'_>) -> Id {
let mut line = format!("span {}", attributes.metadata().name());
attributes.record(&mut Fields(&mut line));
self.push(line);
Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1)
}
fn record(&self, _: &Id, values: &Record<'_>) {
let mut line = String::from("span record");
values.record(&mut Fields(&mut line));
self.push(line);
}
fn record_follows_from(&self, _: &Id, _: &Id) {}
fn event(&self, event: &Event<'_>) {
let metadata = event.metadata();
let mut line = format!("{} {}:", metadata.level(), metadata.target());
event.record(&mut Fields(&mut line));
self.push(line);
}
fn enter(&self, _: &Id) {}
fn exit(&self, _: &Id) {}
}
/// Run `f` on this thread with a subscriber that takes in everything logged at
/// TRACE and above, and return what `f` returned with the lines logged.
pub fn at_trace<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
let lines = Arc::new(Mutex::new(Vec::new()));
let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) };
let out = tracing::subscriber::with_default(subscriber, f);
let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner));
(out, lines)
}
/// How many of the lines say that a checkpoint was blocked.
pub fn blocked_checkpoints(lines: &[String]) -> usize {
lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count()
}
+2 -1
View File
@@ -1075,7 +1075,8 @@ impl Task {
}
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
Event::MediaAdded(m) => {
if !self.mids.iter().any(|(mid, _)| *mid == m.mid) {
let known = self.mids.iter().any(|(mid, _)| *mid == m.mid);
if !known {
self.mids.push((m.mid, m.kind));
}
}
+2 -1
View File
@@ -801,7 +801,8 @@ impl StreamerSession {
}
StreamNotification::JoinRequest { viewer, remove: true, .. }
| StreamNotification::ViewerLeft { viewer, .. } => {
if self.viewers.remove(&viewer.0).is_some() {
let was_viewer = self.viewers.remove(&viewer.0).is_some();
if was_viewer {
self.emit_viewers(out);
self.update_targets(out);
}
+10 -5
View File
@@ -16,24 +16,29 @@ path = "src/lib.rs"
# must show neither. The front ends convert these types (docs/ui.md).
[dependencies]
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
# Picture sizes (the header of a file); PNG and JPEG are listed as the
# front end's toolkit used to bring them.
# Whether a picture file decodes, and its size; PNG and JPEG are listed as
# the front end's toolkit used to bring them.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
serde = { version = "1", features = ["derive"] }
# JSON values of the settings and the gateway's configuration keys.
serde_json = "1"
# Whether an SVG document is XML with an svg root (the vector renderers read
# it with this parser too).
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
# The Twemoji archive's blocks (raw deflate).
miniz_oxide = "0.8"
# Grapheme clusters for emoji in chat text.
unicode-segmentation = "1.13"
# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests.
png = "0.18"
# What the shared server sequences (`servers::sequence`) log, as both front
# ends log it.
tracing = "0.1.44"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { workspace = true }
voelin-store = { path = "../voelin-store" }
[dev-dependencies]
png = "0.18"
[lints]
workspace = true
+15 -1
View File
@@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500;
/// How a span of text looks.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Style {
/// Bold (`[b]`).
pub bold: bool,
/// Italic (`[i]`).
pub italic: bool,
/// Underlined (`[u]`).
pub underline: bool,
/// Struck through (`[s]`).
pub strike: bool,
/// Code: on a background.
pub code: bool,
@@ -51,12 +55,16 @@ pub struct Style {
/// A piece of a block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Span {
/// Text with one style.
Text {
/// The characters.
text: String,
/// How they look.
style: Style,
},
/// A picture at an address (`[img]…[/img]`).
Image {
/// Where the picture is.
url: String,
},
}
@@ -68,7 +76,10 @@ pub enum BlockKind {
Text,
/// A line of a quote; the first names who said it (`[quote=Name]`), when
/// the quote does.
Quote { author: String },
Quote {
/// Who said it, empty when the quote does not say.
author: String,
},
/// Code: all its lines in one span.
Code,
/// An item of a list.
@@ -80,13 +91,16 @@ pub enum BlockKind {
/// A line, a quote's line, code, a list item or a rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
/// What the block is.
pub kind: BlockKind,
/// Its pieces, left to right.
pub spans: Vec<Span>,
}
/// A message's text: its blocks, top to bottom.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Doc {
/// The lines, quotes, code and rules in order.
pub blocks: Vec<Block>,
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,9 @@
//! Chat lines: one [`ChatLine`] per message, with its text in blocks of
//! styled runs (`vm::bbcode`), its reactions and the files and pictures it
//! links.
//! links; [`logic`] has what happens to a session's chats when the engine
//! tells something.
pub mod logic;
use std::borrow::Cow;
use std::cell::RefCell;
@@ -9,7 +12,7 @@ use std::path::PathBuf;
use unicode_segmentation::UnicodeSegmentation;
use voelin_core::HistoryMessage;
use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence};
use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails};
use crate::avatar;
use crate::bbcode::{self, BlockKind, Doc, Span, Style};
@@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
use crate::color::Rgb;
use crate::emoji;
use crate::image::ImageRef;
use crate::state::{SessionView, Tab};
/// Where the server's welcome and host message keep what their lines were
/// built from (`LineCache`), apart from the messages' ids.
pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1];
/// What the server says to everyone who connects, with where its line keeps
/// its parts: its welcome message, and its host message when that goes to
/// the chat log.
pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> {
let host = details.host_message_mode == HostMessageMode::Log;
[Some(&details.welcome_message), host.then_some(&details.host_message)]
.into_iter()
.zip(SERVER_LINES)
.filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id)))
.collect()
}
/// The text of the server's line `key` (-1, -2, ...) of a server chat, if
/// `tab` is one.
pub fn server_text<'a, L>(view: &'a SessionView<L>, tab: &Tab<L>, key: i32) -> Option<&'a str> {
if tab.target != ChatTarget::Server || key >= 0 {
return None;
}
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
}
/// Lines of the same author within this time are grouped (no header).
const GROUP_MS: i64 = 5 * 60 * 1000;
@@ -24,7 +53,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000;
/// The author and time of the line before, for grouping.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Previous {
/// Who wrote it.
pub author: String,
/// When, in milliseconds since the epoch.
pub ts_ms: i64,
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
//! The sample data of `VOELIN_DEMO_UI` and the helpers of the development
//! switches that only look at the state. [`logic`] has the sample servers,
//! people, chats, contacts, notices and pictures as plain values and as the
//! events a server would send.
pub mod logic;
+2
View File
@@ -298,7 +298,9 @@ pub fn first_key(text: &str) -> Option<String> {
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
/// The text: the word with its space, or the emoji's own characters.
pub text: String,
/// The key of the Twemoji picture, none for plain text.
pub emoji: Option<String>,
}
+103
View File
@@ -0,0 +1,103 @@
//! What a server's gateway tells besides chat: its events (the events page,
//! RSVP, reminders), the stream directory and the activity feed (the home
//! page), our permissions there, its configuration (gateway administration).
//! The pins, reactions and topics are in `chat::logic`.
use voelin_core::{GatewayRequest, GatewayUpdate};
use voelin_gateway_proto::{EventQuery, feature};
use crate::host::Cx;
use crate::social::{NoticeKind, NoticeRequest, NoticeTarget, server_name};
use crate::state::{AppState, Lines};
/// Keep what a gateway update tells the home, events and administration
/// screens (before the chat handles its part), and ask for what a new
/// connection needs.
pub fn extra<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, update: &GatewayUpdate) {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
let has = |f: &str| capabilities.iter().any(|c| c == f);
ask.push(GatewayRequest::Permissions { channel: None });
if has(feature::EVENTS) {
ask.push(GatewayRequest::Events { query: EventQuery::default() });
}
if has(feature::STREAMS) {
ask.push(GatewayRequest::Streams);
}
if has(feature::ACTIVITY) {
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
}
}
U::Disconnected { .. } => {
extra.directory.clear();
extra.events.clear();
extra.events_loaded = false;
extra.activity.clear();
extra.actions.clear();
extra.config.clear();
extra.perms.clear();
}
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
U::Events { events } => {
extra.events = events.clone();
extra.events.sort_by_key(|e| e.spec.start_ms);
extra.events_loaded = true;
}
U::Event { event } => {
match extra.events.iter().position(|e| e.id == event.id) {
Some(i) => extra.events[i] = event.clone(),
None => extra.events.push(event.clone()),
}
extra.events.sort_by_key(|e| e.spec.start_ms);
}
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
U::EventReminder { event, starts_in_ms } => remind = Some((event.clone(), *starts_in_ms)),
U::Streams { streams } => extra.directory = streams.clone(),
U::StreamStarted { stream }
| U::StreamUpdated { stream }
| U::StreamRegistered { stream } => {
extra.directory.retain(|e| e.id != stream.id);
extra.directory.push(stream.clone());
}
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
U::Activity { entries, .. } => extra.activity = entries.clone(),
U::ActivityAdded { entry } => {
extra.activity.insert(0, entry.clone());
extra.activity.truncate(100);
}
U::Config { entries } => extra.config = entries.clone(),
U::ConfigValue { entry } => match extra.config.iter().position(|e| e.key == entry.key) {
Some(i) => extra.config[i] = entry.clone(),
None => extra.config.push(entry.clone()),
},
U::PermRules { rules } => extra.perms = rules.clone(),
_ => return,
}
for request in ask {
cx.gateway_to(id, request);
}
if let Some((event, starts_in_ms)) = remind {
let minutes = starts_in_ms / 60_000;
let title = if minutes <= 0 {
format!("{} starts now", event.spec.title)
} else {
format!("{} starts in {minutes} min", event.spec.title)
};
cx.update.notices.push(NoticeRequest {
kind: NoticeKind::Event,
title,
body: format!("on {}", server_name(state, id)),
target: NoticeTarget::Event(id, event.id),
name: event.creator.name.clone(),
uid: Some(event.creator.uid.clone()),
});
}
cx.update.refresh.home = true;
cx.update.refresh.events = true;
cx.update.refresh.gateways = true;
}
+531
View File
@@ -0,0 +1,531 @@
//! What the engine's events do to the client's state. [`handle`] takes an
//! [`Event`], changes the [`AppState`] and the [`Social`] state and returns
//! an [`Update`]: what to draw again, the status line, the commands for the
//! engine, what to keep. A front end calls it for every event and then does
//! what the update says; it has no dispatch of its own, so the Slint client
//! and a GPUI one change the state the same way. [`apply`] is the part that
//! changes the [`AppState`] alone; [`handle`] first lets
//! [`crate::social::logic::event`] look at the event (the friends, the
//! pokes, the notices and the offline messages), which has to see the state
//! as it was before the event.
//!
//! In [`Update::rest`] come back the events whose state is not in the
//! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a
//! setting that changed (the settings service), and the answers to the
//! offline message requests (the list that failed, a request that is done),
//! which the messages page keeps (docs/ui.md, "Controllers still to split").
//! A front end handles them before it draws what the update says is to be
//! drawn again. The text of an offline message is not among them: it is
//! state of the [`Social`], changed by [`handle`].
mod gateway;
use voelin_core::{BackendInfo, Command, Event, GatewayUpdate, JoinFailure, Source, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::Bookmark;
use crate::chat::logic::{
add_message, gateway_update, history_batch, load_reads, open_chat, save_reads, track_reading,
transfer_progress,
};
use crate::host::{Cx, Host, Persist, Update};
use crate::previews::fetch_previews;
use crate::servers::{AfterConnect, JoinStep, after_connect, join_password};
use crate::settings::LastVoice;
use crate::social::logic::Social;
use crate::state::{AppState, Lines, SessionView};
use crate::streams::logic as streams;
/// Apply an event to the [`AppState`]; see the [module](self).
pub fn apply<L: Lines>(state: &mut AppState<L>, host: &dyn Host, event: Event) -> Update {
let mut cx = Cx::new(host);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// Take an event in: what the social screens make of it first
/// ([`crate::social::logic::event`]), then [`apply`]. The one entry point
/// of a front end.
pub fn handle<L: Lines, D>(
state: &mut AppState<L>,
social: &mut Social<D>,
host: &dyn Host,
event: Event,
) -> Update {
let mut cx = Cx::new(host);
crate::social::logic::event(state, social, &mut cx, &event);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// The status line shows what the update says.
fn finish<L>(state: &mut AppState<L>, cx: Cx<'_>) -> Update {
if let Some(text) = &cx.update.status {
state.status.clone_from(text);
}
cx.update
}
fn dispatch<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, event: Event) {
// The Stream Studio's stream is the studio's.
if let Event::StreamState { session, .. } | Event::StreamViewers { session, .. } = &event
&& cx.host.studio_streams_to(*session as i64)
{
cx.update.rest = Some(event);
return;
}
match event {
Event::State { session, state: now } => session_state(state, cx, session as i64, now),
Event::ServerInfo { session, name, backend, capabilities } => {
let id = session as i64;
state.sessions.entry(id).or_default().capabilities = capabilities;
adopt_server_name(state, cx, id, &name);
if state.current == Some(id) {
cx.status(connected_status(&name, &backend));
}
cx.update.refresh.streams = true;
cx.update.autoshare = true;
}
Event::Presence { session, presence } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
// The server chat shows its welcome and host message, with their
// pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection), or
// renamed.
let path = |v: &SessionView<L>| {
v.state.own_channel.map(|c| crate::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
apply_client_playback(state, cx, id);
join_after_connect(state, cx, id);
if renamed && remember_voice(state, cx, id) {
cx.update.refresh.servers = true;
}
if state.current == Some(id) {
if said {
fetch_previews(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true);
cx.update.first_client = true;
}
}
Event::Talking { session, client, talking } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => state.current == Some(s as i64),
None => state.mic_test,
};
if shown {
cx.update.input_level = Some((level_db, sending));
}
}
Event::MicrophoneTestError { message } => {
cx.status(format!("Microphone test: {message}"));
}
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !state.sessions.entry(id).or_default().has_history() {
add_message(state, cx, id, message);
}
}
Event::ChatHistory { session, target, messages, source, complete } => {
history_batch(state, cx, session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
let id = session as i64;
if let GatewayUpdate::Connected { url, .. } = &update {
gateway_in_use(state, cx, id, url);
}
gateway::extra(state, cx, id, &update);
gateway_update(state, cx, id, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::ServerDetails { session, address, details } => {
remember_server_icon(state, cx, session as i64, &address, details.icon);
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let id = session as i64;
// A file that arrives again is decoded again if it changed.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().avatars.insert(client_uid, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.tree, r.chat, r.toolbar, r.member_card, r.streams) =
(true, true, true, true, true);
}
}
Event::IconReady { session, icon, path } => {
let id = session as i64;
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().icons.insert(icon, path);
cx.update.refresh.servers = true;
if state.current == Some(id) {
cx.update.refresh.tree = true;
cx.update.refresh.toolbar = true;
}
}
Event::PictureReady { session, url, path } => {
let id = session as i64;
// The host banner reloads into the same file.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().pictures.insert(url, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.member_card) = (true, true, true, true);
}
}
Event::Transfer { session, transfer, state: progress } => {
transfer_progress(state, cx, session as i64, transfer, progress);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if cx.host.demo_ui() && !state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
cx.update.refresh.member_card = true;
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if cx.host.demo_ui() => {}
Event::Error { message, .. } => cx.status(message),
Event::JoinFailed { session, channel, reason } => {
join_failed(state, cx, session as i64, channel, reason);
}
Event::SettingRejected { key, message } => {
cx.status(format!("Setting {key}: {message}"));
}
Event::StreamsChanged { session, streams } => {
let id = session as i64;
// Development switch: watch the first stream that shows up.
let autowatch = cx.host.autowatch() && !cx.host.watching() && state.current == Some(id);
// A client whose stream was asked for while it was looked up.
let pending = state
.pending_watch
.filter(|(s, _)| *s == id)
.and_then(|(_, client)| streams.iter().find(|s| s.streamer == client))
.map(|s| s.id.clone());
let view = state.sessions.entry(id).or_default();
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer))
.map(|s| s.id.clone());
view.streams = streams;
cx.update.refresh.streams = true;
cx.update.refresh.servers = true;
if let Some(stream) = pending {
state.pending_watch = None;
cx.update.watch = Some(stream);
} else if autowatch && let Some(stream) = first {
cx.update.watch = Some(stream);
}
}
// The streams we share and watch.
Event::StreamState { session, state: now } => {
streams::share_state(state, cx, session as i64, now);
}
Event::StreamViewerRequest { session, viewer, .. } => {
streams::viewer_request(state, cx, session as i64, viewer);
}
Event::StreamViewers { session, viewers } => {
streams::viewers(state, cx, session as i64, viewers);
}
Event::WatchState { session, stream_id, state: now } => {
streams::watch_state(state, cx, session as i64, &stream_id, now);
}
Event::WatchLayers { session, stream_id, layers, layer } => {
streams::watch_layers(state, cx, session as i64, &stream_id, layers, layer);
}
// Also flagged on the sink, which the encoder reads.
Event::StreamKeyframeRequest { .. } | Event::StreamLayerBitrate { .. } => {}
// The text of an offline message is in the `Social` state, which
// `handle` has changed before (`social::logic::event`).
Event::OfflineMessage { .. } => {}
// What the settings service and the offline messages' requests make
// of the rest, the front end keeps (see the module's note).
event => cx.update.rest = Some(event),
}
}
/// A session's connections changed.
fn session_state<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
now: voelin_core::SessionState,
) {
let view = state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = now.clone();
if now.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if now.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected {
view.channel_passwords.clear();
view.join_after_connect = None;
}
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept when the
// session ends.
load_reads(state, cx, id);
let off = |voice: VoiceState, observe: voelin_core::ObserveState| {
voice == VoiceState::Disconnected && observe == voelin_core::ObserveState::Off
};
if off(now.voice, now.observe) && !off(was_voice, was_observe) {
save_reads(state, cx, id);
}
let focus = !state.sessions.entry(id).or_default().focused_own_channel;
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
cx.status("Connected");
}
if state.current == Some(id) {
if track_reading(state, cx) {
cx.update.refresh.chat = true;
}
// The voice channel's chat is always at hand, and focused once per
// connection.
if let (Some(cid), VoiceState::Connected) = (now.own_channel, now.voice) {
open_chat(state, cx, ChatTarget::Channel(cid), focus);
state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last place,
// which the rail's refresh shows (voice on another server does not take
// it back at each of its events).
if (now.voice, now.own_channel) != (was_voice, was_channel) {
remember_voice(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.streams) = (true, true, true, true);
cx.update.autoshare = true;
if state.current == Some(id) {
cx.update.first_client = true;
}
join_after_connect(state, cx, id);
}
/// The status line once a server answered: "Connected to Nightfall Guild
/// (TeamSpeak 6 6.0.0-beta13.1)".
pub fn connected_status(name: &str, backend: &BackendInfo) -> String {
format!("Connected to {name} ({})", backend.label())
}
/// The gateway logged in at `url`: it is the one in use from now on.
fn gateway_in_use<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, url: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if b.gateway_in_use(url) {
cx.persist(Persist::Bookmark { id, what: "gateway in use" });
}
}
/// The server told its name: a server still named by its address takes it,
/// so the address is all a user has to type.
fn adopt_server_name<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, name: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
return;
};
if name.trim().is_empty() || cx.host.demo_ui() {
return;
}
b.name = name.trim().to_owned();
cx.persist(Persist::Bookmark { id, what: "server named" });
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
pub fn apply_server_icon<L>(
bookmark: &mut Bookmark,
view: &mut SessionView<L>,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
/// Keep only metadata supplied by the bookmark's current server.
fn remember_server_icon<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
address: &str,
icon: u32,
) {
let Some(bookmark) = state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed = apply_server_icon(bookmark, state.sessions.entry(id).or_default(), address, icon);
if changed && !cx.host.demo_ui() {
cx.persist(Persist::Bookmark { id, what: "server icon" });
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub fn remember_voice<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) -> bool {
if cx.host.demo_ui() {
return false;
}
let Some(view) = state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = crate::tree::channel_path(&view.presence, cid);
let Some(b) = state.bookmarks.iter().find(|b| b.id == session).filter(|_| !channel.is_empty())
else {
return false;
};
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
state.settings.last_voice = Some(last);
cx.persist(Persist::Settings);
true
}
/// Send the stored volumes of clients that appeared in a voice session.
pub fn apply_client_playback<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| state.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
cx.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume });
if playback.muted {
cx.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
/// Connected into another channel than the one asked for
/// (`SessionView::join_after_connect`): the server says nothing when, for
/// one, the password was wrong, so it is joined again, and that move says
/// why. Once the channel shows in the voice connection's presence, which
/// can come after the own channel.
pub fn join_after_connect<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect) else {
return;
};
let known = view.presence.channels.contains_key(&asked);
match after_connect(view.state.own_channel, asked, known) {
AfterConnect::Wait => {}
AfterConnect::Joined => view.join_after_connect = None,
AfterConnect::JoinAgain => {
view.join_after_connect = None;
move_into(state, cx, session, asked);
}
}
}
/// Move into a channel of a session connected with voice: with its
/// password, or asking for one when it is locked and none was given this
/// connection.
fn move_into<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64, channel: ChannelId) {
let Some(view) = state.sessions.get(&session) else { return };
let Some(info) = view.presence.channels.get(&channel) else { return };
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match join_password(info, remembered) {
JoinStep::Send(password) => {
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
}
JoinStep::Ask => ask_password(state, cx, session, channel, false),
}
}
/// Open the password dialog for a locked channel; `wrong`: the one given
/// was refused.
pub fn ask_password<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
wrong: bool,
) {
let Some(info) = state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
else {
return;
};
let name = crate::tree::channel_title(info).0.to_owned();
state.join_target = Some((session, channel));
cx.ask_password(name, wrong);
}
/// The server refused a move ([`Event::JoinFailed`]): a password asks again
/// (the one given is forgotten), the rest is a toast.
pub fn join_failed<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
reason: JoinFailure,
) {
match reason {
JoinFailure::Password => {
let given = state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
.is_some();
ask_password(state, cx, session, channel, given);
}
JoinFailure::Full => cx.status("The channel is full"),
JoinFailure::Other(text) => cx.status(text),
}
}
#[cfg(test)]
mod tests;
+725
View File
@@ -0,0 +1,725 @@
//! Tapes of engine events replayed through [`apply`] against a fake host:
//! the state they leave, and what each update asks of a front end.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use voelin_core::StreamState;
use voelin_core::gateway::Pin;
use voelin_core::stream::StreamInfo;
use voelin_core::{
BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
JoinFailure, TransferState, VoiceState,
};
use voelin_gateway_proto::{UserRef, feature};
use voelin_model::{Capabilities, ChatMessage, ChatTarget};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget};
use super::*;
use crate::host::Refresh;
use crate::host::testing::Fake;
use crate::settings::{ClientPlayback, LastVoice};
use crate::host::testing::{State, presence, said, session, state};
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
Event::ChatHistory {
session: 1,
target: ChatTarget::Channel(2),
messages,
source,
complete: true,
}
}
fn run(state: &mut State, host: &Fake, tape: Vec<Event>) -> Vec<Update> {
tape.into_iter().map(|event| apply(state, host, event)).collect()
}
fn gateway(update: GatewayUpdate) -> Event {
Event::Gateway { session: 1, update }
}
fn open_chats(update: &Update) -> Vec<ChatTarget> {
update
.commands
.iter()
.filter_map(|c| match c {
Command::OpenChat { target, .. } => Some(target.clone()),
_ => None,
})
.collect()
}
/// A first connection to a server, event by event: what the session knows
/// after each, and what the front end is told to do.
#[test]
fn a_first_connection() {
let mut st = state();
let host = Fake {
reads: HashMap::from([(
"srv=".to_owned(),
vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })],
)]),
..Default::default()
};
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() };
let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() };
// Connecting: the rail and the bar change, nothing is sent.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }],
);
assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting);
assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree);
assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare);
// The server answers: it gives its name to a bookmark that has only the
// address, and says what it runs.
let ups = run(
&mut st,
&host,
vec![Event::ServerInfo {
session: 1,
name: " Nightfall Guild ".into(),
backend,
capabilities: caps,
}],
);
assert_eq!(st.bookmarks[0].name, "Nightfall Guild");
assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]);
assert_eq!(
ups[0].status.as_deref(),
Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)")
);
assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)");
assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams);
// Its presence: the bar, the tree and the chat are drawn; the stored
// volume of Alice is sent once voice is connected, not before.
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
assert_eq!(st.sessions[&1].presence.clients.len(), 2);
assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client);
assert!(ups[0].commands.is_empty());
// Voice connected into Games: its chat opens and is shown, with the
// store's read marker; the place is remembered.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
let view = &st.sessions[&1];
assert_eq!(view.reads_of.as_deref(), Some("srv="));
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
assert_eq!(view.tabs[view.current_tab].read, Some((200, 7)));
assert_eq!(view.channel_tab, ChatTarget::Channel(2));
assert!(view.focused_own_channel);
assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]);
assert_eq!(ups[0].status.as_deref(), Some("Connected"));
assert_eq!(
st.settings.last_voice,
Some(LastVoice {
bookmark: 1,
address: "ts.example".into(),
channel: vec!["Games".into()]
})
);
assert!(ups[0].persist.contains(&Persist::Settings));
assert!(ups[0].refresh.chat && ups[0].refresh.servers);
// The presence again, now that voice is connected: Alice's volume goes
// to the engine, once.
let ups = run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::Presence { session: 1, presence: presence() },
],
);
assert!(matches!(
ups[0].commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume },
Command::SetClientMuted { session: 1, client: 11, muted: true },
] if *volume == 0.5
));
assert!(ups[1].commands.is_empty());
}
/// The messages of a chat: a stored page, then live ones, with the chat on
/// screen or not, and what is kept of how far it was read.
#[test]
fn messages_are_counted_read_and_kept() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
// The stored page: two read before, one new. (Its marker came from the
// store: nothing here, so what the tab held when the page came counts as
// read.)
let ups = run(
&mut st,
&host,
vec![games(
vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")],
HistorySource::Local,
)],
);
let tab = &st.sessions[&1].tabs[1];
assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::<Vec<_>>(), [6, 7, 8]);
assert!(tab.complete && !tab.loading);
assert_eq!(tab.unread, 0, "a first page is what was read");
assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]);
assert!(ups[0].refresh.chat);
// A live message while the chat is not on screen is new.
let ups =
run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
assert!(ups[0].refresh.servers, "the rail counts it");
// Our own is not.
st.own_uids.insert("me=".into());
run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
// The chat comes on screen: read up to its end, a divider over the new.
host.shown.set(true);
let mut cx = Cx::new(&host);
assert!(crate::chat::logic::track_reading(&mut st, &mut cx));
let tab = &st.sessions[&1].tabs[1];
assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10))));
assert_eq!(st.reading, Some((1, ChatTarget::Channel(2))));
// A live one now is read at once.
run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 0);
assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11)));
// The session ends: where the chats were read is stored, and what the
// store has is what the tab then says it has.
let mut ended = session(VoiceState::Disconnected, None);
ended.server_uid = Some("srv=".into());
let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]);
let written = host.written.borrow();
assert_eq!(written.len(), 1, "{written:?}");
assert_eq!(written[0].0, "srv=");
assert_eq!(written[0].1, StoredTarget::Channel(2));
assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11));
assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11)));
assert!(ups[0].refresh.servers);
}
/// Where the chat lines go when the engine keeps no history (it does not
/// know the server yet): one row appended per message.
#[test]
fn a_session_without_history_appends_lines() {
let mut st = state();
let host = Fake::default();
let message = |text: &str| ChatMessage {
target: ChatTarget::Server,
author_name: "Alice".into(),
author_uid: Some("alice=".into()),
author_id: Some(11),
text: text.into(),
ts_ms: 1000,
via_relay: false,
blocked: false,
};
let ups = run(
&mut st,
&host,
vec![
Event::Chat { session: 1, message: message("one") },
Event::Chat { session: 1, message: message("two") },
],
);
let tab = &st.sessions[&1].tabs[0];
assert_eq!(tab.lines.len(), 2);
assert_eq!(tab.unread, 2);
assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]);
assert!(ups[1].refresh.chat && ups[1].refresh.servers);
// With a server unique id the engine has the history, and the live
// message arrives as `ChatHistory`.
st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into());
run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]);
assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2);
}
/// What a gateway brings: capabilities, requests for what the screens
/// show, pins, the stream directory, reminders for the bell.
#[test]
fn a_gateway_connects_and_tells() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
let caps: Vec<String> = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS]
.map(String::from)
.into();
st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()];
let ups = run(
&mut st,
&host,
vec![gateway(GatewayUpdate::Connected {
url: "wss://gw.example/v1".into(),
gateway_id: "g".into(),
server_uid: "srv=".into(),
server_name: "Nightfall Guild".into(),
uid: "me=".into(),
capabilities: caps,
})],
);
let view = &st.sessions[&1];
assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS));
assert_eq!(view.extra.gateway_uid.as_deref(), Some("me="));
assert_eq!(
st.bookmarks[0].gateway_url.as_deref(),
Some("wss://gw.example/v1"),
"the gateway in use is kept"
);
assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" }));
// The permissions, the events and the directory, then the current
// chat's pins and topics.
let asked: Vec<&GatewayRequest> = ups[0]
.commands
.iter()
.filter_map(|c| match c {
Command::Gateway { session: 1, request } => Some(request),
_ => None,
})
.collect();
assert!(matches!(
asked.as_slice(),
[
GatewayRequest::Permissions { channel: None },
GatewayRequest::Events { .. },
GatewayRequest::Streams,
GatewayRequest::Pins { target: ChatTarget::Channel(2) },
GatewayRequest::Topics { target: ChatTarget::Channel(2), .. },
]
));
assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways);
// The answers: pins (newest first), the directory's viewer counts, a
// failed request of the user.
let pin = |id: i64, ts_ms: i64| Pin {
message: said(id, ts_ms, false, "pinned"),
by: UserRef { uid: "alice=".into(), name: "Alice".into() },
ts_ms,
};
let ups = run(
&mut st,
&host,
vec![
gateway(GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
pins: vec![pin(3, 10), pin(4, 20)],
}),
gateway(GatewayUpdate::Failed {
request: "pin".into(),
code: Some(voelin_gateway_proto::ErrorCode::Forbidden),
message: "no".into(),
}),
],
);
let tab = &st.sessions[&1].tabs[1];
assert!(tab.pins_loaded);
assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [4, 3]);
assert!(ups[0].refresh.chat);
assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server."));
// Gone: nothing of the gateway stays.
run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]);
let view = &st.sessions[&1];
assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded);
}
/// A password that was refused asks again, and says so the second time.
#[test]
fn a_locked_channel_asks_for_its_password() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password };
let ups = run(&mut st, &host, vec![failed()]);
let prompt = ups[0].password.clone().unwrap();
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(st.join_target, Some((1, 1)));
// A password was given and refused: it is forgotten, the prompt says so.
st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into());
let ups = run(&mut st, &host, vec![failed()]);
assert!(ups[0].password.as_ref().unwrap().wrong);
assert!(st.sessions[&1].channel_passwords.is_empty());
// The others are a toast.
let ups = run(
&mut st,
&host,
vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }],
);
assert_eq!(ups[0].status.as_deref(), Some("The channel is full"));
}
/// Connected into another channel than the one asked for: joined again,
/// with the password given this connection.
#[test]
fn a_channel_asked_for_and_not_entered_is_joined_again() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let view = st.sessions.get_mut(&1).unwrap();
view.join_after_connect = Some(1);
view.channel_passwords.insert(1, "pw".into());
// Connected into Games, not the Lobby that was asked for.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(ups[0].commands.iter().any(|c| matches!(
c,
Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw"
)));
assert_eq!(st.sessions[&1].join_after_connect, None);
// The sample sessions send nothing to the engine.
let mut demo = state();
let host = Fake { demo: true, ..Default::default() };
run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]);
demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1);
let ups = run(
&mut demo,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(open_chats(&ups[0]).is_empty());
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. })));
}
/// Pictures and files: the engine's cache, an upload from the composer, a
/// download that runs, the contacts, errors.
#[test]
fn pictures_files_contacts_and_errors() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let path = PathBuf::from("/cache/avatars/ab");
let ups = run(
&mut st,
&host,
vec![
Event::AvatarReady {
session: 1,
client_uid: "alice=".into(),
path: path.clone(),
hash: "ab".into(),
},
Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() },
Event::PictureReady {
session: 1,
url: "https://e.com/a.png".into(),
path: "/cache/pictures/a".into(),
},
],
);
let view = &st.sessions[&1];
assert_eq!(view.avatars.get("alice="), Some(&path));
assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png"));
assert_eq!(ups[0].reloaded, [path]);
assert_eq!(
ups[0].refresh,
Refresh {
tree: true,
chat: true,
toolbar: true,
member_card: true,
streams: true,
..Refresh::default()
}
);
assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat);
// An upload from the composer posts its link once it is up.
st.uploads.insert(7, (1, 2, "notes.txt".into()));
let done = TransferState::Done { size: 12, data: None, path: None };
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]);
assert!(st.uploads.is_empty());
assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared"));
assert!(matches!(
ups[0].commands.as_slice(),
[Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt")
));
st.uploads.insert(8, (1, 2, "big.iso".into()));
let failed = TransferState::Failed("full".into());
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]);
assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full"));
// Errors and rejected settings reach the status line, but not the sample
// sessions' (the engine does not know them).
let ups = run(
&mut st,
&host,
vec![
Event::Error { session: 1, message: "kicked".into() },
Event::SettingRejected { key: "audio".into(), message: "no".into() },
Event::MicrophoneTestError { message: "no device".into() },
],
);
assert_eq!(ups[0].status.as_deref(), Some("kicked"));
assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no"));
assert_eq!(st.status, "Microphone test: no device");
let demo = Fake { demo: true, ..Default::default() };
let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]);
assert!(ups[0].status.is_none());
}
/// A client that talks, the meter, the groups in the order TeamSpeak sorts
/// them.
#[test]
fn talking_the_meter_and_groups() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let ups = run(
&mut st,
&host,
vec![
Event::Talking { session: 1, client: 11, talking: true },
Event::Talking { session: 1, client: 11, talking: false },
Event::InputLevel { session: Some(1), level_db: -20.0, sending: true },
Event::InputLevel { session: None, level_db: -30.0, sending: false },
Event::InputLevel { session: Some(2), level_db: -10.0, sending: true },
],
);
assert!(st.sessions[&1].talking.is_empty());
assert!(ups[0].refresh.tree);
assert_eq!(ups[2].input_level, Some((-20.0, true)));
assert_eq!(ups[3].input_level, None, "no microphone test is running");
assert_eq!(ups[4].input_level, None, "another server's");
st.mic_test = true;
let ups = run(
&mut st,
&host,
vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }],
);
assert_eq!(ups[0].input_level, Some((-30.0, false)));
let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() };
run(
&mut st,
&host,
vec![Event::Groups {
session: 1,
server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]),
channel_groups: Arc::new(vec![group(5, 0)]),
}],
);
let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect();
assert_eq!(ids, [9, 6, 7]);
}
/// The streams the voice connection lists: the one a lookup waited for is
/// to be watched; the rest of the stream events are the front end's.
#[test]
fn streams_are_listed_and_a_lookup_is_watched() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let stream = |id: &str, streamer| StreamInfo {
id: id.into(),
streamer,
name: "screen".into(),
kind: voelin_core::stream::StreamKind::Screen,
bitrate: 0,
viewer_limit: 0,
audio: false,
viewers: Some(1),
};
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }],
);
assert_eq!(st.sessions[&1].streams.len(), 1);
assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none());
// A client's stream was asked for before the list knew it.
st.pending_watch = Some((1, 11));
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s2"));
assert_eq!(st.pending_watch, None);
// The development switch watches the first stream that is not ours.
let host = Fake { autowatch: true, ..Default::default() };
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s3"));
// Keyframe requests are the encoder's, read from the sink; a setting that
// changed is the settings service's: the front end keeps it.
let ups = run(
&mut st,
&host,
vec![
Event::StreamKeyframeRequest { session: 1, layer: 0 },
Event::SettingChanged { key: "audio".into() },
],
);
assert!(ups[0].rest.is_none() && ups[0].refresh.is_empty() && ups[0].commands.is_empty());
assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio"));
}
/// The streams of the events: the studio's stream is the studio's; ours and
/// the one we watch change the state and say what the capture and the
/// decoder are to do.
#[test]
fn the_streams_we_share_and_watch_follow_the_events() {
use crate::streams::logic::{Sharing, Watching, demo_viewers};
use voelin_core::WatchState;
use voelin_core::stream::EndReason;
let mut st = state();
run(&mut st, &Fake::default(), vec![Event::Presence { session: 1, presence: presence() }]);
st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false });
st.watch = Some(Watching {
session: Some(1),
stream_id: "s1".into(),
title: "Speedrun".into(),
streamer: "Alice".into(),
status: String::new(),
connected: true,
ended: false,
has_frame: true,
shown: true,
since: None,
layers: Vec::new(),
layer: None,
});
// The studio streams to the server: its events are handed back as they
// are, and our share is not touched.
let studio = Fake { studio: Some(1), ..Default::default() };
let ups = run(
&mut st,
&studio,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) },
],
);
assert!(matches!(ups[0].rest, Some(Event::StreamViewers { .. })));
assert!(matches!(ups[1].rest, Some(Event::StreamState { .. })));
assert!(st.share.as_ref().unwrap().viewers.is_empty() && st.share.as_ref().unwrap().live);
// Elsewhere they are ours.
let host = Fake::default();
let ups = run(
&mut st,
&host,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamViewerRequest { session: 1, viewer: 11, message: "hi".into() },
Event::WatchState {
session: 1,
stream_id: "s1".into(),
state: WatchState::Ended(EndReason::Stopped),
},
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) },
],
);
assert!(ups[0].refresh.streams && ups[0].rest.is_none());
assert_eq!(ups[1].status.as_deref(), Some("Alice wants to watch your stream"));
let watch = st.watch.as_ref().unwrap();
assert!(watch.ended && ups[2].stream.drop_decoder);
assert_eq!(watch.status, "The stream has ended.");
assert!(st.share.is_none() && ups[3].stream.drop_share && ups[3].stream.mixer);
assert_eq!(ups[3].status.as_deref(), Some("You stopped sharing"));
}
/// Pictures linked in a chat are downloaded once, up to the limit.
#[test]
fn linked_pictures_are_fetched_once() {
let mut st = state();
let host = Fake { limit: 100 * 1024, ..Default::default() };
let mut connected = session(VoiceState::Connected, Some(2));
connected.server_uid = Some("srv=".into());
run(
&mut st,
&host,
vec![
Event::ServerInfo {
session: 1,
name: "S".into(),
backend: BackendInfo::default(),
capabilities: Capabilities { file_transfer: true, ..Default::default() },
},
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: connected },
],
);
let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]";
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
let downloads: Vec<_> =
ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect();
assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands);
// Asked once: the same page again asks for nothing.
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. })));
}
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)");
}
#[test]
fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(
&path,
r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#,
)
.unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
// Details from another address, queued before an edit, change nothing.
assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77));
assert_eq!(view.server_icon, 1234);
std::fs::remove_file(path).unwrap();
}
+2
View File
@@ -18,9 +18,11 @@ pub enum ResumeAction {
/// The card: the server, the channel and the button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resume {
/// The id of the server's bookmark.
pub bookmark: i64,
/// The channel's path, its names from the top as the server has them.
pub path: Vec<String>,
/// What the button does.
pub action: ResumeAction,
}
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more