34 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
28 changed files with 4579 additions and 283 deletions

No files matched your search

+23 -2
View File
@@ -45,11 +45,32 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
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 redraws the members panel and nothing else of the window (the
tree does not mark who talks), and the pictures the engine writes again show
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.
+3 -2
View File
@@ -21,8 +21,9 @@ 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).
+664 -11
View File
@@ -42,7 +42,7 @@ use gpui_kit::{ClipboardItem, Context};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tracing::{debug, warn};
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_core::{Command, Engine, Event, VoiceState};
use voelin_core::{Command, Engine, Event, TransmitMode, VoiceState};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store};
use voelin_ui_vm::bridge::{BookmarkForm, ChatLine};
use voelin_ui_vm::events;
@@ -52,13 +52,14 @@ use voelin_ui_vm::servers::logic;
use voelin_ui_vm::servers::sequence::{self, Backing};
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ThemeChoice, TreeStates, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME,
UI_TREE, UI_WINDOW, WindowState,
UI_TREE, UI_VOICE_COMPACT, UI_WINDOW, UiSettings, WindowState,
};
use voelin_ui_vm::social::logic::Social;
use voelin_ui_vm::tree::ChannelId;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::hotkey::GlobalPtt;
use crate::meter::Counters;
use crate::pictures;
use crate::signals::{Area, Signals};
@@ -181,6 +182,15 @@ pub fn appearance(prefs: &Settings, switches: &Switches) -> (Choice, f32) {
(choice, switches.font_scale.unwrap_or_else(|| prefs.get(&UI_FONT_SCALE)))
}
/// The key the global push-to-talk hotkey is registered with at start: the
/// settings' (`global_ptt`, `ptt_key`), with an engine to send the presses to
/// and not with the sample servers, which send nothing (and whose run must not
/// ask the desktop for a shortcut).
fn hotkey_wanted(settings: &UiSettings, demo_ui: bool, has_engine: bool) -> Option<String> {
let key = settings.ptt_key.trim();
(settings.global_ptt && !demo_ui && has_engine && !key.is_empty()).then(|| key.to_owned())
}
/// Where the window's place is kept between ticks.
#[derive(Debug, Default)]
struct WindowKeeper {
@@ -251,6 +261,21 @@ pub struct AppState {
tree_states: TreeStates,
/// The servers whose remembered folds are in their sessions.
tree_restored: HashSet<i64>,
/// The voice page shows the smaller stage (`ui.voice_compact`, or the
/// development switch that asks for it).
voice_compact: bool,
/// The global push-to-talk hotkey's task, once one was wanted.
ptt: Option<GlobalPtt>,
/// How the hotkey stands, as its task last said.
ptt_status: String,
/// The session the hotkey turned transmit on for and has not turned off.
hotkey_held: Option<i64>,
/// The session the window's hold-to-talk button turned transmit on for and
/// has not turned off.
button_held: Option<i64>,
/// The window is closing: ignore late push-to-talk presses (such as one
/// already queued from the hotkey task through [`Later`]).
shutting_down: bool,
/// Where the sample servers' pictures were written (`VOELIN_DEMO_UI`),
/// removed with the state.
demo_dir: Option<PathBuf>,
@@ -364,17 +389,28 @@ impl AppState {
password: None,
tree_states,
tree_restored: HashSet::new(),
voice_compact: false,
ptt: None,
ptt_status: String::new(),
hotkey_held: None,
button_held: None,
shutting_down: false,
demo_dir: None,
later: Later(later),
#[cfg(test)]
sent: Default::default(),
};
state.window.opening_reports = if state.wants_maximized() { OPENING_REPORTS } else { 0 };
state.voice_compact =
state.switches.voice_compact || state.backend.prefs.get(&UI_VOICE_COMPACT);
if state.switches.demo_ui {
state.load_demo();
} else if let Some(id) = state.vm.current {
state.restore_tree(id);
}
if state.switches.voice {
state.transition(cx, |state, cx| logic::show_voice_view(state, cx, true));
}
state
}
@@ -487,10 +523,20 @@ impl AppState {
) {
let mut refresh = Refresh::default();
for event in events {
let was_connected = match &event {
Event::State { session, .. } => {
let id = *session as i64;
self.is_voice_connected(id).then_some(id)
}
_ => None,
};
self.events_handled += 1;
self.counters.engine_events.incr();
let update = self.handle(event);
refresh.merge(self.perform(update, cx));
if let Some(id) = was_connected {
self.release_lost_transmit(id);
}
}
self.counters.connections.set(self.connections() as u64);
// Each area once for the whole batch.
@@ -498,6 +544,64 @@ impl AppState {
cx.notify();
}
/// Whether `id` currently has voice connected.
fn is_voice_connected(&self, id: i64) -> bool {
self.vm.sessions.get(&id).is_some_and(|view| view.state.voice == VoiceState::Connected)
}
/// The release guard of Hold to talk and the global hotkey, for voice that
/// dropped: checked per event inside [`Self::handle_events`] so a drop and
/// reconnect in one batch cannot mask it. When `id` leaves `Connected`, any
/// active button or hotkey hold on it ends, and the session is told
/// `SetTransmitting(false)` once if either was held or the engine still
/// reports it transmitting.
fn release_lost_transmit(&mut self, id: i64) {
let Some(view) = self.vm.sessions.get(&id) else { return };
if view.state.voice != VoiceState::Connected {
let mut was_held = false;
if self.hotkey_held == Some(id) {
self.hotkey_held = None;
was_held = true;
}
if self.button_held == Some(id) {
self.button_held = None;
was_held = true;
}
if was_held || view.state.transmitting {
self.send(Command::SetTransmitting { session: id as u64, on: false });
}
}
}
/// Which session the window's hold-to-talk button is holding, if any.
pub(crate) fn button_held(&self) -> Option<i64> {
self.button_held
}
/// Stop transmitting in `id` once neither the window's button nor the global
/// hotkey holds it.
fn stop_transmitting_if_unheld(&self, id: i64) {
if self.hotkey_held != Some(id) && self.button_held != Some(id) {
self.send(Command::SetTransmitting { session: id as u64, on: false });
}
}
/// Release the window button's hold, stopping transmit if the global hotkey
/// does not also hold the same session. Returns whether a hold was active.
fn release_button_hold(&mut self) -> bool {
let Some(id) = self.button_held.take() else { return false };
self.stop_transmitting_if_unheld(id);
true
}
/// Release the global hotkey's hold, stopping transmit if the window button
/// does not also hold the same session. Returns whether a hold was active.
fn release_hotkey_hold(&mut self) -> bool {
let Some(id) = self.hotkey_held.take() else { return false };
self.stop_transmitting_if_unheld(id);
true
}
/// One engine event ([`AppState::handle_events`]).
pub fn handle_event(&mut self, event: Event, cx: &mut Context<Self>) {
self.handle_events([event], cx);
@@ -535,6 +639,13 @@ impl AppState {
let mut transition = Cx::new(&host);
let result = f(&mut self.vm, &mut transition, &backing);
let update = transition.update;
// Whichever server the transition left on screen (a removal shows the
// first, a save the saved one, a connect the one it connects) has its
// remembered folds before the tree is built from it, and before the
// next fold writes them over.
if let Some(id) = self.vm.current {
self.restore_tree(id);
}
let refresh = self.perform(update, cx);
self.signals.raise(&refresh, cx);
result
@@ -559,6 +670,12 @@ impl AppState {
std::mem::take(&mut *self.sent.borrow_mut())
}
/// The folder the sample pictures were written to, while there is one.
#[cfg(test)]
pub(crate) fn demo_dir(&self) -> Option<&PathBuf> {
self.demo_dir.as_ref()
}
/// A command for the session on screen.
fn command(&self, f: impl FnOnce(u64) -> Command) {
if let Some(id) = self.vm.current {
@@ -578,7 +695,7 @@ impl AppState {
/// ([`Signals::raise`]) once for as many updates as it has handled.
fn perform(&mut self, update: Update, cx: &mut Context<Self>) -> Refresh {
let Update {
refresh,
mut refresh,
status,
commands,
persist,
@@ -614,7 +731,7 @@ impl AppState {
}
// What the front end keeps itself comes before the drawing.
if let Some(Event::SettingChanged { key }) = rest {
self.setting_changed(&key, cx);
refresh.merge(self.setting_changed(&key, cx));
}
refresh
}
@@ -658,16 +775,36 @@ impl AppState {
}
}
/// A setting changed, maybe elsewhere (a command, another window): take
/// the values the window keeps copies of. Today that is what the theme
/// follows; the development switches keep what they set.
fn setting_changed(&mut self, key: &str, cx: &mut Context<Self>) {
/// A setting changed, maybe elsewhere (a command, another window, the
/// config file): take the values the window keeps copies of, and say which
/// areas show them. What the theme follows is applied (the development
/// switches keep what they set); the audio settings (the transmit mode
/// decides whether the voice card has Hold to talk), the clients' volumes
/// (the tree and the card show who is muted) and the smaller stage of the
/// voice page are read again, as the Slint front end's `setting_changed`
/// does.
fn setting_changed(&mut self, key: &str, cx: &mut Context<Self>) -> Refresh {
let mut refresh = Refresh::default();
if key == UI_THEME.name() || key == UI_FONT_SCALE.name() {
let (choice, scale) = appearance(&self.backend.prefs, &self.switches);
let appearance = cx.window_appearance();
VoelinTheme::set_choice(cx, choice, appearance);
VoelinTheme::set_font_scale(cx, scale);
} else if key == AUDIO.name() && !self.vm.audio_dirty {
self.vm.audio = self.backend.prefs.get(&AUDIO);
if self.vm.audio.transmit != TransmitMode::PushToTalk {
self.release_button_hold();
}
refresh.toolbar = true;
} else if key == CLIENT_PLAYBACK.name() {
self.vm.playback = self.backend.prefs.get(&CLIENT_PLAYBACK);
refresh.tree = true;
refresh.member_card = true;
} else if key == UI_VOICE_COMPACT.name() && !self.switches.demo_ui {
// The stage's own observer (MainView's) hears the root notify.
self.voice_compact = self.backend.prefs.get(&UI_VOICE_COMPACT);
}
refresh
}
/// The once-a-second work: what the Slint front end's `App::tick` will be
@@ -788,10 +925,12 @@ impl AppState {
/// Show a server, and observe it.
pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) {
self.restore_tree(id);
self.transition_with(cx, |state, cx, backing| {
sequence::select_server(state, cx, backing, id)
});
if self.button_held.is_some_and(|held| Some(held) != self.vm.current) {
self.release_button_hold();
}
cx.notify();
}
@@ -840,10 +979,139 @@ impl AppState {
/// Start or stop transmitting (the window's hold-to-talk button).
pub fn push_to_talk(&mut self, on: bool, cx: &mut Context<Self>) {
self.command(|session| Command::SetTransmitting { session, on });
if on {
if self.shutting_down {
return;
}
let Some(id) = self.vm.current else { return };
if let Some(old) = self.button_held.replace(id) {
if old == id {
return;
}
self.stop_transmitting_if_unheld(old);
}
if self.hotkey_held != Some(id) {
self.send(Command::SetTransmitting { session: id as u64, on: true });
}
cx.notify();
} else if self.release_button_hold() {
cx.notify();
}
}
/// The voice channel page on or off (`show_voice_view` of
/// `bind/servers.rs`, through [`logic::show_voice_view`]): the channel's
/// chat is the one shown, and the people of our channel lead the members
/// panel while the page is.
pub fn show_voice_view(&mut self, on: bool, cx: &mut Context<Self>) {
self.transition(cx, |state, cx| logic::show_voice_view(state, cx, on));
cx.notify();
}
/// Whether the main area is the voice page: it was asked for, and voice is
/// connected on the server on screen (the Slint front end's
/// `Nav.voice-view && Bridge.voice-connected`; the page is asked for again
/// by a reconnect, as there).
pub fn voice_page_shown(&self) -> bool {
self.vm.voice_view
&& self
.vm
.current
.and_then(|id| self.vm.sessions.get(&id))
.is_some_and(|view| view.state.voice == VoiceState::Connected)
}
/// Whether the voice page is on its smaller stage by choice (a window under
/// 800 pixels tall has it whatever this says).
pub fn voice_compact(&self) -> bool {
self.voice_compact
}
/// The voice page's Smaller stage / Larger stage: kept in `ui.voice_compact`
/// (nothing is kept with the sample servers).
pub fn toggle_voice_compact(&mut self, cx: &mut Context<Self>) {
self.voice_compact = !self.voice_compact;
if !self.switches.demo_ui
&& let Err(e) = self.backend.prefs.set(&UI_VOICE_COMPACT, self.voice_compact)
{
warn!(%e, "could not store the stage size");
}
cx.notify();
}
/// Start the global push-to-talk hotkey as the settings say (`global_ptt`,
/// `ptt_key`) when there is an engine and no sample servers. [`crate::run`]
/// calls it once the window is open; the state does not start it by itself,
/// so that a test of the state with a real engine never asks the desktop for
/// a shortcut.
pub fn start_global_ptt(&mut self) {
let key = hotkey_wanted(&self.vm.settings, self.switches.demo_ui, self.engine.is_some());
self.set_global_ptt(key);
}
/// Register the global push-to-talk hotkey with `key` in place of the one
/// registered, or none: the task starts on the engine's runtime with the
/// first key ([`crate::hotkey`]; the settings page of its slice calls this
/// when the choice changes). Nothing without an engine.
pub fn set_global_ptt(&mut self, key: Option<String>) {
if self.ptt.is_none() && key.is_some() {
let Some(engine) = &self.engine else { return };
let (status, held) = (self.later(), self.later());
self.ptt = Some(GlobalPtt::start(
engine.runtime(),
move |line| {
status.run(move |app, _| app.ptt_status_changed(line));
},
move |on| {
held.run(move |app, cx| app.hotkey_transmit(on, cx));
},
));
}
if let Some(ptt) = &self.ptt {
ptt.set(key);
}
}
/// How the hotkey stands, as its task last said ("Active: Ctrl+Shift+T
/// (X11)", why it could not be registered); empty until it said.
pub fn ptt_status(&self) -> &str {
&self.ptt_status
}
/// The hotkey task's word on how the key stands.
fn ptt_status_changed(&mut self, line: String) {
tracing::info!(target: "voelin_gpui::hotkey", "{line}");
self.ptt_status = line;
}
/// The global push-to-talk key went down or up. It transmits into the
/// session on screen while that has voice, and the release ends that same
/// session's transmit, whichever is on screen by then (a server chosen
/// while the key is down). A repeated press on another connected server
/// ends the first session's transmit before starting the new one. A press
/// without voice, or during shutdown, does nothing.
pub fn hotkey_transmit(&mut self, on: bool, cx: &mut Context<Self>) {
if on {
if self.shutting_down {
return;
}
let connected = self.vm.current.filter(|&id| self.is_voice_connected(id));
let Some(id) = connected else { return };
if let Some(old) = self.hotkey_held.replace(id) {
if old == id {
return;
}
self.stop_transmitting_if_unheld(old);
}
if self.button_held != Some(id) {
self.send(Command::SetTransmitting { session: id as u64, on: true });
}
cx.notify();
} else if self.release_hotkey_hold() {
cx.notify();
}
}
/// A link to the voice channel we are in, copied to the clipboard with a
/// note in the status line; the reason in the status line without one.
pub fn invite(&mut self, cx: &mut Context<Self>) -> Option<String> {
@@ -899,6 +1167,41 @@ impl AppState {
self.password.as_ref()
}
/// The volume of a client of the server on screen, in percent (the member
/// card's slider): the engine plays them so, and the choice is kept by their
/// unique id.
pub fn set_member_volume(&mut self, client: u16, percent: f32, cx: &mut Context<Self>) {
self.set_client_audio(client, |form| form.volume = percent, cx);
}
/// Play a client of the server on screen or not (the member card's Mute for
/// me), kept by their unique id.
pub fn set_member_muted(&mut self, client: u16, muted: bool, cx: &mut Context<Self>) {
self.set_client_audio(client, |form| form.muted = muted, cx);
}
/// What the volume dialog of the Slint front end does, without the dialog:
/// the client's volume and mute as the vm has them, changed by `change`, and
/// handed back to `client_playback_changed` (the engine's commands, what is
/// kept, the tree's marks).
fn set_client_audio(
&mut self,
client: u16,
change: impl FnOnce(&mut voelin_ui_vm::bridge::ClientAudio),
cx: &mut Context<Self>,
) {
self.transition(cx, |state, cx| {
let Some(mut form) = voelin_ui_vm::settings_page::logic::open_client(state, client)
else {
return;
};
change(&mut form);
voelin_ui_vm::settings_page::logic::client_playback_changed(state, cx, &form);
state.playback_dialog = None;
});
cx.notify();
}
/// Fold or unfold a channel of the tree (`toggle_collapse`), and remember
/// it for the server ([`UI_TREE`]).
pub fn toggle_collapse(&mut self, channel: ChannelId, cx: &mut Context<Self>) {
@@ -936,7 +1239,10 @@ impl AppState {
self.transition(cx, |state, cx| logic::open_member(state, cx, client));
}
/// Put the folds a server's tree remembered into its session, once.
/// Put the folds a server's tree remembered into its session, once: every
/// transition that can change the server on screen
/// ([`AppState::transition_with`]) and the start do it for the one that is
/// shown.
fn restore_tree(&mut self, id: i64) {
if self.switches.demo_ui || !self.tree_restored.insert(id) {
return;
@@ -1038,6 +1344,12 @@ impl AppState {
cx.notify();
return;
}
if self.hotkey_held == Some(id) {
self.hotkey_held = None;
}
if self.button_held == Some(id) {
self.button_held = None;
}
self.transition_with(cx, |state, cx, backing| {
sequence::delete_bookmark(state, cx, backing, id)
});
@@ -1085,6 +1397,10 @@ impl AppState {
/// the engine time to act on them before the runtime goes (none without an
/// engine, none in demo mode).
pub fn shutdown(&mut self, cx: &mut Context<Self>) -> usize {
self.shutting_down = true;
self.ptt = None;
self.release_button_hold();
self.release_hotkey_hold();
self.flush_window();
// The sample pictures are not needed once the window is closing.
if let Some(folder) = self.demo_dir.take() {
@@ -1124,6 +1440,7 @@ mod tests {
use voelin_core::{Backends, Command, Event, ObserveState, SessionState, VoiceState};
use voelin_store::MemorySecrets;
use voelin_ui_vm::dev::logic as sample;
use voelin_ui_vm::settings::TreeState;
use super::*;
use crate::backend::testing::TempDir;
@@ -1338,6 +1655,10 @@ mod tests {
switches: Switches::default(),
};
let app = cx.new(|cx| AppState::new(setup, cx));
assert!(
app.read_with(cx, |app, _| app.ptt.is_none()),
"the state starts no hotkey by itself: run does, with the window"
);
assert_eq!(app.update(cx, |app, cx| app.shutdown(cx)), 0, "no session open yet");
tx.send(voice(VoiceState::Connected)).unwrap();
cx.run_until_parked();
@@ -1487,6 +1808,68 @@ mod tests {
});
}
/// Two saved servers, the second with a fold remembered in `ui.tree`.
fn two_servers_the_second_with_a_fold() -> (Backend, [i64; 2]) {
let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
let ids: Vec<i64> = backend.store.bookmarks().unwrap().iter().map(|b| b.id).collect();
let fold = TreeState { collapsed: vec![7], selected: None };
backend.prefs.set(&UI_TREE, TreeStates::from([(ids[1].to_string(), fold)])).unwrap();
(backend, [ids[0], ids[1]])
}
/// What `ui.tree` holds of a server.
fn remembered(app: &Entity<AppState>, id: i64, cx: &mut TestAppContext) -> Option<TreeState> {
app.read_with(cx, |app, _| app.backend().prefs.get(&UI_TREE).remove(&id.to_string()))
}
/// The server that comes on screen when the one shown is removed has the
/// folds `ui.tree` remembers for it, and the next fold adds to them where
/// it used to write over them (the session had none, so the stored ones
/// were replaced by the one just made).
#[gpui::test]
fn the_server_shown_after_a_removal_has_its_remembered_folds(cx: &mut TestAppContext) {
let (backend, [first, second]) = two_servers_the_second_with_a_fold();
let (app, _, _) = entity_over(cx, backend, Switches::default());
app.read_with(cx, |app, _| assert_eq!(app.vm.current, Some(first)));
app.update(cx, |app, cx| app.delete_bookmark(first, cx));
app.read_with(cx, |app, _| {
assert_eq!(app.vm.current, Some(second));
assert_eq!(app.vm.sessions[&second].collapsed, HashSet::from([7]));
});
app.update(cx, |app, cx| app.toggle_collapse(3, cx));
assert_eq!(
remembered(&app, second, cx),
Some(TreeState { collapsed: vec![3, 7], selected: None }),
"the fold made now is added to the one remembered"
);
}
/// The same for a server a save brings on screen: editing another server
/// shows it.
#[gpui::test]
fn a_server_a_save_shows_has_its_remembered_folds(cx: &mut TestAppContext) {
let (backend, [first, second]) = two_servers_the_second_with_a_fold();
let (app, _, _) = entity_over(cx, backend, Switches::default());
app.read_with(cx, |app, _| {
assert_eq!(app.vm.current, Some(first));
assert!(!app.vm.sessions.contains_key(&second), "not shown yet, not put back yet");
});
let form = app.read_with(cx, |app, _| app.bookmark_form(second));
app.update(cx, |app, cx| app.save_bookmark(&form, cx));
app.read_with(cx, |app, _| {
assert_eq!(app.vm.current, Some(second));
assert_eq!(app.vm.sessions[&second].collapsed, HashSet::from([7]));
});
app.update(cx, |app, cx| app.toggle_collapse(3, cx));
assert_eq!(
remembered(&app, second, cx),
Some(TreeState { collapsed: vec![3, 7], selected: None })
);
}
#[gpui::test]
fn a_removed_server_goes_from_the_rail_and_the_store_and_the_first_is_shown(
cx: &mut TestAppContext,
@@ -1659,6 +2042,276 @@ mod tests {
assert!(empty.read_with(cx, |app, _| app.take_sent()).is_empty(), "no session on screen");
}
/// The global push-to-talk key is registered at start with the settings'
/// key when there is an engine to send to, not with the sample servers.
#[test]
fn the_hotkey_is_wanted_with_an_engine_outside_the_sample_servers() {
let settings = |global_ptt, key: &str| UiSettings {
global_ptt,
ptt_key: key.into(),
..Default::default()
};
let on = settings(true, " Ctrl+Shift+T ");
assert_eq!(hotkey_wanted(&on, false, true).as_deref(), Some("Ctrl+Shift+T"));
assert_eq!(hotkey_wanted(&on, true, true), None, "the sample servers ask for nothing");
assert_eq!(hotkey_wanted(&on, false, false), None, "no engine: nowhere to send");
assert_eq!(hotkey_wanted(&settings(false, "F9"), false, true), None, "switched off");
assert_eq!(hotkey_wanted(&settings(true, " "), false, true), None, "no key");
assert_eq!(
hotkey_wanted(&UiSettings::default(), false, true).as_deref(),
Some("Ctrl+Shift+T"),
"the default is on, as in the Slint front end"
);
}
/// What the commands sent since the last call say about transmitting: the
/// session and whether it was turned on.
fn transmits(app: &Entity<AppState>, cx: &mut TestAppContext) -> Vec<(u64, bool)> {
app.read_with(cx, |app, _| app.take_sent())
.into_iter()
.filter_map(|command| match command {
Command::SetTransmitting { session, on } => Some((session, on)),
_ => None,
})
.collect()
}
/// The global key transmits into the session on screen while it has voice,
/// and its release ends that session's transmit, whichever is on screen by
/// then; a press without voice, or a second press, does nothing.
#[gpui::test]
fn the_hotkey_transmits_into_the_session_that_has_voice_and_its_release_ends_it(
cx: &mut TestAppContext,
) {
let (app, tx, _) = entity_over(
cx,
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
Switches::default(),
);
let [first, second] =
app.read_with(cx, |app, _| [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id]);
let hotkey = |app: &Entity<AppState>, cx: &mut TestAppContext, on| {
app.update(cx, |app, cx| app.hotkey_transmit(on, cx))
};
hotkey(&app, cx, true);
assert_eq!(transmits(&app, cx), [], "no voice, no transmit");
hotkey(&app, cx, false);
assert_eq!(transmits(&app, cx), [], "and nothing to release");
tx.send(Event::State {
session: first as u64,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
})
.unwrap();
cx.run_until_parked();
hotkey(&app, cx, true);
hotkey(&app, cx, true);
assert_eq!(transmits(&app, cx), [(first as u64, true)], "once");
// Another server is shown while the key is down: the release still ends
// the transmit of the one it began in.
app.update(cx, |app, cx| app.select_server(second, cx));
app.read_with(cx, |app, _| assert_eq!(app.vm.current, Some(second)));
hotkey(&app, cx, false);
assert_eq!(transmits(&app, cx), [(first as u64, false)]);
hotkey(&app, cx, false);
assert_eq!(transmits(&app, cx), [], "released once");
}
/// The hotkey task runs on the engine's runtime and hands each press and
/// release to GPUI's thread through `Later`.
#[gpui::test]
fn the_hotkey_tasks_thread_reaches_the_entity_through_later(cx: &mut TestAppContext) {
let (app, _, _) =
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = app.update(cx, |app, _| {
let id = app.vm.bookmarks[0].id;
app.vm.sessions.entry(id).or_default().state.voice = VoiceState::Connected;
id as u64
});
let later = app.read_with(cx, |app, _| app.later());
let queued = std::thread::spawn(move || later.run(|app, cx| app.hotkey_transmit(true, cx)))
.join()
.unwrap();
assert!(queued);
cx.run_until_parked();
assert_eq!(transmits(&app, cx), [(id, true)]);
}
/// The voice that drops under a held key ends the hold: the session is told
/// once (the release guard), and the key's own release has nothing left to
/// end.
#[gpui::test]
fn voice_that_drops_under_the_hotkey_ends_its_hold(cx: &mut TestAppContext) {
let (app, tx, _) =
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64;
let state = |voice, transmitting| Event::State {
session: id,
state: SessionState { voice, transmitting, ..Default::default() },
};
tx.send(state(VoiceState::Connected, false)).unwrap();
cx.run_until_parked();
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
tx.send(state(VoiceState::Connected, true)).unwrap();
cx.run_until_parked();
assert_eq!(transmits(&app, cx), [(id, true)]);
tx.send(state(VoiceState::Disconnected, true)).unwrap();
cx.run_until_parked();
assert_eq!(transmits(&app, cx), [(id, false)], "told once");
app.update(cx, |app, cx| app.hotkey_transmit(false, cx));
assert_eq!(transmits(&app, cx), [], "the release has nothing to end");
}
/// A second hotkey press without a release between them, after switching to
/// another connected server (a portal that repeats `Activated`), ends the
/// first session's transmit before starting the new one.
#[gpui::test]
fn a_second_hotkey_press_on_another_server_releases_the_first(cx: &mut TestAppContext) {
let (app, tx, _) = entity_over(
cx,
backend_with(&[
("Nightfall", "ts.example"),
("Lounge", "lounge.example"),
("Offline", "off.example"),
]),
Switches::default(),
);
let [first, second, third] = app.read_with(cx, |app, _| {
[app.vm.bookmarks[0].id, app.vm.bookmarks[1].id, app.vm.bookmarks[2].id]
});
for id in [first, second] {
tx.send(Event::State {
session: id as u64,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
})
.unwrap();
}
cx.run_until_parked();
transmits(&app, cx);
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
app.update(cx, |app, cx| app.select_server(second, cx));
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
app.update(cx, |app, cx| app.hotkey_transmit(false, cx));
assert_eq!(
transmits(&app, cx),
[
(first as u64, true),
(first as u64, false),
(second as u64, true),
(second as u64, false)
],
"switching connected servers under repeated Activated stops the old session first"
);
// Switching to an offline server and getting a repeated press leaves the
// active hold intact so the real release still ends it.
app.update(cx, |app, cx| app.select_server(first, cx));
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
app.update(cx, |app, cx| app.select_server(third, cx));
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
app.update(cx, |app, cx| app.hotkey_transmit(false, cx));
assert_eq!(transmits(&app, cx), [(first as u64, true), (first as u64, false)]);
}
/// Deleting a bookmarked server clears any button or hotkey hold on it so a
/// subsequent release does not send a stale command to the closed session.
#[gpui::test]
fn removing_a_server_clears_active_transmit_holds(cx: &mut TestAppContext) {
let (app, tx, _) = entity_over(
cx,
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
Switches::default(),
);
let [first, second] =
app.read_with(cx, |app, _| [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id]);
for id in [first, second] {
tx.send(Event::State {
session: id as u64,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
})
.unwrap();
}
cx.run_until_parked();
transmits(&app, cx);
app.update(cx, |app, cx| {
app.hotkey_transmit(true, cx);
app.push_to_talk(true, cx);
});
assert_eq!(transmits(&app, cx), [(first as u64, true)]);
app.update(cx, |app, cx| app.delete_bookmark(first, cx));
let sent = app.read_with(cx, |app, _| app.take_sent());
assert!(
sent.iter().any(
|c| matches!(c, Command::CloseSession { session } if *session == first as u64)
),
"{sent:?}"
);
app.update(cx, |app, cx| {
app.hotkey_transmit(false, cx);
app.push_to_talk(false, cx);
});
assert_eq!(transmits(&app, cx), [], "no stale release to the deleted session");
app.update(cx, |app, cx| {
app.hotkey_transmit(true, cx);
app.hotkey_transmit(false, cx);
});
assert_eq!(transmits(&app, cx), [(second as u64, true), (second as u64, false)]);
}
/// Closing the window releases any active hotkey or button hold and ignores
/// late presses queued through `Later` after shutdown.
#[gpui::test]
fn closing_releases_a_held_transmit_and_ignores_late_presses(cx: &mut TestAppContext) {
// Hotkey held during shutdown + late release/press queued on `Later`.
let (app, tx, _) =
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64;
tx.send(Event::State {
session: id,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
})
.unwrap();
cx.run_until_parked();
transmits(&app, cx);
app.update(cx, |app, cx| app.hotkey_transmit(true, cx));
assert_eq!(transmits(&app, cx), [(id, true)]);
app.update(cx, |app, cx| app.shutdown(cx));
assert_eq!(transmits(&app, cx), [(id, false)], "shutdown releases the held key");
let later = app.read_with(cx, |app, _| app.later());
assert!(later.run(|app, cx| {
app.hotkey_transmit(false, cx);
app.hotkey_transmit(true, cx);
app.push_to_talk(true, cx);
}));
cx.run_until_parked();
assert_eq!(transmits(&app, cx), [], "late presses after shutdown are ignored");
// Window button held during shutdown is released too.
let (app2, tx2, _) =
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id2 = app2.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64;
tx2.send(Event::State {
session: id2,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
})
.unwrap();
cx.run_until_parked();
transmits(&app2, cx);
app2.update(cx, |app, cx| app.push_to_talk(true, cx));
assert_eq!(transmits(&app2, cx), [(id2, true)]);
app2.update(cx, |app, cx| app.shutdown(cx));
assert_eq!(transmits(&app2, cx), [(id2, false)], "shutdown releases the held button");
}
/// Showing a server also observes it, invisibly, through the gateway it
/// published or its own query login, as the Slint front end does.
#[gpui::test]
+22 -2
View File
@@ -7,6 +7,9 @@
//! 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
@@ -42,6 +45,12 @@ 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
@@ -69,6 +78,8 @@ impl Default for Switches {
fn default() -> Self {
Self {
open: Page::Shell,
voice: false,
voice_compact: false,
demo_ui: false,
demo_pictures: false,
demo_server: None,
@@ -95,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)"
),
}
}
@@ -166,7 +179,7 @@ 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"),
@@ -176,6 +189,7 @@ mod tests {
("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));
@@ -185,6 +199,12 @@ mod tests {
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(&[
+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);
});
}
}
+5
View File
@@ -11,6 +11,7 @@ pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod hotkey;
pub mod meter;
pub mod pictures;
pub mod shell;
@@ -150,6 +151,9 @@ fn open_main_window(
};
move |cx| AppState::new(setup, cx)
});
// The global push-to-talk key, on the engine's runtime (docs/ui.md): once the
// state exists, and never from a test of the state.
app.update(cx, |app, _| app.start_global_ptt());
let options = {
let app = app.read(cx);
window_options(switches, app.remembered_window(), app.window_title(), cx)
@@ -217,6 +221,7 @@ pub fn run() -> Result<()> {
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
shell::bind_keys(cx);
fonts::load(cx);
// The mode and the text size are the settings', or a development
// switch's.
+6 -3
View File
@@ -60,11 +60,13 @@ pub struct Panes {
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); 6] {
pub fn named(&self) -> [(&'static str, Counter); 7] {
[
("rail", self.rail.clone()),
("topbar", self.topbar.clone()),
@@ -72,6 +74,7 @@ impl Panes {
("tree", self.tree.clone()),
("main", self.main.clone()),
("members", self.members.clone()),
("voice", self.voice.clone()),
]
}
}
@@ -278,9 +281,9 @@ mod tests {
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"]);
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], "the counters are the panes' own");
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
}
#[test]
+46 -2
View File
@@ -6,12 +6,18 @@
//! ([`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: `show_voice_view` to the voice
//! page, `client_audio_changed` to the dialogs, and `copied` (the toast that
//! 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};
@@ -41,9 +47,47 @@ actions!(
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)]
+67 -14
View File
@@ -19,8 +19,9 @@ 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, StatefulInteractiveElement as _, Styled as _,
StyledImage as _, Subscription, Window, div, list, px,
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;
@@ -28,8 +29,8 @@ use voelin_ui_vm::tree::ChannelId;
use super::actions::{
EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel,
};
use super::tree_model::{Emptiness, TreeEvent, TreeModel};
use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture};
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};
@@ -37,6 +38,13 @@ 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>>,
@@ -58,10 +66,7 @@ impl ChannelTree {
};
let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::Rows(changes) => {
let new = model.read(cx).rows().clone();
this.apply(changes, new);
}
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 => {
@@ -71,7 +76,7 @@ impl ChannelTree {
}
this.emptiness = emptiness;
}
TreeEvent::People(_) | TreeEvent::Card => return,
TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return,
}
cx.notify();
});
@@ -96,11 +101,18 @@ impl ChannelTree {
self.selected
}
/// Take the new rows in, telling the list which rows came, went or
/// changed their height (a channel row and a person's differ).
/// 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 {
@@ -141,7 +153,10 @@ fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::NoServer => "No server yet.",
Emptiness::Loading => "Loading the channels…",
Emptiness::Connect => "Connect to see 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.",
}
}
@@ -202,9 +217,11 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme
} 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))
@@ -217,8 +234,21 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme
.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 tint of our own channel.
// 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()
@@ -251,6 +281,18 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme
.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()
@@ -337,7 +379,8 @@ fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
.gap(px(m.space_3))
.child(
Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint)
.image(item.avatar.clone()),
.image(item.avatar.clone())
.speaking(item.talking),
)
.child(
div()
@@ -356,6 +399,16 @@ fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
.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| {
+16 -2
View File
@@ -14,7 +14,7 @@ use gpui_kit::{
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer};
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer, ShowVoiceView};
use super::widgets::{Avatar, Presence, icon, panel, tagged};
use crate::app::AppState;
use crate::meter::Counters;
@@ -173,7 +173,7 @@ impl Render for MainPanel {
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Its chat and its voice page come with the next slices."),
.child("Its chat comes with a later slice."),
)
.child(
div()
@@ -202,6 +202,20 @@ impl Render for MainPanel {
}),
))
})
.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(
+168 -26
View File
@@ -5,15 +5,17 @@
//!
//! [`MembersPane`] is a cached pane over a virtual list that follows
//! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations
//! the list applies). It is the pane a talker redraws: a person's row has the
//! speaking ring, "Speaking" and the bars, and nothing else of the window is
//! told. [`MemberCardView`] is the card, a card over the window with a scrim
//! that a click outside closes; its buttons (the volume, a message, a poke,
//! friends, blocking) come with the slices that have those dialogs.
//! 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,
@@ -23,8 +25,8 @@ use gpui_kit::{
use voelin_ui_vm::bridge::{MemberCard, MemberItem};
use voelin_ui_vm::list::Changes;
use super::actions::{OpenMember, SearchMembers};
use super::tree_model::{Emptiness, TreeEvent, TreeModel};
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,
};
@@ -61,7 +63,12 @@ impl MembersPane {
) -> Self {
let (rows, total, emptiness, open) = {
let model = model.read(cx);
(model.people().clone(), model.total(), model.emptiness(), model.card().map(|c| c.id))
(
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…"))
@@ -69,20 +76,17 @@ impl MembersPane {
let subscriptions = vec![
cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::People(changes) => {
let new = model.read(cx).people().clone();
this.apply(changes, new);
}
TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Lists => {
let model = model.read(cx);
let now = (model.total(), model.emptiness());
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::Selection => return,
TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return,
}
cx.notify();
}),
@@ -117,16 +121,23 @@ impl MembersPane {
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, telling the list which rows came, went or changed
/// their height (the first row of a section has the heading above it).
/// 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 {
@@ -182,6 +193,7 @@ impl MembersPane {
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.",
}
}
@@ -438,25 +450,67 @@ impl Render for MembersPane {
}
/// 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.
/// 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,
_subscription: Subscription,
/// 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, cx: &mut Context<Self>) -> Self {
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 subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
if matches!(event, TreeEvent::Card) {
this.card = model.read(cx).card().cloned();
cx.notify();
}
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))
});
Self { card, panel_width, _subscription: subscription }
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.
@@ -475,6 +529,79 @@ fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement {
.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() };
@@ -601,7 +728,8 @@ impl Render for MemberCardView {
)),
)
})
.child(facts);
.child(facts)
.child(volume(&theme, &person, &self.slider));
// The card stands beside the panel, near the top.
div()
.id("member-card-scrim")
@@ -624,3 +752,17 @@ impl Render for MemberCardView {
.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.");
}
}
+14 -5
View File
@@ -1,12 +1,13 @@
//! 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 server form and the toast, each an entity
//! 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
//! and the main area 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.
//! 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;
@@ -19,6 +20,7 @@ mod sidebar;
mod toast;
mod topbar;
mod tree_model;
mod voice;
pub mod widgets;
pub use channels::ChannelTree;
@@ -26,8 +28,15 @@ 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};
+29 -11
View File
@@ -5,15 +5,24 @@
//! 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::{Escape, Input, InputEvent, InputState};
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, StatefulInteractiveElement as _, Styled as _, Window,
div, px,
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;
@@ -21,11 +30,23 @@ 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 {
@@ -44,7 +65,7 @@ impl ChannelPassword {
})
.detach();
input.update(cx, |input, cx| input.focus(window, cx));
Self { channel: ask.name.clone(), wrong: ask.wrong, input }
Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() }
}
/// The channel it asks for.
@@ -76,12 +97,8 @@ impl Render for ChannelPassword {
div()
.id("password-prompt")
.debug_selector(|| "password-prompt".into())
.key_context("ChannelPassword")
// The field has the keys, and its Escape has nothing to undo and
// passes the key on: it closes the prompt.
.on_action(cx.listener(|_, _: &Escape, window, cx| {
window.dispatch_action(Box::new(CancelChannelPassword), cx)
}))
.key_context(CONTEXT)
.track_focus(&self.focus)
.absolute()
.top(px(0.0))
.left(px(0.0))
@@ -95,6 +112,7 @@ impl Render for ChannelPassword {
.child(
div()
.id("password-card")
.debug_selector(|| "password-card".into())
.w(px(380.0))
.flex()
.flex_col()
+99 -12
View File
@@ -1,5 +1,6 @@
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen, its channel tree
//! `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
@@ -8,8 +9,8 @@
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Subscription, Window, div, px,
ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, StyledImage as _, Subscription, Window, div, px,
};
use voelin_core::TransmitMode;
use voelin_ui_vm::Rgb;
@@ -21,9 +22,10 @@ use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::channels::ChannelTree;
use super::widgets::{Avatar, IconButton, Presence, card, icon, panel};
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};
@@ -34,6 +36,8 @@ pub struct SidebarView {
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.
@@ -54,6 +58,9 @@ pub struct SidebarView {
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 {
@@ -68,6 +75,7 @@ impl SidebarView {
Self {
server,
stats: card.server_stats,
server_banner: card.server_banner,
nickname: card.nickname,
own_channel: card.own_channel,
own_avatar: card.own_avatar,
@@ -78,6 +86,7 @@ impl SidebarView {
output_muted: card.output_muted,
transmitting: card.transmitting,
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
transmit: app.vm.audio.transmit,
}
}
}
@@ -104,7 +113,23 @@ impl Sidebar {
};
let subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let view = SidebarView::of(app.read(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();
@@ -118,6 +143,19 @@ impl Sidebar {
&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) {
@@ -126,18 +164,41 @@ impl Sidebar {
}
}
/// The server's name, its icon and how many are there.
/// 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())
@@ -158,16 +219,22 @@ fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> im
.child(item.name.to_string()),
)
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(stats),
div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats),
),
)
}
/// "Voice Connected" and our channel, disconnect and hold to talk.
/// 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,
@@ -235,6 +302,26 @@ fn voice_card(
}),
),
)
.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()
+146 -38
View File
@@ -6,20 +6,26 @@
//! ([`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`]): 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.
//! ([`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 tree does not mark who is talking.** Its rows are built with
//! `talking` cleared: a talker changes the rows of the members panel (and the
//! sidebar's own card), not the tree's, which therefore is not drawn again
//! with every start and stop of someone's voice. The Slint tree draws speaking
//! bars on the row; docs/ui.md records the difference.
//! 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::{Context, Entity, EventEmitter, Subscription};
use voelin_core::ObserveState;
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;
@@ -33,83 +39,151 @@ use crate::signals::Area;
pub enum Emptiness {
/// No server is on screen.
NoServer,
/// The server is observed and its presence is on the way.
/// 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.
/// 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 => Self::Loading,
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 old rows to
/// [`TreeModel::rows`].
Rows(Changes),
/// The members panel's rows: the operations from the old rows to
/// [`TreeModel::people`].
People(Changes),
/// 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::total`]).
/// ([`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 (mut rows, people, total) = match logic::tree_view(vm, false) {
Some(tree) => (tree.rows, tree.server_members, tree.member_total),
None => (Vec::new(), Vec::new(), 0),
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),
};
for row in &mut rows {
row.talking = false;
}
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)))
@@ -127,20 +201,20 @@ impl TreeModel {
let state = app.read(cx);
(Snapshot::of(state), state.signals().clone())
};
let subscriptions = signals.watch(
app,
&[Area::Tree, Area::Toolbar, Area::MemberCard],
cx,
|this: &mut Self, _, cx| this.refresh(cx),
);
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,
}
}
@@ -155,6 +229,12 @@ impl TreeModel {
&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
@@ -170,13 +250,32 @@ impl TreeModel {
self.selected
}
/// Why the lists are empty, were they.
/// Why the tree is empty, were it.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Build the rows again, and tell the panes what differs.
/// 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);
@@ -186,17 +285,26 @@ impl TreeModel {
if !people.is_empty() {
self.people = Arc::new(new.people);
}
let lists = (self.emptiness, self.total) != (new.emptiness, new.total);
(self.emptiness, self.total) = (new.emptiness, new.total);
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));
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
}
if !people.is_empty() {
cx.emit(TreeEvent::People(people));
cx.emit(TreeEvent::People(people, self.people.clone()));
}
if voice {
cx.emit(TreeEvent::Voice(self.voice.clone()));
}
if lists {
cx.emit(TreeEvent::Lists);
+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."),
)
}
}
+45 -14
View File
@@ -4,6 +4,8 @@
//! 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 _,
@@ -181,7 +183,10 @@ impl RenderOnce for Avatar {
.justify_center()
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match key {
Some(key) => face.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
// 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(
@@ -229,7 +234,7 @@ 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.
/// dimmed and does nothing, and keeps its tooltip.
#[derive(IntoElement)]
pub struct IconButton {
id: ElementId,
@@ -337,8 +342,14 @@ impl RenderOnce for IconButton {
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(self.id)
.id(id)
.debug_selector(move || selector)
.size(px(self.size))
.flex_none()
@@ -351,14 +362,17 @@ impl RenderOnce for IconButton {
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))).tooltip(
move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
},
);
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,
@@ -432,13 +446,14 @@ pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement {
/// 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 {
let c = &theme.colors;
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(c.success))
div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color))
};
div()
.w(px(size))
@@ -483,11 +498,27 @@ pub fn chip(
.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.
+503 -51
View File
@@ -18,14 +18,15 @@ use crate::dev::Page;
use crate::meter::Counters;
use crate::shell::actions::{
AddServer, CancelChannelPassword, CancelServerForm, ConnectVoice, DeleteServer,
DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, MoveClient, OpenClient,
OpenMember, OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SearchMembers,
SelectChannel, SelectServer, SetInputMuted, SetOutputMuted, SubmitChannelPassword,
ToggleChannel,
DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, LeaveVoice, MoveClient,
OpenClient, OpenMember, OpenSearch, OpenSettings, OpenShare, OpenVoiceSettings, PushToTalk,
SaveAndConnect, SaveServer, SearchMembers, SelectChannel, SelectServer, SetInputMuted,
SetMemberMuted, SetMemberVolume, SetOutputMuted, ShowVoiceView, SubmitChannelPassword,
ToggleChannel, ToggleVoiceCompact,
};
use crate::shell::{
ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, ServerForm,
ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel,
ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, SHORT_WINDOW,
ServerForm, ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel, VoicePage,
};
use crate::swatch::swatch;
use crate::theme::{VoelinTheme, hsla};
@@ -66,6 +67,10 @@ pub struct MainView {
/// How wide the members panel is (`ui.members_width`, read at start).
members_width: f32,
main: Entity<MainPanel>,
/// The voice channel page, which the main area is while voice is on screen.
voice: Entity<VoicePage>,
/// The main area is the voice page.
voice_shown: bool,
toast: Entity<Toast>,
form: Option<Entity<ServerForm>>,
/// The prompt for a locked channel's password, when one is open, and how
@@ -115,6 +120,18 @@ impl MainView {
this.form = None;
cx.notify();
}
// The voice page takes the main area while it is asked for and voice
// is connected, and keeps the stage the setting says: an observer of
// the root state reads it and sets its own fields.
let (shown, compact) = {
let app = app.read(cx);
(app.voice_page_shown(), app.voice_compact())
};
if shown != this.voice_shown {
this.voice_shown = shown;
cx.notify();
}
this.voice.update(cx, |page, cx| page.set_compact(compact, cx));
// A channel's password was asked for.
let (generation, ask) = {
let app = app.read(cx);
@@ -127,7 +144,27 @@ impl MainView {
cx.notify();
}
}),
cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)),
// The release guard of Hold to talk for a window that loses the focus
// while the button is held: the mouse button comes up somewhere else,
// and the release never reaches the button. Only the window's own
// button: the global hotkey is for use while another window has the
// focus.
cx.observe_window_activation(window, |this, window, cx| {
if window.is_window_active() {
return;
}
this.sidebar.update(cx, |sidebar, _| {
let _ = sidebar.release();
});
this.app.update(cx, |app, cx| app.push_to_talk(false, cx));
}),
cx.observe_window_bounds(window, |this, window, cx| {
report(&this.app, window, cx);
// A cached pane renders only when told: it is told when the window
// becomes short or tall.
let short = is_short(window);
this.voice.update(cx, |page, cx| page.set_short(short, cx));
}),
];
report(&app, window, cx);
// The window is mapped by now: a window the last run left maximized
@@ -140,7 +177,13 @@ impl MainView {
let model = cx.new(|cx| TreeModel::new(&app, cx));
let tree = cx.new(|cx| ChannelTree::new(&model, counters.clone(), cx));
let members = cx.new(|cx| MembersPane::new(&model, counters.clone(), window, cx));
let card = cx.new(|cx| MemberCardView::new(&model, members_width, cx));
let card = cx.new(|cx| MemberCardView::new(&model, members_width, window, cx));
let (voice_shown, compact) = {
let app = app.read(cx);
(app.voice_page_shown(), app.voice_compact())
};
let short = is_short(window);
let voice = cx.new(|cx| VoicePage::new(&app, &model, compact, short, cx));
// The members panel comes with the first server on screen.
subscriptions.push(cx.subscribe(&model, |_, _, event: &TreeEvent, cx| {
if matches!(event, TreeEvent::Lists) {
@@ -157,6 +200,8 @@ impl MainView {
card,
members_width,
main: cx.new(|cx| MainPanel::new(&app, cx)),
voice,
voice_shown,
toast: cx.new(|cx| Toast::new(&app, cx)),
app,
page,
@@ -195,6 +240,28 @@ impl MainView {
&self.card
}
/// What the sidebar shows now.
#[cfg(test)]
pub(crate) fn sidebar_view(&self, cx: &gpui_kit::App) -> crate::shell::SidebarView {
self.sidebar.read(cx).view().clone()
}
/// Whether the sidebar's hold-to-talk button is held down.
#[cfg(test)]
pub(crate) fn sidebar_holding(&self, cx: &gpui_kit::App) -> bool {
self.sidebar.read(cx).is_holding()
}
/// The voice channel page.
pub fn voice_page(&self) -> &Entity<VoicePage> {
&self.voice
}
/// Whether the main area is the voice page now.
pub fn voice_page_shown(&self) -> bool {
self.voice_shown
}
/// Open the form with `form`'s values.
fn open_form(
&mut self,
@@ -241,6 +308,63 @@ impl MainView {
self.app.update(cx, |app, cx| app.invite(cx));
}
fn set_member_volume(
&mut self,
action: &SetMemberVolume,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.app.update(cx, |app, cx| app.set_member_volume(action.client, action.percent, cx));
}
fn set_member_muted(
&mut self,
action: &SetMemberMuted,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.app.update(cx, |app, cx| app.set_member_muted(action.client, action.muted, cx));
}
fn show_voice_view(&mut self, action: &ShowVoiceView, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.show_voice_view(action.on, cx));
}
/// The voice page's Leave: the page goes (the chat it stands for is what
/// the main area shows next time), then voice is left.
fn leave_voice(&mut self, _: &LeaveVoice, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| {
app.show_voice_view(false, cx);
app.disconnect_voice(cx);
});
}
fn toggle_voice_compact(
&mut self,
_: &ToggleVoiceCompact,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.app.update(cx, |app, cx| app.toggle_voice_compact(cx));
}
fn open_share(&mut self, _: &OpenShare, _: &mut Window, _: &mut Context<Self>) {
tracing::info!(
"sharing a screen comes with the stream slices (docs/ui.md, \"What is next\")"
);
}
fn open_voice_settings(
&mut self,
_: &OpenVoiceSettings,
_: &mut Window,
_: &mut Context<Self>,
) {
tracing::info!(
"the voice settings come with the settings slice (docs/ui.md, \"What is next\")"
);
}
fn add_server(&mut self, _: &AddServer, window: &mut Window, cx: &mut Context<Self>) {
let form = self.app.read(cx).bookmark_form(-1);
self.open_form(form, window, cx);
@@ -397,6 +521,11 @@ fn zoom(_: &Window) {
tests::ZOOMS.with(|zooms| zooms.set(zooms.get() + 1));
}
/// Whether `window` is too short for the voice page's larger stage.
fn is_short(window: &Window) -> bool {
f32::from(window.viewport_size().height) < SHORT_WINDOW
}
/// Tell `app` where `window` is: it keeps the place at the next tick.
fn report(app: &Entity<AppState>, window: &Window, cx: &mut App) {
if let Some(state) = window_state(window, cx) {
@@ -428,13 +557,14 @@ impl Render for MainView {
// says and not narrower than the least a panel can be.
let people = self.model.read(cx).emptiness() != Emptiness::NoServer;
let members_width = self.members_width.max(m.right_panel_min);
// The main area is the server form, else the voice page while voice is
// asked for and connected, else the server page. A cached pane renders
// only when it was told, and the one not chosen is not in the tree.
let place = StyleRefinement::default().flex_1().min_w_0().h_full();
let main = match &self.form {
Some(form) => form.clone().into_any_element(),
None => self
.main
.clone()
.cached(StyleRefinement::default().flex_1().min_w_0().h_full())
.into_any_element(),
None if self.voice_shown => self.voice.clone().cached(place).into_any_element(),
None => self.main.clone().cached(place).into_any_element(),
};
frame
.key_context("Shell")
@@ -449,6 +579,13 @@ impl Render for MainView {
.on_action(cx.listener(Self::set_output_muted))
.on_action(cx.listener(Self::push_to_talk))
.on_action(cx.listener(Self::invite))
.on_action(cx.listener(Self::set_member_volume))
.on_action(cx.listener(Self::set_member_muted))
.on_action(cx.listener(Self::show_voice_view))
.on_action(cx.listener(Self::leave_voice))
.on_action(cx.listener(Self::toggle_voice_compact))
.on_action(cx.listener(Self::open_share))
.on_action(cx.listener(Self::open_voice_settings))
.on_action(cx.listener(Self::add_server))
.on_action(cx.listener(Self::edit_server))
.on_action(cx.listener(Self::save_server))
@@ -525,7 +662,7 @@ mod tests {
use tokio::sync::mpsc::{self, UnboundedSender};
use voelin_core::{Command, Event, SessionState, VoiceState};
use voelin_store::{Bookmark, MemorySecrets};
use voelin_ui_vm::bridge::{BookmarkForm, TreeItem};
use voelin_ui_vm::bridge::{BookmarkForm, MemberItem, TreeItem};
use voelin_ui_vm::dev::logic as sample;
use voelin_ui_vm::list::{Change, Changes};
use voelin_ui_vm::settings::{TreeState, TreeStates, UI_TREE, UI_WINDOW};
@@ -538,6 +675,7 @@ mod tests {
use crate::pictures::PictureKey;
use crate::shell::actions::{EditChannel, MoveClient, OpenClient};
use crate::shell::{RailView, TreeEvent};
use crate::signals::Area;
use crate::theme::Choice;
use crate::window_bounds;
@@ -552,11 +690,11 @@ mod tests {
/// What a test of the shell holds: the root state, the window's view, the
/// engine's events and the meter's counters.
struct Shell {
app: Entity<AppState>,
view: Entity<MainView>,
events: UnboundedSender<Event>,
counters: Counters,
pub(super) struct Shell {
pub(super) app: Entity<AppState>,
pub(super) view: Entity<MainView>,
pub(super) events: UnboundedSender<Event>,
pub(super) counters: Counters,
}
fn bookmark(name: &str, address: &str) -> Bookmark {
@@ -568,7 +706,7 @@ mod tests {
}
}
fn backend_with(servers: &[(&str, &str)]) -> Backend {
pub(super) fn backend_with(servers: &[(&str, &str)]) -> Backend {
let backend = Backend::in_memory().unwrap();
for (name, address) in servers {
backend.store.add_bookmark(&bookmark(name, address)).unwrap();
@@ -578,13 +716,14 @@ mod tests {
/// Open the window of the shell on `backend`, with the theme and the
/// components set up as `run` sets them.
fn open(
pub(super) fn open(
cx: &mut TestAppContext,
backend: Backend,
switches: Switches,
) -> (Shell, &mut VisualTestContext) {
cx.update(|cx| {
gpui_kit::init(cx);
crate::shell::bind_keys(cx);
VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0);
});
let (events, rx) = mpsc::unbounded_channel();
@@ -603,23 +742,26 @@ mod tests {
}
/// Run what is queued and draw the window.
fn frame(cx: &mut VisualTestContext) {
pub(super) fn frame(cx: &mut VisualTestContext) {
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Where the element with this debug selector is on screen.
fn at(cx: &mut VisualTestContext, selector: &str) -> Option<Bounds<gpui_kit::Pixels>> {
pub(super) fn at(
cx: &mut VisualTestContext,
selector: &str,
) -> Option<Bounds<gpui_kit::Pixels>> {
cx.debug_bounds(Box::leak(selector.to_owned().into_boxed_str()))
}
fn click(cx: &mut VisualTestContext, selector: &str) {
pub(super) fn click(cx: &mut VisualTestContext, selector: &str) {
let bounds = at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen"));
cx.simulate_click(bounds.center(), Default::default());
frame(cx);
}
fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec<i64> {
pub(super) fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec<i64> {
shell.app.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.id).collect())
}
@@ -631,7 +773,7 @@ mod tests {
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
}
fn connected(id: i64) -> Event {
pub(super) fn connected(id: i64) -> Event {
Event::State {
session: id as u64,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
@@ -879,7 +1021,7 @@ mod tests {
/// A server as an engine reports one: the sample server's events (nested
/// channels, spacers, a locked channel, people with groups) played into the
/// window, its bookmark the one shown. Voice is up and we are in Chill Zone.
fn sample_server(shell: &Shell, cx: &mut VisualTestContext) {
pub(super) fn sample_server(shell: &Shell, cx: &mut VisualTestContext) {
shell.app.update(cx, |app, _| {
app.vm.bookmarks = sample::bookmarks();
app.vm.current = Some(sample::DEMO);
@@ -939,12 +1081,12 @@ mod tests {
(log, subscription)
}
/// The row operations the model told the tree.
fn rows_told(log: &Rc<RefCell<Vec<TreeEvent>>>) -> Vec<Changes> {
/// The row operations the model told the tree, with the rows they lead to.
fn rows_told(log: &Rc<RefCell<Vec<TreeEvent>>>) -> Vec<(Changes, Arc<Vec<TreeItem>>)> {
log.borrow()
.iter()
.filter_map(|event| match event {
TreeEvent::Rows(changes) => Some(changes.clone()),
TreeEvent::Rows(changes, rows) => Some((changes.clone(), rows.clone())),
_ => None,
})
.collect()
@@ -974,7 +1116,8 @@ mod tests {
/// The sample server's channels and people are the rows of the tree, in
/// the Slint tree's order and nesting, with its spacers, the locked
/// channel and the counts, each on screen; none of them marks a talker.
/// channel and the counts, each on screen; Kairo, who talks as the sample
/// starts, is marked.
#[gpui::test]
fn a_server_with_channels_and_people_fills_the_tree_with_its_rows(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
@@ -1011,7 +1154,8 @@ mod tests {
assert_eq!((channel("Gaming").spacer, channel("Staff").spacer), (2, 3), "centred, right");
assert_eq!(rows.iter().find(|r| r.spacer == 4).map(|r| r.is_channel), Some(true));
assert!(channel("Officers").locked && !channel("Lobby").locked);
assert!(rows.iter().all(|r| !r.talking), "Kairo talks; the tree does not say so");
let talking: Vec<&str> = rows.iter().filter(|r| r.talking).map(|r| &*r.name).collect();
assert_eq!(talking, ["Kairo"], "Kairo talks, and the tree says so");
assert!(at(cx, "tree-empty").is_none());
for row in rows.iter() {
let selector = if row.is_channel {
@@ -1211,9 +1355,43 @@ mod tests {
assert!(at(cx, "password-prompt").is_none(), "closed");
}
/// Escape closes the password prompt wherever the focus is in it, not only
/// while its field has it: a click on the card, off the field, moves the
/// focus away from the field (to the card), and the key must still reach
/// the prompt.
#[gpui::test]
fn escape_closes_the_password_prompt_after_a_click_on_its_card(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
shell.app.read_with(cx, |app, _| app.take_sent());
let prompt_open = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, _| view.password_prompt().is_some())
};
for aim in ["the card's corner", "the card's disabled Join"] {
double_click(cx, "tree-channel-7");
assert!(prompt_open(&shell, cx), "{aim}: asked for the password");
if aim == "the card's corner" {
let card = at(cx, "password-card").expect("the card is on screen");
let corner = card.origin + point(px(6.0), px(6.0));
cx.simulate_click(corner, Default::default());
frame(cx);
} else {
click(cx, "password-join");
}
assert!(prompt_open(&shell, cx), "{aim}: a click inside the card closes nothing");
cx.simulate_keystrokes("escape");
frame(cx);
assert!(!prompt_open(&shell, cx), "{aim}: Escape closes the prompt");
assert!(at(cx, "password-prompt").is_none());
assert!(shell.app.read_with(cx, |app, _| app.vm.join_target.is_none()));
}
assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "nothing joined");
}
/// The channels with a banner picture are drawn with the veil of the
/// surface colour over it (so that their text reads over any picture); the
/// others have none.
/// others have none. The picture covers the row's own background, so a
/// selected banner row is tinted by a child above the veil.
#[gpui::test]
fn a_banner_is_drawn_under_a_veil(cx: &mut TestAppContext) {
let switches = Switches { demo_ui: true, demo_pictures: true, ..Switches::default() };
@@ -1234,6 +1412,31 @@ mod tests {
let plain = plain.expect("a channel without a banner");
assert!(at(cx, &format!("tree-channel-{}", plain.id)).is_some(), "it is on screen");
assert!(at(cx, &format!("tree-scrim-{}", plain.id)).is_none(), "and has no veil");
// A click selects a row; a banner row shows it by a tint over its picture.
let tinted =
|cx: &mut VisualTestContext, id: i32| at(cx, &format!("tree-selected-{id}")).is_some();
// (Our own channel has the accent tint of its own instead.)
let others: Vec<i32> = rows
.iter()
.filter(|r| r.is_channel && banners.contains(&r.id) && !r.own)
.map(|r| r.id)
.collect();
let [first, second, ..] = others[..] else { panic!("two other banners: {others:?}") };
assert!(!tinted(cx, first) && !tinted(cx, second), "nothing is selected yet");
click(cx, &format!("tree-channel-{first}"));
assert!(tinted(cx, first), "the selected banner row is tinted");
assert!(!tinted(cx, second));
click(cx, &format!("tree-channel-{second}"));
assert!(tinted(cx, second) && !tinted(cx, first), "and the tint follows the selection");
// The sample pictures are files of a folder of the state's own in the
// temporary directory; the window's close, as the app ends, removes it
// (the entity of a test is not released when the test ends).
let folder = shell.app.read_with(cx, |app, _| app.demo_dir().cloned());
assert!(folder.as_ref().is_some_and(|folder| folder.is_dir()), "{folder:?}");
shell.app.update(cx, |app, cx| app.shutdown(cx));
assert!(!folder.is_some_and(|folder| folder.exists()), "the close removes it");
}
/// A person who changes channel makes the rows between the two places
@@ -1253,8 +1456,11 @@ mod tests {
.unwrap();
frame(cx);
let dex = before.iter().position(|r| !r.is_channel && r.id == 5).unwrap();
assert_eq!(rows_told(&log), [Changes(vec![Change::Update(dex)])]);
let told = rows_told(&log);
let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) };
assert_eq!(*changes, Changes(vec![Change::Update(dex)]));
assert!(before[dex].muted && !tree_rows(&shell, cx)[dex].muted);
assert_eq!(*carried, tree_rows(&shell, cx), "the event carries the rows it leads to");
// Zeph (7) leaves Raid Night for Gaming: its parent's count, his row
// and the row of the sub-channel change; the rest stay.
@@ -1271,7 +1477,8 @@ mod tests {
["C0 Gaming", "P1 Talon", "P1 Zeph", "C1 Raid Night", "C0 Music"],
);
let told = rows_told(&log);
let [changes] = &told[..] else { panic!("{:?}", log.borrow()) };
let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) };
assert_eq!(*carried, after);
let gaming = 8;
assert_eq!(
changes.0,
@@ -1281,31 +1488,168 @@ mod tests {
assert_eq!((after[gaming].members, after[gaming + 3].members), (2, 0));
}
/// Who talks changes the members panel and the sidebar's own card, not the
/// tree: its pane is not drawn for a talker, and its rows stay as they
/// were.
/// The gate's probe. A state change made by an observer while a flush is
/// running must not make a pane apply the first row operations to the
/// second rows: the events carry the rows their operations lead to. A
/// Presence event raises the toolbar and the tree; the model makes its
/// first rows on the toolbar, an observer of the toolbar that was made
/// after the model's puts the observed server on screen (it has no rows
/// yet), and the model makes its second rows, none, on the tree before
/// the panes are told of the first: a shrink under operations made for
/// the rows before it.
#[gpui::test]
fn a_talker_does_not_draw_the_tree_again(cx: &mut TestAppContext) {
fn a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows(
cx: &mut TestAppContext,
) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let rows = tree_rows(&shell, cx);
assert!(!tree_rows(&shell, cx).is_empty());
let toolbar = shell.app.read_with(cx, |app, _| app.signals().of(Area::Toolbar).clone());
let fired = Rc::new(Cell::new(false));
let _observer = cx.update(|_, cx| {
let (app, fired) = (shell.app.clone(), fired.clone());
cx.observe(&toolbar, move |_, cx| {
if !fired.replace(true) {
app.update(cx, |app, cx| app.select_server(sample::DEMO + 1, cx));
}
})
});
let (log, _subscription) = tree_events(&shell, cx);
let unmute = presence_changed!(p => p.clients.get_mut(&5).unwrap().input_muted = false);
shell.events.send(unmute).unwrap();
frame(cx);
assert!(fired.get(), "the observer ran inside the flush");
assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(sample::DEMO + 1));
// The model told its panes twice, and each time with the rows its
// operations lead to: the first leaves the server's rows with dex
// unmuted, the second takes them all away.
let told = rows_told(&log);
let [first, second] = &told[..] else { panic!("{:?}", log.borrow()) };
assert_eq!(first.1.len(), 18, "the first rows are the sample server's");
assert!(!first.1.iter().any(|r| !r.is_channel && r.id == 5 && r.muted));
assert_eq!((first.0.updated(), first.0.removed(), first.0.inserted()), (1, 0, 0));
assert!(second.1.is_empty() && second.0.removed() == 18, "{:?}", second.0);
// The panes end with the model's rows, in the order they were told.
assert!(tree_rows(&shell, cx).is_empty());
let (tree, people) = shell.view.read_with(cx, |view, cx| {
(view.channel_tree().read(cx).rows().len(), view.members_pane().read(cx).rows().len())
});
assert_eq!((tree, people), (0, 0));
assert!(at(cx, "tree-empty").is_some(), "the tree says it is loading");
}
/// Who talks is marked on the tree's row, as the Slint tree marks it (the
/// ring on the avatar, the bars on the row): each start and stop changes
/// exactly that person's row, the tree pane is drawn once for it, and the
/// row says so on screen.
#[gpui::test]
fn a_talker_changes_one_row_and_draws_the_tree_once(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let kairo = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, cx| {
let tree = view.channel_tree().read(cx);
tree.rows().iter().position(|r| !r.is_channel && r.id == 3).unwrap()
})
};
let place = kairo(&shell, cx);
assert!(tree_rows(&shell, cx)[place].talking, "Kairo talks as the sample starts");
let (log, _subscription) = tree_events(&shell, cx);
let drawn = |shell: &Shell| shell.counters.panes.tree.get();
let before = drawn(&shell);
for talking in [false, true, false, true] {
let before = drawn(&shell);
log.borrow_mut().clear();
let event = Event::Talking { session: sample::DEMO as u64, client: 3, talking };
shell.events.send(event).unwrap();
frame(cx);
let told = rows_told(&log);
let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) };
assert_eq!(*changes, Changes(vec![Change::Update(place)]), "only Kairo's row");
assert_eq!(carried[place].talking, talking);
assert_eq!(drawn(&shell), before + 1, "the tree pane was drawn once");
let pane = shell
.view
.read_with(cx, |view, cx| view.channel_tree().read(cx).rows()[place].talking);
assert_eq!(pane, talking, "the pane has it");
assert_eq!(at(cx, "tree-speaking-3").is_some(), talking, "and the bars are on screen");
}
assert!(rows_told(&log).is_empty(), "the model told the tree nothing: {:?}", log.borrow());
assert_eq!(log.borrow().len(), 4, "and the members panel four times");
assert_eq!(drawn(&shell), before, "the tree pane was not rendered");
assert_eq!(tree_rows(&shell, cx), rows);
assert!(
shell.app.read_with(cx, |app, _| app.vm.sessions[&sample::DEMO].talking.contains(&3))
);
}
/// The people of our voice channel are the model's too, out of the same
/// build as the tree's rows and the members panel's: they come with the
/// connected voice, a talker or a mute changes just that person's row, a
/// change elsewhere on the server tells nobody of them, and the model
/// builds once for each change, not once more for the voice page.
#[gpui::test]
fn the_model_keeps_the_people_of_our_channel_out_of_the_same_build(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
let model = shell.view.read_with(cx, |view, _| view.tree_model().clone());
assert!(model.read_with(cx, |model, _| model.voice().is_empty()), "no server");
sample_server(&shell, cx);
let people = |cx: &mut VisualTestContext| model.read_with(cx, |m, _| m.voice().clone());
let names = |rows: &[MemberItem]| {
rows.iter().map(|m| (m.name.to_string(), m.talking, m.muted)).collect::<Vec<_>>()
};
assert_eq!(
names(&people(cx)),
[
("Lumen".to_owned(), false, false),
("Kairo".to_owned(), true, false),
("Nova".to_owned(), false, false),
("dex".to_owned(), false, true),
("Mira".to_owned(), false, false),
],
"our channel's people, by group and name; Kairo talks, dex's microphone is off"
);
let (log, _subscription) = tree_events(&shell, cx);
let voice_told = |log: &Rc<RefCell<Vec<TreeEvent>>>| -> Vec<Arc<Vec<MemberItem>>> {
log.borrow()
.iter()
.filter_map(|e| match e {
TreeEvent::Voice(rows) => Some(rows.clone()),
_ => None,
})
.collect()
};
let refreshes = |cx: &mut VisualTestContext| model.read_with(cx, |m, _| m.refreshes());
let before = refreshes(cx);
shell
.events
.send(Event::Talking { session: sample::DEMO as u64, client: 3, talking: false })
.unwrap();
frame(cx);
let told = voice_told(&log);
let [rows] = &told[..] else { panic!("{:?}", log.borrow()) };
assert!(!rows.iter().find(|m| m.id == 3).unwrap().talking, "Kairo stopped");
assert_eq!(*rows, people(cx), "the rows the event carries are the model's");
assert_eq!(refreshes(cx), before + 1, "one build for the tree, the panel and the page");
// Someone in another channel talks: the tree and the panel change, the
// page has nothing new.
log.borrow_mut().clear();
shell
.events
.send(Event::Talking { session: sample::DEMO as u64, client: 6, talking: true })
.unwrap();
frame(cx);
assert!(voice_told(&log).is_empty(), "{:?}", log.borrow());
assert!(!rows_told(&log).is_empty(), "though the tree has a row to change");
// Voice gone: nobody is in our channel.
log.borrow_mut().clear();
let gone = SessionState { voice: VoiceState::Disconnected, ..Default::default() };
shell.events.send(Event::State { session: sample::DEMO as u64, state: gone }).unwrap();
frame(cx);
let told = voice_told(&log);
assert!(matches!(&told[..], [rows] if rows.is_empty()), "{told:?}");
}
/// The members panel as the pane has it: the rows' names, `H` before the
/// first of a section with its heading.
fn members_shape(shell: &Shell, cx: &mut VisualTestContext) -> Vec<String> {
@@ -1369,11 +1713,80 @@ mod tests {
assert_eq!(shell.app.read_with(cx, |app, _| app.vm.member_filter.clone()), "");
}
/// Someone who starts or stops talking redraws the members panel and no
/// other pane: not the tree, the rail, the top bar nor the main area. The
/// A search that matches nobody on a server that has people says so, where
/// "Connect to see who is here." would be false; the tree is not told (it
/// is not searched), and closing the search shows everyone again.
#[gpui::test]
fn a_search_with_no_match_says_nobody_matches(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let emptiness = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, cx| {
(
view.members_pane().read(cx).emptiness(),
view.channel_tree().read(cx).emptiness(),
view.tree_model().read(cx).people_emptiness(),
)
})
};
assert_eq!(emptiness(&shell, cx).0, Emptiness::Connect, "full: only said when empty");
assert!(at(cx, "members-empty").is_none());
click(cx, "members-search");
// The first key typed draws the tree once whatever it is (the field's
// focus: not the search's doing); what follows must not.
cx.simulate_input("z");
frame(cx);
assert_eq!(members_shape(&shell, cx), ["Streaming — 1: Zeph", "Guest — 1: Blaze"]);
let tree_drawn = shell.counters.panes.tree.get();
cx.simulate_input("zz");
frame(cx);
assert!(members_shape(&shell, cx).is_empty(), "nobody is called zzz");
let (panel, tree, model) = emptiness(&shell, cx);
assert_eq!((panel, model), (Emptiness::NoMatch, Emptiness::NoMatch));
assert_eq!(tree, Emptiness::Connect, "the tree is not searched and says nothing new");
assert!(at(cx, "members-empty").is_some(), "the panel says so");
assert_eq!(shell.counters.panes.tree.get(), tree_drawn, "and the tree was not drawn");
// Closing the search shows everyone again, with no word for emptiness.
click(cx, "members-search");
assert_eq!(members_shape(&shell, cx).len(), 9);
assert!(at(cx, "members-empty").is_none());
assert_eq!(emptiness(&shell, cx).0, Emptiness::Connect);
}
/// A server whose voice is connecting has its people and channels on the
/// way: both panes say they are loading, not that one has to connect.
#[gpui::test]
fn a_server_being_connected_says_it_is_loading(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let third = sample::DEMO + 2;
shell.app.update(cx, |app, cx| app.select_server(third, cx));
frame(cx);
let words = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, cx| {
(view.members_pane().read(cx).emptiness(), view.channel_tree().read(cx).emptiness())
})
};
assert_eq!(words(&shell, cx), (Emptiness::Connect, Emptiness::Connect), "not connected");
let voice = |voice| Event::State {
session: third as u64,
state: SessionState { voice, ..Default::default() },
};
shell.events.send(voice(VoiceState::Connecting)).unwrap();
frame(cx);
assert_eq!(words(&shell, cx), (Emptiness::Loading, Emptiness::Loading), "connecting");
shell.events.send(voice(VoiceState::Disconnected)).unwrap();
frame(cx);
assert_eq!(words(&shell, cx), (Emptiness::Connect, Emptiness::Connect), "gave up");
}
/// Someone who starts or stops talking redraws the members panel and the
/// tree and no other pane: not the rail, the top bar nor the main area. The
/// row says so while they talk.
#[gpui::test]
fn a_talker_redraws_the_members_panel_and_no_other_pane(cx: &mut TestAppContext) {
fn a_talker_redraws_the_tree_and_the_members_panel_and_no_other_pane(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let panes = &shell.counters.panes;
@@ -1396,10 +1809,11 @@ mod tests {
}
let after = seen();
assert!(after[4] > before[4], "the members panel was drawn: {before:?} -> {after:?}");
assert!(after[2] > before[2], "and the tree: {before:?} -> {after:?}");
assert_eq!(
[after[0], after[1], after[2], after[3]],
[before[0], before[1], before[2], before[3]],
"the rail, the top bar, the tree and the main area were not"
[after[0], after[1], after[3]],
[before[0], before[1], before[3]],
"the rail, the top bar and the main area were not"
);
}
@@ -1506,6 +1920,41 @@ mod tests {
assert!(cx.update(|_, cx| crate::pictures::is_cached(&second, cx)), "the new one is drawn");
}
/// A change that raises three of the model's signals (a picture that
/// arrives raises the toolbar, the tree and the member card) builds the
/// rows once: the signals are raised together, and the model's first
/// refresh sees all of them.
#[gpui::test]
fn a_picture_that_arrives_builds_the_rows_once(cx: &mut TestAppContext) {
let dir = TempDir::new("refresh-once");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar-demo-3");
std::fs::write(&path, sample::demo_picture(40, 40, 1)).unwrap();
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
sample_server(&shell, cx);
let refreshes = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, cx| view.tree_model().read(cx).refreshes())
};
let before = refreshes(&shell, cx);
let arrives = Event::AvatarReady {
session: sample::DEMO as u64,
client_uid: "demo-3".into(),
path,
hash: String::new(),
};
shell.events.send(arrives).unwrap();
frame(cx);
assert_eq!(refreshes(&shell, cx), before + 1, "three signals, one build");
// A batch of two events that raise the same signals is one build as
// well.
let (a, b) = (presence_changed!(p => p.server.name = "A".into()), connected(sample::DEMO));
shell.events.send(a).unwrap();
shell.events.send(b).unwrap();
frame(cx);
assert_eq!(refreshes(&shell, cx), before + 2, "a batch of events: one build");
}
/// What the context menus offer that has no slice yet (the channel editor,
/// a person's volume dialog, moving a client) is logged and sends nothing.
#[gpui::test]
@@ -1848,3 +2297,6 @@ mod tests {
shell.view.read_with(cx, |view, _| assert!(view.form().is_none()));
}
}
#[cfg(test)]
mod voice_tests;
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -66,8 +66,17 @@ 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. The next slice is the voice page and the
call bar.
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 |
|---|---|---|---|
+560 -86
View File
@@ -663,7 +663,7 @@ live when they change (settings page, `--set`, another window):
| `ui.members_width` | pixels | 280 | width of the members panel (dragging its edge sets it) |
| `ui.window` | JSON `{width, height, x?, y?, maximized}` | none | where the main window was when the last run ended: its size (the one it returns to when `maximized`), its position where the platform tells one (Wayland does not: no `x` and `y`), and whether it was maximized; the next run opens there. Read at start, not applied live; written by the GPUI front end only (the Slint app neither registers nor reads it) |
| `ui.tree` | JSON by server id: `{"<id>": {collapsed, selected}}` | none | what each server's channel tree remembers: the channels folded shut (`collapsed`, channel ids) and the channel last selected (`selected`), under the id of the server's bookmark; a server with nothing folded or selected has no entry. Read at start, written at every fold, unfold and selection (not with the sample servers); written by the GPUI front end only (the Slint app neither registers nor reads it: its tree forgets both when it ends) |
| `ui.voice_compact` | bool | false | the voice channel view's smaller stage (its Smaller stage / Larger stage button sets it; windows under 800 px tall always have it) |
| `ui.voice_compact` | bool | false | the voice channel view's smaller stage (its Smaller stage / Larger stage button sets it, in both front ends; windows under 800 px tall always have it) |
| `ui.image_preview_kb` | kilobytes | 8192 | pictures linked in chat (files and `[img]`) up to this size show as pictures (0: never) |
| `notify.mentions`, `notify.private_messages`, `notify.pokes`, `notify.event_reminders`, `notify.friends_online` | off / app / desktop | desktop (friends: app) | what the bell and the desktop say about each kind |
| `video.camera`, `video.background`, `video.resolution`, `video.mirror` | device id; none / blur; auto or WxH; bool | first camera, none, auto, true | the camera of the preview and the default of camera sources |
@@ -990,6 +990,8 @@ crates/voelin-gpui/
and the callbacks of the Slint `bind/servers.rs` that the shell, the
channel tree and the members have (over `voelin_ui_vm::servers::
{logic, sequence}`, which Slint calls too)
hotkey.rs GlobalPtt: the global push-to-talk key's task, spawned on the engine's
runtime, its presses and releases handed to GPUI's thread through Later
signals.rs `Update.refresh` as per-area signals: entities with a generation
that the panes observe
pictures.rs the engine's pictures on screen: decoded per file and stamp, the
@@ -999,8 +1001,9 @@ crates/voelin-gpui/
title, the window's place
shell/ the desktop shell and its panes (below): rail.rs, sidebar.rs,
topbar.rs, main_panel.rs, channels.rs (the tree), members.rs (the
panel and its card), tree_model.rs, password.rs, form.rs, toast.rs,
actions.rs, widgets.rs
panel and its card, with the volume of a person), voice.rs (the
voice channel page and its call bar), tree_model.rs, password.rs,
form.rs, toast.rs, actions.rs, widgets.rs
swatch.rs the swatch page (every token, widgets, icons)
theme/ VoelinTheme: tokens.rs, components.rs, slint_parity.rs (test)
fonts.rs Inter, from crates/voelin-ui/ui/assets/fonts
@@ -1053,10 +1056,10 @@ crates/voelin-gpui/
not told), the channel tree and the members panel on the sample server's
events (the rows, folds kept in the settings and found by the next run, a
double-click that joins, the password prompt, a move and a mute as their
exact row operations, a talker that redraws the members panel and no other
pane, the member card, an avatar written again), a connect through a real
exact row operations, a talker that redraws the tree and the members panel
and no other pane, the member card, an avatar written again), a connect through a real
engine that has no connector (it answers that none serves the address, which
reaches the status line), the store on a
reaches the status line), the voice page and the call bar (below), the store on a
directory of its own, the theme (it reaches gpui-component, follows the window's
appearance and the text size), the Slint file's tokens equal the Rust ones
(below), the icons and fonts load. `tests/launch_failure.rs` starts the built
@@ -1115,13 +1118,14 @@ anyway).
| Switch | Does |
|---|---|
| `VOELIN_OPEN=swatch` | the swatch page in place of the shell; the Slint front end's other pages are not here yet and are named in a warning |
| `VOELIN_OPEN=voice` (`voice:compact`) | the voice channel page in the main area once voice is connected (with the sample servers the first one is, so at start); `voice:compact` on the smaller stage, which is not stored |
| `VOELIN_DEMO_UI=1` | the Slint front end's sample servers (`voelin_ui_vm::dev::logic`) in place of the stored ones, through the app's own events (the first is connected, with its channels, people and their pictures, the second observed); nothing is sent to the engine or kept in the store, the window's place and what the trees remember included, and the servers cannot be changed. The pictures are files of a folder of the state's own in the temporary directory, removed when the window closes (a killed run leaves it) |
| `VOELIN_DEMO_SERVER=2` | with the sample servers, the one on screen, counting from 0: the first (the default) is connected and populated, the second observed (its tree says it is loading), the third not connected (its tree says to connect) |
| `VOELIN_DEMO_TALK=10` | with the sample servers, one sample person starts or stops talking this many times a second (a rate from 0.1 to 100), 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 settings' `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: the window's place is not kept while it is set |
| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders: one render is one pass of the window's root view, a frame; the renders of each pane, `rail`, `topbar`, `sidebar`, `tree`, `main` and `members`; `Later` jobs) and the voice connections up |
| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders: one render is one pass of the window's root view, a frame; the renders of each pane, `rail`, `topbar`, `sidebar`, `tree`, `main`, `members` and `voice`; `Later` jobs) and the voice connections up |
Screenshots are made headless, the way `scripts/shots.sh` makes the Slint
ones: `scripts/gpui-shot.sh out.png swatch 1440x960` runs the binary under
@@ -1199,15 +1203,16 @@ rendered with every frame ([what a change costs](#what-a-change-costs)).
"Voelin"), the search box and the settings button, which log that their
slices are to come (`OpenSearch`, `OpenSettings`).
- **The sidebar** (`sidebar.rs`): the server on screen (name, "9 online · 9
channels" once its presence is known, else its address), the channel tree
(slice 2), the voice card while voice is connecting or connected
(the channel we are in, copy an invite, disconnect, and Hold to talk when the
transmit mode is push-to-talk) and the user's card (nickname, Online,
Observing or Offline, the microphone and sound buttons, which work with
voice).
channels" once its presence is known, else its address, over the server's
banner when it has one: slice 3), the channel tree (slice 2), the voice card
while voice is connecting or connected (the channel we are in, copy an invite,
disconnect, and Hold to talk when the transmit mode is push-to-talk, else the
mode in words) and the user's card (nickname, Online, Observing or Offline, the
microphone and sound buttons, which work with voice).
- **The main area** (`main_panel.rs`): "No server selected" with an Add a server
button, or the server on screen (name, address, its state) with Connect or
Disconnect and Edit, until the voice page and the chat come.
Disconnect, Voice channel (while voice is connected: it opens the voice page,
[below](#the-voice-page-and-the-call-bar)) and Edit, until the chat comes.
- **The server form** (`form.rs`), in the place of the main area until the
dialogs slice: address (all a server needs), name (empty: the server's own),
nickname (the default identity's, else the system user's) and the server's
@@ -1237,14 +1242,15 @@ front end](#shared-with-the-slint-front-end)):
| `edit_bookmark` | `EditServer { id }` | opens the form with `servers::form` |
| `save_bookmark` | `SaveServer` | `logic::bookmark_from_form`, the store, the secrets; shows the server |
| `save_and_connect` | `SaveAndConnect` | saves, then connects into the form's channel or the default one (`servers::connect_to`) |
| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server` |
| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server`; the server that comes on screen has its remembered folds put back (as has any server a transition puts on screen: a save, a connect) |
| `invite` | `Invite` | `logic::invite_link`, the link on the clipboard, the status line's note |
The others of that file: `join_channel`, `join_with_password`, `toggle_collapse`,
`search_members` and `open_client` are slice 2's ([the channel tree and the
members](#the-channel-tree-and-the-members)); `show_voice_view` is the voice
page's (slice 3), `client_audio_changed` the dialogs', and `copied`, which the
Slint toast of a copy needs, `Invite` does for itself. `AddServer`,
page's (slice 3, [below](#the-voice-page-and-the-call-bar)), `client_audio_changed`
the dialogs' (the member card has the volume of a person, `SetMemberVolume`), and
`copied`, which the Slint toast of a copy needs, `Invite` does for itself. `AddServer`,
`CancelServerForm`, `OpenSearch` and `OpenSettings` are the shell's own.
#### Shared with the Slint front end
@@ -1289,7 +1295,8 @@ state: the thread hop of the gateway lookup (`look_up_gateway`: each front end
runs `sequence::find_gateways` on the engine's runtime and comes back through
its own `Later`/`later`), `perform` (what an `Update` does to a window), the
status line's toast, the invite's clipboard write, `HostedEngine` (`engine.rs`),
the guards of the GPUI shell's save (`save_refused`: the sample servers are not
`GlobalPtt` (`hotkey.rs`: the global key's task needs the engine's runtime and the
front end's own way back to its state), the guards of the GPUI shell's save (`save_refused`: the sample servers are not
kept, and a server needs an address, which the Slint dialog checks in
`dialogs.slint` before it calls), the store at start (`Backend::open` against
`run()`: the identity import, the crash reports and `--set` of the Slint one)
@@ -1425,6 +1432,15 @@ through Vulkan on Xvfb `:201` of 3840 by 2160 with openbox, 1440 by 960): the
banner rows, Raid Night and Music, are under the veil, and the avatars of the
tree show one letter.
![the tree with a banner row selected and one under the pointer, dark](ui/gpui-tree-banner-selected-dark.png)
`gpui-tree-banner-selected-dark.png` is the same window with Raid Night selected
(a click) and the pointer on Music: a banner row shows its selection and its
hover as a tint over the picture, as the speaking ring and bars show on Kairo's
row (release build of the commit that tinted them, lavapipe through Vulkan on
Xvfb `:233` of 3840 by 2160 with openbox, 1440 by 960, two `xdotool` moves and
`xwd`, the state under the checkout's `.scratch/`).
What is on screen:
- **The channel tree** (`channels.rs`, in the sidebar between the server card
@@ -1437,9 +1453,14 @@ What is on screen:
the banner picture behind it and our channel highlighted. The banner has the
veil of `components/banner-picture.slint` over it (`widgets::banner_scrim`:
the surface colour, 74 % opaque on the left to 66 % on the right, under the
tint of our channel), so the name keeps more than 4.5 to 1 against any
tints of the row), so the name keeps more than 4.5 to 1 against any
picture in both themes (a test states it for the weakest end over a black
and a white picture). A person's row has their avatar (the first letter
and a white picture). The row's own background (the selected one's and the
hover's) is under the picture, which covers it from the indent on, so a row
with a banner shows its states as translucent tints over the veil: our
channel's accent tint, the selected row's (surface 3 at 75 %) and the hover's
(surface 3 at 50 %, as `channels.slint` tints it). A person's row has their
avatar (the first letter
only, at half the size, under 28 pixels as `avatar.slint` does), name (ours
in the accent colour, someone away muted), badges, a
LIVE tag while they stream, the marks of local mute (or volume) and of their
@@ -1461,19 +1482,21 @@ What is on screen:
power. The search narrows the sections to the names it matches.
- **The member card**: a click on a person opens their card over the panel with
a scrim a click outside closes: name, status, description, groups, badges (what
each is for on hover), talk power and country. It follows the person while it
is open and goes when they leave.
each is for on hover), talk power and country, and since the voice page the
Volume rows: what they are played at, a mute for us and a slider. It follows
the person while it is open and goes when they leave.
- **The password prompt**: joining a channel that has a password and whose
password was not given this connection asks for it (a card over the window,
Enter joins); a password the server refuses asks again, in words. As in the
Slint dialog, Join is off and Enter does nothing while the field is empty
(the prompt stays), and Escape closes it without joining.
(the prompt stays), and Escape closes it without joining, wherever in the
prompt the last click was (below).
#### Per-area signals and cached panes
The foundation's and the shell's reviews left the design for this slice: a
change of the channel tree must not draw the rail, and a talker must not draw
the tree. Two parts of it came from reading gpui-pre 0.3.10 and were checked by
change of the channel tree must not draw the rail, and a talker draws the tree
and the members panel and nothing else (the gate's parity ruling, below). Two parts of it came from reading gpui-pre 0.3.10 and were checked by
the tests:
- **`Update.refresh` is raised as signals** (`signals.rs`). The root state
@@ -1502,15 +1525,24 @@ the tests:
entity builds the rows for both panes on the tree, toolbar and member-card
signals, compares them with the rows it had (`voelin_ui_vm::list::diff`, the
operations the Slint front end applies to its `VecModel`) and emits what
differs. A pane applies the operations to its list state (`gpui::ListState`:
a person who joins is a row inserted and the scroll stays where it was), and a
change that moves none of the rows of a pane emits nothing to it.
- **The tree carries no `talking`.** Its rows are built with the flag cleared,
so someone who starts or stops talking changes the members panel (and the
sidebar's own card when it is us) and not the tree: its pane is not rendered
(the `a_talker_does_not_draw_the_tree_again` test counts it). The Slint tree
draws speaking bars on the row, which would redraw the tree with every start
and stop of someone's voice; this front end leaves them to the members panel.
differs, with the rows the operations lead to (`TreeEvent::Rows(Changes,
Arc<Vec<TreeItem>>)`, `People` the same). A pane applies the operations to its
list state (`gpui::ListState`: a person who joins is a row inserted and the
scroll stays where it was) and to the rows it has, and keeps the rows the
event carries, not the model's at the moment it hears of them; a change that
moves none of the rows of a pane emits nothing to it.
- **The tree marks who talks, and is drawn once for each start and stop.** Its
rows keep `talking`, so the avatar has the green ring and the row the three
speaking bars, as `channels.slint` draws them (the bars stand still: nothing
here draws the window with the clock). Someone who starts or stops talking
changes one row of the tree and one of the members panel, and each of those
two panes is rendered once for it, with the sidebar, which every frame
renders; no other pane is (the `a_talker_changes_one_row_and_draws_the_tree_once`
and `a_talker_redraws_the_tree_and_the_members_panel_and_no_other_pane` tests
count it). The first version of the slice cleared the flag to keep the tree out
of it; the gate ruled for parity with the Slint tree, and the cost was
measured: 9.97 renders of the tree a second for 9.97 starts and stops a second
([what a change costs](#what-a-change-costs)).
#### What a change costs
@@ -1532,20 +1564,18 @@ window's frames, and each pane's passes):
A window nobody touches is not drawn, with the tree and the panel on screen as
before (the shell alone was 192.7 MiB; the pictures and the two panes' state
are the difference, not itemized). Someone who talks is one engine event and so
one frame: the members panel is the only pane that is rendered for it, and the
sidebar, which every frame renders (its cards are small and have no size of
their own to cache at); the rail, the top bar, the main area and the tree are
not rendered at all in the 570 events of the run. GPUI's own thread spends 5 %
one frame: the members panel was the only pane that was rendered for it (the
tree carried no `talking` then; the figures of the talking marks are below),
and the sidebar, which every frame renders (its cards are small and have no size
of their own to cache at); the rail, the top bar, the main area and the tree
were not rendered at all in the 570 events of the run. GPUI's own thread spends 5 %
of a core on the 9.7 frames a second (the first run, of the `aa640cf` tree on a
quieter machine, 3.4 % at 10.0 frames, with `llvmpipe` at 100.9 % and 105.4 % in
all; the loaded machine starved the process of a frame in ten).
The rest is the software device: `llvmpipe` draws the whole 1440 by 960 window
again for every frame, about 90 ms of CPU a frame on this machine, which a GPU
does; so the figure that says what a talker costs the app is the thread's, and
the one that says what a window nobody touches costs is the idle row. (The
Slint tree draws speaking bars on its rows; with them the tree pane would be
rendered for each of those frames too, which is why this one does not: not
measured.)
the one that says what a window nobody touches costs is the idle row.
**Again after the review's fixes** (the banner veil, one letter on small avatars
and the password prompt change what a row draws, not when a pane is rendered):
@@ -1556,6 +1586,23 @@ person talking 10 times a second: 106.4 % (111 %) in all, `llvmpipe` 102.3 %,
GPUI's thread 3.1 %, 225.9 MiB, 10.0 frames a second, rendered per second 0, 0,
10.0, 0, 0, 10.0 (the sidebar and the members panel only, as above).
**Again with the talking marks on the tree** (the speaking ring and bars on the
tree's rows, which the gate's ruling restored; they make the tree pane change
with every start and stop): the talking run on the release build of the commit
that restored them, lavapipe (Mesa 26.2.5, `llvmpipe (LLVM 21.1.8, 256 bits)`
through Vulkan) on Xvfb `:231` of 3840 by 2160 with openbox, 1440 by 960, the
state under the checkout's `.scratch/`, the machine at a load average of 83 at
the start and 41 at the end, 60 samples after the first 15 of 75. A sample person
talking 10 times a second (`VOELIN_DEMO_TALK=10`): 102.2 % (112 %) in all,
`llvmpipe` 95.6 %, GPUI's thread 5.0 % (8 % at most), 224.0 MiB, 9.97 engine
events and 9.97 window frames a second, rendered per second 0, 0, 9.97, 9.97, 0,
9.97 (rail, top bar, sidebar, tree, main, members): the tree pane is rendered
once for each start and stop, as the members panel is, and the rail, the top bar
and the main area not at all. The tree's pane costs no measurable CPU on top: the
thread's 5.0 % is the figure of the first run (5.0 %) and above the second's
(3.1 %), a spread the load of the machine makes, and `llvmpipe` draws the whole
window for a frame whichever pane asked for it.
**Seen against a server** (the TeamSpeak 3 development server of
`dev/docker-compose.yml`, 3.13.8, release build of the tree committed as
`aa640cf` (built just before that commit, whose own changes to the tests came
@@ -1595,6 +1642,34 @@ Alt+F4 ended the app with status 0, 3.3 s after the key, and left no ghost
client on the server. Against the TeamSpeak 6 server the form showed "1 online ·
1 channel", the tree and the panel, and the close ended with status 0.
**Seen again after the minors round** (`phase5/gpui-tree-minors`, the release
build of `1dbe5d5`; one Xvfb of 3840 by 2160 with openbox for each run, `:236`
(the prompt), `:239` (TeamSpeak 3), `:242` (TeamSpeak 6), `:243` (the sample
server's tree) and `:245` (the talking run), after runs on `:235`, `:237` and
`:238` that only found where to click; Mesa 26.2.5's lavapipe,
`llvmpipe (LLVM 21.1.8, 256 bits)` through Vulkan, 1440 by 960; the state under
the checkout's `.scratch/`, no Wayland, no session bus and no XDG directory of
the desktop in any run; the load average 16 to 25; the two development servers
used read-only, nothing created, deleted or reset on them, and one connect to
each). On the sample
server (`VOELIN_DEMO_UI=1`, nobody talks on the real ones): Kairo's row in the
tree has the green ring and the three bars; a click on Raid Night tints the row
over its picture and the pointer on Music tints that one (the picture above); a
double-click on the locked Officers opens the password prompt, a click on the
card's corner takes the focus from the field and the prompt stays, and Escape
closes it. Against the TeamSpeak 3 server (3.13.8, `127.0.0.1:9987`, a nickname
set in the form, Save and connect): "1 online · 1 channel", Default Channel with
the client in it, "Members — 1"; the members search with `zzz` typed says "Nobody
matches." where it said to connect; Alt+F4 ended the app with status 0 and
`clientlist` over ServerQuery after the close showed the query client only, no
ghost. Against the TeamSpeak 6 server (6.0.0-beta13.1, `127.0.0.1:9988`) the
same tree, panel and "Nobody matches.", and the close ended with status 0 (its
ghosts were not looked for: its ServerQuery is SSH). The talking run again on
this build (`VOELIN_DEMO_TALK=10`, 60 samples after the first 15 of 75, load
average 24 to 17): 106 % (114 %) in all, `llvmpipe` 100.7 %, GPUI's thread
4.2 % (7 % at most), 221.8 MiB, 9.98 engine events and frames a second, rendered
per second 0, 0, 9.98, 9.98, 0, 9.98: the tree once for each start and stop.
#### The callbacks and the properties
The plan counts "about 13 properties and 6 callbacks" for the two panes. The
@@ -1622,7 +1697,7 @@ seventh standing in for the chat. The callbacks are GPUI actions
| `connect_voice` (`channels.slint`, the server card's Connect) | `ConnectVoice` | slice 1 (the shell) |
| `Nav.add_server`, `Nav.edit_server` (`channels.slint`, the server card's menu) | `AddServer`, `EditServer { id }` | slice 1 (the shell) |
| `watch_client` (`channels.slint`, the LIVE tag of a person who streams) | none | the tag is drawn and not clickable: the stream viewer, slice 6 |
| `member_action("mute")` and `member_volume` (`members.slint`, the card's mute button and volume slider) | none | the card has no buttons yet: the person's volume, with `open_client` and `client_audio_changed`, the dialogs slice (9) |
| `member_action("mute")` and `member_volume` (`members.slint`, the card's mute button and volume slider) | `SetMemberMuted`, `SetMemberVolume` | slice 3: the card's Volume rows ([below](#the-voice-page-and-the-call-bar)); the volume dialog of `open_client` and `client_audio_changed` stays the dialogs slice's (9) |
| `member_action("watch")` | none | the stream viewer, slice 6 |
| `member_action("message")` | none | the chat, slice 4 |
| `member_action("poke")` | none | the poke dialog, the dialogs slice (9) |
@@ -1631,28 +1706,304 @@ seventh standing in for the chat. The callbacks are GPUI actions
| Slint property (used by) | Here |
|---|---|
| `tree` (`channels.slint`) | `TreeModel::rows`, the `talking` flag cleared |
| `tree` (`channels.slint`) | `TreeModel::rows` |
| `server_members` (`members.slint`) | `TreeModel::people` |
| `member_total` (`members.slint`) | `TreeModel::total` ("Members — N") |
| `member_card` (`members.slint`) | `TreeModel::card` (`voelin_ui_vm::tree::member_card`), shown by `MemberCardView` |
| `members` (the people in our channel: the voice page, not the two files) | built by `tree_view` and not shown: the voice page (slice 3) draws it |
| `members` (the people in our channel: the voice page, not the two files) | `TreeModel::voice` (`TreeEvent::Voice`), built with the other two lists and shown by the voice page (slice 3) |
| `current_server` (`channels.slint`) | `AppState::vm.current` (slice 1) |
| `observing` (`channels.slint`, `members.slint`) | `SidebarView::observing` (slice 1: the user's card says Observing); here also `Emptiness`, the words of a list with nothing in it ("No server yet.", "Loading the channels…", "Connect to see the channels.") |
| `observing` (`channels.slint`, `members.slint`) | `SidebarView::observing` (slice 1: the user's card says Observing); here also `Emptiness`, the words of a list with nothing in it: the tree's ("No server yet.", "Loading the channels…", "Connect to see the channels.") and the panel's ("Loading who is here…", "Connect to see who is here.", and "Nobody matches." for a search that leaves nobody of a server that has people); a server whose voice is connecting is loading |
| `server_title`, `server_icon`, `server_stats` (`channels.slint`, the server card) | slice 1: the sidebar's server card (`ServerItem`'s name and icon, `SidebarView::stats`, "9 online · 9 channels") |
| `voice_connected`, `voice_connecting` (`channels.slint`, the server card and its Connect) | slice 1: `SidebarView::voice_connected` and `voice_connecting`, the voice card ("Voice Connected", "Connecting…") |
| `server_banner` (`channels.slint`, the server card's picture) | not drawn: the sidebar's server card has no banner behind it. The same `BannerPicture` and veil (`widgets::banner_scrim`, which the tree's rows use) would do; it comes with the slice that lays the sidebar's cards again, the voice page and call bar (3) |
| `server_banner` (`channels.slint`, the server card's picture) | `SidebarView::server_banner`, behind the sidebar's server card under the same veil as the tree's rows (slice 3) |
| `Nav.right_panel_width`, `Nav.right_panel_open` (the frame, `desktop.slint`, not the two files) | `ui.members_width`, read at start (no resize handle yet), and the panel is there while a server is on screen (the pins and topics drawers that share it come with the chat) |
`show_voice_view` (the voice page) and `client_audio_changed` (the volume
dialog) are the other server callbacks of the Bridge that these panes will meet
later; neither file uses them.
`show_voice_view` (the voice page, slice 3) and `client_audio_changed` (the volume
dialog) are the other server callbacks of the Bridge that these panes meet;
neither file uses them.
What differs from the Slint tree and panel, beside the tree's talkers above:
What differs from the Slint tree and panel:
the speaking bars stand still (nothing here may draw the window with the clock);
the lists scroll with the wheel and have no scrollbar; a click on a channel
selects it where Slint opens its chat; the card has no buttons; the members
selects it where Slint opens its chat; the card has the volume and the mute of a
person and none of the buttons of the dialogs' slices; the members
panel has no resize handle; the fill spacer's line is drawn with the channel's
own characters, as the rows give it; the sidebar's server card has no banner.
own characters, as the rows give it.
### The voice page and the call bar
Slice 3 of plan section 6 step 3: the voice channel page of the Slint front end
(`screens/voice.slint`, with the `Participant` of `voice-parts.slint`) and its
call bar, the sidebar's server card with its banner behind it, the release guard
of Hold to talk, the global push-to-talk key and the volume of a person, on the
same `voelin-ui-vm` rows (`TreeView::members`) and logic as the Slint front end.
| The larger stage | The smaller stage |
|---|---|
| ![the voice page, dark](ui/gpui-voice-dark.png) | ![the voice page on the smaller stage, dark](ui/gpui-voice-compact-dark.png) |
| ![the voice page, light](ui/gpui-voice-light.png) | ![the voice page on the smaller stage, light](ui/gpui-voice-compact-light.png) |
The pictures are the shell at 1440 by 960 under `scripts/gpui-shot.sh` (the
recipe above: `VOELIN_DEMO_UI=1` with `VOELIN_OPEN=voice` and `voice:compact`, a
display of its own, the state under the checkout's `.scratch/`): the larger
stage on the release build of `7140718` (Xvfb `:511` and `:512` of 3840 by 2160
with openbox, Mesa 26.2.5's lavapipe) and the smaller stage re-shot on the
release build of `15a1b60` after centring its row (Xvfb `:621` and `:622` of
3840 by 2160 with openbox, Mesa 26.3.0's lavapipe, both `llvmpipe (LLVM 21.1.8,
256 bits)` through Vulkan). The first sample
server's Chill Zone: Kairo talks (the green ring and the bars in the corner of
the avatar, "Speaking"), Lumen streams (the blue ring, "Streaming" or LIVE), dex's
microphone is off (the mark in the corner), the channel's banner is behind the
header, and the server's own banner behind the server card of the sidebar. Two
more pictures are from the live run against the TeamSpeak 3 development server
([below](#seen-against-the-servers)): the voice page with a second client
that talks (a real `Event::Talking`), and the card of that person with the
volume rows.
| A real talker (TeamSpeak 3 server) | The volume of a person |
|---|---|
| ![the voice page on a TeamSpeak 3 server, dark](ui/gpui-voice-live-dark.png) | ![a person's card with the volume, dark](ui/gpui-voice-card-dark.png) |
What is on screen:
- **The page** (`voice.rs`, `VoicePage`, a cached pane of its own). It is the main
area while the page is asked for and voice is connected (the Slint front end's
`Nav.voice-view && Bridge.voice-connected`): the server page's Voice channel
button asks for it (`ShowVoiceView { on: true }`, through `logic::show_voice_view`,
which also puts the people of our channel first in the members panel) and
the page's Chat only button gives the area back to the server page, where the
chat will be. A connection that drops takes the page away and a reconnect brings
it back, as in Slint (the flag is kept); Leave asks for the page off and leaves
voice (`LeaveVoice`: `show_voice_view(false)`, then the engine's
`DisconnectVoice`). `MainView` puts the page *instead of* the server page (they
are siblings, never nested: a cached view inside a view that renders again is
rendered again), so `panes.main` is not rendered while the page is up.
- **The header**: the channel's name, its topic, "5 in voice / 50 total" (the
limit when the channel has one) and, behind them, the channel's banner under
the same surface veil as the tree's rows (`widgets::banner_scrim`; the text
reads in the text colour instead of the secondary one over a picture). Copy
invite link (`Invite`), Smaller stage / Larger stage (`ToggleVoiceCompact`,
kept in `ui.voice_compact`, which both front ends read) and Chat only.
- **The people**, from `TreeView::members` as the model's `TreeEvent::Voice` (the
tree model builds the three lists once and tells the page its rows when they
differ, so the page builds nothing of its own): large avatars (80 pixels) in a
wrapping row, centred; a ring that is green while they talk and blue while they
stream (3 pixels, else 2 in the border colour), the mark in the corner of the
avatar (the speaking bars, else the headphones off, else the microphone off), the
name (ours in the accent colour) with the crown of an admin, and "Speaking",
"Streaming" or "Away" with the bars or the monitor mark. A click opens the
person's card (`OpenMember`). The smaller stage is one row of 54 pixel avatars
(a flex-row scroll container whose inner row carries `.flex_none().mx_auto()`),
centred horizontally while the people fit and scrolling sideways from the left
edge without clipping when they outgrow the page, ringed only while they talk
or stream, with the name and the crown, and LIVE under a streamer. A window
under 800 pixels tall has the smaller stage whatever the setting says and the
button is off, with the reason as its tooltip (`Nav.short`): `MainView` tells
the page when the window crosses 800 pixels, since a cached pane does not see
a resize.
- **The call bar**: Mute and Deafen (44 pixel round buttons, red while on:
`SetInputMuted`, `SetOutputMuted`), Share when the server can stream and the
voice settings (`OpenShare`, `OpenVoiceSettings`: logged, their pages are
the stream slices' and the settings slice's), and Leave. `IconButton` keys its
GPUI element ID by both its base ID and its label (`ElementId::NamedChild`,
keeping `.debug_selector` on the base ID), so toggle buttons (`call-mic`,
`call-sound`, `member-mute`, `user-mic`, `user-sound`, `voice-stage`) drop
stale hover/tooltip state and render the updated tooltip as soon as their
label changes. The streams of the Slint page and its channel chat come with
their slices; the page says so where the chat will be.
- **The voice card and the modes.** Hold to talk is for the push-to-talk mode of
the audio settings; for voice activity and for an open microphone the card says
the mode in words instead of showing a button. `SettingChanged` for `audio`,
`client_playback` and `ui.voice_compact` is read again, as the Slint front end's
`setting_changed` does, so the modes, the volumes and the stage follow the
config file and the commands.
- **The volume of a person**: the member card (a click on a person on the voice
page or in the members panel) has the Slint card's Volume rows, the percentage, a
mute for us and a slider (0 to 200 percent in steps of 5), off for a person the
server gave no unique id. They are `SetMemberVolume` and `SetMemberMuted`, which
go through `voelin_ui_vm::settings_page::logic::{open_client,
client_playback_changed}` (the logic the Slint volume dialog calls: the engine's
`SetClientVolume` and `SetClientMuted`, the `client_playback` key by the person's
unique id, the tree's mark of who is muted). The dialog of `open_client` itself,
which the tree's click on a person asks for, stays the dialogs slice's.
- **The server card's banner**: `server_banner` behind the card of the sidebar, as
`ServerHeader` of `channels.slint` has it (the picture covers the card and is
cropped to its inside, the veil lies over it, the stats read in the text
colour). GPUI clips to rectangles, so the picture's corners are square, as the
tree's banner rows'.
**The release guard of Hold to talk and the global hotkey** (the risk slice 2
recorded, hardened in the voice fix round). `AppState` tracks the window button
(`button_held`), the global hotkey (`hotkey_held`), and window teardown
(`shutting_down`) independently, with `stop_transmitting_if_unheld`,
`release_button_hold`, and `release_hotkey_hold`: holding both at once keeps
transmit active until both release without duplicate start or stop commands.
Every path that can orphan a hold is guarded:
- *Voice that drops:* checked per event inside `AppState::handle_events` (not
only across a whole 64-event batch, so a drop and reconnect inside one batch
cannot mask it). Whenever a session leaves `Connected`, any button or hotkey
hold on it ends, and `SetTransmitting(false)` is emitted once if either was
held or the engine still reports `transmitting` (the engine's answer and a
reconnect are not answered). `Sidebar`'s signal observer clears its own
`holding` flag whenever voice disconnects, transmit leaves push-to-talk, the
shown server changes, or `AppState::button_held` no longer matches (it only
sets its own field and never mutates root state).
- *Leaving push-to-talk, switching servers, or removing a server:*
`setting_changed` releases `button_held` when `audio.transmit` leaves
`PushToTalk` (while `!audio_dirty`); `select_server` releases `button_held`
when the held server leaves the screen (without touching `hotkey_held`, so the
global key still releases the server it started on); `delete_bookmark` clears
any hold on the removed session before closing it.
- *Window focus loss and shutdown:* `MainView`'s `observe_window_activation`
unconditionally releases `Sidebar` and calls `AppState::push_to_talk(false)`
when the window becomes inactive (a no-op when `button_held` is `None`;
`hotkey_held` is untouched so the global key keeps working while another
window has focus). `AppState::shutdown` sets `shutting_down`, drops `ptt`, and
releases both holds before sending `CloseSession`, ignoring any late press
that arrives through `Later` after close begins.
Each guard has deterministic tests (`hold_to_talk_is_released_when_voice_drops`,
`hold_to_talk_is_released_when_the_window_loses_the_focus`,
`leaving_push_to_talk_releases_a_held_button`,
`a_drop_and_reconnect_in_one_batch_releases_a_held_button_and_hotkey`,
`holding_the_button_and_the_hotkey_together_stops_only_when_both_let_go`,
`switching_servers_releases_a_held_button_but_keeps_the_global_hotkey`,
`focus_loss_releases_app_button_hold_unconditionally`,
`a_second_hotkey_press_on_another_server_releases_the_first`,
`removing_a_server_clears_active_transmit_holds`,
`closing_releases_a_held_transmit_and_ignores_late_presses`), and each guard was
mutated to confirm its test goes red.
**The global push-to-talk key** (`hotkey.rs`). `voelin_platform::HotkeyManager`
(the desktop's portal on Wayland, XInput2 on X11) runs in a task spawned on the
engine's runtime: the portal backend calls `tokio::spawn` when it is made, which
panics where no tokio runtime is current, and a GPUI foreground task has none
("For the next slices" said so). `run()` starts it once the window is open when
there is an engine, no sample servers and the settings (`ui`: `global_ptt`, on by
default, and `ptt_key`, `Ctrl+Shift+T`) ask for it; the state does not start it by
itself, so that a test of the state with a real engine never asks the desktop for
a shortcut (the first version of the commit did, and the test scheduler found it:
the status line came back from a tokio thread). Its presses and releases come to
GPUI's thread through `Later`: a press transmits into the session on screen while
it has voice, a repeated press on a different connected server ends the previous
session's transmit before starting the new one, and the release ends the session
the press began in, whichever is on screen then. The event loop (`run_loop`,
tested over private `EventStream` / `Registrar` traits without a portal or
display) fails closed on both termination paths, calling `transmit(false)` before
exiting when the command channel closes and before reporting status when the
desktop removes the shortcut mid-hold. How the key stands ("Active: Ctrl+Shift+T
(X11)", why it could not be registered) is in the log and `AppState::ptt_status`;
changing the key at run time (`AppState::set_global_ptt`) is the settings slice's.
The loop is the Slint front end's `GlobalPtt` repeated, as `HostedEngine` is.
#### The properties and callbacks of the voice page
The plan counts 6 properties and 6 callbacks. The properties the page reads, and
the callbacks of `bind/servers.rs` (and of `Nav`, whose functions call it) that its
controls have, each with what takes it here; the first six rows of each table are
the plan's six.
| Slint property (used by) | Here |
|---|---|
| `members` (`voice.slint`) | `TreeModel::voice`, `VoicePage::people` |
| `own_channel` (`voice.slint`, the voice card) | `VoiceHead::channel` |
| `own_channel_topic` (`voice.slint`) | `VoiceHead::topic` |
| `own_channel_banner` (`voice.slint`) | `VoiceHead::banner`, the veil of `banner_scrim` |
| `own_channel_limit` (`voice.slint`) | `VoiceHead::limit` ("5 in voice / 50 total") |
| `server_banner` (`channels.slint`) | `SidebarView::server_banner`, behind the server card |
| `input_muted`, `output_muted`, `voice_connected` (`VoiceButtons`) | `VoiceHead`, the call bar's buttons |
| `audio.transmit` (`VoiceCard`) | `SidebarView::transmit`: Hold to talk, or the mode in words |
| `transmitting` (`VoiceCard`, `UserCard`) | `SidebarView::transmitting` (the button, the ring of our avatar) |
| `Nav.voice_view`, `Nav.voice_compact`, `Nav.short` | `vm.voice_view` (`logic::show_voice_view`), `AppState::voice_compact` (`ui.voice_compact`), `VoicePage::short` |
| `streams`, `messages`, `streams_available`, `can_share` | the stream slices' and the chat's; the call bar shows Share when `streams_available` |
| Slint callback (used by) | Action | What it does |
|---|---|---|
| `show_voice_view` (`Nav.show-voice`) | `ShowVoiceView { on }` | `logic::show_voice_view`: the page asked for or not |
| `disconnect_voice` (the call bar's Leave, with `Nav.show-voice(false)`) | `LeaveVoice` | the page off, then `Command::DisconnectVoice` |
| `set_input_muted`, `set_output_muted` (`VoiceButtons`) | `SetInputMuted`, `SetOutputMuted` | the shell's, from the call bar too |
| `invite` (the header's Copy invite link) | `Invite` | the shell's |
| `open_member` (`Participant`) | `OpenMember` | slice 2's: the card |
| `voice_compact_changed` (`Nav.toggle-voice-compact`) | `ToggleVoiceCompact` | `ui.voice_compact` kept (not with the sample servers) |
| `push_to_talk` (`HoldToTalk`) | `PushToTalk` | the shell's, with the two guards above |
| `Nav.open-settings(voice)`, the share menu | `OpenVoiceSettings`, `OpenShare` | logged: the settings slice and the stream slices |
| `member_volume`, `member_action("mute")` (the card) | `SetMemberVolume`, `SetMemberMuted` | `client_playback_changed` |
What differs from the Slint page: no members button (the panel is there while a
server is on screen), no streams and no chat under the call bar (their slices), no
Share menu (logged), the speaking bars stand still, the page does not open by
itself when voice connects (Slint's chat is its default; here the server page has
the Voice channel button, and `VOELIN_OPEN=voice` asks for it at start), and the
smaller stage is the desktop's row of small avatars (the phone's compact layout is
dropped with the phone layouts).
#### What the voice page costs
`VOELIN_METER=1`, release build of `7140718`, 1440 by 960 on Mesa 26.2.5's lavapipe
through Vulkan on Xvfb `:531` and `:532` with openbox, the first sample server on
screen with the voice page open (`VOELIN_OPEN=voice`: the larger stage, nine
people on the server, five in Chill Zone), the machine's other jobs at a load
average of 10.1 before the first run, 3.7 between the two and 2.4 after (the one-minute figure); the first 15 seconds of 75 left out; CPU in percent of one
core, whose resolution is the 1 % of a clock tick; renders per second as the meter
counts them:
| | CPU, mean (max) | Of it `llvmpipe` | GPUI's thread | Resident memory | Window frames a second | Rendered a second: rail, top bar, sidebar, tree, main, members, voice page |
|---|---|---|---|---|---|---|
| Idle, the voice page of the first sample server on screen | 0.3 % (2 %) | none | 0.1 % (1 %) | 223.2 MiB | 0.0 | 0, 0, 0, 0, 0, 0, 0 |
| A sample person starts or stops talking 10 times a second (`VOELIN_DEMO_TALK=10`) | 123.9 % (127 %) | 117.4 % | 3.6 % (6 %) | 227.9 MiB | 10.0 | 0, 0, 10.0, 10.0, 0, 10.0, 10.0 |
60 samples each. The same two runs on the release build before the last three
small commits (`65b60f2`; Xvfb `:431` and `:432`, load average 25.3 before and 21.0
after): idle 0.5 % (2 %), 220.2 MiB, no pane rendered; talking 109.9 % (122 %) in
all, `llvmpipe` 102.1 %, GPUI's thread 6.4 % (11 %), 226.3 MiB, 9.95 events and
frames a second, the sidebar, the tree, the members panel and the voice page
rendered 9.97 times a second each (59 samples: the loaded machine left a second
out). The software device's share moves with the machine's load (102 to 117 %
here); the thread's, which is the app's, did not.
A window nobody touches is not drawn, with the voice page on screen as before.
Someone who starts or stops talking is one engine event, one frame and one render
of the sidebar (every frame renders it), the tree, the members panel and the voice
page, and none of the rail, the top bar and the main area; the model builds the
rows once for the three lists. The page's own cost is within the spread the load
of the machine makes (the tree slice's figures at the same rate were 102 to 106 %
in all and 3.1 to 5.0 % for GPUI's thread, 4.2 % on the minors round's); `llvmpipe`
draws the whole window again for every frame whichever pane asked for it, which is
the 90 ms of CPU a frame of this software device and what a GPU takes over.
#### Seen against the servers
Release build of `7140718`, the two development servers of
`dev/docker-compose.yml` used read-only (nothing created, deleted or reset; for
each, one connect of the app and one of a second client), a display of its own for
each run (Xvfb `:533` and `:534` of 3840 by 2160 with openbox, Mesa 26.2.5's
lavapipe, `llvmpipe (LLVM 21.1.8, 256 bits)` through Vulkan as the log's "Selected
GPU adapter" says, 1440 by 960), the state under the checkout's `.scratch/`, no
Wayland, no session bus, no XDG directory of the desktop, `ALSA_CONFIG_PATH` empty
(no sound card), driven with `xdotool` and read back with `xwd`. *TeamSpeak 3*
(3.13.8, `127.0.0.1:9987`): the form's Save and connect (the nickname `gpui-voice`)
shows the server page "Connected with voice", and ServerQuery's `clientlist -voice`
has the client in Default Channel; the Voice channel button opens the page with
one person; a second client, `voelinctl connect 127.0.0.1:9987 --nick
voelinctl-talker voice send --tone 440 --seconds 25`, joins and talks: the page
shows two people and the talker's ring, the bars in the corner of their avatar
and "Speaking" (the server's `client_flag_talking=1`, the page's marks from the
engine's `Talking` events), the same in the tree and the panel, which lead with
"In Voice — 2". The call bar's mute: the server says `client_input_muted=1`;
deafen: `client_output_muted=1` too; both clicked back: 0 and 0. Hold to talk held
with the pointer says "Talking…" and rings our avatar, as does `Ctrl+Shift+T` held
with `xdotool` (the log's line from the hotkey task: "Active: Ctrl+Shift+T
(X11)"); there is no microphone, so no audio goes out and the server's
`client_flag_talking` stays 0 for our client: the held key and button are seen in
the window, and the engine got `SetTransmitting`. The smaller stage, and the card
of the talker with the volume at 100 %. Leave: the page goes, and `clientlist`
does not have the client; Alt+F4 ended the app with exit status 0 and `clientlist`
after the close had no ghost of the app's client either. *TeamSpeak 6*
(6.0.0-beta13.1, `127.0.0.1:9988`), the same steps up to Leave (the smaller stage
and the card were not repeated) with Share in the call bar (the server can
stream: the click is logged) and no ServerQuery (it is SSH): the same page, marks,
hold, key and close, exit status 0; the pictures here are the TeamSpeak 3 run's.
### The theme
@@ -1722,13 +2073,15 @@ Slint `Bridge` (`ui/bridge.slint:801-1206`; properties / callbacks):
`toggle_collapse`, `search_members` and `open_member` as actions beside the
shell's (`open_client` logged), and the password prompt the transitions ask
for;
3. **next: the voice page and the call bar** (6 / 6): the people of our
channel (`TreeView::members`, built and not shown yet), `show_voice_view`,
the voice card's controls, the sidebar's server card with the banner behind
it (`server_banner`, which the tree slice left out:
[the table](#the-callbacks-and-the-properties)), and the release guard of
Hold to talk (below);
4. chat, the composer and emoji (about 19 / 18, and the `Emoji` global 3 / 3):
3. the **voice page and the call bar** (done,
[above](#the-voice-page-and-the-call-bar); 6 / 6): the people of our channel
(`TreeView::members`, through the tree model) with their marks,
`show_voice_view`, the call bar (mute, deafen, Share and the voice settings
logged, Leave) with the remembered smaller stage, the voice card's modes, the
volume of a person on the member card, the sidebar's server card with the banner
behind it (`server_banner`), the release guard of Hold to talk and the global
push-to-talk key on the engine's runtime;
4. **next:** chat, the composer and emoji (about 19 / 18, and the `Emoji` global 3 / 3):
first the two open choices of the report that it touches
(design/gpui-spikes.md, "Open choices for step 3"): emoji (the one-line
`gpui-pre-wgpu` patch for colour emoji, or Noto Color Emoji bundled with a
@@ -1765,7 +2118,67 @@ the slices that meet it; none of it is a defect of what exists today.
its own and a signal of its own, embeds it cached as a sibling of the other
panes (a cached view inside a view that renders again is rendered again), and
raises its flag from `Signals::areas`. A new area is one more variant of
`signals::Area`.
`signals::Area`. The voice page (slice 3) is such a pane and needed no new area:
it watches the servers' and the toolbar's signals for its header and call bar,
takes its people from the model's `TreeEvent::Voice`, and `MainView` pushes
what no signal says (the stage chosen, the window too short) into it.
- **No state change from a signal's observer, inside a flush.** The model
listens to three signals (tree, toolbar, member card) and a batch raises
several of them, so it may refresh twice in one flush of GPUI's effects, and
what it emitted the first time is delivered after the second refresh has
run. An observer that changes the state in that window (`select_server`,
say, in the observer of a signal) makes the second refresh a different list
from the one the first operations were made for. The events carry their rows
for that reason, and the panes check in debug builds that the operations lead
from the rows they have to the rows carried (`debug_check`); a probe in the
tests makes exactly this change, from the observer of the toolbar signal
during a Presence flush, and found the old code indexing past the end of the
rows (`a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows`).
The rule for a new part is that an observer of a signal reads the state and
sets its own fields, and a change of the root state belongs to an action's
handler or a task of its own, not to a signal's observer. The events that
carry no rows (`Selection`, `Lists`, `Card`) are read from the model at
delivery and end right whatever the order.
- **The model builds everything for every batch it hears of.** A raised batch
builds the whole `tree_view` again: every channel and every person, O(people
+ channels) rows, and for each picture a row refers to the stat of its file
(`ImageSource::file`'s stamp, the review counted two per picture); then
`list::diff` against the rows it had. A talker's start or stop is one row of
change and the whole list built. The batches themselves are one build each
now (the model keeps the generations of its three signals it last built at,
so the signals of one change, three for a picture that arrives, are one
build: `a_picture_that_arrives_builds_the_rows_once`), but what a build costs
is what a server of hundreds of people will pay for each event. A refresh that
only flips `talking` of the rows it has (the talker's row, from the event's
client) or a reuse of the `ImageRef`s of the rows that did not change is still
a later slice's, when a measurement on a large server says it matters; the
9-person sample server does not. The voice page (slice 3) did not need it: its
people are the third list of the same build (`TreeView::members`), not a
second build, and a talker is still one build for the tree, the panel and the
page ([what the voice page costs](#what-the-voice-page-costs)).
- **The rail, the top bar and the main area refresh on the servers flag only.**
Before the tree slice they compared what they would show with what they
showed on every notify of the root; they listen to `Refresh::servers` now
(`signals.rs`, the per-area signals). A transition of `voelin-ui-vm` that
changes what they show and forgets to set `servers` leaves them stale, and
the Slint front end, which redraws by the same flags, is stale with it: the
flags of `Refresh` are the contract between the transitions and both front
ends, and a new transition sets every flag of what it touches. Nothing tests
that for the transitions that exist; a test per front end that plays the
events through `events::handle` and compares the parts with a rebuild from
the state would.
- **The members search's caret blink draws the window twice a second.** While
the search box is open and focused, the widget's caret blinks every 500 ms and
notifies its input, which the members panel and the window draw again: on the
first sample server, 2.00 window frames a second, 2.00 renders of the sidebar
and of the members panel and none of the others, `llvmpipe` at 21 % of a
core and GPUI's thread at 0.6 % (the release build of `f28c02a`, Xvfb `:234`
with openbox and lavapipe, the search opened with a click, 27 samples after
the first 15 of 42, load average 8 to 12). On a GPU that is two frames a second
of a mostly static window; the software device pays 90 ms of CPU for each. The
field of the chat's composer (slice 4) has the same blink; turning it off or
slowing it is the widget's option, if gpui-component has one, else a
property of the field the slice decides.
- **A click renders every pane; a hover only the pane it is over.** In gpui-pre
0.3.10 pressing a clickable element and releasing it call `window.refresh()`
(`elements/div.rs`), which ignores every cache for that frame, so a click on a
@@ -1777,23 +2190,32 @@ the slices that meet it; none of it is a defect of what exists today.
What the caches save is the stream of engine events (a talker, a join), not
the user's own clicks.
- **The tree's and the panel's lists have no scrollbar and the panel no resize
handle**; the wheel scrolls (`gpui::ListState`), as the voice page's and the
chat's lists will have to as well, with gpui-component's scrollbar if it fits
a `ListState`, and `ui.members_width` is read at start.
handle**; the wheel scrolls (`gpui::ListState`), as the chat's list will have to
as well, with gpui-component's scrollbar if it fits a `ListState`, and
`ui.members_width` is read at start. The voice page's people scroll with the
wheel too (a plain scrolling container: down on the larger stage when the rows
outgrow the page, sideways on the smaller one) and have no scrollbar.
- **Three copies stay in the Slint crate**, because `voelin-ui` is not edited
beyond the identity helper in this round: `connect_into` and the two joins of
`bind/servers.rs` (the shared ones are `sequence::join_channel`,
`join_with_password` and its `connect_into`), the card `refresh_member_card`
builds inline (`tree::member_card`), and `open_member` setting the session's
field (`logic::open_member`). They go with Slint (step 9), or each is a call
of the shared one when the Slint crate is next touched.
- **`SettingChanged` for the audio and the playback keys is not reloaded.**
`AppState::setting_changed` follows `ui.theme` and `ui.font_scale` only; the
Slint front end also reloads `audio` (unless the page has unsaved edits) and
`client_playback`, the crash-reports flag and the decoder keys. The values the
window keeps copies of (`vm.audio`, `vm.playback`) go stale when a command,
the config file or another window changes them; the settings slice (5) adds
the reload with the page that shows them.
of the shared one when the Slint crate is next touched. Until then the
shared versions in `voelin-ui-vm` (`sequence::join_channel`,
`join_with_password` and `connect_into`, `logic::join_channel`,
`join_with_password` and `open_member`, `tree::member_card`) are called by
the GPUI front end alone, and Slint's copies can drift from them: a change
to the rules of a join or of the card is made in both, or the Slint copy
becomes the call first.
- **`SettingChanged` is reloaded for the keys the voice page shows, not yet for
all of the Slint front end's.** `AppState::setting_changed` follows `ui.theme`
and `ui.font_scale`, and since the voice slice `audio` (unless the page has
unsaved edits: `audio_dirty`), `client_playback` and `ui.voice_compact`. The
Slint front end also reloads the crash-reports flag, the stream audio sources
and the decoder keys; and the `ui` value (the hotkey's `global_ptt` and
`ptt_key` are read at start only here); the settings slice (5) and the stream
slices add those with the pages and the parts that use them.
- **Settled by the shell slice: the engine-event task and the tick.** The task
takes what is queued (64 events at most) in one `update` with one
`cx.notify()` and yields between steps, and the tick notifies nobody (the
@@ -1808,12 +2230,28 @@ the slices that meet it; none of it is a defect of what exists today.
start and takes the focus back when the element that had it is gone
(`on_focus_lost`: the form closed, a button replaced by another). A later
window (the Stream Studio's) does the same, and a new page's buttons dispatch
actions the root handles rather than listeners of their own.
- **The hotkey portal calls `tokio::spawn`** (`voelin-platform`,
`hotkey/portal.rs`, `PortalBackend::new`): it panics where no tokio runtime
is current, and a GPUI foreground task has none. The GPUI front end starts
the hotkey task on the engine's runtime (`runtime.spawn(...)`), as the Slint
front end's `GlobalPtt::start(runtime, ...)` does, not from a foreground task.
actions the root handles rather than listeners of their own. A key that
belongs to an overlay needs the overlay on that path. The root's handle takes
the focus on every mouse down inside the window (GPUI transfers it to the
element under the pointer that has a handle, the root being under all of
them), and the overlay is a child of the root, not an ancestor of the root's
handle: a click on the overlay that no handle inside it takes leaves the
focus on the root, and the overlay's key context is off the path. The
password prompt therefore holds a focus handle of its own on its scrim (the
card is on it), and Escape is a key binding of its key context
(`shell::bind_keys`, called beside `gpui_kit::init`), not a listener on the
field's `Escape`: with the field focused its Escape passes the key on and the
binding closes the prompt, with anything else in the prompt focused the
binding is the only one there.
- **Settled by the voice slice: the hotkey runs on the engine's runtime.** The
hotkey portal calls `tokio::spawn` (`voelin-platform`, `hotkey/portal.rs`,
`PortalBackend::new`): it panics where no tokio runtime is current, and a GPUI
foreground task has none, so `hotkey.rs` spawns the task on the engine's
runtime, as the Slint front end's `GlobalPtt::start(runtime, ...)` does, and
`run()` starts it (`AppState::start_global_ptt`), never the state itself: a
test of the state with a real engine would ask the desktop for a shortcut. A
new part that talks to the desktop (a portal, a hotkey) is started by `run()`
and not by `AppState::new` for the same reason.
- **`PortalCapture::stop` closes the portal session only inside a tokio
runtime** (`voelin-media`, `capture/portal.rs`: `Handle::try_current()`;
elsewhere the session closes only with the connection). Stop a capture inside
@@ -1861,15 +2299,57 @@ the slices that meet it; none of it is a defect of what exists today.
`overlay` gets `scrim`), and gpui-base's non-colour tokens (radii, spacing,
type, shadows, motion) are not written: gpui-base 0.8.1 has no storage to
write them to, so those live in `VoelinTheme::metrics` only.
- **The TeamSpeak 3 development server bans an address that connects in a
burst** (tooling, not the app). `dev/docker-compose.yml` allowlists the
private ranges so that the addresses clients reach it from skip the
anti-flood bans "that rapid test connections would otherwise trigger"; a
client that is not in them, or a script that connects and closes many times
in a few seconds, gets banned by it for a while, and its connects are refused
until the ban ends (ServerQuery's `banlist` shows it, `banclear` lifts it,
which is for whoever owns the server). A live run of the front end connects
once, and runs that follow one another are spaced; the servers are used
read-only by a run, never reset (`docker compose down` or `-v` is not part of
one).
- **The close grace is seen end to end now** (the shell opens sessions): a
connected window closed with Alt+F4 leaves no ghost client on the TeamSpeak 3
development server and exits with status 0 ([The desktop
shell](#the-desktop-shell)). `run()` waits `CLOSE_GRACE` (500 ms) for the engine
to send the closes only when the window's close found sessions to close.
- **Four risks of the shell the gate found by reading, left to the slices that
- **What the voice slice leaves to the slices that meet it.**
- *The chat's slice puts the way to the voice page where the chat is.* Today the
server page has the Voice channel button and the voice page's Chat only goes
back to it; with the chat, the button goes to the chat's header as in Slint
and the page's lower part is the channel's chat (the page says so where it
will be). `show_voice_view(true)` already opens the channel's chat tab in the
state (`open_chat`, with `focus`), whose reading marks wait for the front
end's answer to `Host::chat_shown` (`ShellHost` says `false` until a page
shows a chat), so the chat slice answers that from its own state.
- *The streams of the Slint page and the Share menu* are the stream slices':
the call bar's Share is logged (`OpenShare`) and shows when the server can
stream (`streams_available`), and the stream cards go between the people and
the call bar.
- *The person's volume writes `client_playback` at every step of a drag* (the
Slint card does too: `member_volume` stores each change). A settings page
that shows the volumes, or a profile that shows the writes, may want the
write on release (`SliderEvent::Release`) and the engine's command at every
step. The volume dialog the tree's click on a person asks for (`OpenClient`)
is still logged: the dialogs slice's.
- *The hotkey's key is read at start.* `AppState::set_global_ptt` is the entry
for the settings page that changes it, and the `ui` value is not reloaded on
`SettingChanged` (above).
- *A test of a pane that follows the window's height resizes the window first*:
GPUI's test platform has a window of 1024 by 768, which is under the 800
pixels of the voice page's smaller stage (`voice_tests.rs`, `tall`).
- *Two X11 test binaries need an Xvfb with no window manager* (`voelin-media`'s
`x11_capture` and `voelin-platform`'s `x11`: CI has "xvfb only"): on
`spikes/gpui/headless.sh`'s display, with openbox, they fail (the first reads
the wrong pixels of its test window, the second hears no release of the key),
and they pass on the same display with `headless.sh -n`.
- **Three risks of the shell the gate found by reading, left to the slices that
meet them** (none reproduced here, none is a defect of a path the shell's
tests exercise):
tests exercise; the fourth, Hold to talk staying on if voice drops while the
button is held, was settled by the voice slice, [above](#the-voice-page-and-the-call-bar)):
- *The server on screen is not remembered across restarts.* `AppState::new`
takes the first saved server (`bookmarks.first()`), whichever the user had
on screen; the Slint app does the same and keeps only the last voice channel
@@ -1879,12 +2359,6 @@ the slices that meet it; none of it is a defect of what exists today.
without asking*, and what was typed in it is gone (`MainView::select_server`
and `delete_server` drop `form`). The dialogs slice (9) turns the form into
a dialog; it keeps the draft or asks.
- *Hold to talk stays on if voice drops while the button is held.* The voice
card, with the button, goes when voice leaves `Connected`, so the release
(`on_mouse_up`, `on_mouse_up_out`) has no element to land on: `Sidebar`
keeps `holding` and the session keeps `transmitting` until the next press.
Releasing on the window, or clearing the flag when voice drops, belongs
with the voice page (slice 3).
- *A tiling compositor's tile is stored as the window size* (and, on X11
under a tiling window manager, as its position): `ui.window` takes what the
window reports without asking whether it is tiled or floating, so the next
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 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