87 Commits
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
85 changed files with 15419 additions and 913 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
+70 -3
View File
@@ -9,9 +9,7 @@ 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 titled Voelin with one line of the app's state in it (the version,
the voice connections that are up, the engine events handled, the seconds
up), fed by the same engine and the same view models as the Slint app
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
@@ -26,6 +24,53 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
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.
@@ -223,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
Generated
+6 -4
View File
@@ -12587,6 +12587,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"voelin-core",
"voelin-platform",
"voelin-store",
@@ -12596,7 +12597,7 @@ dependencies = [
[[package]]
name = "voelin-identity"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"aws-lc-rs",
"base64 0.23.1",
@@ -12654,8 +12655,8 @@ dependencies = [
[[package]]
name = "voelin-model"
version = "0.1.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"prost",
"serde",
@@ -12694,7 +12695,7 @@ dependencies = [
[[package]]
name = "voelin-proto"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"bytes",
"prost",
@@ -12789,6 +12790,7 @@ dependencies = [
"roxmltree 0.21.1",
"serde",
"serde_json",
"tracing",
"unicode-segmentation",
"voelin-audio",
"voelin-core",
+10 -7
View File
@@ -59,15 +59,18 @@ 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 c5bb6b9: the account-bound
# KeyStore whose sign-out keeps every device key and the release of a device key,
# Phase 2 task 34; the account types of the session seam).
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
# 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 = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
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 = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
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,
+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 c5bb6b9 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),
"{:?}",
@@ -333,7 +333,7 @@ enum Expect {
}
use Expect::{NotRun, Passes, Skipped};
/// Every case of the suite of the protocol repository at `c5bb6b9`, 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.
///
+8 -3
View File
@@ -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
+8 -4
View File
@@ -21,18 +21,22 @@ 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).
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
# 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 Host trait's types (what the store knows of a chat's read marker).
voelin-store = { path = "../voelin-store" }
# 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" }
File diff suppressed because it is too large. Load diff
+6
View File
@@ -25,11 +25,17 @@ 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)
}
+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));
}
}
+87 -8
View File
@@ -7,10 +7,25 @@
//! 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 will give (`ui.theme` in the Slint front end).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
//! 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`]).
@@ -19,7 +34,7 @@ use crate::theme::Choice;
/// A page the window can be opened on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
/// The shell. Today an empty window with the state line.
/// The desktop shell.
Shell,
/// Every theme token, a few components and the icons.
Swatch,
@@ -30,6 +45,25 @@ pub enum Page {
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.
@@ -42,7 +76,19 @@ pub struct Switches {
impl Default for Switches {
fn default() -> Self {
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
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,
}
}
}
@@ -60,8 +106,10 @@ impl Switches {
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 is)"
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)"
),
}
}
@@ -84,7 +132,22 @@ impl Switches {
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
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
}
}
@@ -116,19 +179,32 @@ mod tests {
#[test]
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch"),
("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(&[
@@ -136,6 +212,9 @@ mod tests {
("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());
+21 -2
View File
@@ -7,7 +7,8 @@
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::{Engine, Event};
use voelin_core::settings::Settings;
use voelin_core::{Backends, Engine, Event, History};
/// An engine owned by the caller of [`crate::run`].
pub struct HostedEngine {
@@ -24,7 +25,25 @@ pub struct HostedEngine {
impl HostedEngine {
/// A new engine on `runtime`, all of whose events go to the window.
pub fn start(runtime: &Runtime) -> Self {
let engine = runtime.block_on(async { Engine::start() });
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 {
+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);
});
}
}
+118 -27
View File
@@ -7,10 +7,15 @@
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;
@@ -20,17 +25,27 @@ use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
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;
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::{Choice, VoelinTheme};
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.
@@ -58,18 +73,50 @@ pub fn init_logging() {
.try_init();
}
/// The main window's options: titled with the app's name, grouped by its id,
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
/// 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(voelin_platform::APP_NAME.into()),
..Default::default()
}),
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(640.0), px(480.0))),
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
window_bounds: Some(window_bounds(switches, remembered, cx)),
..Default::default()
}
}
@@ -81,6 +128,7 @@ fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
@@ -94,10 +142,22 @@ fn open_main_window(
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let counters = counters.clone();
move |cx| AppState::new(Some(engine), events, counters, cx)
let setup = Setup {
engine: Some(engine),
events,
counters: counters.clone(),
backend,
switches: switches.clone(),
};
move |cx| AppState::new(setup, cx)
});
let options = window_options(switches, 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();
@@ -108,7 +168,7 @@ fn open_main_window(
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.read(cx).shutdown());
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
cx.quit();
true
}
@@ -120,6 +180,14 @@ fn open_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();
@@ -139,6 +207,13 @@ pub fn run() -> Result<()> {
.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({
@@ -146,16 +221,14 @@ pub fn run() -> Result<()> {
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
shell::bind_keys(cx);
fonts::load(cx);
// Until the settings are read here (the shell slice), the mode and
// the text size are the development switches' or the defaults.
VoelinTheme::init(
cx,
switches.theme.unwrap_or(Choice::System),
cx.window_appearance(),
switches.font_scale.unwrap_or(1.0),
);
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
// 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
@@ -172,7 +245,7 @@ pub fn run() -> Result<()> {
// 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 {
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
give_the_engine_time(&runtime, CLOSE_GRACE);
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
@@ -180,3 +253,21 @@ pub fn run() -> Result<()> {
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));
}
}
+57 -3
View File
@@ -41,6 +41,44 @@ impl Counter {
}
}
/// 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 {
@@ -50,6 +88,8 @@ pub struct Counters {
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,
@@ -194,12 +234,15 @@ pub fn start(counters: Counters) {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated = [
let rated: Vec<(&str, Counter)> = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
("later_jobs", counters.later_jobs.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 {
@@ -232,6 +275,17 @@ pub fn start(counters: Counters) {
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");
+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);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -27,7 +27,7 @@ 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,
+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::*;
+40
View File
@@ -407,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
@@ -718,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.
+48 -2
View File
@@ -791,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();
@@ -1887,9 +1892,19 @@ fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row(
};
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!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
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");
@@ -1905,6 +1920,37 @@ fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row(
}
}
#[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
+3
View File
@@ -31,6 +31,9 @@ miniz_oxide = "0.8"
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" }
+56
View File
@@ -119,6 +119,56 @@ impl Refresh {
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
/// Every part either of the two names: what a front end that handles a
/// batch of events draws once, however many events set a part.
pub fn merge(&mut self, other: Self) {
let Self {
servers,
toolbar,
tree,
chat,
streams,
viewer,
member_card,
home,
events,
gateways,
people,
conversations,
dm,
} = other;
self.servers |= servers;
self.toolbar |= toolbar;
self.tree |= tree;
self.chat |= chat;
self.streams |= streams;
self.viewer |= viewer;
self.member_card |= member_card;
self.home |= home;
self.events |= events;
self.gateways |= gateways;
self.people |= people;
self.conversations |= conversations;
self.dm |= dm;
}
}
#[cfg(test)]
mod refresh_tests {
use super::Refresh;
#[test]
fn merging_names_the_parts_of_both() {
let mut a = Refresh { tree: true, chat: true, ..Default::default() };
a.merge(Refresh { toolbar: true, tree: true, ..Default::default() });
assert_eq!(a, Refresh { toolbar: true, tree: true, chat: true, ..Default::default() });
let mut none = Refresh::default();
none.merge(Refresh::default());
assert!(none.is_empty());
none.merge(Refresh::ALL);
assert_eq!(none, Refresh::ALL);
}
}
/// What a transition wants kept.
@@ -179,6 +229,12 @@ pub struct Update {
/// Pictures the engine wrote again: a front end drops what it decoded
/// of them.
pub reloaded: Vec<PathBuf>,
/// Servers whose gateway is to be looked up in DNS (bookmark id and
/// address; [`crate::servers::logic::discover_wanted`] said so): the front
/// end runs [`crate::servers::sequence::find_gateways`] on the engine's
/// runtime and, when it finds some, calls
/// [`crate::servers::sequence::gateway_found`] on its own thread.
pub discover: Vec<(i64, String)>,
/// The microphone meter: level in dBFS, and whether voice is sent.
pub input_level: Option<(f32, bool)>,
/// Open the password dialog.
+1 -1
View File
@@ -59,7 +59,7 @@ impl fmt::Debug for ImageSource {
/// What identifies a file's content without reading it: its length and the
/// time it was last written. Both zero for a file that is missing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Stamp {
len: u64,
modified: Option<SystemTime>,
+36
View File
@@ -339,6 +339,16 @@ pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String)
}
}
/// Open the card of a client of the server shown over the members panel
/// (`None` closes it).
pub fn open_member<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, client: Option<u16>) {
let Some(view) = state.current.and_then(|id| state.sessions.get_mut(&id)) else { return };
if view.member_card != client {
view.member_card = client;
cx.update.refresh.member_card = true;
}
}
/// The voice channel view was opened or closed: its chat is our channel's,
/// and its people lead the members panel.
pub fn show_voice_view<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) {
@@ -863,6 +873,32 @@ mod tests {
assert!(st.sessions[&1].collapsed.is_empty());
}
/// The card of a client opens over the members panel of the server shown
/// and closes again; the card is drawn again only when it changed.
#[test]
fn the_member_card_opens_and_closes() {
let (mut st, host) = (state(), Fake::default());
st.current = Some(1);
st.sessions.insert(1, SessionView::default());
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert_eq!(st.sessions[&1].member_card, Some(11));
assert!(cx.update.refresh.member_card);
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert!(!cx.update.refresh.member_card, "the same card: nothing to draw");
open_member(&mut st, &mut cx, None);
assert_eq!(st.sessions[&1].member_card, None);
assert!(cx.update.refresh.member_card);
// No server on screen: no card.
st.current = None;
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert!(cx.update.refresh.is_empty());
}
/// A chat takes its server's colour only while it is a server chat of a
/// server in the list: a chat whose server is gone, and a chat that is a
/// channel's or a person's, take the colour of their own title. Black
+1
View File
@@ -3,6 +3,7 @@
//! and the channel tree as plain data.
pub mod logic;
pub mod sequence;
use std::sync::Arc;
+858
View File
@@ -0,0 +1,858 @@
//! What both front ends do for a server that is more than a state change: the
//! sequences over the store, the secrets and the engine.
//!
//! [`logic`](super::logic) has the transitions that touch the state alone;
//! these also read and write the client's store and its secrets (a
//! bookmark and its passwords), pick the identity a connection is made with
//! and build the engine's commands, and they were written twice, once for
//! each front end, before they were one. Each is a transition: it takes the
//! state, the transition's [`Cx`] and the [`Backing`], changes the state and
//! the store, and says what the front end is to do through the `Cx`
//! (commands for the engine, the status line, what to keep, which gateways to
//! look up), so that a front end carries it out with its own `perform` and
//! tests it as it tests the others: in the GPUI front end the commands of a
//! test are the ones its `perform` was handed, and a sample server's are
//! dropped there.
//!
//! What stays with each front end is what needs its toolkit or its runtime:
//! the thread hop of a gateway lookup (it runs [`find_gateways`] on the
//! engine's runtime and calls [`gateway_found`] when something is found, as
//! `Update::discover` asks), the clipboard, the toast, and what it adds to a
//! connect (the stream codecs the Slint front end can decode).
use std::time::Instant;
use tracing::{debug, info, warn};
use voelin_core::stream::PeerConfig;
use voelin_core::{Command, IdentityBlob, ObserveState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport, Secrets, Store};
use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan};
use crate::bridge::BookmarkForm;
use crate::host::Cx;
use crate::state::{AppState, Lines};
/// What the sequences read and write besides the state: the client's store, its
/// secrets and the identity a connection is made with.
pub struct Backing<'a> {
/// The bookmarks, the identities and the chats' read marks.
pub store: &'a Store,
/// The servers' passwords.
pub secrets: &'a dyn Secrets,
/// The identity a connection to a server whose bookmark names `named` is
/// made with, as the engine takes it ([`Store::identity_for`]: the named
/// one if the store has it, else the default one, else the front end's).
pub identity: &'a dyn Fn(Option<i64>) -> IdentityBlob,
}
/// The nickname a new server gets: the default identity's (one imported from
/// TeamSpeak keeps the nickname used there), else the system user's.
pub fn default_nickname(store: &Store) -> String {
store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// The server dialog's form for server `id` (-1: a new one), with its
/// password from the secrets and its session's state.
pub fn bookmark_form<L>(
state: &AppState<L>,
store: &Store,
secrets: &dyn Secrets,
id: i64,
) -> BookmarkForm {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else {
return BookmarkForm {
id: -1,
nickname: default_nickname(store).into(),
..Default::default()
};
};
let password = secrets.get(&b.server_password_key()).ok().flatten();
let session = state.sessions.get(&b.id).map(|view| &view.state);
super::form(b, session, password.as_deref().unwrap_or_default())
}
/// Show a server, and observe it.
pub fn select_server<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
) {
logic::select_server(state, cx, id);
observe(state, cx, backing, id);
}
/// Connect the server on screen with voice, into its default channel.
pub fn connect_voice<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
stream_peer: Option<PeerConfig>,
) -> bool {
let channel = state
.current
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
.and_then(|b| b.default_channel.clone());
connect_voice_to(state, cx, backing, channel, None, None, stream_peer)
}
/// Connect the server on screen with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for. `stream_peer`: what the front end can decode
/// of a stream, if it says (the engine's default otherwise).
pub fn connect_voice_to<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
stream_peer: Option<PeerConfig>,
) -> bool {
let Some(b) = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id)).cloned()
else {
return false;
};
if cx.host.demo_ui() {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
cx.status(error);
return false;
}
};
options.identity = Some((backing.identity)(b.identity));
options.server_password = backing.secrets.get(&b.server_password_key()).ok().flatten();
if let Some(peer) = stream_peer {
options.stream_peer = peer;
}
cx.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
cx.status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
discover_gateway(state, cx, b.id);
true
}
/// Join a channel of a session (a double-click in the tree, joining a friend):
/// move there with voice ([`logic::join_channel`]), ask for the password of a
/// locked channel first, and without voice on that server connect into it.
pub fn join_channel<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
session: i64,
channel: ChannelId,
stream_peer: Option<PeerConfig>,
) {
if let Some(password) = logic::join_channel(state, cx, session, channel) {
connect_into(state, cx, backing, session, channel, password, stream_peer);
}
}
/// The password dialog's Join ([`logic::join_with_password`]): the same, with
/// the password given.
pub fn join_with_password<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
password: String,
stream_peer: Option<PeerConfig>,
) {
if let Some((session, channel, password)) = logic::join_with_password(state, cx, password) {
connect_into(state, cx, backing, session, channel, password, stream_peer);
}
}
/// Connect voice into a channel of a server that has none: the server is
/// shown first, and the channel is named by its id (by its name the server
/// finds only a top-level channel, and a subchannel's name connects into the
/// default channel). Joined again after the connect if the server puts us
/// elsewhere ([`logic::join_after_connect`]).
fn connect_into<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
session: i64,
channel: ChannelId,
password: Option<String>,
stream_peer: Option<PeerConfig>,
) {
if state.current != Some(session) {
select_server(state, cx, backing, session);
}
let asked = connect_voice_to(
state,
cx,
backing,
Some(format!("/{channel}")),
password,
None,
stream_peer,
);
if asked {
logic::join_after_connect(state, session, channel);
}
}
/// Ask for the gateway of a server to be looked up ([`voelin_core::discover`]),
/// once a run ([`logic::discover_wanted`]): every one the server publishes is
/// kept, best first, and tried in turn; they take the place of a stored one
/// that is no longer published (a gateway that moved, or one typed into an
/// older version, which showed the field). Nothing found keeps what is
/// stored. The front end looks it up (`Update::discover`).
pub fn discover_gateway<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
if let Some(address) = logic::discover_wanted(state, cx, id) {
cx.update.discover.push((id, address));
}
}
/// What looking up the gateways of a server found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Found {
/// Every URL the server publishes, best first.
pub urls: Vec<String>,
/// How long the lookup took.
pub elapsed_ms: u64,
}
/// Look the gateways of the server at `address` up in DNS; none when the
/// server publishes none (logged). Runs on the engine's runtime; what it
/// finds goes to [`gateway_found`] on the front end's own thread.
pub async fn find_gateways(address: &str) -> Option<Found> {
let started = Instant::now();
let urls = voelin_core::discover::gateways(address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
None
} else {
Some(Found { urls, elapsed_ms })
}
}
/// Gateways were found for the server at `address` (best first); they are kept
/// unless the server changed meanwhile ([`logic::gateway_found`]), and the
/// server is observed through them if it is the one shown. Users never hear of
/// them (logged only).
pub fn gateway_found<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
address: &str,
urls: Vec<String>,
elapsed_ms: u64,
) {
match logic::gateway_found(state, cx, id, address, urls) {
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
GatewayFound::Kept { observe: now } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if now {
observe(state, cx, backing, id);
}
}
GatewayFound::Changed { stop, observe: now, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
cx.send(Command::StopObserving { session: id as u64 });
}
if now {
observe(state, cx, backing, id);
}
}
}
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its gateway,
/// else its own query login. Without either the gateway is looked up first,
/// and observing starts when it is found ([`gateway_found`]).
pub fn observe<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, backing: &Backing<'_>, id: i64) {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
let session = b.id as u64;
let gateway = |urls| Command::ObserveGateway {
session,
urls,
identity: Box::new((backing.identity)(b.identity)),
};
match logic::observe_plan(state, cx, id) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
cx.send(gateway(urls));
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
cx.send(gateway(urls));
// Still the one the server publishes?
discover_gateway(state, cx, b.id);
}
ObservePlan::Query(q) => {
let secret = backing.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
cx.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
discover_gateway(state, cx, b.id);
return;
}
}
cx.status("Observing invisibly…");
}
/// Save the server the form describes in the store and the secrets, and show
/// it: its id, none when it could not be saved (the status line says why). A
/// new address stops what was observed at the old one.
pub fn save_bookmark<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
form: &BookmarkForm,
) -> Option<i64> {
let old = state.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || default_nickname(backing.store));
let result = if bookmark.id < 0 {
backing.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
backing.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
cx.status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
backing.secrets.delete(&key)
} else {
backing.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its gateway is
// looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = backing.secrets.delete(&old.query_password_key());
}
state.gateways_looked_up.remove(&bookmark.id);
cx.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
state.bookmarks = backing.store.bookmarks().unwrap_or_default();
select_server(state, cx, backing, bookmark.id);
Some(bookmark.id)
}
/// The server dialog's Connect: save the server, then connect it with voice,
/// into the channel of the link that filled the form if one did
/// ([`super::connect_to`]). Only once saved: connecting what is shown after a
/// failed save would connect the server shown before. Whether it was saved.
pub fn save_and_connect<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
form: &BookmarkForm,
stream_peer: Option<PeerConfig>,
) -> bool {
let saved = save_bookmark(state, cx, backing, form);
let to = super::connect_to(
form,
saved.and_then(|id| state.bookmarks.iter().find(|b: &&Bookmark| b.id == id)),
);
let Some(to) = to else { return false };
connect_voice_to(state, cx, backing, to.channel, to.channel_password, to.token, stream_peer);
true
}
/// Remove a server: its session is closed, its passwords and the bookmark go,
/// and the first server is shown.
pub fn delete_bookmark<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
) {
cx.send(Command::CloseSession { session: id as u64 });
if let Some(b) = state.bookmarks.iter().find(|b| b.id == id) {
let _ = backing.secrets.delete(&b.server_password_key());
let _ = backing.secrets.delete(&b.query_password_key());
}
let _ = backing.store.delete_bookmark(id);
let bookmarks = backing.store.bookmarks().unwrap_or_default();
logic::forget_server(state, cx, id, bookmarks);
}
#[cfg(test)]
mod tests {
use voelin_store::{MemorySecrets, QueryConfig};
use std::sync::Arc;
use voelin_core::VoiceState;
use super::*;
use crate::host::Update;
use crate::host::testing::{Fake, State, presence, session};
/// A store, secrets and a front end of the tests' own.
struct Rig {
store: Store,
secrets: MemorySecrets,
host: Fake,
}
impl Rig {
fn new() -> Self {
Self {
store: Store::open_in_memory().unwrap(),
secrets: MemorySecrets::default(),
host: Fake::default(),
}
}
/// A state with these servers saved, the first on screen.
fn state(&self, servers: &[(&str, &str)]) -> State {
for (name, address) in servers {
let bookmark = Bookmark {
name: (*name).into(),
address: (*address).into(),
nickname: "Nova".into(),
..Default::default()
};
self.store.add_bookmark(&bookmark).unwrap();
}
let bookmarks = self.store.bookmarks().unwrap();
let mut state = State::new(
bookmarks.clone(),
Default::default(),
Default::default(),
Default::default(),
);
state.current = bookmarks.first().map(|b| b.id);
state
}
/// Run a sequence, and what it asks of the front end.
fn run<R>(
&self,
state: &mut State,
f: impl FnOnce(&mut State, &mut Cx<'_>, &Backing<'_>) -> R,
) -> (R, Update) {
let identity = |named: Option<i64>| {
IdentityBlob::teamspeak(format!("identity-{}", named.unwrap_or(-1)), 8, "{}")
};
let backing =
Backing { store: &self.store, secrets: &self.secrets, identity: &identity };
let mut cx = Cx::new(&self.host);
let result = f(state, &mut cx, &backing);
(result, cx.update)
}
}
fn form(address: &str) -> BookmarkForm {
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
}
#[test]
fn a_server_with_no_identity_to_name_it_gets_the_users_name_or_a_fallback() {
let nickname = default_nickname(&Store::open_in_memory().unwrap());
assert!(!nickname.trim().is_empty(), "servers refuse an empty nickname");
assert!(nickname != CREATED_IDENTITY && nickname != "imported");
}
/// A connect names the server on screen, its nickname and channel, the
/// identity it is made with and the password the secrets keep; it says so
/// in the status line and asks for the gateway to be looked up, once.
#[test]
fn a_connect_asks_the_engine_with_what_the_store_and_the_secrets_know() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
rig.secrets.set(&state.bookmarks[0].server_password_key(), "hunter2").unwrap();
let (asked, update) = rig.run(&mut state, |state, cx, backing| {
connect_voice_to(state, cx, backing, Some("Lobby".into()), None, None, None)
});
assert!(asked);
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
panic!("{:?}", update.commands.len())
};
assert_eq!(*session, id as u64);
assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova"));
assert_eq!(options.channel.as_deref(), Some("Lobby"));
assert_eq!(options.server_password.as_deref(), Some("hunter2"));
assert_eq!(options.identity.as_ref().map(|i| i.uid.as_str()), Some("identity--1"));
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
// The second connect of a run does not look it up again.
let (_, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert_eq!(update.commands.len(), 1);
assert!(update.discover.is_empty());
}
/// The sample servers connect nothing, and a client version that is none
/// is refused in words.
#[test]
fn a_connect_that_cannot_be_made_asks_nothing() {
let mut rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
rig.host.demo = true;
let (asked, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked && update.commands.is_empty() && update.status.is_none());
rig.host.demo = false;
state.bookmarks[0].client_version = Some("nonsense@0".into());
let (asked, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked && update.commands.is_empty());
assert!(update.status.is_some_and(|s| s.starts_with("Invalid client compatibility")));
state.current = None;
let (asked, _) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked, "no server on screen");
}
/// A state whose first server has a session with `voice` and the channels
/// of `host::testing::presence`: Lobby (1), Games (2, where we are).
fn joined(rig: &Rig, voice: VoiceState, locked: Option<ChannelId>) -> (State, i64) {
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
let mut presence = (*presence()).clone();
if let Some(channel) = locked {
presence.channels.get_mut(&channel).unwrap().has_password = true;
}
let view = state.sessions.entry(id).or_default();
view.presence = Arc::new(presence);
view.state = session(voice, Some(2));
(state, id)
}
/// A double-click in the tree with voice up asks the engine to move there,
/// and connects nothing.
#[test]
fn joining_a_channel_with_voice_moves_there() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Connected, None);
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
let [Command::MoveToChannel { session, channel, password }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*session, *channel, password.as_deref()), (id as u64, 1, None));
assert!(update.password.is_none());
}
/// With no voice on the server the join connects into the channel, named
/// by its id, and remembers to join it again if the server puts us
/// elsewhere; a server that is not the one shown is shown first.
#[test]
fn joining_a_channel_without_voice_connects_into_it() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Disconnected, None);
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*session, options.channel.as_deref()), (id as u64, Some("/1")));
assert_eq!(state.sessions[&id].join_after_connect, Some(1));
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
// Another server is shown, then connected into the channel.
let other = rig.store.add_bookmark(&Bookmark {
name: "Lounge".into(),
address: "lounge.example".into(),
nickname: "Nova".into(),
..Default::default()
});
state.bookmarks = rig.store.bookmarks().unwrap();
let other = other.unwrap();
let view = state.sessions.entry(other).or_default();
view.presence = Arc::new((*presence()).clone());
let (_, update) = rig
.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, other, 2, None));
assert_eq!(state.current, Some(other));
assert!(
update.commands.iter().any(|c| matches!(c, Command::ConnectVoice { session, options }
if *session == other as u64 && options.channel.as_deref() == Some("/2"))),
"{:?}",
update.commands
);
}
/// A locked channel asks for its password first (nothing is sent), the
/// dialog's Join sends it with the move, and the same channel does not ask
/// again this connection.
#[test]
fn a_locked_channel_asks_for_its_password_and_joins_with_it() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Connected, Some(1));
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
assert!(update.commands.is_empty(), "{:?}", update.commands);
let prompt = update.password.expect("the dialog opens");
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(state.join_target, Some((id, 1)));
let (_, update) = rig.run(&mut state, |state, cx, backing| {
join_with_password(state, cx, backing, "secret".into(), None)
});
let [Command::MoveToChannel { channel, password, .. }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*channel, password.as_deref()), (1, Some("secret")));
assert_eq!(state.join_target, None);
// Remembered for this connection: no dialog the second time.
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
assert!(update.password.is_none());
assert!(
matches!(&update.commands[..], [Command::MoveToChannel { password, .. }]
if password.as_deref() == Some("secret")),
"{:?}",
update.commands
);
// An empty password joins nothing.
state.join_target = Some((id, 1));
let (_, update) = rig.run(&mut state, |state, cx, backing| {
join_with_password(state, cx, backing, String::new(), None)
});
assert!(update.commands.is_empty());
}
/// A new server is in the store with its password in the secrets, is the
/// one on screen, and has its gateway looked up (it has none to observe
/// through yet).
#[test]
fn saving_a_new_server_keeps_it_and_its_password_and_shows_it() {
let rig = Rig::new();
let mut state = rig.state(&[]);
let form = BookmarkForm { server_password: "hunter2".into(), ..form(" ts.example ") };
let (saved, update) =
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &form));
let id = saved.expect("saved");
let stored = rig.store.bookmarks().unwrap();
assert_eq!((stored.len(), stored[0].id), (1, id));
assert_eq!(
(stored[0].address.as_str(), stored[0].name.as_str()),
("ts.example", "ts.example")
);
assert!(!stored[0].nickname.is_empty(), "the default nickname");
assert_eq!(
rig.secrets.get(&stored[0].server_password_key()).unwrap().as_deref(),
Some("hunter2")
);
assert_eq!(state.current, Some(id));
assert_eq!(state.bookmarks, stored);
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
assert!(update.commands.is_empty());
// An empty password in the form removes it.
let edit = BookmarkForm { id: id as i32, ..form_of(&stored[0], "") };
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &edit));
assert_eq!(rig.secrets.get(&stored[0].server_password_key()).unwrap(), None);
}
fn form_of(bookmark: &Bookmark, password: &str) -> BookmarkForm {
crate::servers::form(bookmark, None, password)
}
/// Another address is another server: what was observed at the old one
/// stops, its query password goes, and the gateway is looked up anew.
#[test]
fn a_new_address_stops_what_was_observed_at_the_old_one() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let old = state.bookmarks[0].clone();
let id = old.id;
state.gateways_looked_up.insert(id);
rig.secrets.set(&old.query_password_key(), "query-secret").unwrap();
state.bookmarks[0].query = Some(QueryConfig::default());
rig.store.update_bookmark(&state.bookmarks[0]).unwrap();
state.sessions.entry(id).or_default().state.observe = ObserveState::Observing;
let moved = BookmarkForm { address: "ts.elsewhere".into(), ..form_of(&old, "") };
let (saved, update) =
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &moved));
assert_eq!(saved, Some(id));
assert!(
matches!(&update.commands[..], [Command::StopObserving { session }] if *session == id as u64)
);
assert_eq!(rig.secrets.get(&old.query_password_key()).unwrap(), None);
assert_eq!(state.sessions[&id].state.observe, ObserveState::Off);
assert_eq!(update.discover, [(id, "ts.elsewhere".to_owned())]);
assert_eq!(state.bookmarks[0].address, "ts.elsewhere");
}
/// The form's Connect connects only what was saved.
#[test]
fn save_and_connect_connects_the_server_it_saved() {
let rig = Rig::new();
let mut state = rig.state(&[]);
let linked =
BookmarkForm { channel: "Games".into(), token: "key".into(), ..form("ts.example") };
let (done, update) = rig.run(&mut state, |state, cx, backing| {
save_and_connect(state, cx, backing, &linked, None)
});
assert!(done);
let [Command::ConnectVoice { options, .. }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(
(options.channel.as_deref(), options.token.as_deref()),
(Some("Games"), Some("key"))
);
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
}
/// A server is removed with its session, its passwords and its row, and
/// the first of the others is shown.
#[test]
fn deleting_a_server_closes_its_session_and_forgets_its_secrets() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
let [first, second] = [state.bookmarks[0].clone(), state.bookmarks[1].clone()];
rig.secrets.set(&first.server_password_key(), "hunter2").unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| delete_bookmark(state, cx, backing, first.id));
assert!(
matches!(&update.commands[..], [Command::CloseSession { session }] if *session == first.id as u64)
);
assert_eq!(rig.secrets.get(&first.server_password_key()).unwrap(), None);
assert_eq!(
rig.store.bookmarks().unwrap().iter().map(|b| b.id).collect::<Vec<_>>(),
[second.id]
);
assert_eq!((state.current, state.bookmarks.len()), (Some(second.id), 1));
}
/// Showing a server observes it: through its gateways if it has some (and
/// looks the gateway up again, in case it moved), else through its query
/// login with the password the secrets keep, else it looks the gateway up
/// and observes when it is found.
#[test]
fn showing_a_server_observes_it_the_way_it_can_be() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
assert!(
update.commands.is_empty() && update.status.is_none(),
"nothing to observe through yet"
);
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
state.bookmarks[0].query = Some(QueryConfig {
host: "query.example".into(),
port: 10022,
user: "serveradmin".into(),
..Default::default()
});
rig.secrets.set(&state.bookmarks[0].query_password_key(), "q").unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
let [Command::ObserveQuery { session, connect }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(*session, id as u64);
assert_eq!(connect.address, "query.example:10022");
assert_eq!((connect.user.as_str(), connect.secret.as_deref()), ("serveradmin", Some("q")));
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
state.bookmarks[0].set_gateways(vec!["ws://gw.example/".into()]);
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
let [Command::ObserveGateway { urls, identity, .. }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(urls, &["ws://gw.example/".to_owned()]);
assert_eq!(identity.uid, format!("identity-{}", -1));
assert!(update.discover.is_empty(), "looked up once");
}
/// What a lookup found is kept for the next start, and the server on
/// screen is observed through it.
#[test]
fn a_found_gateway_is_kept_and_the_server_on_screen_is_observed_through_it() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
state.gateways_looked_up.insert(id);
let urls = vec!["ws://gw.example/".to_owned()];
let (_, update) = rig.run(&mut state, |state, cx, backing| {
gateway_found(state, cx, backing, id, "ts.example", urls.clone(), 12)
});
assert_eq!(state.bookmarks[0].gateways(), urls);
assert!(
update
.persist
.iter()
.any(|p| matches!(p, crate::host::Persist::Bookmark { id: i, .. } if *i == id))
);
assert!(matches!(&update.commands[..], [Command::ObserveGateway { .. }]));
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
// For a server that changed meanwhile, nothing.
let (_, update) = rig.run(&mut state, |state, cx, backing| {
gateway_found(state, cx, backing, id, "another.example", urls.clone(), 12)
});
assert!(update.commands.is_empty() && update.persist.is_empty());
}
/// The dialog's form: a new server gets the default nickname, a saved one
/// its own with the password from the secrets.
#[test]
fn the_form_of_a_server_has_its_password_and_a_new_one_a_nickname() {
let rig = Rig::new();
let state = rig.state(&[("Nightfall", "ts.example")]);
let saved = &state.bookmarks[0];
rig.secrets.set(&saved.server_password_key(), "hunter2").unwrap();
let form = bookmark_form(&state, &rig.store, &rig.secrets, saved.id);
assert_eq!(
(form.address.as_ref(), form.server_password.as_ref()),
("ts.example", "hunter2")
);
assert_eq!(form.nickname.as_ref(), "Nova");
let new = bookmark_form(&state, &rig.store, &rig.secrets, -1);
assert_eq!((new.id, new.nickname.as_ref()), (-1, default_nickname(&rig.store).as_str()));
}
}
+267 -1
View File
@@ -3,11 +3,14 @@
//! the settings page.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use tracing::warn;
use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind};
use voelin_core::settings::{Key, Kind, Settings};
use voelin_core::{AudioSettings, TransmitMode};
use voelin_model::ChannelId;
use crate::bridge::AudioForm;
@@ -113,6 +116,113 @@ pub static UI_VOICE_COMPACT: Key<bool> = Key::new(
|| false,
);
/// Where the main window was and how large, as the last run left it: size and
/// position in logical pixels, and whether it was maximized (then the size is
/// the one it returns to). The position is left out where the platform does
/// not tell it (Wayland). A front end keeps it in [`UI_WINDOW`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WindowState {
/// Width in logical pixels.
pub width: u32,
/// Height in logical pixels.
pub height: u32,
/// Distance of the window's left edge from the screen's, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x: Option<i32>,
/// Distance of the window's top edge from the screen's, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub y: Option<i32>,
/// The window was maximized.
#[serde(default)]
pub maximized: bool,
}
impl WindowState {
/// The smallest size a window can have been left at.
pub const MIN_SIZE: (u32, u32) = (320, 240);
/// The largest size and the farthest position taken as real: a value
/// beyond it is a damaged setting, not a screen.
pub const LIMIT: u32 = 16_384;
/// Whether the values can be a window: a size within [`Self::MIN_SIZE`]
/// and [`Self::LIMIT`], a position within it either way, and a position
/// that is given whole or not at all.
pub fn is_sane(&self) -> bool {
let limit = i64::from(Self::LIMIT);
(Self::MIN_SIZE.0..=Self::LIMIT).contains(&self.width)
&& (Self::MIN_SIZE.1..=Self::LIMIT).contains(&self.height)
&& self.x.is_some() == self.y.is_some()
&& [self.x, self.y].into_iter().flatten().all(|at| i64::from(at).abs() <= limit)
}
}
fn valid_window(state: &Option<WindowState>) -> Result<(), String> {
match state {
Some(state) if !state.is_sane() => Err("a window of 320x240 to 16384x16384".into()),
_ => Ok(()),
}
}
/// `ui.window`: the main window's size and position as the last run left them
/// (none until a run has). The GPUI front end writes it; the Slint one does
/// not read it.
pub static UI_WINDOW: Key<Option<WindowState>> = Key::new(
"ui.window",
Kind::Json,
"The main window's size and position as the last run left them (none: not stored yet).",
|| None,
)
.validated(valid_window);
/// What the channel tree remembers of one server: the channels folded shut and
/// the channel last selected (a click on its row).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TreeState {
/// The channels folded shut, in ascending order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub collapsed: Vec<ChannelId>,
/// The channel last selected, if one was.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selected: Option<ChannelId>,
}
impl TreeState {
/// Nothing is remembered.
pub fn is_empty(&self) -> bool {
self.collapsed.is_empty() && self.selected.is_none()
}
}
/// What the channel tree remembers, by the id of the server's bookmark
/// (as text: a JSON object's keys are).
pub type TreeStates = BTreeMap<String, TreeState>;
/// The most channels one server may have folded in [`UI_TREE`]: a server has
/// far fewer channels, so more is a damaged setting.
const TREE_STATE_LIMIT: usize = 10_000;
fn valid_tree(states: &TreeStates) -> Result<(), String> {
if states.keys().any(|id| id.parse::<i64>().is_err()) {
return Err("keyed by the id of a server".into());
}
if states.values().any(|state| state.collapsed.len() > TREE_STATE_LIMIT) {
return Err(format!("at most {TREE_STATE_LIMIT} folded channels of a server"));
}
Ok(())
}
/// `ui.tree`: which channels each server's tree has folded shut, and which
/// channel was selected, by the id of the server's bookmark. The GPUI front
/// end writes it; the Slint one does not read it (its tree forgets both
/// when the app ends).
pub static UI_TREE: Key<TreeStates> = Key::new(
"ui.tree",
Kind::Json,
"The channels each server's tree has folded and the channel selected, by server.",
TreeStates::new,
)
.validated(valid_tree);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
[
@@ -262,6 +372,53 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
]
}
/// The settings service on the client database in `dir` (`client.db`), the way
/// both front ends open it: the keys they read registered ([`UI`],
/// [`CLIENT_PLAYBACK`], [`appearance_keys`] and [`page_keys`]; `register` adds
/// the keys of one front end only, before anything is read), then a config file
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists), the
/// `VOELIN_SETTING_*` variables and `overrides` (`--set key=value`) below the
/// stored values. Without the database the settings live in memory. What
/// cannot be applied is logged, not fatal.
pub fn open_settings(
dir: &Path,
overrides: &[String],
register: impl FnOnce(&Settings),
) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
register_keys(&prefs);
register(&prefs);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
}
/// Make the keys both front ends read known to `prefs`.
pub fn register_keys(prefs: &Settings) {
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
for key in appearance_keys() {
prefs.register(key);
}
for key in page_keys() {
prefs.register(key);
}
}
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
/// offers, in the order of its lists (`dialogs.slint`); any other value can
/// be typed in.
@@ -604,6 +761,74 @@ mod tests {
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
}
/// The settings both front ends open: the shared keys, the config file's
/// values, then `--set` over it, a front end's own key only when it
/// registers it, and a database in the directory given.
#[test]
fn the_settings_open_with_the_shared_keys_a_config_file_and_overrides() {
let dir =
std::env::temp_dir().join(format!("voelin-ui-vm-settings-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"\"ui.theme\" = \"light\"\n\"ui.members_width\" = 300\n",
)
.unwrap();
let overrides = ["ui.font_scale=1.5".to_owned(), "ui.members_width=320".to_owned()];
let prefs = open_settings(&dir, &overrides, |prefs| prefs.register(&UI_WINDOW));
assert_eq!(prefs.get(&UI_THEME), ThemeChoice::Light, "from the config file");
assert_eq!(prefs.get(&UI_FONT_SCALE), 1.5, "from --set");
assert_eq!(prefs.get(&UI_MEMBERS_WIDTH), 320, "--set over the file");
assert_eq!(prefs.get(&UI_WINDOW), None);
let names = |prefs: &Settings| prefs.keys().iter().map(|k| k.name()).collect::<Vec<_>>();
for shared in
["ui", "client_playback", "ui.theme", "notify.mentions", "ui.image_preview_kb"]
{
assert!(names(&prefs).contains(&shared), "{shared}");
}
assert!(names(&prefs).contains(&"ui.window"), "the front end's own key");
prefs.set(&UI_FONT_SCALE, 1.25).unwrap();
prefs.flush().unwrap();
drop(prefs);
assert!(dir.join("client.db").is_file(), "the database is in the directory given");
let plain = open_settings(&dir, &[], |_| {});
assert!(!names(&plain).contains(&"ui.window"), "not registered by this front end");
assert_eq!(plain.get(&UI_FONT_SCALE), 1.25, "what was stored wins over nothing");
drop(plain);
std::fs::remove_dir_all(&dir).unwrap();
}
/// The tree's memory is a JSON object by server, round-trips through the
/// service, and a damaged value is refused.
#[test]
fn tree_key() {
let settings = voelin_core::settings::Settings::in_memory();
settings.register(&UI_TREE);
assert!(settings.get(&UI_TREE).is_empty(), "nothing remembered at first");
let states = TreeStates::from([
("3".to_owned(), TreeState { collapsed: vec![4, 9], selected: Some(2) }),
("5".to_owned(), TreeState { collapsed: Vec::new(), selected: Some(1) }),
]);
settings.set(&UI_TREE, states.clone()).unwrap();
assert_eq!(settings.get(&UI_TREE), states);
assert_eq!(
settings.get_json("ui.tree"),
Some(
serde_json::json!({"3": {"collapsed": [4, 9], "selected": 2}, "5": {"selected": 1}})
)
);
// What an older build wrote without a field still loads.
settings.set_json("ui.tree", serde_json::json!({"7": {}})).unwrap();
assert!(settings.get(&UI_TREE)["7"].is_empty());
for damaged in
[serde_json::json!({"nope": {}}), serde_json::json!({"1": {"selected": "x"}})]
{
assert!(settings.set_json("ui.tree", damaged).is_err());
}
}
#[test]
fn voice_compact_key() {
let settings = voelin_core::settings::Settings::in_memory();
@@ -616,6 +841,47 @@ mod tests {
assert!(settings.set_json("ui.voice_compact", "small".into()).is_err());
}
/// The window's state is stored as the setting `ui.window`, comes back as it
/// went, and a damaged value is refused in words.
#[test]
fn window_state_roundtrip() {
let state =
WindowState { width: 1440, height: 960, x: Some(-20), y: Some(35), maximized: true };
let settings = voelin_core::settings::Settings::in_memory();
assert_eq!(settings.get(&UI_WINDOW), None, "none until a run left one");
settings.set(&UI_WINDOW, Some(state)).unwrap();
assert_eq!(settings.get(&UI_WINDOW), Some(state));
assert_eq!(
settings.get_json("ui.window"),
Some(
serde_json::json!({"width": 1440, "height": 960, "x": -20, "y": 35, "maximized": true})
)
);
// A platform that does not tell the position leaves it out.
let no_position = WindowState { x: None, y: None, maximized: false, ..state };
let json = serde_json::to_value(no_position).unwrap();
assert_eq!(json, serde_json::json!({"width": 1440, "height": 960, "maximized": false}));
assert_eq!(serde_json::from_value::<WindowState>(json).unwrap(), no_position);
let older: WindowState = serde_json::from_str(r#"{"width":800,"height":600}"#).unwrap();
assert_eq!(
older,
WindowState { width: 800, height: 600, x: None, y: None, maximized: false }
);
for damaged in [
WindowState { width: 0, ..state },
WindowState { height: 100_000, ..state },
WindowState { x: Some(1_000_000), ..state },
WindowState { y: None, ..state },
] {
assert!(!damaged.is_sane(), "{damaged:?}");
assert!(settings.set(&UI_WINDOW, Some(damaged)).is_err(), "{damaged:?}");
}
assert!(settings.set_json("ui.window", "big".into()).is_err());
assert_eq!(settings.get(&UI_WINDOW), Some(state), "a refused value changes nothing");
settings.set(&UI_WINDOW, None).unwrap();
assert_eq!(settings.get(&UI_WINDOW), None);
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
+102 -4
View File
@@ -4,16 +4,18 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub use voelin_model::channel_title;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges,
tree_rows,
BannerMode, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges, tree_rows,
};
pub use voelin_model::{ChannelId, channel_title};
use voelin_core::{Contact, Relation};
use crate::avatar;
use crate::bridge::{BadgeItem, MemberItem, TreeItem};
use crate::bridge::{BadgeItem, MemberCard, MemberItem, TreeItem};
use crate::image::ImageRef;
use crate::settings::ClientPlaybackMap;
use crate::state::SessionView;
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
pub fn banner_mode(mode: BannerMode) -> i32 {
@@ -54,6 +56,47 @@ pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec
.collect()
}
/// The card over a member row: everything about the client `id` of a session
/// and what is known of it locally (the contact, the playback settings).
/// None when the presence has no such client (it left).
pub fn member_card<L>(
view: &SessionView<L>,
id: u16,
contacts: &HashMap<String, Contact>,
playback: &ClientPlaybackMap,
) -> Option<MemberCard> {
let client = view.presence.clients.get(&id)?;
let uid = client.uid.as_ref();
let contact = uid.and_then(|u| contacts.get(u));
let local = uid.and_then(|u| playback.get(u)).copied().unwrap_or_default();
let groups = client
.server_groups
.iter()
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
.map(|g| g.name.as_str().into())
.collect();
Some(MemberCard {
open: true,
id: i32::from(id),
name: client.nickname.as_str().into(),
initials: avatar::initials(&client.nickname).into(),
tint: avatar::tint(&client.nickname),
avatar: avatar::image(view.avatar(id)),
status: status_of(client, view.talking.contains(&id)).into(),
description: client.description.as_deref().unwrap_or_default().into(),
groups,
badges: badge_items(&client.badges, &view.pictures),
country: client.country.as_deref().unwrap_or_default().into(),
talk_power: client.talk_power,
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
blocked: contact.is_some_and(|c| c.relation == Relation::Blocked),
volume: local.volume * 100.0,
muted: local.muted,
known: uid.is_some(),
streaming: client.streaming == Some(true),
})
}
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
/// The channels and clients of the server.
@@ -901,6 +944,61 @@ mod tests {
);
}
/// The card has what the row has, the groups by name, the badges, the
/// contact's relation and the local playback; a client that left has none.
#[test]
fn the_member_card_is_what_is_known_of_one_client() {
use std::sync::Arc;
use crate::settings::ClientPlayback;
let mut p = presence();
let bob = p.clients.get_mut(&11).unwrap();
bob.uid = Some("bob=".into());
bob.server_groups = vec![6, 99];
bob.description = Some("Raid lead".into());
bob.country = Some("DE".into());
bob.talk_power = 75;
bob.badges = vec!["4b27be5a-b92a-4b30-8b2d-14b59653f427".into()];
bob.streaming = Some(true);
let mut view = SessionView::<()> {
presence: Arc::new(p),
server_groups: vec![GroupInfo {
id: 6,
name: "Moderator".into(),
..Default::default()
}],
..Default::default()
};
view.talking.insert(11);
let mut friend = Contact::new("bob=");
friend.relation = Relation::Friend;
let contacts = HashMap::from([("bob=".to_owned(), friend)]);
let playback = ClientPlaybackMap::from([(
"bob=".to_owned(),
ClientPlayback { volume: 1.5, muted: true },
)]);
let card = member_card(&view, 11, &contacts, &playback).expect("bob is there");
assert!(card.open);
assert_eq!((card.id, &*card.name, &*card.initials), (11, "bob", "BO"));
assert_eq!(card.tint, avatar::tint("bob"));
assert_eq!(&*card.status, "Speaking");
assert_eq!((&*card.description, &*card.country, card.talk_power), ("Raid lead", "DE", 75));
let groups: Vec<&str> = card.groups.iter().map(|g| &**g).collect();
assert_eq!(groups, ["Moderator"], "a group the server did not list is left out");
assert_eq!(card.badges.len(), 1);
assert_eq!(&*card.badges[0].name, "20th Anniversary");
assert!(card.friend && !card.blocked && card.known && card.streaming && card.muted);
assert_eq!(card.volume, 150.0);
// Someone nobody knows: not known, nothing local, listening.
let alice = member_card(&view, 10, &contacts, &playback).unwrap();
assert!(!alice.known && !alice.friend && !alice.muted && alice.volume == 100.0);
assert_eq!(&*alice.status, "Listening");
assert!(member_card(&view, 99, &contacts, &playback).is_none(), "a client that left");
}
#[test]
fn channel_paths() {
let mut p = presence();
+12 -67
View File
@@ -37,83 +37,28 @@ use crate::vm;
slint::include_modules!();
/// The settings service on the client database: the UI's keys registered,
/// then a config file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it
/// exists), `VOELIN_SETTING_*` variables and `overrides` below the stored
/// values. Without the database the settings live in memory.
/// The settings service on the client database
/// ([`vm::settings::open_settings`], which the GPUI front end opens the same
/// way): the UI's keys registered, with the Stream Studio's, then a config
/// file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it exists),
/// `VOELIN_SETTING_*` variables and `overrides` below the stored values.
/// Without the database the settings live in memory.
fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
for key in appearance_keys() {
prefs.register(key);
}
for key in crate::settings::page_keys() {
prefs.register(key);
}
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
}
/// Secrets in the OS keyring, or in memory when there is none (headless
/// Linux without a Secret Service).
#[cfg(not(target_os = "android"))]
struct FallbackSecrets {
keyring: voelin_store::KeyringSecrets,
memory: MemorySecrets,
vm::settings::open_settings(dir, overrides, |prefs| {
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
})
}
/// The secrets store when [`RunOptions::secrets`] is not given: the OS
/// keyring on desktop, memory elsewhere.
/// keyring on desktop (memory behind it where the keyring refuses: a headless
/// Linux without a Secret Service), memory elsewhere.
fn default_secrets() -> Box<dyn Secrets> {
#[cfg(not(target_os = "android"))]
return Box::new(FallbackSecrets {
keyring: voelin_store::KeyringSecrets::new("voelin"),
memory: MemorySecrets::default(),
});
return Box::new(voelin_store::FallbackSecrets::new("voelin"));
#[cfg(target_os = "android")]
return Box::new(MemorySecrets::default());
}
#[cfg(not(target_os = "android"))]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::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) -> voelin_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
/// The lines of a chat as the chat view shows them.
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
+37 -1
View File
@@ -15,6 +15,7 @@ use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB};
use crate::social::Social;
use crate::studio::StudioState;
use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
use crate::vm::servers::sequence::Backing;
/// What the transitions ask while they run: the window, the store and the
/// settings, borrowed from the app besides its state.
@@ -87,6 +88,16 @@ impl App {
pub(crate) fn with_social<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R,
) -> R {
self.with_parts(|state, social, host, _| f(state, social, host))
}
/// Run `f` with the state, the social state, the host and the
/// [`Backing`] of the server sequences (the store, the secrets and the
/// identity, borrowed from the app besides its state).
fn with_parts<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>, &Backing<'_>) -> R,
) -> R {
let host = SlintHost {
demo_ui: self.demo_ui,
@@ -99,7 +110,11 @@ impl App {
prefs: &self.prefs,
studio: &self.studio,
};
f(&mut self.state, &mut self.social, &host)
let identity = |named| {
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
};
let backing = Backing { store: &self.store, secrets: &*self.secrets, identity: &identity };
f(&mut self.state, &mut self.social, &host, &backing)
}
/// An engine event: what it does to the state is in `voelin-ui-vm`
@@ -123,6 +138,22 @@ impl App {
result
}
/// Like [`App::transition`], for a sequence that also reads and writes the
/// store and the secrets and picks the identity
/// (`voelin_ui_vm::servers::sequence`).
pub(crate) fn transition_with<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Cx<'_>, &Backing<'_>) -> R,
) -> R {
let (result, update) = self.with_parts(|state, _, host, backing| {
let mut cx = Cx::new(host);
let result = f(state, &mut cx, backing);
(result, cx.update)
});
self.perform(update);
result
}
/// Like [`App::transition`], for a transition that changes the social
/// state too.
pub(crate) fn social_transition<R>(
@@ -148,6 +179,7 @@ impl App {
commands,
persist,
reloaded,
discover,
input_level,
password,
notices,
@@ -169,6 +201,10 @@ impl App {
for command in commands {
self.engine.send(command);
}
// The gateways to look up, on the engine's runtime.
for (id, address) in discover {
self.look_up_gateway(id, address);
}
// The capture and the decoder.
if let Some(sink) = stream.attach
&& let Some(share) = &self.share
+58 -215
View File
@@ -3,273 +3,116 @@
//! the channel tree, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::servers::logic`.
use std::time::Instant;
use slint::ComponentHandle;
use tracing::{debug, info, warn};
use voelin_core::{Command, JoinFailure, ObserveState};
use voelin_core::JoinFailure;
use voelin_core::stream::PeerConfig;
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use voelin_store::Bookmark;
use crate::app::{App, Bridge, later};
use crate::bind::convert;
use crate::vm;
use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan};
use crate::vm::servers::logic;
use crate::vm::servers::sequence;
impl App {
/// Connect the server on screen with voice, into its default channel
/// ([`sequence::connect_voice`]).
pub(crate) fn connect_voice(&mut self) {
let channel = self
.state
.current
.and_then(|id| self.bookmark(id))
.and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None);
let peer = self.stream_peer();
self.transition_with(|state, cx, backing| {
sequence::connect_voice(state, cx, backing, Some(peer))
});
}
/// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for.
/// whether it was asked for ([`sequence::connect_voice_to`]).
pub(crate) fn connect_voice_to(
&mut self,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
self.set_status(error);
return false;
}
};
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id);
true
let peer = self.stream_peer();
self.transition_with(|state, cx, backing| {
sequence::connect_voice_to(
state,
cx,
backing,
channel,
channel_password,
token,
Some(peer),
)
})
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
/// What this front end can decode of a stream, to connect with: the
/// codecs of the machine, the configured one first.
fn stream_peer(&self) -> PeerConfig {
self.video.peer_config(PeerConfig::default())
}
/// The nickname a new server gets ([`sequence::default_nickname`]).
pub(crate) fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![logic::CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
sequence::default_nickname(&self.store)
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
/// run ([`logic::discover_wanted`]): every one the server publishes is
/// kept, best first, and tried in turn; they take the place of a stored
/// one that is no longer published (a gateway that moved, or one typed
/// into an older version, which showed the field). Nothing found keeps
/// what is stored.
pub(crate) fn discover_gateway(&mut self, id: i64) {
let Some(address) = self.transition(|state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
/// Look the gateway of a server up on the engine's runtime
/// ([`sequence::find_gateways`]), as `Update::discover` asks; what is found
/// comes back through [`later`].
pub(crate) fn look_up_gateway(&mut self, id: i64, address: String) {
self.engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
if let Some(found) = sequence::find_gateways(&address).await {
later(move |app| app.gateway_found(id, &address, found.urls, found.elapsed_ms));
}
});
}
/// Gateways were found for the server at `address` (best first); they
/// are kept unless the server changed meanwhile ([`logic::gateway_found`]),
/// and the server is observed through them if it is the one shown. Users
/// never hear of them (logged only).
/// Gateways were found for the server at `address`
/// ([`sequence::gateway_found`]).
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
let found = self.transition(|state, cx| logic::gateway_found(state, cx, id, address, urls));
match found {
GatewayFound::Same => {
debug!(server = %address, elapsed_ms, "gateway found, as kept");
}
GatewayFound::Kept { observe } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if observe {
self.observe(id);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.engine.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id);
}
}
}
self.transition_with(|state, cx, backing| {
sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
});
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its
/// gateway, else its own query login. Without either the gateway is
/// looked up first, and observing starts when it is found
/// (`gateway_found`).
/// Observe the server invisibly ([`sequence::observe`]).
pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return };
let session = b.id as u64;
match self.transition(|state, cx| logic::observe_plan(state, cx, id)) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
}
ObservePlan::Query(q) => {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id);
return;
}
}
self.set_status("Observing invisibly…");
self.transition_with(|state, cx, backing| sequence::observe(state, cx, backing, id));
}
/// Show a server, and observe it.
/// Show a server, and observe it ([`sequence::select_server`]).
pub(crate) fn select_server(&mut self, id: i64) {
self.transition(|state, cx| logic::select_server(state, cx, id));
self.observe(id);
self.transition_with(|state, cx, backing| sequence::select_server(state, cx, backing, id));
}
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: self.default_nickname().into(),
..Default::default()
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
sequence::bookmark_form(&self.state, &self.store, &*self.secrets, id)
}
/// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why).
/// could not be saved (the toast says why) ([`sequence::save_bookmark`]).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || self.default_nickname());
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its
// gateway is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
self.transition_with(|state, cx, backing| sequence::save_bookmark(state, cx, backing, form))
}
/// The server dialog's Connect: save the server, then connect it with
/// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
/// shown after a failed save would connect the server shown before.
/// Whether it was saved.
/// ([`sequence::save_and_connect`]). Whether it was saved.
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form);
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
return false;
};
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
let peer = self.stream_peer();
self.transition_with(|state, cx, backing| {
sequence::save_and_connect(state, cx, backing, form, Some(peer))
})
}
pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
let bookmarks = self.store.bookmarks().unwrap_or_default();
self.transition(|state, cx| logic::forget_server(state, cx, id, bookmarks));
self.transition_with(|state, cx, backing| {
sequence::delete_bookmark(state, cx, backing, id)
});
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
+13 -14
View File
@@ -426,23 +426,22 @@ impl App {
self.state.own_uids = uids;
}
/// The identity servers see us as on `bookmark` (the one place that
/// picks it): the bookmark's own if it names one that exists, else the
/// store's default.
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
let entries = self.store.identities().unwrap_or_default();
bookmark
.and_then(|b| self.bookmark(b))
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.default_identity_id())
/// The identity a bookmark names, if it names one.
fn named_identity(&self, bookmark: Option<i64>) -> Option<i64> {
bookmark.and_then(|b| self.bookmark(b)).and_then(|b| b.identity)
}
/// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]).
/// The identity servers see us as on `bookmark`: the bookmark's own if it
/// names one that exists, else the store's default (the one place that
/// picks it is [`voelin_store::Store::identity_id_for`]).
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
self.store.identity_id_for(self.named_identity(bookmark))
}
/// The identity a connection to `bookmark` uses
/// ([`voelin_store::Store::identity_for`]).
pub(crate) fn identity_for(&self, bookmark: Option<i64>) -> tsclientlib::Identity {
self.identity_id_for(bookmark)
.and_then(|id| self.store.identity(id).ok())
.unwrap_or_else(|| self.identity.clone())
self.store.identity_for(self.named_identity(bookmark), &self.identity)
}
/// The store's default identity (`Store::default_identity`).
+15 -2
View File
@@ -90,13 +90,26 @@ WORKDIR /src
# `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 (Gradle's cargo-ndk inherits the agent and the
# variable below).
# the first cargo command needs this: 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 (the packages of every
# target, so the Android ones too): 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).
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
cargo fetch --locked
# Gradle starts cargo-ndk, which starts cargo: the variable makes every one of
# them offline, as `--offline` does for the other Dockerfiles (the Gradle task
# is left as it is, because a developer's own build has network and no
# `cargo fetch`). The build uses what the step above fetched (the registry in
# the cache mount shared with it, the git checkout of VoelinProtocol in its
# layer) or fails.
ENV CARGO_NET_OFFLINE=true
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-android,target=/src/target \
--mount=type=cache,id=voelin-gradle,target=/root/.gradle \
--mount=type=secret,id=keystore,required=false \
+11 -2
View File
@@ -45,14 +45,23 @@ WORKDIR /src
# `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.
# the first cargo command needs this: 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. It shares the registry
# cache with the build below, which has no ssh mount (so no agent socket and no
# key in reach of the code it compiles and runs) and is --offline: it uses what
# this step fetched (the registry in the cache mount, the git checkout of
# VoelinProtocol in this step's layer) or fails.
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
cargo fetch --locked
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-linux,target=/src/target \
cargo build --release --locked -p voelin-ui -p voelin-gateway \
cargo build --release --locked --offline -p voelin-ui -p voelin-gateway \
&& scripts/package.sh linux /out
FROM scratch AS artifacts
+12 -3
View File
@@ -98,15 +98,24 @@ WORKDIR /src
# `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.
# the first cargo command needs this: 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 . .
# FFmpeg's LGPL DLLs go into the packages (scripts/fetch-ffmpeg-windows.sh).
# Only this step is given the agent, and it only fetches (the packages of every
# target, so the Windows ones too): 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: it
# uses what this step fetched (the registry in the cache mount shared with it,
# the git checkout of VoelinProtocol in this step's layer) or fails.
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
cargo fetch --locked
# FFmpeg's LGPL DLLs go into the packages (scripts/fetch-ffmpeg-windows.sh).
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-windows,target=/src/target \
cargo build --release --locked --target x86_64-pc-windows-gnu -p voelin-ui \
cargo build --release --locked --offline --target x86_64-pc-windows-gnu -p voelin-ui \
&& scripts/fetch-ffmpeg-windows.sh /tmp/ffmpeg \
&& FFMPEG_DLL_DIR=/tmp/ffmpeg WINDOWS_TARGET=x86_64-pc-windows-gnu scripts/package.sh windows /out
+2 -1
View File
@@ -516,7 +516,8 @@ deleted. Keys deleted before `secure_delete` was on stay in the free pages until
the database is vacuumed.
`voelin-identity` comes from the private VoelinProtocol repository as a git
dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)).
dependency pinned by its release tag, `v0.2.0`
([building.md](building.md#depending-on-voelinprotocol)).
## Streams
+28 -17
View File
@@ -86,7 +86,8 @@ The same with plain Docker, e.g. `docker build --ssh default -f docker/linux.Doc
**The builds need an ssh-agent that holds a key able to read the private
VoelinProtocol repository** ([below](#depending-on-voelinprotocol)): Cargo
fetches it inside the image, through the agent that `--ssh default` hands to the
build. The key stays in the agent; it is not copied into the image or the build
build, in a `RUN cargo fetch` of its own: the build after it has no agent and is
offline. The key stays in the agent; it is not copied into the image or the build
cache. `scripts/docker-build.sh` passes `--ssh default` itself and stops with a
message when `ssh-add -l` shows no agent or no key (`eval "$(ssh-agent -s)"`,
then `ssh-add` your key). The server's host key comes from
@@ -161,15 +162,20 @@ dependencies in the workspace `Cargo.toml`:
```toml
[workspace.dependencies]
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
```
They are pinned by one commit until the protocol tags a release; moving
to a newer protocol means changing the `rev` of all three (later a `tag`) and committing
They are pinned by the protocol's release tag, all three at the same one
(`v0.2.0` is the first tag with the protocol crates; VoelinProtocol's README,
"Releases", says how to pin, and its `CHANGELOG.md`, "For consumers", what a
move changes). Moving to a newer release means changing the `tag` of all three,
making what its "For consumers" list asks of this repository, and committing
the resulting `Cargo.lock` together with `THIRD_PARTY_NOTICES.md`, which
`scripts/notices.sh` regenerates (the CI notices job fails on a stale one).
`scripts/notices.sh` regenerates (the CI notices job fails on a stale one). The
lock then has one revision of each crate, and `spikes/gpui/Cargo.toml` pins
`voelin-model` at the same tag with a lock of its own.
Cargo fetches it over SSH, so the machine needs an SSH key that can read
VoelinProtocol (an `ssh-agent` or a `~/.ssh/config` entry for
`git.faumaray.com`); if Cargo's built-in git client cannot use your SSH setup,
@@ -178,15 +184,19 @@ set `net.git-fetch-with-cli = true` in `~/.cargo/config.toml`.
compiler (gcc or clang) and cmake.
`deny.toml` allows this one git source.
**CI and the Docker builds read it with a read-only SSH deploy key.** The key
is registered on VoelinProtocol and stored as the repository secret
`VOELIN_PROTOCOL_DEPLOY_KEY`; the Gitea workflows write it to `~/.ssh` (CI) or
load it into an ssh-agent (release builds), the server's host key comes from the
committed `.gitea/known_hosts`, and Cargo is told to fetch with the system git
(`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because its built-in git client ignores
`~/.ssh/config`. The Docker builds use the same key through
`docker build --ssh default` (see above). What was set up, how to re-check the
host key's fingerprint and what each failure means:
**CI and the Docker builds read it with a read-only SSH deploy key, and only to
fetch.** The key is registered on VoelinProtocol and stored as the repository
secret `VOELIN_PROTOCOL_DEPLOY_KEY`. The CI job writes it to a directory of its
own (nothing in `~/.ssh`), runs `cargo fetch --locked` with it as the one
`ssh -i` of that step, deletes it, and runs every later cargo command
`--offline`; the release builds load it into an ssh-agent, and each Dockerfile
gives the agent to a `RUN cargo fetch` only, the `cargo build --offline` after it
has none. The server's host key comes from the committed `.gitea/known_hosts`, and
Cargo is told to fetch with the system git (`CARGO_NET_GIT_FETCH_WITH_CLI=true`)
because its built-in git client cannot use a key file. The Docker builds use the
same key through `docker build --ssh default` (see above). What was set up, the
order of the steps, why a runner that may print the key does not get it, how to
re-check the host key's fingerprint and what each failure means:
[ci.md](ci.md#voelinprotocol-access). A runner of your own gets the same setup
from the workflows; the alternative to a deploy key is an access token (rewrite
the SSH URL to HTTPS with
@@ -219,4 +229,5 @@ voelin-model = { path = "../VoelinProtocol/crates/voelin-model" }
- With the patch active Cargo rewrites `Cargo.lock` (the patched crates lose
their git `source`). Do not commit that: run `git checkout Cargo.lock` before
committing, or remove the file and run `cargo update -p voelin-identity -p voelin-proto -p voelin-model`
after changing the `rev` (for all three crates). CI builds with `--locked` and has no patch.
after changing the `tag` (for all three crates; `cargo update -p` can move unrelated
lock edges, so review the lock diff or edit the lock by hand). CI builds with `--locked` and has no patch.
+292 -71
View File
@@ -2,8 +2,9 @@
GitHub Actions runs `.github/workflows/ci.yml`, including Linux checks,
Windows and Android Clippy, and TeamSpeak integration smoke tests. Automatic
runs are off: CI, the dependency audit and fuzzing run only by hand
(Actions → the workflow → Run workflow; the same on Gitea). Only the package
runs are off there: CI, the dependency audit and fuzzing run only by hand
(Actions → the workflow → Run workflow). On Gitea, CI also runs on pushes to
`main` and on pull requests ([Gitea Actions](#gitea-actions)). Only the package
builds run by themselves, on `v*` tags, and they run none of these checks.
Both GitHub and Gitea provide release packaging; see [release.md](release.md)
and [building.md](building.md).
@@ -22,10 +23,18 @@ runtime performance has not been benchmarked for this change.
## Gitea Actions
`.gitea/workflows/ci.yml` runs a single Linux job when dispatched by hand
(automatic runs on pushes and pull requests are off).
`.gitea/workflows/ci.yml` runs a single Linux job on pushes to `main`, on pull
requests (not when only `docs/` or Markdown files change, apart from
`THIRD_PARTY_NOTICES.md`) and when dispatched by hand.
The job runs:
Before any check the job fetches every dependency with the read-only deploy key
with which Cargo reads the private VoelinProtocol repository, and deletes the key
again; the checks run `--offline`, in a job that holds no key
([VoelinProtocol access](#voelinprotocol-access)). The repository secret
`VOELIN_PROTOCOL_DEPLOY_KEY` is needed for it, and the job refuses a runner that
may print it and a fork's pull request.
The checks are:
- formatting and warnings-as-errors Clippy for our crates;
- workspace Clippy (vendored warnings are reported, compilation errors fail);
@@ -61,10 +70,13 @@ the separate `release.yml` workflow below.
distribution servers, crates.io and dependency/license sources used by
cargo-about. The
workspace also depends on the **private** VoelinProtocol repository
(`voelin-identity`, over SSH), so the job needs read access to it and the
server's SSH port. The workflows set that up themselves from a repository
secret: [VoelinProtocol access](#voelinprotocol-access). A runner needs
nothing for it beyond the network access and the image tools above.
(`voelin-identity`, `voelin-proto` and `voelin-model` at its release tag,
over SSH), so the job needs read access to it and the server's SSH port.
The workflows set that up themselves from a repository secret:
[VoelinProtocol access](#voelinprotocol-access). A runner needs nothing for
it beyond the network access and the image tools above, **and a version that
masks multi-line secrets in the job log** (3.1.0 or newer): the workflows do
not give the key to an older runner and fail the job instead.
4. Provision enough RAM, swap and free disk for a full Slint workspace build
plus cargo-deny/cargo-about compilation. These are large builds; monitor
the first run and size the runner accordingly. The workflow limits Cargo
@@ -90,8 +102,10 @@ the separate `release.yml` workflow below.
The workflow shares the repository's local system-dependencies action with
GitHub CI and bootstraps rustup if absent, then installs the toolchain and
components pinned in `rust-toolchain.toml` (1.95: a channel change there is all
the runner needs). Checkout uses a fully qualified GitHub action URL rather
than depending on the instance's action-source configuration.
the runner needs); these are steps of `ci.yml`, and the composite action
`.gitea/actions/checks` holds the checks that run after the fetch. Checkout uses
a fully qualified GitHub action URL rather than depending on the instance's
action-source configuration.
No GitHub cache/artifact service or reusable-workflow support is required.
The job does not need a Docker socket mounted inside its container; the
@@ -194,61 +208,150 @@ known and left alone.
### VoelinProtocol access
The workspace depends on `voelin-identity` from the **private** repository
`Voelin/VoelinProtocol`, as a git dependency over SSH
([building.md](building.md#depending-on-voelinprotocol)). Cargo resolves the
whole workspace before it builds anything, so *every* cargo command needs
that access: all of CI, all three package images and the gateway image (whose
crate does not use `voelin-identity` itself). Without it the first cargo
command fails with `unknown SSH host key` (runs 1037 and 1050 did).
The workspace depends on `voelin-identity`, `voelin-proto` and `voelin-model`
from the **private** repository `Voelin/VoelinProtocol`, as git dependencies over
SSH, pinned by its release tag `v0.2.0`
([building.md](building.md#depending-on-voelinprotocol)). The tag is read over
the same SSH access as the commit it replaced (Cargo fetches it through the
system `git`, like any ref). Cargo resolves the whole workspace before it builds
anything, so *every* cargo command needs that access until the sources are on
disk: all of CI, all three package images and the gateway image (whose crate does
not use `voelin-identity` itself). Without it the first cargo command fails with
`unknown SSH host key` (runs 1037 and 1050 did). The workflows therefore fetch
first, with the key, and build afterwards without it.
What is set up:
- **The deploy key.** A read-only SSH deploy key is registered on
`Voelin/VoelinProtocol` (Settings → Deploy Keys, write access off). It has
no other use and no access to any other repository. Its private half is the
repository secret **`VOELIN_PROTOCOL_DEPLOY_KEY`** of `Voelin/VoelinClient`
(Settings → Actions → Secrets): the whole OpenSSH private key file, BEGIN
and END lines included, without a passphrase. To rotate it, make a new pair
(`ssh-keygen -t ed25519 -N '' -C voelin-client-ci -f key`), register
`key.pub` on VoelinProtocol, replace the secret with the contents of
`key`, run CI, then delete the old deploy key and `key`.
- **CI** (`ci.yml`). The workflow hands the secret to the checks action as its
input `protocol-deploy-key` (a repository secret is not visible inside a
composite action). The action's first step fails at once, naming the secret,
if the input is empty or is not a private key. Otherwise it writes the key to
`~/.ssh/voelin_protocol` (mode 0600, `~/.ssh` 0700), appends the host key
line to `~/.ssh/known_hosts`, writes a `Host git.faumaray.com` block to
`~/.ssh/config` (`User gitea`, that `IdentityFile`, `IdentitiesOnly yes`,
`StrictHostKeyChecking yes`) and exports `CARGO_NET_GIT_FETCH_WITH_CLI=true`
and `GIT_SSH_COMMAND` for the rest of the job (`ci.yml` sets the first one
in its own `env` as well). It prints only the key's
public fingerprint; the key is never echoed. After the system packages a
second step runs `git ls-remote` on VoelinProtocol, so a wrong key or host
key fails there, with the reason, and not inside a cargo command. The key
lives in the job container and goes with it.
- **Release** (`release.yml`). A step after checkout starts an `ssh-agent` on
the release host, loads the key into it from stdin (it is never written to
disk) and exports `SSH_AUTH_SOCK`; the agent forgets the key after nine
hours, and a last step, which also runs after a failure, stops it. The
builds pass the agent on with `docker build --ssh default`
(`scripts/docker-build.sh` does it for the three packages; the gateway image
step does it itself).
- **The images.** Each cargo `RUN` of `docker/*.Dockerfile` and
`crates/voelin-gateway/Dockerfile` has `--mount=type=ssh,required=true`, so
the key exists only inside that step, through the agent socket, and never
reaches a layer, a build argument or the cache; a build without `--ssh`
stops there with `unset ssh forward key default`. The build stage copies
`.gitea/known_hosts` to `/etc/ssh/ssh_known_hosts` and sets the same
`CARGO_NET_GIT_FETCH_WITH_CLI=true`; the toolchain stages install `git` and
`openssh-client`.
`Voelin/VoelinProtocol` (Settings → Deploy Keys, write access off; deploy key
**id 7**, "VoelinClient CI (read-only)", made on 2026-10-28,
`SHA256:TWpZx3NgSMKTBkNLfp0C+Q1/DPD0E44Gy+GiHwK/zpI`). It has no other use and no
access to any other repository. It replaced this repository's first deploy key
(the secret of 2026-10-24), which a job log had shown in clear
([The key and the runners](#the-key-and-the-runners)); that key is deleted, and so
are the runs that printed it. The private half is the repository secret
**`VOELIN_PROTOCOL_DEPLOY_KEY`** of `Voelin/VoelinClient` (Settings → Actions →
Secrets): the whole OpenSSH private key file, BEGIN and END lines included,
without a passphrase. The key step prints the public fingerprint on every run,
to compare with the Deploy Keys page of VoelinProtocol. To rotate it, make a
new pair (`ssh-keygen -t ed25519 -N '' -C voelin-client-ci -f key`), register
`key.pub` on VoelinProtocol, replace the secret with the contents of `key`, run
CI and look at the fingerprint the key step prints, then delete the old deploy
key and `key`. If the old key may have been seen, delete the runs that could
have shown it and count the lines in the logs that remain
([Looking at a run](#looking-at-a-run)).
- **CI** (`ci.yml`). In order; the key exists only between steps 3 and 4:
1. **Check that this job may hold the VoelinProtocol deploy key.** It reads
`GITEA_ACTIONS_RUNNER_VERSION`; a plain `X.Y.Z` (an optional leading `v`) of
`MIN_MASKING_RUNNER_VERSION` (3.1.0) or more passes the runner part. A lower
version, no version, or anything else (`3.1.0-rc1`) fails it. For a pull
request it also asks whether the PR's head is in this repository (below). If
both hold it writes `VOELIN_KEY_ALLOWED=yes` to `GITHUB_ENV`; otherwise it
prints each reason as an error and **fails the job**: 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. Run it again to be given
another runner.
2. The system packages (the `system-deps` action, apt) and the pinned Rust
toolchain. No key yet.
3. **Install the VoelinProtocol deploy key.** The secret is the `env:` of this
one step, through `${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}`,
and the step has `if: env.VOELIN_KEY_ALLOWED == 'yes'`: both ask for the
positive flag, so a runner that is not trusted, or one whose expression
context does not hold what an earlier step wrote to `GITHUB_ENV`, leaves the
step not started and the variable empty. The script never prints the key and
has no `set -x`. It writes the key to `id` (mode 0600) in a directory of the
job's own, `mktemp -d "$RUNNER_TEMP/voelin-protocol-key.XXXXXX"` (mode 0700;
the name goes to `GITHUB_ENV` first so that the cleanup finds it even if this
step is killed), checks it with `ssh-keygen -y` and prints the fingerprint. From
the `mktemp` on, the step removes the directory itself on every way out but
the last line (an `EXIT` trap: a key that is not a key, a full disk, a
termination). It writes nothing to `~/.ssh`: no key file, no `known_hosts`,
no config block.
4. **Fetch the dependencies with the deploy key.** The only step that uses the
key, and the only one that sets `GIT_SSH_COMMAND` (not in `GITHUB_ENV`, so no
other step has it):
`ssh -F /dev/null -i <dir>/id -o IdentitiesOnly=yes -o IdentityAgent=none -o UserKnownHostsFile=<workspace>/.gitea/known_hosts -o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes -o BatchMode=yes -o ConnectTimeout=30`.
`-F /dev/null` leaves out every ssh config file, the identity is that file and
nothing from an agent, and the host key accepted is the committed line and no
other (a changed or unknown host key fails rather than asks). The paths are
absolute because Cargo runs git in its own directory, not in the checkout.
The step runs `git ls-remote` on VoelinProtocol first, so a wrong key or host
key fails there, with the reason, and not inside Cargo; then
`cargo fetch --locked`, which downloads every package of `Cargo.lock` (all
targets, because cargo-deny and cargo-about read the whole graph) and runs **no
build script, procedural macro or test**; then it deletes the directory (on
every way out of the step, a failed fetch included) and checks that it is
gone.
5. **Delete the deploy key**, `if: always()`: removes the directory if it is
still there (the key step failed after creating it, the job was cancelled) and
says so, or says that none is left. It runs right after the fetch, so the
checks never start with a key in the job.
6. **The checks** (`.gitea/actions/checks`): formatting, Clippy, the build, the
tests under Xvfb, cargo-deny, the notices check and the release tooling tests.
The action has **no input and no secret**: the secret is never handed to the
steps that run the repository's build scripts and tests. Every cargo command
in it is `--offline` (with `--locked`), and the steps that start cargo through
a script or plugin (`scripts/own-crates.sh`, `cargo fmt`, `cargo deny`,
`scripts/notices.sh`) have `CARGO_NET_OFFLINE=true`. cargo-deny's own
`--offline` is not used: it would also stop it fetching the RustSec database
(from github.com, no key), which the check needs; the variable keeps its
`cargo metadata` offline and leaves the fetch alone. The only cargo commands
that go online are the two `cargo install` of cargo-deny and cargo-about, which
read no manifest of this workspace. A dependency added later that Cargo could
not get from `cargo fetch` fails these steps with an offline error instead of
waiting for an ssh key that is not there.
- **A fork's pull request.** A pull request gets the key only when its head branch
is in this repository. The job-level `env` of `ci.yml` asks
`github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository`:
Gitea's event payload names, in `pull_request.head.repo.full_name`, the repository
that holds the branch to be merged. That is `Voelin/VoelinClient` for a branch
pushed here and the fork's own name (`someone/VoelinClient`) for a fork; any other
event has no pull request, and the first operand is true. An absent or different
name reads `no`, and step 1 treats everything but `yes` as no (the same
fail-closed direction as the runner version). Step 1 also asks the question
again in its script, from the name itself: for a `pull_request` event (and for any
event that carries a head repository) it requires `PR_HEAD_REPO`, the same payload
field, to be non-empty and equal to `GITHUB_REPOSITORY`, so a mistake in the
expression or in the script alone does not hand the key to a fork's code. A fork's
pull request therefore fails at step 1 with the reason and the head repository's
name, without a key, as it failed before (at the empty secret). Gitea gives such a
run no secrets in any case; the check also keeps a same-looking head from being
trusted by accident. It does not make a same-repository branch safe: code of a
branch pushed here runs the build scripts and tests with no key (it is gone by
then), but a branch that changes the workflow itself is a change of the workflow
([below](#what-this-does-not-do)).
- **Release** (`release.yml`). A step after the checkout checks the runner as
step 1 above does (a release has no pull request). The step that starts an
`ssh-agent` on the release host has the same flag guard, loads the key into the
agent from stdin (it is never written to disk) and exports `SSH_AUTH_SOCK`; the
agent forgets the key after nine hours. The builds pass the agent on with
`docker build --ssh default` (`scripts/docker-build.sh` does it for the three
packages, the Android one twice, as the debug APK and as the signed release APK;
the gateway image step does it itself). A step directly after the last build,
`if: always()`, stops the agent and empties `SSH_AUTH_SOCK`, so the artifact
upload and the release draft have neither the key nor the socket.
- **The images.** In `docker/linux.Dockerfile`, `docker/windows.Dockerfile`,
`docker/android.Dockerfile` and `crates/voelin-gateway/Dockerfile` only a
`RUN cargo fetch --locked` has `--mount=type=ssh,required=true`; the build after
it has no ssh mount and is offline: `cargo build --release --locked --offline`
in three of them, `CARGO_NET_OFFLINE=true` in the Android one, whose Gradle task
starts cargo-ndk and cargo (the task itself is left as it is, because a
developer's own build has network and no `cargo fetch`). The key exists inside
the fetch only, through the agent socket, and never reaches a layer, a build
argument or the cache; the code that the build compiles and runs (build scripts,
procedural macros, Gradle) has no agent socket in reach. A build without `--ssh`
stops at the fetch with `unset ssh forward key default`. The build stage copies
`.gitea/known_hosts` to `/etc/ssh/ssh_known_hosts` and sets
`CARGO_NET_GIT_FETCH_WITH_CLI=true`; the images install `git` and `openssh-client`
in their build stage. The fetched git checkout of VoelinProtocol stays in the
layer of the fetch step, the registry in the cache mount that the build step
shares (the three package images; the gateway image has no cache mount, its
registry stays in the layer too).
- **Cargo uses the system git** (`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because
Cargo's built-in git client does not read `~/.ssh/config` (so it cannot use
an `IdentityFile`), authenticates with an ssh-agent and checks the host
against `~/.ssh/known_hosts` and its own `net.ssh.known-hosts` setting. The
system git runs `ssh`, which reads the config above (and
`/etc/ssh/ssh_known_hosts` in the images), so the same files serve a plain
`git` call, Cargo and the access check.
Cargo's built-in git client does not run `ssh -i` (so it cannot use a key file),
authenticates with an ssh-agent and checks the host against `~/.ssh/known_hosts`
and its own `net.ssh.known-hosts` setting. The system git runs the command in
`GIT_SSH_COMMAND`, so the same command serves the access check and Cargo.
- **The host key** is committed in [`.gitea/known_hosts`](../.gitea/known_hosts),
never fetched while a job runs. Gitea's built-in SSH server (`SSH-2.0-Go`)
offers an RSA host key only (`ssh-keyscan -t ed25519 git.faumaray.com`
@@ -265,21 +368,135 @@ What is set up:
new `ssh-keyscan -t rsa` line and the date in `.gitea/known_hosts` and the
fingerprint here, and commit all of it in one change. Until then a changed key
makes every job stop with `Host key verification failed`, which is the point.
VoelinGateWay, VoelinProtocol and VoelinServer keep the same line.
Pull requests from forks get no secrets: their CI run stops at the first step
with the message about the empty deploy key. Anyone who can change a workflow of
this repository, or run code in one of its jobs, can read the key; it can only
read VoelinProtocol, and it is replaced as above. That is one more reason to
keep the CI runner isolated, as said above.
#### The key and the runners
Gitea has more than one runner with the same labels (`ubuntu-latest`,
`voelin-release`, `ubuntu-24.04`, `ubuntu-22.04`, `echoion-release-serial`), so
`runs-on` cannot choose between them, and they do not log alike. A runner prints
the `env:` of a step in the job log when the step starts. "Perfrormance Runner"
(act_runner, reports `v3.1.0`, the one that is online) masks a multi-line secret
line by line (`***`). The runner **gitea-runner-docker v0.6.1 (id 1, offline on
2026-10-28) printed the whole private key in clear**, on one line with the line
ends shown as `\n`, in the logs of runs of this repository, of VoelinGateWay and of
VoelinServer on 2026-10-27. On 2026-10-28 every deploy key was rotated and the
runs that printed one were deleted.
What follows from it, in the workflows:
- **The key is not given to such a runner.** Step 1 of the job (and the check in
`release.yml`) writes the flag only for a runner whose reported version is
`MIN_MASKING_RUNNER_VERSION` (3.1.0, the oldest one seen masking) or more; for any
other the job fails there, before any step names the secret, and the key step is
not started. This is a gate on the version number and no test of masking: a
runner that reports 3.1.0 or more is trusted by its number, and a version
that a runner does not report is not trusted. It was **rehearsed** with a
stand-in for the runner (the step script with the reported version set to
`v0.6.1`, to nothing, to `3.0.9`, to `v3.1.0-rc1`, to `3.1` and to a word: the job
fails with the reason and no flag is written; `v3.1.0`, `3.1.0`, `v3.1.1`,
`v10.0.0` pass) and **has not been seen on gitea-runner-docker itself**, because
it is offline, and what that runner reports in `GITEA_ACTIONS_RUNNER_VERSION` is
not known. To let the gate admit an older runner, lower
`MIN_MASKING_RUNNER_VERSION` (in `ci.yml` and in `release.yml`) only after a
canary secret of several lines has been shown masked in the log of that runner.
- **The cause is the runner**, and the fix that covers every secret of every
repository is there: upgrade gitea-runner-docker to a version that masks
multi-line secrets, retire it, or register it with labels no workflow asks for.
- The log of a run that did hold the key shows the step headers with `***` for
each line of the secret; nothing else prints it.
#### What has been seen, and what has not
Seen on a real runner ("Perfrormance Runner", reports `v3.1.0`), by dispatching
`ci.yml` on the branch that introduced this order of steps:
- **Run 1226, the full path, green** (36 minutes). The check passes ("Runner …
reports version v3.1.0, which masks secrets in the log"; "Event
workflow_dispatch: no pull request"); the key step's header shows
`PROTOCOL_DEPLOY_KEY: ***` and one `***` for each further line of the key, and
prints `Deploy key installed: 256 SHA256:TWpZx3NgSMKTBkNLfp0C+Q1/DPD0E44Gy+GiHwK/zpI`
(deploy key id 7); the fetch step reads VoelinProtocol, runs `cargo fetch --locked`
(some eighteen seconds) and prints "The deploy key is removed from the job."; the
cleanup step prints "No deploy key is left in the job."; the checks run
`--offline`; the only `Updating crates.io index` after the fetch are the two
`cargo install` steps. The log of the job has no line with `PRIVATE KEY`.
- **Run 1225, the gate refusing, red by design.** A temporary commit raised
`MIN_MASKING_RUNNER_VERSION` to `99.0.0` (reverted by the next commit): the check
failed the job with "… the runner (Perfrormance Runner) reports version 'v3.1.0',
and only a runner of version 99.0.0 or newer …"; the system packages, the
toolchain, the key step, the fetch and the checks were not started and left no
line in the log (so the secret was named nowhere), the cleanup step ran and said
that no key is left, and the log has no `PRIVATE KEY` line and no mention of the
secret.
- Run 1224, of the same workflow as run 1226, was cancelled four minutes in, as
1225 was started on the same branch (a run started on a branch cancels the one
still running there, so dispatch the next only when the last has ended): the
key step, the fetch and the cleanup had run as in 1226 and the offline Clippy had
started. It shows nothing more.
Rehearsed with stand-ins, not seen on a runner: the runner check of `ci.yml` and of
`release.yml` for the reported versions above, and the pull request rule of
`ci.yml` (head repository empty, another one, equal to the repository, with the
expression's answer yes, no or missing: only equal and named passes); the key step
with a text that is no key, with an empty one and with a failing `GITHUB_ENV` (the
`EXIT` trap removes the directory) and with a key whose lines end in CR (it stays for
the fetch); the fetch step with a key that VoelinProtocol does not know (`Permission
denied (publickey)` from the server whose host key `.gitea/known_hosts` holds, the
directory removed by the step's trap); the cleanup step with and without a
directory; the ssh-agent step of `release.yml` with a key (the fingerprint, the
variables) and its stop step (the agent is gone, the variables are emptied).
Not seen: a job on gitea-runner-docker (offline; the gate is rehearsed with a
stand-in for the runner, above); a `pull_request` run, so neither the same-repository
head (`yes`) nor a fork's (`no`) has been read from a real event payload (the field
is the one that Gitea's API gives as `head.repo.full_name` of a pull request, which
reads `Voelin/VoelinClient` for a branch of this repository, and an absent field
fails closed); `release.yml` on a runner; the four Dockerfiles built (they pass
`docker build --check` with no warning, and the `cargo fetch` then `cargo build
--offline` split is that of VoelinGateWay's `docker/linux.Dockerfile`, which was
built with `docker build --ssh default`; the Android Gradle task with
`CARGO_NET_OFFLINE` has not been run). The first release or image build is the
check.
#### Looking at a run
The fingerprint of the key step, and the proof that no log holds a private key
(the job ids are in `GET .../actions/runs/<run id>/jobs`):
```sh
curl -s -H "Authorization: token $TOKEN" "https://git.faumaray.com/api/v1/repos/Voelin/VoelinClient/actions/jobs/<job id>/logs" | grep -c 'PRIVATE KEY' # 0
```
#### What this does not do
- Anyone who can change a workflow of this repository, or run code in one of its
jobs, can read the key: a branch pushed here that prints it in the key step, or
that lowers `MIN_MASKING_RUNNER_VERSION`, or that adds a step. The key can only
read VoelinProtocol and is replaced as above; keep the CI runner isolated, as said
above. What the hardening does is keep the *code* of a change (build scripts,
procedural macros, tests, tools installed by cargo) away from the key while the
workflow is the reviewed one.
- `cargo fetch` reads the checkout's `Cargo.toml` and `Cargo.lock` files,
`rust-toolchain.toml` and a `.cargo/config.toml` if there is one (there is none
at the root today), and runs the toolchain's `rustc -vV`. A branch that adds a
Cargo configuration with a `build.rustc` or `build.rustc-wrapper` program would
run it while the key exists. That is a change of the build configuration, to be
reviewed as one.
- The job token that `actions/checkout` leaves in the checkout's git configuration
is not touched by this.
If a run fails here:
| Message | Cause |
|---|---|
| `The VoelinProtocol deploy key is empty` | the secret is missing, empty or not visible (a fork's pull request) |
| `The VoelinProtocol deploy key is not given to this job: the runner (…) reports version …` | the job landed on a runner that is not known to mask the key in the log (gitea-runner-docker v0.6.1, or one that reports no version): run it again |
| `… the pull request's head repository is '…'` | a fork's pull request, or an event that did not name the head: push the branch to this repository |
| `The VoelinProtocol deploy key is empty` | the secret is missing or empty |
| `… is not an unencrypted OpenSSH or PEM private key` | the secret holds something else, or a key with a passphrase |
| `Permission denied (publickey)` in "Check read access to VoelinProtocol" | the key is valid but is not a deploy key of VoelinProtocol: compare the fingerprint "Deploy key installed" printed with the one in VoelinProtocol's deploy key settings |
| `Permission denied (publickey)` in "Fetch the dependencies with the deploy key" | the key is valid but is not a deploy key of VoelinProtocol: compare the fingerprint "Deploy key installed" printed with the one in VoelinProtocol's deploy key settings |
| `Host key verification failed` | `.gitea/known_hosts` does not match the server: check as above before changing anything |
| an offline error ("no matching package", "can't update … in offline mode") in a check step | a dependency changed after the fetch, or `cargo fetch --locked` did not get something the checks need: fix the fetch step, do not give the checks a key |
| `unset ssh forward key default` | a Docker build ran without `--ssh default`: a plain `docker build` (`scripts/docker-build.sh` passes it itself and stops earlier when the agent has no key) |
### Gitea release runner
@@ -297,9 +514,13 @@ voelin-release:host
Provision Bash, Git, the OpenSSH client (`ssh-agent` and `ssh-add`), Node.js
20+, Python 3.11+, curl, tar, gzip and rootful Docker 23+ with BuildKit. Use
**act_runner 0.2.7 or newer** (prefer the latest maintained release), or
gitea-runner 2+. Older act_runner does not provide
`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. Register the
**a runner that reports 3.1.0 or newer** (the key gate refuses older ones;
0.2.7 is only the artifact action's minimum; prefer the latest maintained
release), or gitea-runner 2+. Older act_runner does not provide
`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. The workflow also
gives the deploy key only to a runner that reports version 3.1.0 or newer in
`GITEA_ACTIONS_RUNNER_VERSION` ([VoelinProtocol access](#voelinprotocol-access)),
so on a lower one the release stops at its first check. Register the
runner against `https://git.faumaray.ru`, reachable from both the host and
build containers. Gitea 1.25.4 provides the required artifact-v4 API.
The shared checks install native build dependencies
+53 -5
View File
@@ -23,8 +23,9 @@ cases the foundation's review ran again on a quiet machine. The same day the
foundation of step 3 landed on `phase5/gpui-foundation` (items 1 to 4 and 6
of "What step 3's first slice must contain": Rust 1.95, ashpd on `async-io`,
the `voelin-gpui` crate with its root entity, the theme with Inter and Lucide,
the cost meter; item 5, the shell, is next): what exists, how to run it and
the slices that follow are in [docs/ui.md](../ui.md), "The GPUI front end".
the cost meter; item 5, the shell, followed the same day, below): what exists,
how to run it and the slices that follow are in [docs/ui.md](../ui.md), "The
GPUI front end".
The foundation was reviewed and gated the same day (a Sonnet review, then the
Opus gate: no blocker and no major, six minors), and the minors are closed in
the commits after it: the meter's `/proc` test waits for a CPU tick instead of
@@ -32,7 +33,50 @@ burning 60 ms, zbus runs on `async-io` alone in every binary (with a test for
the order of ashpd's callers), the lock figures and the Lucide 1.43 credit are
corrected, the slice list points at "Open choices for step 3", and the parity
test sees a second brush or string. The risks the review and the gate left to
the slices that meet them are in docs/ui.md, "For the next slices".
the slices that meet them are in docs/ui.md, "For the next slices". Item 5, the
desktop shell, is slice 1 of the step's list and landed on `phase5/gpui-shell`
(2026-10-27): the store at start (the client's database, the settings with the
UI's keys, the secrets, the default identity), the server rail, the sidebar,
the top bar and the main area as entities that tell the window when what they
show changed (the window then draws every part: gpui-pre 0.3.10 renders every
uncached child view on every frame), the eleven callbacks of `bind/servers.rs`
as actions through `voelin-ui-vm`'s logic and the engine's commands, the
window's size and position kept in `ui.window`, the engine-event task in steps
and a tick that draws nothing. What it shows, what it costs idle and what it
leaves to the slices after it are in docs/ui.md, "The desktop shell"; the next
slice is the channel tree and the members. The shell was reviewed and gated the
same day (an Opus gate: no blocker and no major, six minors), and the minors are
closed on `phase5/gpui-shell-minors`: the records that said the parts draw only
when what they show changed are corrected (a part tells the window, and the
window draws every part, as gpui-pre 0.3.10 renders every uncached child view on
every frame), a window left maximized is maximized again on X11, the pictures
are 1440 by 960, the connect test sends no DNS query, the sequences both front
ends ran are shared in `voelin-ui-vm`, and the `ui.window` row is in the
settings table; the gate's four risks of the shell are in docs/ui.md, "For the
next slices". Slice 2, the channel tree and the members panel, landed on
`phase5/gpui-tree` (2026-10-28): `Update.refresh` as per-area signals and the
shell's panes cached (the design the shell's review left for it), the pictures
the engine writes again shown and the old copies dropped, the tree over a
virtual list that applies the row operations of `voelin-ui-vm`'s `list::diff`,
the members panel, the member card and the password prompt, with the folds and
the selection kept per server; what a change costs, figure by figure, is in
docs/ui.md, "The channel tree and the members". The slice was reviewed the same
day (one major and five minors) and the commits after it close them: a channel's
banner is drawn under the surface veil of the Slint tree's `BannerPicture`, an
avatar under 28 pixels shows one letter, the password prompt ignores an empty
field and closes on Escape, and the `ui.tree` row of the settings table, the
list of the Bridge's properties and callbacks that the two panes use and some
long lines are corrected in docs/ui.md. Slice 3, the voice page and the call bar,
landed on `phase5/gpui-voice` (2026-10-28): the page as a cached pane of its own
that takes the main area (its people from the tree model's one build, so a talker
is still one build for three lists), the call bar and the smaller stage kept in
`ui.voice_compact`, the sidebar's server card with its banner, the voice card's
transmit modes and the volume of a person following the settings, the release
guard of Hold to talk (voice that drops, a window that loses the focus) and the
global push-to-talk key started on the engine's runtime; it was seen against both
development servers with a second client that talks. What it costs and what it
leaves is in docs/ui.md, "The voice page and the call bar". The next slice is the
chat, the composer and emoji.
| Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict |
|---|---|---|---|
@@ -637,8 +681,12 @@ set; the meter as `VOELIN_METER=1`. The crate is named `voelin-gpui` (binary
`voelin-gpui`), the choices below stayed as the report leaves them except
those named in docs/ui.md ("The GPUI front end"): the theme's second layer is
written as a `ThemeColor` mapping (a table there), and the client's Lucide set
is served under gpui-component's `icons/` paths. Item 5, the shell, is the
next task.
is served under gpui-component's `icons/` paths. Item 5, the shell, is done on
`phase5/gpui-shell` (the status paragraph above, docs/ui.md "The desktop
shell"): the screenshots are made the `docs/ui.md` way
(`scripts/gpui-shot.sh` under `headless.sh`), the form that adds a server is the
shell's own until the dialogs slice, and the open choices that remain (video,
emoji, links) are untouched by it.
### The risks of plan section 6, against what was seen
+10
View File
@@ -35,6 +35,16 @@ HTTPS and never uses GitHub's release API. On this instance the server URL
is `https://git.faumaray.ru`. No registry credentials are needed: the gateway
image is attached as `tsgw-image.tar.gz`, not pushed to an OCI registry.
The builds also read the private VoelinProtocol repository
(`voelin-identity`, `voelin-proto`, `voelin-model`): the repository secret
`VOELIN_PROTOCOL_DEPLOY_KEY`, the read-only deploy key of that repository, is
loaded into an ssh-agent for the Docker builds, given to the `cargo fetch` of each
Dockerfile only, and the agent is stopped right after the last build
([ci.md](ci.md#voelinprotocol-access)). The workflow gives the key only to a
runner of version 3.1.0 or newer (an older one may print it in the job log) and
stops at that check otherwise; without the secret it stops at its ssh-agent step,
naming the secret.
Retries update only a matching **draft**, replacing same-named assets.
Published releases are not changed; a failed upload leaves a partial draft
for retry. Do not publish or modify a draft while the workflow runs. Gitea
+87 -8
View File
@@ -4,7 +4,7 @@ Status: design (2026-10-20); slices 1, 2 and 3 are implemented (section 13
says how slice 1 differs from this text, sections 14 and 15 what its reviews
changed, section 16 what slice 2 built, found and corrected, section 17 what
slice 3 moved, changed and ran, 17.7 the round after its review, which
brought the branch onto main `ad20979`, and 17.8 the round after the gate of the
brought the branch onto main `ad20979`, 17.9 the move of the pin to the tag v0.2.0, and 17.8 the round after the gate of the
merge; 17.6 has the complete edge list for the second half); section 10 has
the slices.
@@ -19,7 +19,7 @@ here; section 11 lists what it has to do.
Read for this design: `crates/voelin-core/src/link.rs`, `ts_link.rs`,
`voice.rs`, `book.rs`, `stream.rs`, `files.rs`, `session.rs` (its use of the
link), `tests/link_fake.rs`, `voelin-audio/src/packet.rs`; and in
VoelinProtocol (main at the pin of that round; moved to `c5bb6b9` by task 34)
VoelinProtocol (main at the pin of that round; moved by task 34, and since then to the tag `v0.2.0`, 17.9)
`crates/voelin-proto/src/link.rs`,
`media.rs` with `media/`, `test_util/` (FakeHost, FakeSession,
FakeConnector, FakeAccountAgent, the conformance suite),
@@ -1218,8 +1218,8 @@ second that works.
### 16.2 The conformance suite
**Through the registry.** `the_conformance_suite_passes_on_a_session_of_the_registry`
runs the 17 cases of the protocol's suite (still 17, in the same order, at
`c5bb6b9`) against the `FakeSession` that
runs the 17 cases of the protocol's suite (still 17, in the same order, at the
pin of task 34 and at the tag `v0.2.0`) against the `FakeSession` that
`Backends::connect(params, LocalCtx::standalone())` hands over: 17 of 17
pass, none is skipped. The registry adds nothing to a plain connector's
session (`host_uid` is the connector's, there is no stream port), so the
@@ -1737,8 +1737,9 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run.
- **The key store follows task 34 (`phase4/keystore-task34`).** Open question 10
of the accounts design (answered by the owner on 2026-10-24) made
`KeyStore::sign_out` keep every device key, and VoelinProtocol `main`
(`c5bb6b9`) has it. `SqliteKeyStore` runs that trait method, so the follow-up
`KeyStore::sign_out` keep every device key, and VoelinProtocol `main` at
the pin of that task (and every release from the tag `v0.2.0`) has it.
`SqliteKeyStore` runs that trait method, so the follow-up
that Phase 2 task 34 leaves to this repository ("Note for VoelinClient") is
the pin of the three protocol crates, the tests that asserted the deletion
of a key made for the account (now kept, unbound, byte for byte; only
@@ -1759,7 +1760,8 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run.
trait's provided `sign_out` lists the key twice in `SignOut.unbound` (once in
its loop over the identities bound to the account, once in the `Auto` branch),
which the tests of this repository do not mind (they use `contains`) and which
is a follow-up for the protocol repository.
is a follow-up for the protocol repository. (Closed in VoelinProtocol
`v0.2.0`: a key is listed once. 17.9 has the tests that now count it.)
- **The same leak in `voelin-store`, closed in `phase4/keystore-task34`.**
`Store::identity` and `Store::identities` read the stored JSON of a
TeamSpeak identity with `?`, so an `Error::Json` whose text is the
@@ -1835,7 +1837,7 @@ changes). `Cargo.lock`, `Cargo.toml`, `README.md`, `docs/ui.md`,
conflict: the lock resolves with `--locked`, and its difference to `main`'s is
the branch's alone (the edges of `voelin-core` to `voelin-identity` and
`voelin-proto`, the revision of the three protocol crates that the branch
pinned (since moved to `c5bb6b9` by task 34), and
pinned (since moved by task 34, and then to the tag `v0.2.0`, 17.9), and
`voelin-model` as a git package). `CHANGELOG.md` is `main`'s entry
(`voelin-ui-vm`); the branch adds none (17.1), and still needs none: nothing
of this round is visible to a user.
@@ -1960,3 +1962,80 @@ targets included.
| `RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p voelin-core --locked` | 1.94 and nightly: clean. |
| `Cargo.lock`, `THIRD_PARTY_NOTICES.md` | Unchanged: `git diff c60acf9 -- Cargo.lock Cargo.toml` is empty, so there was nothing to regenerate. |
| `scripts/it-smoke.sh ts3 ts6`, on `c60acf9` (before) and at the head (after) | The stack of `VoelinGateWay/dev/docker-compose.yml` as a compose project of its own (`voelin-seam-followups`), the state directory under the scratch directory. On a fresh stack each (`down -v`, `up -d` before each): both pass every per-server scenario of ts3 and ts6 (connect and tree, server and channel chat, voice tone, invisible presence, relay, gateway, history, pins and reactions, the engine's voice features, the TeamSpeak 6 streams), the TeamSpeak session module stage (12 passed, 2 ignored; 16.38 s before, 16.73 s after) and fail in the same place, the engine stage at `ts6_banners` (`live.rs:396`, 5 passed, 1 failed), the failure 17.5 and 17.7 record. Two more runs on the first stack, which was no longer fresh (before, then after), gave the same: the outputs have 100 lines each and differ only in ids, counters, tone ratios and the number of tests filtered out of the module stage (236 before, 240 after: this round's four unit tests). The very first run, on `c60acf9` on the first stack, stopped earlier, at the first gateway request of the admin identity of ts3 (`config_set` not answered, observe stayed `Connecting`); it did not repeat on the fresh stack at `c60acf9`, nor in any later run, and was not chased. |
### 17.9 The pin moves to the tag `v0.2.0` (`phase4/protocol-pin-v0.2.0`)
VoelinProtocol released `v0.2.0` on 2026-10-27 (the tag points at `a45c154`;
its `README.md`, "Releases", says how a consumer pins, and its `CHANGELOG.md`,
"For consumers", what a consumer at the pin of task 34 meets). This round, on
`phase4/protocol-pin-v0.2.0` from `0d32ac2`, moves the three entries of
`[workspace.dependencies]` (`voelin-identity`, `voelin-proto`, `voelin-model`)
from that rev to `tag = "v0.2.0"`, and the `voelin-model` of `spikes/gpui` with
them. The `mao-*` agents were not registered in the session, so a
general-purpose agent played `mao-implementer`, attempt 1. No history was
rewritten.
| Commit | What |
|---|---|
| `dccedf2` | `spikes/gpui/Cargo.lock` loses three dependency edges (tokio's `signal-hook-registry` and `tracing`, zbus's `tokio`) and nothing else. It was stale on `main` since `ed49c28` (`voelin-platform`: notify-rust's `z` instead of `z-with-tokio`, which updated the root lock and not this one): `cargo build --locked` in `spikes/gpui` failed there with "cannot update the lock file", before the pin was touched. Separate from the pin so that the pin's own diff to the lock is the three packages. |
| `6938dbe` | The pin. Both `Cargo.toml` files, both locks, the two tests of the sign-out, and the two strings that named the old rev. |
| the commit of this section | The CHANGELOG line, `docs/building.md`, `docs/ci.md`, `docs/architecture.md`, and the four sentences of this file that named the old rev (the rev is not written in the tree any more; it is in the history of `Cargo.toml`). |
**The lock.** `cargo update -p voelin-identity -p voelin-proto -p voelin-model`
also moved ten edges of the lock that have nothing to do with the protocol
(`windows-sys` 0.61.2 to 0.52.0, 0.48.0 and 0.45.0 in seven crates, `itertools`
0.14.0 to 0.11.0, `base64` 0.23.1 to 0.22.1, `getrandom` 0.4.3 to 0.3.4; the
message of `6938dbe` says eleven, ten is right). The manifests of the three
crates are the same at both revisions but for `voelin-model`'s version (0.1.0
to 0.2.0), so the lock was edited by hand instead: the `source` of the three
packages and that one version, in each of the two locks, and
`cargo metadata --locked` accepts both. Each lock has one revision of each
crate, and `cargo tree -d` lists no `voelin-*` package twice, in either
workspace. The lock's set of third-party packages is the same (only the three
protocol packages changed, and `voelin-model`'s version), and
`THIRD_PARTY_NOTICES.md` lists third-party packages, so
`scripts/notices.sh --check` is clean without a regeneration.
**What "For consumers" meant here.**
- `KeyStore::sign_out` lists a device key once. The client never had a test
that failed on the double listing: `a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row`
(the row of the device key carries a device-only binding, the one case in
which the trait listed the key twice, see 17.6) asked `contains`. It counts
now: one entry in `unbound` and none in `removed`. A new test,
`a_device_key_that_carries_a_binding_is_listed_once_as_deleted_when_it_is_forgotten`,
does the same for `Forget` (one entry in `removed`, none in `unbound`; the
key used to be in both lists). Both fail with the pin at the old rev (checked
by putting `Cargo.toml` and `Cargo.lock` of `main` back for the run: the
first sees the key twice in `unbound`, the second once in each list) and pass
at the tag. The other sign-out tests passed unchanged.
- `Debug` of `Hello`, `Welcome`, `Server`, `Channel`, `Member` and the other
messages that `voelin_proto::redact::REDACTED` lists prints `<redacted>` for
their secrets. No code or test of the client formats one of those messages
with `{:?}` and looks at the text: the only `Debug` text a test inspects is
that of the engine's events in
`a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`, which
looks for pieces of a TeamSpeak key. Nothing to adapt; the full test run
below is the evidence.
- Every crate is at 0.2.0, `voelin-model` from 0.1.0: visible in the lock only.
The conformance suite still has 17 cases (`fake_tests.rs` and `live_tests.rs`
name the tag where they named the rev).
- The rest of the list is additive and in crates the client does not use.
**What did not change.** The deploy key, `.gitea/known_hosts`, the CI step that
runs `git ls-remote` on the repository, and `deny.toml` (`allow-git` is the
URL): Cargo fetches the tag over the same SSH access as it fetched the commit
(`git ls-remote` shows the tag as an annotated one, `v0.2.0^{}` being
`a45c154`).
**What ran.** The toolchain of `rust-toolchain.toml` (1.95.0, from the pinned
fenix of `spikes/gpui/shell.sh`), on a machine at a load average of about 40.
| Check | Result |
|---|---|
| `cargo fmt $(scripts/own-crates.sh) -- --check` | clean |
| `cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings` | clean |
| `cargo test --workspace --locked --no-fail-fast`, under Xvfb with `VOELIN_X11_TEST_DISPLAY` | 1,293 passed, 0 failed, 21 ignored. `voelin-store`: 31 unit tests, `identity_text` 4, `keystore` 57 (56 and the new one); `voelin-core`: 273 and 2 ignored, `session_fake` 20 and 2 ignored, `session_backends` 2; the registry's conformance suite passes 17 of 17 |
| `cargo deny --locked --workspace check` (cargo-deny 0.20.2) | advisories, bans, licenses and sources ok; the two warnings, yanked `crypto-bigint` and `clipboard-win`, are of packages this change does not touch |
| `scripts/notices.sh --check` | clean, no regeneration |
| `spikes/gpui`: `cargo build --locked` and `cargo clippy --locked --all-targets -- -D warnings` (`shell.sh`, 1.95) | both clean |
+1226 -83
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+3 -1
View File
@@ -10,7 +10,9 @@
# The workspace depends on the private VoelinProtocol repository, which the
# build fetches over SSH with your ssh-agent (`docker build --ssh default`):
# the agent must hold a key that can read it (docs/building.md, "Depending on
# VoelinProtocol"). The key stays in the agent, never in the image.
# VoelinProtocol"). The key stays in the agent, never in the image, and only the
# Dockerfile's `cargo fetch` step is given the agent: the build after it is
# offline.
#
# Behind an HTTPS proxy, HTTPS_PROXY/HTTP_PROXY/NO_PROXY are passed on to the
# build; a proxy on this machine's loopback is reached with host networking.
+8 -3
View File
@@ -12,7 +12,10 @@
# GPUI_SHOT_HEADLESS=1 spikes/gpui/shell.sh spikes/gpui/headless.sh -- \
# scripts/gpui-shot.sh docs/ui/gpui-swatch-dark.png swatch 1440x960
#
# Needs xdotool, xwd (x11-apps) and ImageMagick.
# Needs xdotool, xwd (x11-apps) and ImageMagick. The screen must be larger
# than the window (headless.sh's is 3840x2160; xvfb-run gets twice the window):
# on one as large as the window the window manager fits the window and its
# frame into the screen, and the picture is smaller than the size asked for.
#
# Wayland is taken out of the environment (GPUI prefers it, so the window
# would open on the desktop), and so are the desktop's session bus and its
@@ -25,7 +28,8 @@
#
# VOELIN_BIN: the binary (default target/release/voelin-gpui, else
# target/debug); DELAY: seconds the window is shown before the picture
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE, VOELIN_DEMO_UI (the sample
# servers: a picture of the shell with one on screen) and the other switches of
# `src/dev.rs` are passed on as set.
set -eu
out=${1:?usage: gpui-shot.sh <out.png> [<VOELIN_OPEN> [<width>x<height>]]}
@@ -70,7 +74,8 @@ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS
"$bin" >"$work/app.log" 2>&1 &
pid=$!
i=0
until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do
# The title is the app's name, and ` - <server>` once a server is on screen.
until win=$(xdotool search --name '^Voelin( - |$)' 2>/dev/null | head -1) && [ -n "$win" ]; do
i=$((i + 1))
kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
[ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
+4 -7
View File
@@ -8959,10 +8959,8 @@ dependencies = [
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -9725,7 +9723,7 @@ dependencies = [
[[package]]
name = "voelin-identity"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"aws-lc-rs",
"base64 0.23.1",
@@ -9768,8 +9766,8 @@ dependencies = [
[[package]]
name = "voelin-model"
version = "0.1.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"prost",
"serde",
@@ -9804,7 +9802,7 @@ dependencies = [
[[package]]
name = "voelin-proto"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
dependencies = [
"bytes",
"prost",
@@ -11304,7 +11302,6 @@ dependencies = [
"rustix",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
+2 -2
View File
@@ -28,8 +28,8 @@ voelin-core = { path = "../../crates/voelin-core", default-features = false, fea
voelin-media = { path = "../../crates/voelin-media", default-features = false, features = ["vpx", "openh264", "ffmpeg", "av1", "x11"] }
voelin-platform = { path = "../../crates/voelin-platform", default-features = false, features = ["x11"] }
voelin-ui-vm = { path = "../../crates/voelin-ui-vm" }
# The revision the root workspace pins (chat messages for voelin-ui-vm).
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
# The tag the root workspace pins (chat messages for voelin-ui-vm).
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# Logs of GPUI (the adapter it picked) and of the client's crates.
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
log = "0.4"