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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:22:40 +03:00
44 changed files with 8928 additions and 372 deletions

No files matched your search

+40 -4
View File
@@ -31,10 +31,46 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
sound, hold to talk and copy an invite link, as in the Slint app; the window's
title names the server on screen, and its size and whether it was maximized
are kept for the next run (setting `ui.window`; on X11 the window is
maximized once it is shown, not before the window manager has it). The channel tree, the chat and the other pages are the
next slices; the search and the settings buttons only log that. `VOELIN_DEMO_UI=1`
shows the Slint app's sample servers without sending or keeping anything
(docs/ui.md, "The desktop shell").
maximized once it is shown, not before the window manager has it, and a
resize made before it answers is kept). The chat and the other pages are the
next slices; the search and the settings buttons only log that.
`VOELIN_DEMO_UI=1` shows the Slint app's sample servers without sending or
keeping anything (docs/ui.md, "The desktop shell").
- The GPUI front end's channel tree and members panel. The server on screen's
channels nest in the sidebar with their spacers, icons, banners (under a veil
that keeps the names readable on any picture), locks and counts, and the
people in them with their badges and marks; a click selects a channel, a
double-click joins it (a locked one asks for its password: Enter joins, and
Escape closes the prompt), the chevron folds it, a right-click offers the
same, and what is folded and selected is kept for each server (setting
`ui.tree`). The panel on the right lists everyone on the server in sections,
with a search; a click on a person opens their card. A person who starts or
stops talking is marked in the tree (the ring on their avatar and the bars on
their row, as in the Slint app) and the members panel, which are redrawn for
it and nothing else of the window, and the pictures the engine writes again show
at once. `VOELIN_METER=1` counts the renders of each pane;
`VOELIN_DEMO_SERVER` and `VOELIN_DEMO_TALK` pick the sample server and make a
sample person talk (docs/ui.md, "The channel tree and the members").
- The GPUI front end's voice channel page and call bar. A server's Voice channel
button (or `VOELIN_OPEN=voice`) shows the channel we are in with its topic,
its banner and who is there: large avatars ringed green while they talk and
blue while they stream, with the marks of a microphone or sound that is off,
and under them the call bar (mute, deafen, share and the voice settings, which
only log until their pages come, and Leave). The smaller stage, one row of
small avatars centred while it fits and scrolling sideways when crowded, is
remembered and a window under 800 pixels tall always has it (the same setting
as the Slint app's); toggle icon buttons refresh their tooltips as soon as
their state flips. The sidebar's server card shows the server's banner, a
person's card has their volume and a mute for us, and the voice card says the
transmit mode when it is not push-to-talk. Hold to talk and the global
push-to-talk key (`Ctrl+Shift+T` by default, as in the Slint app, working
while another window has focus) track button and hotkey holds independently and
fail closed across voice drops (including drop and reconnect within one event
batch), window focus loss, leaving push-to-talk mode, switching or removing
servers, repeated portal activations across servers, desktop shortcut removal,
hotkey task exit, and window shutdown. A person's picture is round in its
avatar. `voelin-gpui` is still not the app (docs/ui.md, "The voice page and
the call bar").
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
+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).
File diff suppressed because it is too large. Load diff
+6 -3
View File
@@ -21,7 +21,9 @@ use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob};
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
use voelin_ui_vm::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings};
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_TREE, UI_WINDOW, UiSettings,
};
/// The client's database, its settings and its secrets.
pub struct Backend {
@@ -67,10 +69,11 @@ fn open_settings(dir: &Path) -> Settings {
voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
}
/// The key that only this front end uses: where the window was
/// (`ui.window`).
/// The keys that only this front end uses: where the window was
/// (`ui.window`) and what the channel trees remember (`ui.tree`).
fn register_own_keys(prefs: &Settings) {
prefs.register(&UI_WINDOW);
prefs.register(&UI_TREE);
}
impl Backend {
+65 -4
View File
@@ -7,8 +7,19 @@
//! 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; nothing is sent to the engine or kept in the store.
//! the app's own events, with their pictures as files of a folder in the
//! temporary directory (removed when the window closes); nothing is sent to
//! the engine or kept in the store.
//! - `VOELIN_DEMO_SERVER=2`: with `VOELIN_DEMO_UI`, the sample server on
//! screen, counting from 0 (the first, which is connected and populated, is
//! the default; the second is observed, the third not connected).
//! - `VOELIN_DEMO_TALK=10`: with `VOELIN_DEMO_UI`, one of the sample people
//! starts and stops talking this many times a second, through the app's own
//! events (what the meter measures while someone talks).
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
//! one the settings give (`ui.theme`).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the
@@ -34,8 +45,25 @@ pub enum Page {
pub struct Switches {
/// The page to open on.
pub open: Page,
/// The voice channel page is asked for (`VOELIN_OPEN=voice`): it shows
/// once voice is connected.
pub voice: bool,
/// With the voice page, the smaller stage, as the switch says (it is not
/// stored, as the Slint front end's `voice:compact`).
pub voice_compact: bool,
/// Show the sample servers instead of the stored ones.
pub demo_ui: bool,
/// Write the sample servers' pictures to a folder of the temporary
/// directory and deliver them: what the binary does with the sample
/// servers, and what a test asks for by name (a test that does not leaves
/// nothing behind).
pub demo_pictures: bool,
/// The sample server to show, by its place in the list, when the switch
/// names one.
pub demo_server: Option<usize>,
/// How many times a second a sample person starts or stops talking (with
/// the sample servers), when the switch names a rate.
pub demo_talk: Option<f32>,
/// The theme mode, when the switch names one.
pub theme: Option<Choice>,
/// The text size factor, when the switch names one.
@@ -50,7 +78,12 @@ impl Default for Switches {
fn default() -> Self {
Self {
open: Page::Shell,
voice: false,
voice_compact: false,
demo_ui: false,
demo_pictures: false,
demo_server: None,
demo_talk: None,
theme: None,
font_scale: None,
window: None,
@@ -73,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)"
),
}
}
@@ -97,8 +132,21 @@ impl Switches {
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
if let Some(text) = get("VOELIN_DEMO_SERVER") {
match text.trim().parse::<usize>() {
Ok(place) if place < 3 => switches.demo_server = Some(place),
_ => tracing::warn!("VOELIN_DEMO_SERVER={text}: 0, 1 or 2 (a sample server)"),
}
}
if let Some(text) = get("VOELIN_DEMO_TALK") {
match text.trim().parse::<f32>() {
Ok(rate) if (0.1..=100.0).contains(&rate) => switches.demo_talk = Some(rate),
_ => tracing::warn!("VOELIN_DEMO_TALK={text}: a rate from 0.1 to 100 a second"),
}
}
let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0"));
switches.demo_ui = flag("VOELIN_DEMO_UI");
switches.demo_pictures = switches.demo_ui;
switches.meter = flag("VOELIN_METER");
switches
}
@@ -131,21 +179,32 @@ mod tests {
#[test]
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch"),
("VOELIN_OPEN", "swatch,voice:compact"),
("VOELIN_DEMO_UI", "1"),
("VOELIN_DEMO_SERVER", "2"),
("VOELIN_DEMO_TALK", "10"),
("VOELIN_DEV_THEME", "light"),
("VOELIN_FONT_SCALE", "1.25"),
("VOELIN_WINDOW_SIZE", "1440x960"),
("VOELIN_METER", "1"),
]);
assert_eq!(s.open, Page::Swatch);
assert!(s.demo_ui);
assert!(s.voice && s.voice_compact, "the voice page, with the smaller stage");
assert!(s.demo_ui && s.demo_pictures, "the sample servers come with their pictures");
assert_eq!(s.demo_server, Some(2));
assert_eq!(s.demo_talk, Some(10.0));
assert_eq!(s.theme, Some(Choice::Light));
assert_eq!(s.font_scale, Some(1.25));
assert_eq!(s.window, Some((1440.0, 960.0)));
assert!(s.meter);
}
#[test]
fn the_voice_page_alone_has_the_larger_stage() {
let s = env(&[("VOELIN_OPEN", "voice")]);
assert_eq!((s.open, s.voice, s.voice_compact), (Page::Shell, true, false));
}
#[test]
fn what_makes_no_sense_is_left_out() {
let s = env(&[
@@ -154,6 +213,8 @@ mod tests {
("VOELIN_FONT_SCALE", "9"),
("VOELIN_WINDOW_SIZE", "10x10"),
("VOELIN_DEMO_UI", "0"),
("VOELIN_DEMO_SERVER", "7"),
("VOELIN_DEMO_TALK", "fast"),
("VOELIN_METER", "0"),
]);
assert_eq!(s, Switches::default());
+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);
});
}
}
+7
View File
@@ -11,8 +11,11 @@ pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod hotkey;
pub mod meter;
pub mod pictures;
pub mod shell;
pub mod signals;
pub mod swatch;
pub mod theme;
pub mod view;
@@ -148,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)
@@ -215,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.
+57 -3
View File
@@ -41,6 +41,44 @@ impl Counter {
}
}
/// How many times each pane of the window was rendered (per second). A pane
/// is an entity of its own that the window draws again only when it was
/// notified (`Entity::cached`), or when something below it was; the figures
/// say which panes a change of the state cost.
#[derive(Clone, Default, Debug)]
pub struct Panes {
/// The server rail.
pub rail: Counter,
/// The top bar.
pub topbar: Counter,
/// The sidebar (the server card, the voice and user cards; the tree is
/// inside it).
pub sidebar: Counter,
/// The channel tree.
pub tree: Counter,
/// The main area.
pub main: Counter,
/// The members panel.
pub members: Counter,
/// The voice channel page.
pub voice: Counter,
}
impl Panes {
/// The counters with the names the meter reports them under.
pub fn named(&self) -> [(&'static str, Counter); 7] {
[
("rail", self.rail.clone()),
("topbar", self.topbar.clone()),
("sidebar", self.sidebar.clone()),
("tree", self.tree.clone()),
("main", self.main.clone()),
("members", self.members.clone()),
("voice", self.voice.clone()),
]
}
}
/// The app's own numbers the meter reports besides the process's.
#[derive(Clone, Default, Debug)]
pub struct Counters {
@@ -50,6 +88,8 @@ pub struct Counters {
pub ticks: Counter,
/// Windows drawn (frames, per second).
pub renders: Counter,
/// Renders of each pane of the window (per second).
pub panes: Panes,
/// Jobs other threads handed to the foreground through
/// [`crate::app::Later`] (per second).
pub later_jobs: Counter,
@@ -194,12 +234,15 @@ pub fn start(counters: Counters) {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated = [
let rated: Vec<(&str, Counter)> = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
("later_jobs", counters.later_jobs.clone()),
];
]
.into_iter()
.chain(counters.panes.named())
.chain([("later_jobs", counters.later_jobs.clone())])
.collect();
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
loop {
@@ -232,6 +275,17 @@ pub fn start(counters: Counters) {
mod tests {
use super::*;
#[test]
fn the_panes_are_counted_by_name() {
let panes = Panes::default();
panes.members.incr();
let named = panes.named();
let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect();
assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]);
let seen: Vec<u64> = named.iter().map(|(_, counter)| counter.get()).collect();
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
}
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
+205
View File
@@ -0,0 +1,205 @@
//! Pictures of the engine's cache on screen.
//!
//! The engine writes a picture that arrives again into the same file in its
//! cache (an avatar or a server icon that changed), and GPUI's `img(path)`
//! keeps what it decoded in the asset cache under the path alone, so the new
//! picture would never show. Here the key of a decoded picture is the file
//! and what the file was when the reference to it was made
//! ([`PictureKey`]: the path and the [`Stamp`] of `voelin_ui_vm::image`, its
//! length and time), so a reference made after the file changed is another
//! picture: it is decoded, and the lists that show it compare unequal and
//! draw the row again. What a changed file left in the cache (the decoded
//! copy under the old key, and the texture the atlas made of it) is dropped
//! when the engine says the file was written again
//! ([`forget_stale`], for `Update::reloaded`).
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::Arc;
use gpui_kit::{
App, Asset, Global, ImageAssetLoader, ImageCacheError, ImageSource, Img, RenderImage, Resource,
img,
};
use voelin_ui_vm::image::{ImageRef, ImageSource as Picture, Stamp};
/// What identifies a decoded picture: the file in the engine's cache and what
/// it was when the picture was referred to.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PictureKey {
path: Arc<Path>,
stamp: Stamp,
}
impl PictureKey {
/// The key of a reference to a file of the cache; none for no picture, a
/// picture that cannot be shown (missing or damaged: the reference's
/// size is none) and the pictures that are not files, which the slices
/// that decode them show.
pub fn of(image: &ImageRef) -> Option<Self> {
match &**image {
Picture::File { path, stamp } if image.size().width > 0 => {
Some(Self { path: Arc::from(path.as_path()), stamp: *stamp })
}
_ => None,
}
}
/// The file.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Decodes the file of a [`PictureKey`] as `img(path)` does, keeping the
/// result under the whole key.
enum PictureLoader {}
impl Asset for PictureLoader {
type Source = PictureKey;
type Output = Result<Arc<RenderImage>, ImageCacheError>;
fn load(
source: PictureKey,
cx: &mut App,
) -> impl Future<Output = Self::Output> + Send + 'static {
<ImageAssetLoader as Asset>::load(Resource::Path(source.path), cx)
}
}
/// The keys that were drawn, by file: what [`forget_stale`] has to look at.
#[derive(Default)]
struct Drawn(HashMap<Arc<Path>, Vec<PictureKey>>);
impl Global for Drawn {}
/// Note that `key` is being drawn.
fn note(key: &PictureKey, cx: &mut App) {
let known = cx.has_global::<Drawn>()
&& cx.global::<Drawn>().0.get(key.path()).is_some_and(|keys| keys.contains(key));
if !known {
cx.default_global::<Drawn>().0.entry(key.path.clone()).or_default().push(key.clone());
}
}
/// The picture at `key` as an image element: decoded once per key, and again
/// when the file is another by the stamp. Give it a size and an object fit.
pub fn picture(key: PictureKey) -> Img {
img(ImageSource::Custom(Arc::new(move |window, cx| {
note(&key, cx);
window.use_asset::<PictureLoader>(&key, cx)
})))
}
/// The engine wrote the file at `path` again: drop what was decoded of it
/// under a stamp it no longer has, and the textures the atlas made of that.
/// The picture under the stamp it has now (a reference made after the write)
/// is kept; one that is made from the old file is drawn again when it is next
/// asked for.
pub fn forget_stale(path: &Path, cx: &mut App) {
if !cx.has_global::<Drawn>() {
return;
}
let now = Stamp::of(path);
let stale: Vec<PictureKey> = {
let Some(keys) = cx.global_mut::<Drawn>().0.get_mut(path) else { return };
let (stale, kept) = std::mem::take(keys).into_iter().partition(|key| key.stamp != now);
*keys = kept;
stale
};
for key in stale {
if let Some(Ok(image)) = cx.fetch_asset::<PictureLoader>(&key) {
cx.drop_image(image, None);
}
cx.remove_asset::<PictureLoader>(&key);
}
}
/// Whether the decoded copy of `key` is in the asset cache (the tests ask).
#[cfg(test)]
pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool {
cx.has_asset::<PictureLoader>(key)
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use voelin_ui_vm::image::ImageSource as Source;
use super::*;
use crate::backend::testing::TempDir;
/// A PNG of `width` by 2 pixels.
fn png(width: u32) -> Vec<u8> {
voelin_ui_vm::dev::logic::demo_picture(width, 2, 1)
}
/// The key of a picture follows the file: a reference made after the
/// engine wrote the file again is another picture, one made before still
/// refers to the old, and what is not a file of the cache has none.
#[test]
fn the_key_of_a_picture_changes_when_the_file_does() {
let dir = TempDir::new("picture-key");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let first = Source::file(&path);
let key = PictureKey::of(&first).expect("a picture in the cache");
assert_eq!(key.path(), path);
assert_eq!(PictureKey::of(&Source::file(&path)), Some(key.clone()), "same file, same key");
std::fs::write(&path, png(7)).unwrap();
let second = PictureKey::of(&Source::file(&path)).unwrap();
assert_ne!(second, key, "the file was written again");
assert_eq!(PictureKey::of(&first), Some(key), "a reference made before keeps its own");
assert_eq!(PictureKey::of(&Source::none()), None);
assert_eq!(PictureKey::of(&Source::file(dir.0.join("missing"))), None);
std::fs::write(dir.0.join("damaged"), b"not a picture").unwrap();
assert_eq!(PictureKey::of(&Source::file(dir.0.join("damaged"))), None);
assert_eq!(PictureKey::of(&Source::rgba(1, 1, vec![0; 4])), None, "not a file");
}
/// A picture rewritten into the same file is decoded again under its new
/// key, and what was decoded of the old one is dropped when the engine says
/// the file was written again; the key of the file as it is stays.
#[gpui::test]
fn a_picture_written_again_is_decoded_again_and_the_old_copy_goes(cx: &mut TestAppContext) {
let dir = TempDir::new("picture-reload");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let old = PictureKey::of(&Source::file(&path)).unwrap();
let width = |cx: &mut TestAppContext, key: &PictureKey| {
cx.update(|cx| match cx.fetch_asset::<PictureLoader>(key) {
Some(Ok(image)) => Some(image.size(0).width.0),
_ => None,
})
};
cx.update(|cx| note(&old, cx));
assert_eq!(width(cx, &old), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &old), Some(3));
// The engine writes the file again, and the window draws the picture
// under the key of the file as it is now, before it is told so.
std::fs::write(&path, png(7)).unwrap();
let new = PictureKey::of(&Source::file(&path)).unwrap();
cx.update(|cx| note(&new, cx));
assert_eq!(width(cx, &new), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &new), Some(7), "the new bytes, not the old ones");
assert_eq!(width(cx, &old), Some(3), "the old copy is still there");
cx.update(|cx| forget_stale(&path, cx));
assert!(!cx.update(|cx| cx.has_asset::<PictureLoader>(&old)), "the old copy is dropped");
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)), "the current key is kept");
assert_eq!(width(cx, &new), Some(7));
// Nothing more to forget; a file nobody drew is nothing to forget.
cx.update(|cx| forget_stale(&path, cx));
cx.update(|cx| forget_stale(&dir.0.join("never-drawn"), cx));
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)));
}
}
+124 -6
View File
@@ -6,12 +6,19 @@
//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings
//! and menus come to the same handlers later.
//!
//! The callbacks of `bind/servers.rs` that are not here belong to the slices
//! after this one: `search_members`, `show_voice_view`, `join_channel`,
//! `join_with_password`, `toggle_collapse`, `open_client` and
//! `client_audio_changed` to the channel tree and the voice page, and `copied`
//! (the toast that follows a copy) to whichever copies: [`Invite`] sets it
//! itself.
//! The voice page and the call bar add `show_voice_view`, the page's own
//! buttons (the smaller stage, Leave) and the two affordances of the call bar
//! whose pages come with later slices (Share, the voice settings), which are
//! logged.
//!
//! The channel tree and the members panel add `join_channel`,
//! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and
//! `open_client` (the last one only logs: the client's volume dialog is a
//! dialog of its own slice). The callbacks of `bind/servers.rs` that are
//! still not here belong to the slices after: `client_audio_changed` to the
//! dialogs (the member card has the volume and the mute of a person,
//! [`SetMemberVolume`] and [`SetMemberMuted`]), and `copied` (the toast that
//! follows a copy) to whichever copies: [`Invite`] sets it itself.
use gpui_kit::{Action, actions};
@@ -36,9 +43,51 @@ actions!(
OpenSearch,
/// The settings buttons: the settings come with their slice, today it is logged.
OpenSettings,
/// `join_with_password`: the password prompt's Join, with what it holds.
SubmitChannelPassword,
/// Close the password prompt without joining.
CancelChannelPassword,
/// The voice page's Leave (`Nav.show-voice(false)` then `disconnect_voice`).
LeaveVoice,
/// The voice page's Smaller stage / Larger stage (`ui.voice_compact`).
ToggleVoiceCompact,
/// The call bar's Share: the share menu comes with the stream slices, today it is logged.
OpenShare,
/// The call bar's voice settings: the settings come with their slice, today it is logged.
OpenVoiceSettings,
]
);
/// `show_voice_view`: the voice channel page on (the main area) or off (back to
/// the server page, where the chat will be).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ShowVoiceView {
/// Shown from now on.
pub on: bool,
}
/// The member card's volume slider: the person's playback volume, in percent
/// (`member_volume` of the Slint card).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberVolume {
/// The client's id on the server.
pub client: u16,
/// 0 to 200.
pub percent: f32,
}
/// The member card's Mute for me: stop playing the person (local only).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberMuted {
/// The client's id on the server.
pub client: u16,
/// Muted from now on.
pub muted: bool,
}
/// `select_server`: show a server (and observe it).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
@@ -86,3 +135,72 @@ pub struct PushToTalk {
/// Transmitting from now on.
pub on: bool,
}
/// `join_channel`: join a channel of the server on screen (a double-click on
/// its row, the context menu's Join).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct JoinChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// A click on a channel's row: select it (the Slint tree opens the channel's
/// chat, which comes with the chat slice).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// `toggle_collapse`: fold or unfold a channel of the tree.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ToggleChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Edit channel: the channel editor is a slice of its own,
/// today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Move to my channel: moving another client needs a command
/// the engine does not have yet, so today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct MoveClient {
/// The client's id on the server.
pub client: u16,
}
/// `open_client`: a click on a person in the tree opens their volume dialog,
/// which is a dialog of its own slice: today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenClient {
/// The client's id on the server.
pub client: u16,
}
/// `search_members`: the members panel's search text.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SearchMembers {
/// What the box holds; empty shows everyone.
pub text: String,
}
/// `open_member`: open the card of a person over the members panel; -1 closes it.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenMember {
/// The client's id on the server, or -1.
pub client: i32,
}
+502
View File
@@ -0,0 +1,502 @@
//! The channel tree of the sidebar (`ChannelTree` of `screens/channels.slint`):
//! the channels of the server on screen with the people in them, nested, with
//! their spacers, pictures, passwords and counts, and the person's marks.
//!
//! A cached pane ([`gpui_kit::Entity::cached`], which needs the size the
//! sidebar gives it) over a virtual list ([`gpui_kit::list`]: only the rows in
//! view are built, the rows differ in height) that follows [`TreeModel`]: the
//! model says which rows changed ([`TreeEvent::Rows`]) and the pane tells its
//! list, so a person who joins is a row inserted and the scroll stays where it
//! was. The pane reads nothing but its own fields while it renders, so
//! nothing but its own notify draws it again. A click selects a channel, a
//! double-click joins it, the chevron folds it, a right-click offers the
//! same; a click on a person is logged (their volume dialog is a slice of
//! its own).
use std::sync::Arc;
use gpui_kit::component::menu::ContextMenuExt as _;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ListAlignment,
ListState, ObjectFit, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, div,
list, px,
};
use voelin_ui_vm::bridge::TreeItem;
use voelin_ui_vm::tree::ChannelId;
use super::actions::{
EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel,
};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture, speaking_bars};
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::theme::{VoelinTheme, hsla};
/// How far each level of the tree is indented.
const INDENT: f32 = 14.0;
/// How opaque the hover and selection tints of a row with a banner are over
/// the banner and its veil: the hover is `channels.slint`'s (`Theme.surface-3.
/// transparentize(0.5)`), the selection, which Slint has no state for, is a
/// stronger one of the same colour.
const BANNER_HOVER: f32 = 0.5;
const BANNER_SELECTED: f32 = 0.75;
/// The channel tree.
pub struct ChannelTree {
rows: Arc<Vec<TreeItem>>,
selected: Option<ChannelId>,
emptiness: Emptiness,
list: ListState,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscription: Subscription,
}
impl ChannelTree {
/// A tree that follows `model`.
pub fn new(model: &Entity<TreeModel>, counters: Counters, cx: &mut Context<Self>) -> Self {
let (rows, selected, emptiness) = {
let model = model.read(cx);
(model.rows().clone(), model.selected(), model.emptiness())
};
let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::Rows(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Selection => this.selected = model.read(cx).selected(),
// The count of people is the members panel's.
TreeEvent::Lists => {
let emptiness = model.read(cx).emptiness();
if emptiness == this.emptiness {
return;
}
this.emptiness = emptiness;
}
TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return,
}
cx.notify();
});
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
selected,
emptiness,
measured_at: 0.0,
counters,
_subscription: subscription,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[TreeItem] {
&self.rows
}
/// The channel it shows selected.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why it shows no rows, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (a
/// channel row and a person's differ).
fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc<Vec<TreeItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut channels: Vec<bool> = self.rows.iter().map(|row| row.is_channel).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if channels[i] != new[i].is_channel {
self.list.splice(i..i + 1, 1);
}
channels[i] = new[i].is_channel;
}
Change::Remove(i) => {
channels.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
channels.insert(i, new[i].is_channel);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The row at `ix`, for the list.
fn row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
match self.rows.get(ix) {
Some(item) if item.is_channel => {
channel_row(&theme, item, self.selected == Some(item.id as ChannelId))
}
Some(item) => client_row(&theme, item),
None => div().into_any_element(),
}
}
}
/// The words of a tree with no rows.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::NoServer => "No server yet.",
Emptiness::Loading => "Loading the channels…",
// The tree is not searched, so it is never `NoMatch` (the members
// panel's, `TreeModel::people_emptiness`): the model gives it
// `Emptiness::of`, which does not say it.
Emptiness::Connect | Emptiness::NoMatch => "Connect to see the channels.",
}
}
/// The chevron of a channel, which folds it.
fn chevron(item: &TreeItem, covered: bool, theme: &VoelinTheme) -> impl IntoElement {
let c = &theme.colors;
let id = item.id as ChannelId;
div()
.id(("tree-toggle", id))
.debug_selector(move || format!("tree-toggle-{id}"))
.w(px(18.0))
.h(px(18.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.on_click(move |_, window, cx| {
cx.stop_propagation();
window.dispatch_action(Box::new(ToggleChannel { channel: id }), cx);
})
.child(icon(
if item.collapsed { "chevron-right" } else { "chevron-down" },
14.0,
if covered { c.text } else { c.text_muted },
))
}
/// One channel: its icon (or a speaker, or a lock), its name as the server
/// set it out, how many are in it, and the chevron.
fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as ChannelId;
let indent = item.depth as f32 * INDENT;
let banner = PictureKey::of(&item.banner);
let covered = banner.is_some();
let strong = item.own || covered;
let (hover, accent_soft, accent, selected_fill) =
(hsla(c.surface_3), hsla(c.accent_soft), hsla(c.accent), hsla(c.surface_3));
let own = item.own;
let has_icon = PictureKey::of(&item.icon).is_some();
let name_color = if strong { c.text } else { c.text_secondary };
let weight = if strong { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM };
let name = div()
.flex_1()
.min_w_0()
.text_size(px(m.font_body))
.font_weight(weight)
.text_color(hsla(name_color))
.when(item.spacer == 2, |name| name.text_center())
.when(item.spacer == 3, |name| name.text_right())
// A line is cut where the row ends; it does not widen the list.
.when(item.spacer == 4, |name| name.overflow_hidden().whitespace_nowrap())
.when(item.spacer != 4, |name| name.truncate())
.child(item.name.to_string());
let counted = item.spacer == 0 && (item.members > 0 || item.max_members >= 0);
let count = if item.max_members >= 0 {
format!("{}/{}", item.members, item.max_members)
} else {
item.members.to_string()
};
let group = SharedString::from(format!("tree-row-{id}"));
let row = div()
.id(("tree-channel", id))
.debug_selector(move || format!("tree-channel-{id}"))
.group(group.clone())
.relative()
.w_full()
.h(px(34.0 * m.font_scale))
.flex_none()
.overflow_hidden()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(own, |row| row.bg(accent_soft).border_1().border_color(accent))
.when(!own && selected, |row| row.bg(selected_fill))
.when(!own && !selected, |row| row.hover(move |style| style.bg(hover)))
// Artwork behind the same compact row as its title, from the indent on,
// under a veil of the surface colour that keeps the text readable over
// any picture, and under the tints of the row: our own channel's, the
// selected one and the one the pointer is over. The artwork covers the
// row's own background (which only the indent shows), so the tints
// are translucent children above the veil, as `channels.slint` does
// for the hover.
.when_some(banner, |row, key| {
let tint = || {
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
};
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id(("tree-scrim", id))
.debug_selector(move || format!("tree-scrim-{id}"))
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.bg(banner_scrim(theme)),
)
.when(own, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
.bg(accent_soft.opacity(0.65)),
)
})
.when(!own && selected, |row| {
row.child(
tint()
.debug_selector(move || format!("tree-selected-{id}"))
.bg(selected_fill.opacity(BANNER_SELECTED)),
)
})
.when(!own && !selected, |row| {
row.child(
tint().group_hover(group, move |style| style.bg(hover.opacity(BANNER_HOVER))),
)
})
})
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent))
.pr(px(m.space_3))
.gap(px(m.space_2))
// A centred spacer is balanced against the chevron.
.when(item.spacer == 2, |row| row.child(div().w(px(18.0)).flex_none()))
.when(item.spacer == 0, |row| match small_picture(&item.icon, 16.0) {
Some(picture) => row.child(picture),
None => row.child(icon(
if item.locked { "lock" } else { "volume-2" },
18.0,
if strong { c.text } else { c.icon },
)),
})
.child(name)
.when(item.locked && (has_icon || item.spacer != 0), |row| {
row.child(icon("lock", 14.0, if covered { c.text } else { c.icon }))
})
.when(counted, |row| {
row.child(
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(own, |count| count.child(icon("users", 14.0, c.text_secondary)))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(if strong { c.text } else { c.text_muted }))
.child(count),
),
)
})
.child(chevron(item, covered, theme))
.on_click(move |event, window, cx| {
if event.click_count() >= 2 {
window.dispatch_action(Box::new(JoinChannel { channel: id }), cx);
} else {
window.dispatch_action(Box::new(SelectChannel { channel: id }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Join channel", Box::new(JoinChannel { channel: id }))
.menu("Fold or unfold", Box::new(ToggleChannel { channel: id }))
.separator()
.menu("Edit channel…", Box::new(EditChannel { channel: id }))
});
row.into_any_element()
}
/// One person: their avatar, name and badges, and the marks of what they do.
fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as u64;
let indent = item.depth as f32 * INDENT;
let (hover, myself) = (hsla(c.surface_3), item.myself);
let name_color = if item.away {
c.text_muted
} else if myself {
c.accent_text
} else {
c.text_secondary
};
let mark = |name: &'static str, color| icon(name, 14.0, color);
div()
.id(("tree-client", id))
.debug_selector(move || format!("tree-client-{id}"))
.w_full()
.h(px(30.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(move |style| style.bg(hover))
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent + 12.0))
.pr(px(m.space_3))
.gap(px(m.space_3))
.child(
Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint)
.image(item.avatar.clone())
.speaking(item.talking),
)
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_body))
.font_weight(if myself { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
// Badges after the name, then the free room.
.child(
div().flex_1().min_w_0().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|badge| small_picture(badge, 14.0)),
),
)
// The Slint bars move; these stand still (nothing here draws the window
// anew with the clock).
.when(item.talking, |row| {
row.child(
div()
.debug_selector(move || format!("tree-speaking-{id}"))
.flex_none()
.child(speaking_bars(theme, 14.0)),
)
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.local_muted, |row| row.child(mark("volume-x", c.warning)))
.when(!item.local_muted && item.local_volume != 100, |row| {
row.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", item.local_volume)),
)
})
.when(item.muted, |row| row.child(mark("mic-off", c.danger)))
.when(item.sound_off, |row| row.child(mark("headphone-off", c.danger)))
.when(item.away, |row| {
row.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child("away"))
})
.children(
[&item.icon, &item.icon_2, &item.icon_3]
.into_iter()
.filter_map(|i| small_picture(i, 16.0)),
)
.on_click(move |_, window, cx| {
if !myself {
window.dispatch_action(Box::new(OpenClient { client: id as u16 }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Show the card", Box::new(OpenMember { client: id as i32 }))
.menu("Volume…", Box::new(OpenClient { client: id as u16 }))
.separator()
.menu("Move to my channel", Box::new(MoveClient { client: id as u16 }))
})
.into_any_element()
}
impl Render for ChannelTree {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.tree.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
// A new text size makes the rows another height.
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
div()
.id("sidebar-channels")
.debug_selector(|| "sidebar-channels".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.px(px(m.space_2))
.child(
div()
.min_h(px(24.0))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_secondary))
.child(icon("volume-2", m.icon_sm, c.text_secondary))
.child("Channels"),
)
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("tree-empty")
.debug_selector(|| "tree-empty".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.row(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
+35 -18
View File
@@ -1,8 +1,9 @@
//! The main area. Until the chat, the voice page and the rest come, it is the
//! The main area. Until the voice page, the chat and the rest come, it is the
//! empty page: the "no server selected" state with the way to add one, and for
//! a server on screen its name, address and state with the buttons that
//! connect, disconnect and edit it. An entity of its own: it observes the root
//! state and tells the window only when what it shows changed.
//! connect, disconnect and edit it. An entity of its own, drawn as a cached
//! pane: it listens to the servers' signal and tells the window only when
//! what it shows changed.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::prelude::FluentBuilder as _;
@@ -13,9 +14,11 @@ 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;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the main area shows.
@@ -51,21 +54,25 @@ fn state_words(status: &str) -> &'static str {
/// The main area.
pub struct MainPanel {
state: MainState,
_subscription: Subscription,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MainPanel {
/// A main area that follows `app`.
/// A main area that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let state = MainState::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (state, counters, signals) = {
let shown = app.read(cx);
(MainState::of(shown), shown.counters().clone(), shown.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let state = MainState::of(app.read(cx));
if state != this.state {
this.state = state;
cx.notify();
}
});
Self { state, _subscription: subscription }
Self { state, counters, _subscriptions: subscriptions }
}
/// What it shows now.
@@ -76,6 +83,7 @@ impl MainPanel {
impl Render for MainPanel {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.main.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let body = match &self.state {
@@ -165,7 +173,7 @@ impl Render for MainPanel {
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Its channels and its chat come with the next slices."),
.child("Its chat comes with a later slice."),
)
.child(
div()
@@ -194,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(
@@ -205,13 +227,8 @@ impl Render for MainPanel {
)
}
};
panel(&theme)
.id("main")
.flex_1()
.min_w_0()
.h_full()
.items_center()
.justify_center()
.child(body)
// The root of a cached pane takes the size its place gives it: laid out
// on its own, `flex_1` would be as wide as its contents.
panel(&theme).id("main").size_full().items_center().justify_center().child(body)
}
}
+768
View File
@@ -0,0 +1,768 @@
//! The members panel (`MembersPanel` and `MemberCardPopup` of
//! `screens/members.slint`): everyone on the server in sections (those
//! streaming first, then each server group), a search, and the card of one
//! person over the panel.
//!
//! [`MembersPane`] is a cached pane over a virtual list that follows
//! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations
//! the list applies). A talker redraws it, with the tree: a person's row has
//! the speaking ring, "Speaking" and the bars, and no other pane of the window
//! is told. [`MemberCardView`] is the card, a card over the window with a scrim
//! that a click outside closes; it has the volume and the mute of the person for
//! us (`SetMemberVolume`, `SetMemberMuted`), and its other buttons (a message, a
//! poke, friends, blocking) come with the slices that have those dialogs.
use std::sync::Arc;
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::slider::{Slider, SliderEvent, SliderState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ListAlignment, ListState, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, list, px,
};
use voelin_ui_vm::bridge::{MemberCard, MemberItem};
use voelin_ui_vm::list::Changes;
use super::actions::{OpenMember, SearchMembers, SetMemberMuted, SetMemberVolume};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{
Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars,
};
use crate::meter::Counters;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// The colour of the shield of a moderator's role.
const ROLE: Rgba = Rgba(0xc06c_ffff);
/// The members panel.
pub struct MembersPane {
rows: Arc<Vec<MemberItem>>,
total: i32,
emptiness: Emptiness,
/// The person whose card is open.
open: Option<i32>,
list: ListState,
search: Entity<InputState>,
searching: bool,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MembersPane {
/// A panel that follows `model`.
pub fn new(
model: &Entity<TreeModel>,
counters: Counters,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let (rows, total, emptiness, open) = {
let model = model.read(cx);
(
model.people().clone(),
model.total(),
model.people_emptiness(),
model.card().map(|c| c.id),
)
};
let search = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Search members…"))
});
let subscriptions = vec![
cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Lists => {
let model = model.read(cx);
let now = (model.total(), model.people_emptiness());
if now == (this.total, this.emptiness) {
return;
}
(this.total, this.emptiness) = now;
}
TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id),
TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return,
}
cx.notify();
}),
cx.subscribe_in(&search, window, |_, input, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::Change) {
let text = input.read(cx).value().to_string();
window.dispatch_action(Box::new(SearchMembers { text }), cx);
}
}),
];
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
total,
emptiness,
open,
search,
searching: false,
measured_at: 0.0,
counters,
_subscriptions: subscriptions,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[MemberItem] {
&self.rows
}
/// The person whose card is open, as the panel marks them.
pub fn open(&self) -> Option<i32> {
self.open
}
/// Why it shows no one, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Whether the search box is shown.
pub fn searching(&self) -> bool {
self.searching
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (the
/// first row of a section has the heading above it).
fn apply(&mut self, changes: &Changes, new: Arc<Vec<MemberItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut headed: Vec<bool> = self.rows.iter().map(|row| row.first_in_group).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if headed[i] != new[i].first_in_group {
self.list.splice(i..i + 1, 1);
}
headed[i] = new[i].first_in_group;
}
Change::Remove(i) => {
headed.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
headed.insert(i, new[i].first_in_group);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The search box was opened or closed: closing it shows everyone again.
fn toggle_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.searching = !self.searching;
if self.searching {
self.search.update(cx, |input, cx| input.focus(window, cx));
} else {
self.search.update(cx, |input, cx| input.set_value("", window, cx));
window.dispatch_action(Box::new(SearchMembers { text: String::new() }), cx);
}
cx.notify();
}
/// The entry at `ix` for the list: the heading of its section if it opens
/// one, then the person.
fn entry(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
let Some(item) = self.rows.get(ix) else { return div().into_any_element() };
let m = &theme.metrics;
div()
.w_full()
.px(px(m.space_3))
.flex()
.flex_col()
.when(item.first_in_group, |entry| entry.child(group_header(&theme, item)))
.child(member_row(&theme, item, self.open == Some(item.id)))
.into_any_element()
}
}
/// The words of a panel with nobody in it.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::Loading => "Loading who is here…",
Emptiness::NoMatch => "Nobody matches.",
Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.",
}
}
/// The heading above the first person of a section: "Moderator — 3".
fn group_header(theme: &VoelinTheme, item: &MemberItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let words = if item.group_count > 0 {
format!("{} — {}", item.group, item.group_count)
} else {
item.group.to_string()
};
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pt(px(m.space_5))
.pb(px(m.space_2))
.pl(px(m.space_2))
.children(small_picture(&item.group_icon, 16.0))
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(words),
)
}
/// One person: avatar, name with their badges and role, what they are doing.
fn member_row(theme: &VoelinTheme, item: &MemberItem, open: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id;
let hover = hsla(c.surface_3);
let presence = if item.away {
Presence::Idle
} else if item.sound_off {
Presence::Dnd
} else {
Presence::Online
};
let name_color = if item.myself {
c.accent_text
} else if !item.role.is_empty() {
c.name_text
} else {
c.text
};
let crowns = div()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(item.admin, |row| row.child(icon("crown", 14.0, c.gold)))
.when(item.priority, |row| row.child(icon("star", 14.0, c.accent_text)))
.when(item.commander, |row| row.child(icon("flag", 14.0, c.info)))
.when(item.recording, |row| row.child(icon("circle-dot", 14.0, c.danger)));
let badges = div().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|b| small_picture(b, 14.0)),
);
div()
.id(("member", id as u64))
.debug_selector(move || format!("member-{id}"))
.w_full()
.h(px(52.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(open, |row| row.bg(hsla(c.accent_soft)))
.when(!open, |row| row.hover(move |style| style.bg(hover)))
.when(item.away, |row| row.opacity(0.6))
.flex()
.flex_row()
.items_center()
.px(px(m.space_2))
.gap(px(m.space_3))
.child(
Avatar::new(("member-avatar", id as u64), 40.0, &item.initials, item.tint)
.image(item.avatar.clone())
.presence(presence)
.speaking(item.talking),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
.child(crowns)
.child(badges),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if item.talking {
c.success
} else {
c.text_muted
}))
.child(item.status.to_string()),
)
.when(item.talking, |row| row.child(speaking_bars(theme, 12.0)))
.when(item.streaming, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
),
)
.when(!item.role.is_empty(), |row| {
row.child(icon("shield-check", 18.0, ROLE)).child(chip(
theme,
item.role.to_string(),
None,
None,
))
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.muted, |row| row.child(icon("mic-off", 16.0, c.danger)))
.when(item.sound_off, |row| row.child(icon("headphone-off", 16.0, c.danger)))
// A hand, as TeamSpeak asks for talk power; the card has the number.
.when(item.cannot_talk, |row| {
row.child(
div()
.id(("member-hand", id as u64))
.tooltip(|window, cx| {
gpui_kit::component::tooltip::Tooltip::new("Needs talk power to speak")
.build(window, cx)
})
.child(icon("hand", 16.0, c.text_muted)),
)
})
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: id }), cx)
})
.into_any_element()
}
impl Render for MembersPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.members.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
let searching = self.searching;
let this = cx.entity();
let search_button = IconButton::new("members-search", "search", "Search members")
.size(32.0)
.checked(searching)
.on_click(move |_, window, cx| {
this.update(cx, |pane, cx| pane.toggle_search(window, cx));
});
div()
.id("members")
.debug_selector(|| "members".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_4))
.pb(px(m.space_2))
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pl(px(m.space_5))
.pr(px(m.space_3))
.child(
div()
.id("members-title")
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text))
.child(format!("Members — {}", self.total)),
)
.child(search_button),
)
.when(searching, |pane| {
pane.child(
div()
.id("members-search-box")
.debug_selector(|| "members-search-box".into())
.px(px(m.space_4))
.child(Input::new(&self.search)),
)
})
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("members-empty")
.debug_selector(|| "members-empty".into())
.px(px(m.space_5))
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.entry(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
/// The card over a member row, over the window: a scrim that a click outside
/// the card closes, and the card with what is known of the person, and the
/// volume and the mute of their voice for us (the Slint card's Volume rows).
pub struct MemberCardView {
card: Option<MemberCard>,
/// How wide the members panel is: the card stands beside it.
panel_width: f32,
/// The volume slider, in percent (0 to 200, as the Slint card's).
slider: Entity<SliderState>,
_subscriptions: Vec<Subscription>,
}
/// The loudest the card's slider plays a person, in percent.
const LOUDEST: f32 = 200.0;
impl MemberCardView {
/// A card that follows `model`, beside a panel `panel_width` pixels wide.
pub fn new(
model: &Entity<TreeModel>,
panel_width: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let card = model.read(cx).card().cloned();
let slider = cx.new(|_| {
SliderState::new()
.min(0.0)
.max(LOUDEST)
.step(5.0)
.default_value(card.as_ref().map_or(100.0, |card| card.volume))
});
let subscriptions = vec![
cx.subscribe_in(
model,
window,
|this: &mut Self, model, event: &TreeEvent, window, cx| {
if matches!(event, TreeEvent::Card) {
this.card = model.read(cx).card().cloned();
// The slider shows the person's volume as it is now (a change
// the slider itself made comes back the same).
if let Some(card) = &this.card {
let volume = card.volume.clamp(0.0, LOUDEST);
this.slider
.update(cx, |slider, cx| slider.set_value(volume, window, cx));
}
cx.notify();
}
},
),
cx.subscribe_in(
&slider,
window,
|this: &mut Self, _, event: &SliderEvent, window, cx| {
if let (SliderEvent::Change(value), Some(card)) = (event, &this.card) {
let client = u16::try_from(card.id).unwrap_or_default();
let percent = value.end();
window.dispatch_action(Box::new(SetMemberVolume { client, percent }), cx);
}
},
),
];
Self { card, panel_width, slider, _subscriptions: subscriptions }
}
/// The card that is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
}
/// The heading of a part of the card: "Groups", "Badges".
fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.text_size(px(m.font_xs))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_muted))
.child(text)
}
/// The card's Volume rows: what the person is played at, a mute for us and
/// the slider. Both need a person the server gave a unique id (the choice is
/// kept by it), as the Slint card's do.
fn volume(
theme: &VoelinTheme,
person: &MemberCard,
slider: &Entity<SliderState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let client = u16::try_from(person.id).unwrap_or_default();
let (muted, known) = (person.muted, person.known);
div()
.id("member-volume")
.debug_selector(|| "member-volume".into())
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_3))
.border_t_1()
.border_color(hsla(c.border_popup))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.flex_1()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child("Volume"),
)
.child(
div()
.id("member-volume-percent")
.debug_selector(|| "member-volume-percent".into())
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", person.volume.round() as i32)),
),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
IconButton::new(
"member-mute",
if muted { "volume-x" } else { "volume-2" },
if muted { "Unmute for me" } else { "Mute for me" },
)
.size(30.0)
.danger()
.checked(muted)
.enabled(known)
.on_click(move |_, window, cx| {
window
.dispatch_action(Box::new(SetMemberMuted { client, muted: !muted }), cx)
}),
)
.child(
div()
.id("member-slider")
.debug_selector(|| "member-slider".into())
.flex_1()
.child(Slider::new(slider).disabled(!known || muted)),
),
)
}
impl Render for MemberCardView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(person) = self.card.clone() else { return div().into_any_element() };
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let facts = div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(m.space_2))
.when(person.talk_power > 0, |row| {
row.child(chip(
&theme,
format!("talk power {}", person.talk_power),
Some("mic"),
None,
))
})
.when(!person.country.is_empty(), |row| {
row.child(chip(&theme, person.country.to_string(), Some("globe"), None))
});
let body = div()
.id("member-card")
.debug_selector(|| "member-card".into())
.w(px(300.0))
.flex()
.flex_col()
.gap(px(m.space_3))
.p(px(m.space_4))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
// Clicks inside stay inside.
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
Avatar::new("member-card-avatar", 52.0, &person.initials, person.tint)
.image(person.avatar.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(person.name.to_string()),
)
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(person.status.to_string()),
),
)
.child(IconButton::new("member-card-close", "x", "Close").size(26.0).on_click(
|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
},
)),
)
.when(!person.description.is_empty(), |card| {
card.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(person.description.to_string()),
)
})
.when(!person.groups.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Groups"))
.children(person.groups.iter().map(|group| {
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(group.to_string())
})),
)
})
.when(!person.badges.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Badges"))
.child(div().flex().flex_row().flex_wrap().gap(px(m.space_2)).children(
person.badges.iter().enumerate().map(|(i, badge)| {
let description = badge.description.clone();
div()
.id(("member-badge", i as u64))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(
description.to_string(),
)
.build(window, cx)
})
.child(chip(
&theme,
badge.name.to_string(),
None,
small_picture(&badge.icon, 14.0),
))
}),
)),
)
})
.child(facts)
.child(volume(&theme, &person, &self.slider));
// The card stands beside the panel, near the top.
div()
.id("member-card-scrim")
.debug_selector(|| "member-card-scrim".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(hsla(c.scrim_light))
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
})
.flex()
.flex_row()
.justify_end()
.items_start()
.pt(px(120.0))
.pr(px(self.panel_width + 24.0))
.child(body)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// What an empty panel says for each reason it can be empty.
#[test]
fn an_empty_panel_says_why() {
assert_eq!(empty_words(Emptiness::NoServer), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Connect), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Loading), "Loading who is here…");
assert_eq!(empty_words(Emptiness::NoMatch), "Nobody matches.");
}
}
+24 -5
View File
@@ -1,23 +1,42 @@
//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and
//! the server callbacks of `bind/servers.rs`): the server rail, the top bar,
//! the sidebar, the main area, the server form and the toast, each an entity
//! that observes the root state ([`crate::app::AppState`]) and tells the window
//! only when what it shows changed (the window then draws every part), and the
//! actions the user's moves are ([`actions`]). [`crate::view::MainView`] puts
//! them in the window.
//! the sidebar, the main area, the voice channel page that takes its place
//! while voice is on screen, the server form and the toast, each an entity
//! that listens to the per-area signals of the root state
//! ([`crate::signals`]) and tells the window only when what it shows changed,
//! and the actions the user's moves are ([`actions`]). The rail, the top bar,
//! the main area and the voice page are embedded cached (they have a size of
//! their own), so gpui-pre 0.3.10 renders them again only when they were told
//! something changed; [`crate::view::MainView`] puts them in the window.
pub mod actions;
mod channels;
mod form;
mod main_panel;
mod members;
mod password;
mod rail;
mod sidebar;
mod toast;
mod topbar;
mod tree_model;
mod voice;
pub mod widgets;
pub use channels::ChannelTree;
pub use form::ServerForm;
pub use main_panel::{MainPanel, MainState};
pub use members::{MemberCardView, MembersPane};
pub use password::ChannelPassword;
/// Bind the shell's keys (Escape in the password prompt): once, after the
/// widget library's own are (`gpui_kit::init`).
pub fn bind_keys(cx: &mut gpui_kit::App) {
password::bind_keys(cx);
}
pub use rail::{RailView, ServerRail};
pub use sidebar::{Sidebar, SidebarView};
pub use toast::{TOAST_TIME, Toast};
pub use topbar::TopBar;
pub use tree_model::{Emptiness, TreeEvent, TreeModel};
pub use voice::{SHORT_WINDOW, VoiceHead, VoicePage};
+171
View File
@@ -0,0 +1,171 @@
//! The password prompt of a locked channel (`ChannelPasswordDialog` of
//! `screens/dialogs.slint`): what the transitions ask for with
//! `Update::password` when a channel with a password is joined and the one
//! given this connection (if any) is not at hand, or was refused. It is a
//! card over the window with a scrim; until the dialogs slice makes every
//! dialog one, it is this view's own. As in the Slint dialog, Join (and Enter)
//! do nothing while the field is empty, and Escape closes the prompt.
//!
//! Escape is a key binding of the prompt's key context ([`bind_keys`]) that
//! dispatches [`CancelChannelPassword`], and the prompt is a focus target of
//! its own (its scrim, which the card is on): a click on the card, off the
//! field, takes the focus from the field, and a click outside any focus target
//! would hand it to the window's root, which the prompt is not under, so
//! without a target the context would not be on the dispatch path and Escape
//! would do nothing. With the field focused its own Escape (which has nothing
//! to undo in a password) passes the key on, and the binding closes the prompt.
use gpui_kit::component::Disableable as _;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FocusHandle, FontWeight, InteractiveElement as _,
IntoElement, KeyBinding, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use voelin_ui_vm::host::PasswordPrompt;
use super::actions::{CancelChannelPassword, SubmitChannelPassword};
use super::widgets::tagged;
use crate::theme::{VoelinTheme, hsla};
/// The key context of the prompt.
const CONTEXT: &str = "ChannelPassword";
/// The keys of the prompt: Escape closes it. Bound once, at start, with the
/// widget library's own.
pub fn bind_keys(cx: &mut App) {
cx.bind_keys([KeyBinding::new("escape", CancelChannelPassword, Some(CONTEXT))]);
}
/// The prompt for the password of one channel.
pub struct ChannelPassword {
channel: String,
wrong: bool,
input: Entity<InputState>,
/// What the prompt's scrim holds the focus with, so that Escape reaches the
/// prompt wherever in it the last click was.
focus: FocusHandle,
}
impl ChannelPassword {
/// A prompt for what `ask` names, with the field focused: Enter joins.
pub fn new(ask: &PasswordPrompt, window: &mut Window, cx: &mut Context<Self>) -> Self {
let input = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Password")).masked(true)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| match event {
InputEvent::PressEnter { .. } => {
window.dispatch_action(Box::new(SubmitChannelPassword), cx);
}
// Join is there while there is something to join with.
InputEvent::Change => cx.notify(),
_ => {}
})
.detach();
input.update(cx, |input, cx| input.focus(window, cx));
Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() }
}
/// The channel it asks for.
pub fn channel(&self) -> &str {
&self.channel
}
/// Whether it says that the last password was refused.
pub fn wrong(&self) -> bool {
self.wrong
}
/// What the field holds. The prompt joins only with something in it.
pub fn text(&self, cx: &App) -> String {
self.input.read(cx).value().to_string()
}
/// Type `text` in the field (the tests type here).
pub fn set_text(&self, text: &str, window: &mut Window, cx: &mut App) {
self.input.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
impl Render for ChannelPassword {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let empty = self.text(cx).is_empty();
div()
.id("password-prompt")
.debug_selector(|| "password-prompt".into())
.key_context(CONTEXT)
.track_focus(&self.focus)
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.flex()
.items_center()
.justify_center()
.bg(hsla(c.scrim))
// A click outside the card closes the prompt.
.on_click(|_, window, cx| window.dispatch_action(Box::new(CancelChannelPassword), cx))
.child(
div()
.id("password-card")
.debug_selector(|| "password-card".into())
.w(px(380.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(format!("{} has a password", self.channel)),
)
.when(self.wrong, |card| {
card.child(
div()
.id("password-wrong")
.debug_selector(|| "password-wrong".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.danger))
.child("That password was not accepted. Try again."),
)
})
.child(Input::new(&self.input))
.child(
div()
.flex()
.flex_row()
.justify_end()
.gap(px(m.space_3))
.child(tagged(
"password-cancel",
Button::new("password-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelChannelPassword), cx)
},
),
))
.child(tagged(
"password-join",
Button::new("password-join")
.primary()
.label("Join")
.disabled(empty)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(SubmitChannelPassword), cx)
}),
)),
),
)
}
}
+15 -7
View File
@@ -1,7 +1,8 @@
//! The server rail: the saved servers as avatars with their state, the
//! selection, the add-server button and the settings button (`ServerRail` of
//! `ui/shells/desktop.slint`). An entity of its own: it observes the root
//! state and tells the window only when the servers it lists changed.
//! `ui/shells/desktop.slint`). An entity of its own, drawn as a cached pane:
//! it listens to the servers' signal ([`crate::signals`]) and tells the window
//! only when the servers it lists changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
@@ -14,6 +15,8 @@ use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, EditServer, OpenSettings, SelectServer};
use super::widgets::{Avatar, IconButton, Presence};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the rail shows: the servers in order, and which is on screen.
@@ -38,21 +41,25 @@ impl RailView {
/// The rail.
pub struct ServerRail {
view: RailView,
_subscription: Subscription,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl ServerRail {
/// A rail that follows `app`.
/// A rail that follows the servers of `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let view = RailView::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (view, counters, signals) = {
let state = app.read(cx);
(RailView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let view = RailView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, _subscription: subscription }
Self { view, counters, _subscriptions: subscriptions }
}
/// What it shows now.
@@ -160,6 +167,7 @@ fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoEl
impl Render for ServerRail {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.rail.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let current = self.view.current;
+127 -55
View File
@@ -1,14 +1,16 @@
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen, the place of its channel tree
//! (the next slice), 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
//! observes the root state and tells the window only when what it shows changed.
//! `shells/common.slint`): the server on screen (its card has the server's
//! banner behind it, under the same veil as the tree's rows), its channel tree
//! ([`super::ChannelTree`], a cached pane of its own), the voice card while
//! voice is connecting or connected, and the user's own card with the voice
//! buttons. An entity of its own: it listens to the servers' and the toolbar's
//! signals and tells the window only when what it shows changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ParentElement as _, Render, StatefulInteractiveElement as _, 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;
@@ -19,8 +21,12 @@ use voelin_ui_vm::servers::logic;
use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::widgets::{Avatar, IconButton, Presence, card, icon, panel};
use super::channels::ChannelTree;
use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the sidebar shows.
@@ -30,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.
@@ -50,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 {
@@ -64,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,
@@ -74,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,
}
}
}
@@ -81,23 +94,48 @@ impl SidebarView {
/// The sidebar.
pub struct Sidebar {
view: SidebarView,
/// The channel tree, a pane of its own between the server card and the
/// voice card.
tree: Entity<ChannelTree>,
/// The hold-to-talk button is held down.
holding: bool,
_subscription: Subscription,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl Sidebar {
/// A sidebar that follows `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let view = SidebarView::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let view = SidebarView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, holding: false, _subscription: subscription }
/// A sidebar that follows the server on screen and the voice state in
/// `app`, with `tree` between its cards.
pub fn new(app: &Entity<AppState>, tree: Entity<ChannelTree>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(SidebarView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let state = app.read(cx);
let view = SidebarView::of(state);
// The button goes away when voice leaves `Connected`, transmit
// leaves push-to-talk, or another server is shown; and a drop
// and reconnect inside one batch ends the hold in `AppState`
// while `view.voice_connected` stays true. Keep `holding` in
// sync with the root state's own button hold (this observer
// only sets its own fields).
let same_server =
view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id);
let held_here = view
.server
.as_ref()
.is_some_and(|s| state.button_held() == Some(i64::from(s.id)));
if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here {
this.holding = false;
}
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, tree, holding: false, counters, _subscriptions: subscriptions }
}
/// What it shows now.
@@ -105,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) {
@@ -113,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())
@@ -145,46 +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),
),
)
}
/// Where the channel tree goes: the next slice.
fn channels(theme: &VoelinTheme, has_server: bool) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("sidebar-channels")
.flex_1()
.min_h_0()
.flex()
.flex_col()
.gap(px(m.space_2))
.px(px(m.space_2))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.text_size(px(m.font_xs))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_secondary))
.child(icon("volume-2", m.icon_sm, c.text_secondary))
.child("Channels"),
)
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(if has_server {
"The channel tree comes with the next slice."
} else {
"Add a server to see its channels."
}))
/// 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.
/// "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,
@@ -252,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()
@@ -400,6 +470,7 @@ fn name_initials(name: &str) -> String {
impl Render for Sidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.sidebar.incr();
let theme = VoelinTheme::global(cx).clone();
let m = &theme.metrics;
let view = &self.view;
@@ -413,7 +484,8 @@ impl Render for Sidebar {
.when_some(view.server.as_ref(), |sidebar, item| {
sidebar.child(server_card(&theme, view, item))
})
.child(channels(&theme, view.server.is_some()))
// The tree has the room the cards leave, whatever their height.
.child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full()))
.when(view.voice_connected || view.voice_connecting, |sidebar| {
sidebar.child(voice_card(&theme, view, cx))
})
+12 -5
View File
@@ -11,6 +11,8 @@ use gpui_kit::{
use super::actions::{OpenSearch, OpenSettings};
use super::widgets::{IconButton, icon};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// The page title: the server on screen, else the app's name.
@@ -24,21 +26,25 @@ pub fn title(app: &AppState) -> String {
/// The top bar.
pub struct TopBar {
title: String,
_subscription: Subscription,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl TopBar {
/// A top bar that follows `app`.
/// A top bar that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let shown = title(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (shown, counters, signals) = {
let state = app.read(cx);
(title(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let shown = title(app.read(cx));
if shown != this.title {
this.title = shown;
cx.notify();
}
});
Self { title: shown, _subscription: subscription }
Self { title: shown, counters, _subscriptions: subscriptions }
}
/// The title it shows now.
@@ -49,6 +55,7 @@ impl TopBar {
impl Render for TopBar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.topbar.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
div()
+319
View File
@@ -0,0 +1,319 @@
//! The narrow entity behind the channel tree and the members panel: what
//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between
//! one change and the next so that the two panes can be told what changed.
//!
//! It listens to the tree, toolbar and member-card signals
//! ([`crate::signals`]), builds the rows once for both panes, compares them
//! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the
//! Slint front end applies to its `VecModel`) and emits what differs
//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the
//! operations to its list state, so a person who joins is a row that is
//! inserted, not a list that starts again at the top. A change that moves none
//! of what a pane shows emits nothing.
//!
//! The people of our voice channel (`TreeView::members`, the voice page's
//! rows) come out of the same build as the other two lists: the model keeps
//! them and emits them when they differ ([`TreeEvent::Voice`]), so the voice
//! page needs no build of its own.
//!
//! **The tree marks who is talking**, as the Slint tree does (the ring on the
//! avatar and the speaking bars on the row): someone who starts or stops
//! talking changes one row of the tree and one of the members panel, so each
//! of the two panes is drawn again once for it, and no other pane is
//! (docs/ui.md, "What a change costs").
use std::sync::Arc;
use gpui_kit::{App, Context, Entity, EventEmitter, Subscription};
use voelin_core::{ObserveState, VoiceState};
use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem};
use voelin_ui_vm::list::{Changes, diff};
use voelin_ui_vm::servers::logic;
use voelin_ui_vm::tree::{ChannelId, member_card};
use crate::app::{AppState, VmState};
use crate::signals::Area;
/// Why a list has no rows, which the pane says in words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Emptiness {
/// No server is on screen.
NoServer,
/// The server is observed or being connected to, and its presence is on
/// the way.
Loading,
/// Nothing is known of the server until it is connected.
Connect,
/// The server has people and the members' search matches none of them (the
/// members panel's only: the tree is not searched).
NoMatch,
}
impl Emptiness {
/// Why the lists of the server on screen are empty: never
/// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s.
pub fn of(vm: &VmState) -> Self {
match vm.current {
None => Self::NoServer,
Some(id) => match vm.sessions.get(&id) {
Some(view)
if view.state.observe != ObserveState::Off
|| view.state.voice == VoiceState::Connecting =>
{
Self::Loading
}
_ => Self::Connect,
},
}
}
/// Why the members panel is empty: as [`Emptiness::of`], except that a
/// search that leaves nobody of the `total` on the server (`shown` rows
/// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here"
/// would be false.
pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self {
if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() {
Self::NoMatch
} else {
Self::of(vm)
}
}
}
/// What changed in the model, as the panes need it.
///
/// The list events carry the rows their operations lead to. A model that
/// refreshed twice before the first event is delivered (an observer that
/// changes the state inside a flush makes it) holds the second rows by the
/// time a pane hears of the first operations, and operations applied to rows
/// they were not made for index past their end. A pane applies them to the
/// rows it has and keeps the rows the event carries, so the events, in the
/// order they are delivered, lead from the rows the pane started with to the
/// model's last.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeEvent {
/// The tree's rows: the operations from the rows the pane has to the rows
/// carried (the model's [`TreeModel::rows`] when it made them).
Rows(Changes, Arc<Vec<TreeItem>>),
/// The members panel's rows: the operations from the rows the pane has to
/// the rows carried (the model's [`TreeModel::people`] when it made them).
People(Changes, Arc<Vec<MemberItem>>),
/// The people of our voice channel, the voice page's rows, as they are
/// now (the whole list: the page lays its people out in a wrapping row, not
/// a virtual list, and takes them as they come).
Voice(Arc<Vec<MemberItem>>),
/// The card over a member row opened, changed or closed
/// ([`TreeModel::card`]).
Card,
/// The selected channel ([`TreeModel::selected`]).
Selection,
/// Why the lists are empty, or how many people there are
/// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`],
/// [`TreeModel::total`]).
Lists,
}
/// The areas the model listens to.
const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard];
/// How many times each of [`AREAS`] was raised.
fn generations(app: &Entity<AppState>, cx: &App) -> [u64; 3] {
let signals = app.read(cx).signals();
AREAS.map(|area| signals.of(area).read(cx).generation())
}
/// The rows of the tree and of the members panel, the member card and the
/// selection of the server on screen.
pub struct TreeModel {
app: Entity<AppState>,
/// The generations of its signals it last built the rows at: a batch that
/// raises several of them (a picture that arrives raises three) has them
/// all raised before the first is heard, so the first refresh builds the
/// rows and the others find nothing new.
seen: [u64; 3],
refreshes: u64,
rows: Arc<Vec<TreeItem>>,
people: Arc<Vec<MemberItem>>,
voice: Arc<Vec<MemberItem>>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
_subscriptions: Vec<Subscription>,
}
impl EventEmitter<TreeEvent> for TreeModel {}
/// Check that `changes` lead from a list of `old` rows to one of `new` rows
/// (debug builds): a pane that applies operations to rows they were not made
/// for finds the counts out of step, where a release build would index past
/// the end or leave its list state out of step with its rows.
pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) {
debug_assert_eq!(
old + changes.inserted(),
new + changes.removed(),
"{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \
for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \
inside a flush)"
);
}
/// Everything the model keeps, as the state gives it now.
struct Snapshot {
rows: Vec<TreeItem>,
people: Vec<MemberItem>,
voice: Vec<MemberItem>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
}
impl Snapshot {
fn of(app: &AppState) -> Self {
let vm = &app.vm;
let view = vm.current.and_then(|id| vm.sessions.get(&id));
let (rows, people, voice, total) = match logic::tree_view(vm, false) {
Some(tree) => (tree.rows, tree.server_members, tree.members, tree.member_total),
None => (Vec::new(), Vec::new(), Vec::new(), 0),
};
Self {
people_emptiness: Emptiness::of_people(vm, people.len(), total),
rows,
people,
voice,
total,
card: view
.and_then(|view| view.member_card.map(|id| (view, id)))
.and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)),
selected: app.selected_channel(),
emptiness: Emptiness::of(vm),
}
}
}
impl TreeModel {
/// A model of what `app` shows now, following its tree signals.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (snapshot, signals) = {
let state = app.read(cx);
(Snapshot::of(state), state.signals().clone())
};
let subscriptions =
signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx));
Self {
app: app.clone(),
seen: generations(app, cx),
refreshes: 0,
rows: Arc::new(snapshot.rows),
people: Arc::new(snapshot.people),
voice: Arc::new(snapshot.voice),
total: snapshot.total,
card: snapshot.card,
selected: snapshot.selected,
emptiness: snapshot.emptiness,
people_emptiness: snapshot.people_emptiness,
_subscriptions: subscriptions,
}
}
/// The rows of the channel tree: channels with the clients in them.
pub fn rows(&self) -> &Arc<Vec<TreeItem>> {
&self.rows
}
/// The rows of the members panel: everyone on the server, in sections.
pub fn people(&self) -> &Arc<Vec<MemberItem>> {
&self.people
}
/// The people of our voice channel, in the voice page's order (empty while
/// voice is not connected).
pub fn voice(&self) -> &Arc<Vec<MemberItem>> {
&self.voice
}
/// How many are on the server (the query clients not counted).
pub fn total(&self) -> i32 {
self.total
}
/// The card over a member row, when one is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
/// The channel selected in the tree.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why the tree is empty, were it.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Why the members panel is empty, were it: the same as
/// [`TreeModel::emptiness`], or that the search matches nobody.
pub fn people_emptiness(&self) -> Emptiness {
self.people_emptiness
}
/// How many times the rows were built again since the model was made: one
/// for each batch of changes, not one for each signal it raised.
pub fn refreshes(&self) -> u64 {
self.refreshes
}
/// Build the rows again, and tell the panes what differs. Nothing, when
/// none of the signals was raised since the last time.
fn refresh(&mut self, cx: &mut Context<Self>) {
let now = generations(&self.app, cx);
if now == self.seen {
return;
}
self.seen = now;
self.refreshes += 1;
let new = Snapshot::of(self.app.read(cx));
let rows = diff(&self.rows, &new.rows);
let people = diff(&self.people, &new.people);
if !rows.is_empty() {
self.rows = Arc::new(new.rows);
}
if !people.is_empty() {
self.people = Arc::new(new.people);
}
let voice = *self.voice != new.voice;
if voice {
self.voice = Arc::new(new.voice);
}
let lists = (self.emptiness, self.people_emptiness, self.total)
!= (new.emptiness, new.people_emptiness, new.total);
(self.emptiness, self.people_emptiness, self.total) =
(new.emptiness, new.people_emptiness, new.total);
let card = self.card != new.card;
self.card = new.card;
let selection = self.selected != new.selected;
self.selected = new.selected;
if !rows.is_empty() {
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
}
if !people.is_empty() {
cx.emit(TreeEvent::People(people, self.people.clone()));
}
if voice {
cx.emit(TreeEvent::Voice(self.voice.clone()));
}
if lists {
cx.emit(TreeEvent::Lists);
}
if card {
cx.emit(TreeEvent::Card);
}
if selection {
cx.emit(TreeEvent::Selection);
}
}
}
+657
View File
@@ -0,0 +1,657 @@
//! The voice channel page (`VoiceView` of `screens/voice.slint`, with its
//! `Participant` of `voice-parts.slint` and the `CallBar`): the channel we are
//! in, who is there and who talks, and the call's controls under them.
//!
//! [`VoicePage`] is a cached pane of its own, a sibling of the server page
//! ([`super::MainPanel`]) that [`crate::view::MainView`] puts in the main
//! area in its place while the page is asked for and voice is connected
//! ([`crate::app::AppState::voice_page_shown`]). It takes its people from the
//! tree model ([`TreeEvent::Voice`]: the rows `TreeView::members` gave the one
//! build the tree and the members panel come from, so the page builds nothing
//! of its own) and the header and the call bar from the servers' and the
//! toolbar's signals, compares what it would show with what it showed, and
//! tells the window only when they differ. A person who starts or stops
//! talking, or mutes, is one row of the page and one render of this pane.
//!
//! The larger stage lays the people out as large avatars in a wrapping row;
//! the smaller stage (`ui.voice_compact`, and always in a window under 800
//! pixels tall) is one row of small avatars that scrolls sideways. The streams
//! of the Slint page come with the stream slices and its chat with the chat's.
use std::sync::Arc;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ObjectFit,
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, StyledImage as _,
Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::MemberItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
Invite, LeaveVoice, OpenMember, OpenShare, OpenVoiceSettings, SetInputMuted, SetOutputMuted,
ShowVoiceView, ToggleVoiceCompact,
};
use super::tree_model::{TreeEvent, TreeModel};
use super::widgets::{Avatar, IconButton, banner_scrim, icon, live_badge, panel, speaking_bars_in};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A window under this tall (pixels) has the smaller stage whatever the
/// setting says (`Nav.short` of the Slint front end).
pub const SHORT_WINDOW: f32 = 800.0;
/// What the page's header and call bar show, from the state.
#[derive(Clone, Debug, PartialEq)]
pub struct VoiceHead {
/// The channel we are in, as the tree shows it.
pub channel: String,
/// Its topic.
pub topic: String,
/// Its banner, empty without one.
pub banner: ImageRef,
/// Its client limit, -1 without one.
pub limit: i32,
/// Voice is connected.
pub connected: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// The server can stream (TeamSpeak 6 with voice): the call bar has Share.
pub can_share: bool,
}
impl VoiceHead {
/// The header and the call bar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |_| ImageRef::default());
let can_share = app
.vm
.current
.and_then(|id| app.vm.sessions.get(&id))
.is_some_and(|view| view.streams_available());
Self {
channel: card.own_channel,
topic: card.own_channel_topic,
banner: card.own_channel_banner,
limit: card.own_channel_limit,
connected: card.voice_connected,
input_muted: card.input_muted,
output_muted: card.output_muted,
can_share,
}
}
}
/// The voice channel page.
pub struct VoicePage {
head: VoiceHead,
people: Arc<Vec<MemberItem>>,
/// The smaller stage by choice.
compact: bool,
/// The window is too short for the larger stage.
short: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl VoicePage {
/// A page that follows `app` for the header and the call bar and `model` for
/// the people, on the stage the setting says (`compact`) in a window that is
/// `short` or not.
pub fn new(
app: &Entity<AppState>,
model: &Entity<TreeModel>,
compact: bool,
short: bool,
cx: &mut Context<Self>,
) -> Self {
let (head, counters, signals) = {
let state = app.read(cx);
(VoiceHead::of(state), state.counters().clone(), state.signals().clone())
};
let mut subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let head = VoiceHead::of(app.read(cx));
if head != this.head {
this.head = head;
cx.notify();
}
});
subscriptions.push(cx.subscribe(model, |this: &mut Self, _, event: &TreeEvent, cx| {
if let TreeEvent::Voice(people) = event {
this.people = people.clone();
cx.notify();
}
}));
let people = model.read(cx).voice().clone();
Self { head, people, compact, short, counters, _subscriptions: subscriptions }
}
/// What the header and the call bar show.
pub fn head(&self) -> &VoiceHead {
&self.head
}
/// The people it shows.
pub fn people(&self) -> &[MemberItem] {
&self.people
}
/// Whether the page is on the smaller stage now: chosen, or the window is too
/// short for the larger.
pub fn compact_shown(&self) -> bool {
self.compact || self.short
}
/// Whether the window is too short for the larger stage (the stage button is
/// off then).
pub fn short(&self) -> bool {
self.short
}
/// The setting `ui.voice_compact` is `compact`: tells the window if the stage
/// changes.
pub fn set_compact(&mut self, compact: bool, cx: &mut Context<Self>) {
if self.compact != compact {
self.compact = compact;
cx.notify();
}
}
/// The window is `short` (under [`SHORT_WINDOW`] tall) or not.
pub fn set_short(&mut self, short: bool, cx: &mut Context<Self>) {
if self.short != short {
self.short = short;
cx.notify();
}
}
}
/// The ring around a person's avatar: green while they talk, blue while they
/// stream (3 pixels, 2 on the smaller stage), else the quiet border of the
/// larger stage (2 pixels; the smaller has none).
fn ring(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> (u8, Rgba) {
let c = &theme.colors;
let loud = if compact { 2 } else { 3 };
if person.talking {
(loud, c.success)
} else if person.streaming {
(loud, c.accent)
} else {
(if compact { 0 } else { 2 }, c.border_strong)
}
}
/// What the corner of a person's avatar says: the bars while they talk, else
/// that their sound or their microphone is off.
fn corner(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> Option<AnyElement> {
let (c, bars) = (&theme.colors, if compact { 12.0 } else { 14.0 });
let size = if compact { 22.0 } else { 26.0 };
if !(person.talking || person.muted || person.sound_off) {
return None;
}
let (face, inside) = if person.talking {
if compact {
(c.accent, speaking_bars_in(theme, bars, c.on_accent).into_any_element())
} else {
(c.surface, speaking_bars_in(theme, bars, c.success).into_any_element())
}
} else {
let name = if person.sound_off { "headphone-off" } else { "mic-off" };
(c.surface, icon(name, if compact { 12.0 } else { 15.0 }, c.danger).into_any_element())
};
let (id, talking) = (person.id, person.talking);
let inset = if compact { 0.0 } else { 2.0 };
Some(
div()
.absolute()
.right(px(inset))
.bottom(px(inset))
.debug_selector(move || {
format!("voice-{}-{id}", if talking { "speaking" } else { "off" })
})
.size(px(size))
.rounded(px(size / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(face))
.flex()
.items_center()
.justify_center()
.child(inside)
.into_any_element(),
)
}
/// One person: an avatar with its ring, the mark in its corner, the name with
/// the crown of an admin, and what they do. A click opens their card.
fn participant(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let size = if compact { 54.0 } else { 80.0 };
let width = if compact { 68.0 } else { 120.0 };
let outer = size + 8.0;
let id = person.id;
let (ring_width, ring_color) = ring(theme, person, compact);
let client = u16::try_from(id).unwrap_or_default();
let name_width = width - if person.admin { 16.0 } else { 0.0 };
let words = if person.talking {
"Speaking"
} else if person.streaming {
"Streaming"
} else if person.away {
"Away"
} else {
""
};
let mut face = div()
.relative()
.size(px(outer))
.flex_none()
.rounded(px(outer / 2.0))
.border_color(hsla(ring_color))
.flex()
.items_center()
.justify_center();
face = match ring_width {
3 => face.border_3(),
2 => face.border_2(),
_ => face,
};
let mut face = face.child(
Avatar::new(("voice-avatar", id as u64), size, &person.initials, person.tint)
.image(person.avatar.clone()),
);
if let Some(mark) = corner(theme, person, compact) {
face = face.child(mark);
}
div()
.id(("voice-member", id as u64))
.debug_selector(move || format!("voice-member-{id}"))
.w(px(width))
.flex_none()
.flex()
.flex_col()
.items_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.cursor_pointer()
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: i32::from(client) }), cx)
})
.child(face)
.child(
div()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.child(
div()
.max_w(px(name_width))
.truncate()
.text_size(px(if compact { m.font_sm } else { m.font_md }))
.font_weight(if compact { FontWeight::NORMAL } else { FontWeight::MEDIUM })
.text_color(hsla(if person.myself { c.accent_text } else { c.text }))
.child(person.name.to_string()),
)
.when(person.admin, |row| {
row.child(icon("crown", if compact { 13.0 } else { 15.0 }, c.gold))
}),
)
.when(!compact, |column| {
column.child(
div()
.h(px(m.font_sm + 4.0))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.when(person.talking, |row| row.child(speaking_bars_in(theme, 12.0, c.success)))
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if person.talking {
c.success
} else {
c.text_secondary
}))
.child(words),
)
.when(person.streaming && !person.talking, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
)
})
.when(compact && person.streaming, |column| column.child(live_badge(theme)))
.into_any_element()
}
/// The channel's name, its topic and how many are in voice, over its banner.
fn header(
theme: &VoelinTheme,
head: &VoiceHead,
people: usize,
page: &VoicePage,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let banner = PictureKey::of(&head.banner);
let ink = if banner.is_some() { c.text } else { c.text_secondary };
let compact = page.compact_shown();
let count = if head.limit >= 0 {
format!("{people} in voice / {} total", head.limit)
} else {
format!("{people} in voice")
};
let stage = if page.short() {
"The window is too short for the larger stage"
} else if compact {
"Larger stage"
} else {
"Smaller stage"
};
div()
.id("voice-header")
.debug_selector(|| "voice-header".into())
.relative()
.w_full()
.flex_none()
.overflow_hidden()
.when_some(banner, |header, key| {
header
.child(
div()
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id("voice-banner")
.debug_selector(|| "voice-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(banner_scrim(theme)),
)
})
.child(
div()
.relative()
.flex()
.flex_row()
.gap(px(m.space_5))
.pl(px(m.space_7))
.pr(px(m.space_5))
.pt(px(m.space_5))
.pb(px(m.space_3))
.child(div().pt(px(m.space_1)).child(icon("volume-2", 40.0, c.text_secondary)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(m.space_1))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
div()
.id("voice-channel")
.debug_selector(|| "voice-channel".into())
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_3xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(head.channel.clone()),
)
.child(
IconButton::new(
"voice-invite",
"user-plus",
"Copy invite link",
)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx)
}),
)
.child(
IconButton::new(
"voice-stage",
if compact { "chevron-down" } else { "chevron-up" },
stage,
)
.enabled(!page.short())
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ToggleVoiceCompact), cx)
}),
)
.child(
IconButton::new(
"voice-chat-only",
"message-square",
"Chat only",
)
.on_click(|_, window, cx| {
window.dispatch_action(
Box::new(ShowVoiceView { on: false }),
cx,
)
}),
),
)
.when(!head.topic.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_md))
.text_color(hsla(ink))
.child(head.topic.clone()),
)
})
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(icon("users", 16.0, c.text_secondary))
.child(
div()
.id("voice-count")
.debug_selector(|| "voice-count".into())
.text_size(px(m.font_body))
.text_color(hsla(ink))
.child(count),
),
),
),
)
}
/// Mute, deafen, share, the voice settings and Leave, under the people.
fn call_bar(theme: &VoelinTheme, head: &VoiceHead) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (input_muted, output_muted) = (head.input_muted, head.output_muted);
let leave = c.danger;
div()
.id("voice-callbar")
.debug_selector(|| "voice-callbar".into())
.w_full()
.flex_none()
.flex()
.flex_row()
.justify_center()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_6))
.pb(px(m.space_3))
.child(
IconButton::new(
"call-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(input_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx)
}),
)
.child(
IconButton::new(
"call-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(output_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx)
}),
)
.when(head.can_share, |bar| {
bar.child(
IconButton::new("call-share", "monitor-up", "Share or go live")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenShare), cx)),
)
})
.child(
IconButton::new("call-settings", "settings", "Voice Settings")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenVoiceSettings), cx)),
)
.child(
div()
.id("call-leave")
.debug_selector(|| "call-leave".into())
.h(px(m.control_height))
.px(px(m.space_5))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(leave.with_alpha(0x73)))
.bg(hsla(c.danger_soft))
.cursor_pointer()
.hover(move |style| style.bg(hsla(c.danger_soft.mix(leave, 0.25))))
.on_click(|_, window, cx| window.dispatch_action(Box::new(LeaveVoice), cx))
.child(icon("phone-off", m.icon_md, leave))
.child(
div()
.text_size(px(m.font_body))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(leave))
.child("Leave"),
),
)
}
impl Render for VoicePage {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.voice.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let compact = self.compact_shown();
let stage = if compact {
// One row, scrolling sideways when there are many; centred while it fits.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
.h(px(112.0))
.flex_none()
.overflow_x_scroll()
.flex()
.flex_row()
.child(
div()
.h_full()
.flex_none()
.mx_auto()
.flex()
.flex_row()
.gap(px(m.space_3))
.px(px(m.space_6))
.pt(px(m.space_2))
.children(
self.people.iter().map(|person| participant(&theme, person, true)),
),
)
} else {
// Centred, wrapping into more rows when there are many.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
// Rows taller than the page scroll; the header and the call bar keep
// their places.
.flex_shrink(1.0)
.min_h_0()
.overflow_y_scroll()
.flex()
.flex_row()
.flex_wrap()
.justify_center()
.gap_x(px(m.space_6))
.gap_y(px(m.space_4))
.px(px(m.space_6))
.pt(px(m.space_3))
.pb(px(m.space_4))
.children(self.people.iter().map(|person| participant(&theme, person, false)))
};
// A cached pane's root takes the size its place gives it.
panel(&theme)
.id("voice-page")
.debug_selector(|| "voice-page".into())
.size_full()
.child(header(&theme, &self.head, self.people.len(), self))
.child(stage)
.child(call_bar(&theme, &self.head))
.child(
div()
.flex_1()
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("The channel's chat comes with a later slice."),
)
}
}
+234 -29
View File
@@ -4,14 +4,19 @@
//! counterparts of `ui/components/avatar.slint`, `button.slint` and
//! `shells/common.slint`'s `Panel`.
use std::sync::Arc;
use gpui_kit::{
App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, img, px,
svg,
AnyElement, App, Background, ClickEvent, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _,
Window, div, linear_color_stop, linear_gradient, px, svg,
};
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
use voelin_ui_vm::Rgb;
use voelin_ui_vm::image::{ImageRef, ImageSource};
use voelin_ui_vm::avatar::first_letter;
use voelin_ui_vm::image::ImageRef;
use crate::pictures::{PictureKey, picture};
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
@@ -34,6 +39,8 @@ pub enum Presence {
Info,
/// Not connected.
Offline,
/// Their sound is off (a person who does not hear).
Dnd,
}
impl Presence {
@@ -58,6 +65,7 @@ impl Presence {
Self::Idle => Some(c.idle),
Self::Info => Some(c.info),
Self::Offline => Some(c.offline),
Self::Dnd => Some(c.dnd),
}
}
}
@@ -67,11 +75,46 @@ pub fn tint(color: Rgb) -> Rgba {
Rgba(color.0 << 8 | 0xff)
}
/// How opaque the veil over a banner is at its left edge and at its right
/// (`components/banner-picture.slint`: `transparentize(0.26)` and `(0.34)`).
const BANNER_VEIL: (f32, f32) = (0.74, 0.66);
/// The veil over a banner picture: the surface colour, left to right from 74 %
/// to 66 % opaque. A row's text (`text`) keeps more than 4.5 to 1 against it
/// whatever the picture, even white behind the dark theme's light text or
/// black behind the light theme's dark text. It lies over the picture and
/// under the row's own tint.
pub fn banner_scrim(theme: &VoelinTheme) -> Background {
let surface = hsla(theme.colors.surface);
linear_gradient(
90.0,
linear_color_stop(surface.opacity(BANNER_VEIL.0), 0.0),
linear_color_stop(surface.opacity(BANNER_VEIL.1), 1.0),
)
}
/// Under this size (pixels) an avatar shows one letter, larger (`avatar.slint`).
const SMALL_AVATAR: f32 = 28.0;
/// What an avatar of `size` pixels writes on its colour, and how large:
/// the initials at 0.38 of the size, but only the first letter at half of it
/// under 28 pixels, where two letters at 0.38 are a few pixels high and cramped
/// (`avatar.slint`'s `small`, with `Images.first-letter`).
fn initials_for(initials: &str, size: f32) -> (SharedString, f32) {
if size < SMALL_AVATAR {
(first_letter(initials).into(), size * 0.5)
} else {
(initials.to_owned().into(), size * 0.38)
}
}
/// An avatar: the picture when there is one (a file of the engine's cache),
/// else the initials on `tint`, square with rounded corners for a server
/// and round for a person, with a presence dot and a green ring while the
/// person's voice goes out. Pictures other than files of the cache are drawn
/// as initials until the slices that decode them (the chat's, the members').
/// else the initials on `tint` (one letter under 28 pixels), square with
/// rounded corners for a server and round for a person, with a presence dot and
/// a green ring while the person's voice goes out. The picture is keyed by the
/// file and its stamp ([`crate::pictures`]), so a picture the engine writes
/// again shows. Pictures other than files of the cache are drawn as initials
/// until the slices that decode them (the chat's).
#[derive(IntoElement)]
pub struct Avatar {
id: ElementId,
@@ -129,10 +172,7 @@ impl RenderOnce for Avatar {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
let picture = match &*self.image {
ImageSource::File { path, .. } if self.image.size().width > 0 => Some(path.clone()),
_ => None,
};
let key = PictureKey::of(&self.image);
let face = div()
.size(px(self.size))
.flex_none()
@@ -141,16 +181,22 @@ impl RenderOnce for Avatar {
.flex()
.items_center()
.justify_center()
.bg(hsla(if picture.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match picture {
Some(path) => face.child(img(path).size_full().object_fit(ObjectFit::Cover)),
None => face.child(
div()
.text_size(px(self.size * 0.38))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child(self.initials),
),
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match key {
// The picture rounds its own corners: a parent's `overflow_hidden`
// clips to a rectangle.
Some(key) => face
.child(picture(key).size_full().rounded(px(radius)).object_fit(ObjectFit::Cover)),
None => {
let (letters, size) = initials_for(&self.initials, self.size);
face.child(
div()
.text_size(px(size))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child(letters),
)
}
};
let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none();
if self.speaking {
@@ -188,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,
@@ -296,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()
@@ -310,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,
@@ -356,3 +411,153 @@ pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div {
pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement {
div().flex_none().debug_selector(|| selector.into()).child(element)
}
/// A picture of the cache in its own colours, `size` pixels square (a group's
/// or a client's icon, a badge); none when it is no picture that shows.
pub fn small_picture(image: &ImageRef, size: f32) -> Option<AnyElement> {
let key = PictureKey::of(image)?;
Some(
picture(key)
.w(px(size))
.h(px(size))
.flex_none()
.object_fit(ObjectFit::Contain)
.into_any_element(),
)
}
/// The red LIVE tag.
pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(18.0))
.px(px(5.0))
.flex_none()
.flex()
.items_center()
.rounded(px(m.radius_xs))
.bg(hsla(c.live))
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child("LIVE")
}
/// Three bars: someone speaks. (The Slint bars move; these stand still, as
/// nothing here may draw the window anew with the clock.)
pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement {
speaking_bars_in(theme, size, theme.colors.success)
}
/// The speaking bars in `color`, for a ground the green does not stand out on
/// (the accent of the voice page's corner badge).
pub fn speaking_bars_in(_theme: &VoelinTheme, size: f32, color: Rgba) -> impl IntoElement {
let bar = move |height: f32| {
div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color))
};
div()
.w(px(size))
.h(px(size))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_between()
.child(bar(1.0))
.child(bar(0.6))
.child(bar(0.8))
}
/// A small rounded label: a role, a fact (talk power, a country), a badge.
/// `picture` is a badge's own picture, `icon` a Lucide icon in the label's
/// colour.
pub fn chip(
theme: &VoelinTheme,
text: impl Into<SharedString>,
icon_name: Option<&'static str>,
picture: Option<AnyElement>,
) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(22.0))
.px(px(m.space_3))
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.rounded(px(m.radius_pill))
.border_1()
.border_color(hsla(c.border_strong))
.bg(hsla(c.surface_3))
.text_size(px(m.font_xs))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.children(icon_name.map(|name| icon(name, 12.0, c.text_secondary).into_any_element()))
.children(picture)
.child(text.into())
}
/// Tooltips built by [`IconButton`] since the last call, as `(selector, label)`.
#[cfg(test)]
pub(crate) fn take_tooltips() -> Vec<(String, String)> {
tests::TOOLTIPS.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use super::*;
use crate::theme::Choice;
thread_local! {
pub(super) static TOOLTIPS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn record_tooltip(selector: &str, label: &str) {
TOOLTIPS.with(|log| log.borrow_mut().push((selector.to_owned(), label.to_owned())));
}
#[test]
fn two_letters_are_written_large_enough_and_one_letter_under_28_pixels() {
// The tree's 22 pixel avatars: one letter, half the size.
assert_eq!(initials_for("DE", 22.0), (SharedString::from("D"), 11.0));
assert_eq!(initials_for("GP", 27.9).0, SharedString::from("G"));
// 28 pixels and up: the initials at 0.38 of the size.
let (letters, size) = initials_for("NS", 28.0);
assert_eq!((letters, size), (SharedString::from("NS"), 28.0 * 0.38));
assert_eq!(initials_for("NS", 46.0).0, SharedString::from("NS"));
// What the engine gave when there is none, and a letter with a mark.
assert_eq!(initials_for("", 22.0).0, SharedString::from(""));
assert_eq!(initials_for("A\u{308}B", 22.0).0, SharedString::from("A\u{308}"));
}
#[test]
fn the_banner_veil_keeps_the_text_readable_over_any_picture() {
for choice in [Choice::Dark, Choice::Light] {
let theme = VoelinTheme::new(choice, choice == Choice::Dark, 1.0);
let c = &theme.colors;
// The weakest end of the veil, over the two pictures that are the
// worst for light and dark text.
for picture in [Rgba(0x0000_00ff), Rgba(0xffff_ffff)] {
let seen = c.surface.mix(picture, 1.0 - BANNER_VEIL.1);
assert!(
c.text.contrast(seen) > 4.5,
"{choice:?}: text on {picture:?} under the veil is {}",
c.text.contrast(seen)
);
}
// Left to right, from the stronger end to the weaker, in the surface's colour.
let surface = hsla(c.surface);
assert_eq!(
banner_scrim(&theme),
linear_gradient(
90.0,
linear_color_stop(surface.opacity(0.74), 0.0),
linear_color_stop(surface.opacity(0.66), 1.0),
)
);
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Per-area signals: `Update.refresh` of the transitions
//! ([`voelin_ui_vm::host::Refresh`]) turned into what the window's parts
//! listen to.
//!
//! The Slint front end draws again what a transition's `refresh` flags name.
//! Here a part of the window is an entity, and gpui-pre 0.3.10 draws a part
//! again when its entity is notified, so each area has an entity of its own,
//! a [`Signal`] with a generation, that the root state raises for the flags
//! of an update ([`Signals::raise`]) and that the parts observe
//! ([`Signals::watch`]): a change of the channel tree notifies the tree's
//! listeners, and the rail, the top bar and the main area are not asked
//! whether anything changed for them. A part still compares what it would show
//! with what it showed before it tells the window, for the many events that
//! set a flag and change nothing it shows.
//!
//! Only the flags of areas this front end has parts for are signals; the
//! others (`chat`, `streams`, ...) are dropped until their slices come, as
//! `perform` dropped all of them before.
use gpui_kit::{App, AppContext as _, Context, Entity, Subscription};
use voelin_ui_vm::host::Refresh;
use crate::app::AppState;
/// An area of the window that a change of the state can concern.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Area {
/// The servers: the rail, the top bar's title, the main area, the server
/// card (`Refresh::servers`).
Servers,
/// The voice and user cards of the sidebar (`Refresh::toolbar`).
Toolbar,
/// The channel tree and the members panel (`Refresh::tree`).
Tree,
/// The card over a member row (`Refresh::member_card`).
MemberCard,
}
impl Area {
/// Every area.
pub const ALL: [Area; 4] = [Area::Servers, Area::Toolbar, Area::Tree, Area::MemberCard];
}
/// The entity of an area: it has nothing but a count of how many times it was
/// raised, so that what observes it is told.
#[derive(Debug, Default)]
pub struct Signal {
generation: u64,
}
impl Signal {
/// How many times it was raised.
pub fn generation(&self) -> u64 {
self.generation
}
}
/// The signals of the areas, owned by the root state.
#[derive(Clone, Debug)]
pub struct Signals {
servers: Entity<Signal>,
toolbar: Entity<Signal>,
tree: Entity<Signal>,
member_card: Entity<Signal>,
}
impl Signals {
/// One signal per area, made in the entity `cx` belongs to.
pub fn new<T: 'static>(cx: &mut Context<T>) -> Self {
Self {
servers: cx.new(|_| Signal::default()),
toolbar: cx.new(|_| Signal::default()),
tree: cx.new(|_| Signal::default()),
member_card: cx.new(|_| Signal::default()),
}
}
/// The signal of an area.
pub fn of(&self, area: Area) -> &Entity<Signal> {
match area {
Area::Servers => &self.servers,
Area::Toolbar => &self.toolbar,
Area::Tree => &self.tree,
Area::MemberCard => &self.member_card,
}
}
/// The areas an update's flags name.
pub fn areas(refresh: &Refresh) -> Vec<Area> {
[
(refresh.servers, Area::Servers),
(refresh.toolbar, Area::Toolbar),
(refresh.tree, Area::Tree),
(refresh.member_card, Area::MemberCard),
]
.into_iter()
.filter_map(|(flagged, area)| flagged.then_some(area))
.collect()
}
/// Raise one area: whatever observes it is told.
pub fn raise_area(&self, area: Area, cx: &mut App) {
self.of(area).update(cx, |signal, cx| {
signal.generation += 1;
cx.notify();
});
}
/// Raise the areas `refresh` names, each once however many flags a batch
/// of events merged into it.
pub fn raise(&self, refresh: &Refresh, cx: &mut App) {
for area in Self::areas(refresh) {
self.raise_area(area, cx);
}
}
/// Run `on` whenever one of `areas` is raised, with the root state; the
/// subscriptions end with the part that holds them. `on` reads the state
/// outside of the part's render: a part that read the root entity while it
/// renders would be drawn again with every change of the root, which is
/// what the signals are for not doing.
pub fn watch<T: 'static>(
&self,
app: &Entity<AppState>,
areas: &[Area],
cx: &mut Context<T>,
on: impl Fn(&mut T, &Entity<AppState>, &mut Context<T>) + Clone + 'static,
) -> Vec<Subscription> {
areas
.iter()
.map(|&area| {
let (app, on) = (app.clone(), on.clone());
cx.observe(self.of(area), move |this, _, cx| on(this, &app, cx))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_flags_of_an_update_name_the_areas_this_front_end_has() {
assert!(Signals::areas(&Refresh::default()).is_empty());
let refresh = Refresh { tree: true, servers: true, chat: true, ..Default::default() };
assert_eq!(Signals::areas(&refresh), [Area::Servers, Area::Tree], "chat has no part yet");
assert_eq!(Signals::areas(&Refresh::ALL), Area::ALL);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+50
View File
@@ -119,6 +119,56 @@ impl Refresh {
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
/// Every part either of the two names: what a front end that handles a
/// batch of events draws once, however many events set a part.
pub fn merge(&mut self, other: Self) {
let Self {
servers,
toolbar,
tree,
chat,
streams,
viewer,
member_card,
home,
events,
gateways,
people,
conversations,
dm,
} = other;
self.servers |= servers;
self.toolbar |= toolbar;
self.tree |= tree;
self.chat |= chat;
self.streams |= streams;
self.viewer |= viewer;
self.member_card |= member_card;
self.home |= home;
self.events |= events;
self.gateways |= gateways;
self.people |= people;
self.conversations |= conversations;
self.dm |= dm;
}
}
#[cfg(test)]
mod refresh_tests {
use super::Refresh;
#[test]
fn merging_names_the_parts_of_both() {
let mut a = Refresh { tree: true, chat: true, ..Default::default() };
a.merge(Refresh { toolbar: true, tree: true, ..Default::default() });
assert_eq!(a, Refresh { toolbar: true, tree: true, chat: true, ..Default::default() });
let mut none = Refresh::default();
none.merge(Refresh::default());
assert!(none.is_empty());
none.merge(Refresh::ALL);
assert_eq!(none, Refresh::ALL);
}
}
/// What a transition wants kept.
+1 -1
View File
@@ -59,7 +59,7 @@ impl fmt::Debug for ImageSource {
/// What identifies a file's content without reading it: its length and the
/// time it was last written. Both zero for a file that is missing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Stamp {
len: u64,
modified: Option<SystemTime>,
+36
View File
@@ -339,6 +339,16 @@ pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String)
}
}
/// Open the card of a client of the server shown over the members panel
/// (`None` closes it).
pub fn open_member<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, client: Option<u16>) {
let Some(view) = state.current.and_then(|id| state.sessions.get_mut(&id)) else { return };
if view.member_card != client {
view.member_card = client;
cx.update.refresh.member_card = true;
}
}
/// The voice channel view was opened or closed: its chat is our channel's,
/// and its people lead the members panel.
pub fn show_voice_view<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) {
@@ -863,6 +873,32 @@ mod tests {
assert!(st.sessions[&1].collapsed.is_empty());
}
/// The card of a client opens over the members panel of the server shown
/// and closes again; the card is drawn again only when it changed.
#[test]
fn the_member_card_opens_and_closes() {
let (mut st, host) = (state(), Fake::default());
st.current = Some(1);
st.sessions.insert(1, SessionView::default());
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert_eq!(st.sessions[&1].member_card, Some(11));
assert!(cx.update.refresh.member_card);
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert!(!cx.update.refresh.member_card, "the same card: nothing to draw");
open_member(&mut st, &mut cx, None);
assert_eq!(st.sessions[&1].member_card, None);
assert!(cx.update.refresh.member_card);
// No server on screen: no card.
st.current = None;
let mut cx = Cx::new(&host);
open_member(&mut st, &mut cx, Some(11));
assert!(cx.update.refresh.is_empty());
}
/// A chat takes its server's colour only while it is a server chat of a
/// server in the list: a chat whose server is gone, and a chat that is a
/// channel's or a person's, take the colour of their own title. Black
+176 -1
View File
@@ -25,6 +25,7 @@ use std::time::Instant;
use tracing::{debug, info, warn};
use voelin_core::stream::PeerConfig;
use voelin_core::{Command, IdentityBlob, ObserveState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport, Secrets, Store};
use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan};
@@ -147,6 +148,67 @@ pub fn connect_voice_to<L>(
true
}
/// Join a channel of a session (a double-click in the tree, joining a friend):
/// move there with voice ([`logic::join_channel`]), ask for the password of a
/// locked channel first, and without voice on that server connect into it.
pub fn join_channel<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
session: i64,
channel: ChannelId,
stream_peer: Option<PeerConfig>,
) {
if let Some(password) = logic::join_channel(state, cx, session, channel) {
connect_into(state, cx, backing, session, channel, password, stream_peer);
}
}
/// The password dialog's Join ([`logic::join_with_password`]): the same, with
/// the password given.
pub fn join_with_password<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
password: String,
stream_peer: Option<PeerConfig>,
) {
if let Some((session, channel, password)) = logic::join_with_password(state, cx, password) {
connect_into(state, cx, backing, session, channel, password, stream_peer);
}
}
/// Connect voice into a channel of a server that has none: the server is
/// shown first, and the channel is named by its id (by its name the server
/// finds only a top-level channel, and a subchannel's name connects into the
/// default channel). Joined again after the connect if the server puts us
/// elsewhere ([`logic::join_after_connect`]).
fn connect_into<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
session: i64,
channel: ChannelId,
password: Option<String>,
stream_peer: Option<PeerConfig>,
) {
if state.current != Some(session) {
select_server(state, cx, backing, session);
}
let asked = connect_voice_to(
state,
cx,
backing,
Some(format!("/{channel}")),
password,
None,
stream_peer,
);
if asked {
logic::join_after_connect(state, session, channel);
}
}
/// Ask for the gateway of a server to be looked up ([`voelin_core::discover`]),
/// once a run ([`logic::discover_wanted`]): every one the server publishes is
/// kept, best first, and tried in turn; they take the place of a stored one
@@ -356,9 +418,13 @@ pub fn delete_bookmark<L: Lines>(
mod tests {
use voelin_store::{MemorySecrets, QueryConfig};
use std::sync::Arc;
use voelin_core::VoiceState;
use super::*;
use crate::host::Update;
use crate::host::testing::{Fake, State};
use crate::host::testing::{Fake, State, presence, session};
/// A store, secrets and a front end of the tests' own.
struct Rig {
@@ -482,6 +548,115 @@ mod tests {
assert!(!asked, "no server on screen");
}
/// A state whose first server has a session with `voice` and the channels
/// of `host::testing::presence`: Lobby (1), Games (2, where we are).
fn joined(rig: &Rig, voice: VoiceState, locked: Option<ChannelId>) -> (State, i64) {
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
let mut presence = (*presence()).clone();
if let Some(channel) = locked {
presence.channels.get_mut(&channel).unwrap().has_password = true;
}
let view = state.sessions.entry(id).or_default();
view.presence = Arc::new(presence);
view.state = session(voice, Some(2));
(state, id)
}
/// A double-click in the tree with voice up asks the engine to move there,
/// and connects nothing.
#[test]
fn joining_a_channel_with_voice_moves_there() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Connected, None);
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
let [Command::MoveToChannel { session, channel, password }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*session, *channel, password.as_deref()), (id as u64, 1, None));
assert!(update.password.is_none());
}
/// With no voice on the server the join connects into the channel, named
/// by its id, and remembers to join it again if the server puts us
/// elsewhere; a server that is not the one shown is shown first.
#[test]
fn joining_a_channel_without_voice_connects_into_it() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Disconnected, None);
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*session, options.channel.as_deref()), (id as u64, Some("/1")));
assert_eq!(state.sessions[&id].join_after_connect, Some(1));
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
// Another server is shown, then connected into the channel.
let other = rig.store.add_bookmark(&Bookmark {
name: "Lounge".into(),
address: "lounge.example".into(),
nickname: "Nova".into(),
..Default::default()
});
state.bookmarks = rig.store.bookmarks().unwrap();
let other = other.unwrap();
let view = state.sessions.entry(other).or_default();
view.presence = Arc::new((*presence()).clone());
let (_, update) = rig
.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, other, 2, None));
assert_eq!(state.current, Some(other));
assert!(
update.commands.iter().any(|c| matches!(c, Command::ConnectVoice { session, options }
if *session == other as u64 && options.channel.as_deref() == Some("/2"))),
"{:?}",
update.commands
);
}
/// A locked channel asks for its password first (nothing is sent), the
/// dialog's Join sends it with the move, and the same channel does not ask
/// again this connection.
#[test]
fn a_locked_channel_asks_for_its_password_and_joins_with_it() {
let rig = Rig::new();
let (mut state, id) = joined(&rig, VoiceState::Connected, Some(1));
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
assert!(update.commands.is_empty(), "{:?}", update.commands);
let prompt = update.password.expect("the dialog opens");
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(state.join_target, Some((id, 1)));
let (_, update) = rig.run(&mut state, |state, cx, backing| {
join_with_password(state, cx, backing, "secret".into(), None)
});
let [Command::MoveToChannel { channel, password, .. }] = &update.commands[..] else {
panic!("{:?}", update.commands)
};
assert_eq!((*channel, password.as_deref()), (1, Some("secret")));
assert_eq!(state.join_target, None);
// Remembered for this connection: no dialog the second time.
let (_, update) =
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
assert!(update.password.is_none());
assert!(
matches!(&update.commands[..], [Command::MoveToChannel { password, .. }]
if password.as_deref() == Some("secret")),
"{:?}",
update.commands
);
// An empty password joins nothing.
state.join_target = Some((id, 1));
let (_, update) = rig.run(&mut state, |state, cx, backing| {
join_with_password(state, cx, backing, String::new(), None)
});
assert!(update.commands.is_empty());
}
/// A new server is in the store with its password in the secrets, is the
/// one on screen, and has its gateway looked up (it has none to observe
/// through yet).
+79
View File
@@ -10,6 +10,7 @@ use tracing::warn;
use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind, Settings};
use voelin_core::{AudioSettings, TransmitMode};
use voelin_model::ChannelId;
use crate::bridge::AudioForm;
@@ -173,6 +174,55 @@ pub static UI_WINDOW: Key<Option<WindowState>> = Key::new(
)
.validated(valid_window);
/// What the channel tree remembers of one server: the channels folded shut and
/// the channel last selected (a click on its row).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TreeState {
/// The channels folded shut, in ascending order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub collapsed: Vec<ChannelId>,
/// The channel last selected, if one was.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selected: Option<ChannelId>,
}
impl TreeState {
/// Nothing is remembered.
pub fn is_empty(&self) -> bool {
self.collapsed.is_empty() && self.selected.is_none()
}
}
/// What the channel tree remembers, by the id of the server's bookmark
/// (as text: a JSON object's keys are).
pub type TreeStates = BTreeMap<String, TreeState>;
/// The most channels one server may have folded in [`UI_TREE`]: a server has
/// far fewer channels, so more is a damaged setting.
const TREE_STATE_LIMIT: usize = 10_000;
fn valid_tree(states: &TreeStates) -> Result<(), String> {
if states.keys().any(|id| id.parse::<i64>().is_err()) {
return Err("keyed by the id of a server".into());
}
if states.values().any(|state| state.collapsed.len() > TREE_STATE_LIMIT) {
return Err(format!("at most {TREE_STATE_LIMIT} folded channels of a server"));
}
Ok(())
}
/// `ui.tree`: which channels each server's tree has folded shut, and which
/// channel was selected, by the id of the server's bookmark. The GPUI front
/// end writes it; the Slint one does not read it (its tree forgets both
/// when the app ends).
pub static UI_TREE: Key<TreeStates> = Key::new(
"ui.tree",
Kind::Json,
"The channels each server's tree has folded and the channel selected, by server.",
TreeStates::new,
)
.validated(valid_tree);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
[
@@ -750,6 +800,35 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
/// The tree's memory is a JSON object by server, round-trips through the
/// service, and a damaged value is refused.
#[test]
fn tree_key() {
let settings = voelin_core::settings::Settings::in_memory();
settings.register(&UI_TREE);
assert!(settings.get(&UI_TREE).is_empty(), "nothing remembered at first");
let states = TreeStates::from([
("3".to_owned(), TreeState { collapsed: vec![4, 9], selected: Some(2) }),
("5".to_owned(), TreeState { collapsed: Vec::new(), selected: Some(1) }),
]);
settings.set(&UI_TREE, states.clone()).unwrap();
assert_eq!(settings.get(&UI_TREE), states);
assert_eq!(
settings.get_json("ui.tree"),
Some(
serde_json::json!({"3": {"collapsed": [4, 9], "selected": 2}, "5": {"selected": 1}})
)
);
// What an older build wrote without a field still loads.
settings.set_json("ui.tree", serde_json::json!({"7": {}})).unwrap();
assert!(settings.get(&UI_TREE)["7"].is_empty());
for damaged in
[serde_json::json!({"nope": {}}), serde_json::json!({"1": {"selected": "x"}})]
{
assert!(settings.set_json("ui.tree", damaged).is_err());
}
}
#[test]
fn voice_compact_key() {
let settings = voelin_core::settings::Settings::in_memory();
+102 -4
View File
@@ -4,16 +4,18 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub use voelin_model::channel_title;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges,
tree_rows,
BannerMode, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges, tree_rows,
};
pub use voelin_model::{ChannelId, channel_title};
use voelin_core::{Contact, Relation};
use crate::avatar;
use crate::bridge::{BadgeItem, MemberItem, TreeItem};
use crate::bridge::{BadgeItem, MemberCard, MemberItem, TreeItem};
use crate::image::ImageRef;
use crate::settings::ClientPlaybackMap;
use crate::state::SessionView;
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
pub fn banner_mode(mode: BannerMode) -> i32 {
@@ -54,6 +56,47 @@ pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec
.collect()
}
/// The card over a member row: everything about the client `id` of a session
/// and what is known of it locally (the contact, the playback settings).
/// None when the presence has no such client (it left).
pub fn member_card<L>(
view: &SessionView<L>,
id: u16,
contacts: &HashMap<String, Contact>,
playback: &ClientPlaybackMap,
) -> Option<MemberCard> {
let client = view.presence.clients.get(&id)?;
let uid = client.uid.as_ref();
let contact = uid.and_then(|u| contacts.get(u));
let local = uid.and_then(|u| playback.get(u)).copied().unwrap_or_default();
let groups = client
.server_groups
.iter()
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
.map(|g| g.name.as_str().into())
.collect();
Some(MemberCard {
open: true,
id: i32::from(id),
name: client.nickname.as_str().into(),
initials: avatar::initials(&client.nickname).into(),
tint: avatar::tint(&client.nickname),
avatar: avatar::image(view.avatar(id)),
status: status_of(client, view.talking.contains(&id)).into(),
description: client.description.as_deref().unwrap_or_default().into(),
groups,
badges: badge_items(&client.badges, &view.pictures),
country: client.country.as_deref().unwrap_or_default().into(),
talk_power: client.talk_power,
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
blocked: contact.is_some_and(|c| c.relation == Relation::Blocked),
volume: local.volume * 100.0,
muted: local.muted,
known: uid.is_some(),
streaming: client.streaming == Some(true),
})
}
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
/// The channels and clients of the server.
@@ -901,6 +944,61 @@ mod tests {
);
}
/// The card has what the row has, the groups by name, the badges, the
/// contact's relation and the local playback; a client that left has none.
#[test]
fn the_member_card_is_what_is_known_of_one_client() {
use std::sync::Arc;
use crate::settings::ClientPlayback;
let mut p = presence();
let bob = p.clients.get_mut(&11).unwrap();
bob.uid = Some("bob=".into());
bob.server_groups = vec![6, 99];
bob.description = Some("Raid lead".into());
bob.country = Some("DE".into());
bob.talk_power = 75;
bob.badges = vec!["4b27be5a-b92a-4b30-8b2d-14b59653f427".into()];
bob.streaming = Some(true);
let mut view = SessionView::<()> {
presence: Arc::new(p),
server_groups: vec![GroupInfo {
id: 6,
name: "Moderator".into(),
..Default::default()
}],
..Default::default()
};
view.talking.insert(11);
let mut friend = Contact::new("bob=");
friend.relation = Relation::Friend;
let contacts = HashMap::from([("bob=".to_owned(), friend)]);
let playback = ClientPlaybackMap::from([(
"bob=".to_owned(),
ClientPlayback { volume: 1.5, muted: true },
)]);
let card = member_card(&view, 11, &contacts, &playback).expect("bob is there");
assert!(card.open);
assert_eq!((card.id, &*card.name, &*card.initials), (11, "bob", "BO"));
assert_eq!(card.tint, avatar::tint("bob"));
assert_eq!(&*card.status, "Speaking");
assert_eq!((&*card.description, &*card.country, card.talk_power), ("Raid lead", "DE", 75));
let groups: Vec<&str> = card.groups.iter().map(|g| &**g).collect();
assert_eq!(groups, ["Moderator"], "a group the server did not list is left out");
assert_eq!(card.badges.len(), 1);
assert_eq!(&*card.badges[0].name, "20th Anniversary");
assert!(card.friend && !card.blocked && card.known && card.streaming && card.muted);
assert_eq!(card.volume, 150.0);
// Someone nobody knows: not known, nothing local, listening.
let alice = member_card(&view, 10, &contacts, &playback).unwrap();
assert!(!alice.known && !alice.friend && !alice.muted && alice.volume == 100.0);
assert_eq!(&*alice.status, "Listening");
assert!(member_card(&view, 99, &contacts, &playback).is_none(), "a client that left");
}
#[test]
fn channel_paths() {
let mut p = presence();
+13 -14
View File
@@ -426,23 +426,22 @@ impl App {
self.state.own_uids = uids;
}
/// The identity servers see us as on `bookmark` (the one place that
/// picks it): the bookmark's own if it names one that exists, else the
/// store's default.
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
let entries = self.store.identities().unwrap_or_default();
bookmark
.and_then(|b| self.bookmark(b))
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.default_identity_id())
/// The identity a bookmark names, if it names one.
fn named_identity(&self, bookmark: Option<i64>) -> Option<i64> {
bookmark.and_then(|b| self.bookmark(b)).and_then(|b| b.identity)
}
/// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]).
/// The identity servers see us as on `bookmark`: the bookmark's own if it
/// names one that exists, else the store's default (the one place that
/// picks it is [`voelin_store::Store::identity_id_for`]).
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
self.store.identity_id_for(self.named_identity(bookmark))
}
/// The identity a connection to `bookmark` uses
/// ([`voelin_store::Store::identity_for`]).
pub(crate) fn identity_for(&self, bookmark: Option<i64>) -> tsclientlib::Identity {
self.identity_id_for(bookmark)
.and_then(|id| self.store.identity(id).ok())
.unwrap_or_else(|| self.identity.clone())
self.store.identity_for(self.named_identity(bookmark), &self.identity)
}
/// The store's default identity (`Store::default_identity`).
+38 -15
View File
@@ -39,21 +39,44 @@ desktop shell, is slice 1 of the step's list and landed on `phase5/gpui-shell`
UI's keys, the secrets, the default identity), the server rail, the sidebar,
the top bar and the main area as entities that tell the window when what they
show changed (the window then draws every part: gpui-pre 0.3.10 renders every
uncached child view on every frame), the eleven callbacks of `bind/servers.rs` as actions through
`voelin-ui-vm`'s logic and the engine's commands, the window's size and
position kept in `ui.window`, the engine-event task in steps and a tick that
draws nothing. What it shows, what it costs idle and what it leaves to the
slices after it are in docs/ui.md, "The desktop shell"; the next slice is the
channel tree and the members. The shell was reviewed and gated the same day (an
Opus gate: no blocker and no major, six minors), and the minors are closed on
`phase5/gpui-shell-minors`: the records that said the parts draw only when what
they show changed are corrected (a part tells the window, and the window draws
every part, as gpui-pre 0.3.10 renders every uncached child view on every
frame), a window left maximized is maximized again on X11, the pictures are
1440 by 960, the connect test sends no DNS query, the sequences both front ends
ran are shared in `voelin-ui-vm`, and the `ui.window` row is in the settings
table; the gate's four risks of the shell are in docs/ui.md, "For the next
slices".
uncached child view on every frame), the eleven callbacks of `bind/servers.rs`
as actions through `voelin-ui-vm`'s logic and the engine's commands, the
window's size and position kept in `ui.window`, the engine-event task in steps
and a tick that draws nothing. What it shows, what it costs idle and what it
leaves to the slices after it are in docs/ui.md, "The desktop shell"; the next
slice is the channel tree and the members. The shell was reviewed and gated the
same day (an Opus gate: no blocker and no major, six minors), and the minors are
closed on `phase5/gpui-shell-minors`: the records that said the parts draw only
when what they show changed are corrected (a part tells the window, and the
window draws every part, as gpui-pre 0.3.10 renders every uncached child view on
every frame), a window left maximized is maximized again on X11, the pictures
are 1440 by 960, the connect test sends no DNS query, the sequences both front
ends ran are shared in `voelin-ui-vm`, and the `ui.window` row is in the
settings table; the gate's four risks of the shell are in docs/ui.md, "For the
next slices". Slice 2, the channel tree and the members panel, landed on
`phase5/gpui-tree` (2026-10-28): `Update.refresh` as per-area signals and the
shell's panes cached (the design the shell's review left for it), the pictures
the engine writes again shown and the old copies dropped, the tree over a
virtual list that applies the row operations of `voelin-ui-vm`'s `list::diff`,
the members panel, the member card and the password prompt, with the folds and
the selection kept per server; what a change costs, figure by figure, is in
docs/ui.md, "The channel tree and the members". The slice was reviewed the same
day (one major and five minors) and the commits after it close them: a channel's
banner is drawn under the surface veil of the Slint tree's `BannerPicture`, an
avatar under 28 pixels shows one letter, the password prompt ignores an empty
field and closes on Escape, and the `ui.tree` row of the settings table, the
list of the Bridge's properties and callbacks that the two panes use and some
long lines are corrected in docs/ui.md. Slice 3, the voice page and the call bar,
landed on `phase5/gpui-voice` (2026-10-28): the page as a cached pane of its own
that takes the main area (its people from the tree model's one build, so a talker
is still one build for three lists), the call bar and the smaller stage kept in
`ui.voice_compact`, the sidebar's server card with its banner, the voice card's
transmit modes and the volume of a person following the settings, the release
guard of Hold to talk (voice that drops, a window that loses the focus) and the
global push-to-talk key started on the engine's runtime; it was seen against both
development servers with a second client that talks. What it costs and what it
leaves is in docs/ui.md, "The voice page and the call bar". The next slice is the
chat, the composer and emoji.
| Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict |
|---|---|---|---|
+896 -119
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB