Author SHA1 Message Date
faumarayandClaude Fable 5.1 2e985d793c Merge phase5/ui-vm-2: the remaining Slint controllers split into toolkit-free logic (voelin-ui-vm) and Slint bind files, the engine-event transitions in vm::events::apply, the ui-vm gate follow-ups (plan section 6 step 2)
CI / Linux checks (push) Successful in 25m39s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:59:44 +03:00
faumarayandClaude Fable 5.1 4491ecee25 Merge main (3930ef2) into phase5/ui-vm-2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Fable 5.1 785bbd050b docs: the three minors of the Opus gate of phase5/ui-vm-2
docs/ui.md: the app.rs row of the step-3 table points the toolbar and
tree refreshes at servers/bind.rs, where they live; app.rs only calls them.
voelin-ui-vm host.rs: the doc of Update::rest matches the events module
(the Studio's stream, a changed setting, the offline-message answers; the
watched and shared streams are state and go through the stream effects).
CHANGELOG: the two visible fixes of the branch are named instead of
"nothing changes on screen".

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:26:46 +03:00
faumarayandClaude Sonnet 5.5 6329e56780 Make peer_config_follows_codecs state what preferred_codec promises on any machine
The test compared preferred_codec(&all, Some(H264)).is_some() with whether an
H.264 encoder exists. preferred_codec falls back to another encodable codec
when the configured one cannot be encoded, so is_some() is true on every
machine with any encoder and the assertion held only where an H.264 encoder
exists. The first CI run that could fetch the private dependency (Gitea run
1089, runner image without an H.264 encoder) failed on it; a developer machine
with FFmpeg or a GPU passed.

The test now says the contract: a configured H.264 is the result when
all.encoder_codecs() has it, and otherwise the result equals the automatic
choice, preferred_codec(&all, None). The built-in codecs (no OpenH264) pin both
branches on every machine: VP9 configured gives VP9, H.264 configured gives
the automatic choice, VP8.

The H.264-in-software offer assertion assumed VP8 second after H.264
(offer_codecs(&all, H264)[..2]). A hardware AV1 or VP9 encoder ranks before
libvpx's VP8, so a machine with software H.264 and one of them fails it (the
dev machine does with the named av1_vaapi encoder and hardware off). It now
says H.264 leads exactly the codecs the VP8-led offer has.

Checked at 9714dc2 in docker.gitea.com/runner-images:ubuntu-24.04 with the
apt packages of .github/actions/system-deps and rustup 1.94: the test failed
at media.rs:3426 and passes now; the voelin-core lib tests there were 268
passed, 1 failed, 2 ignored before and are 269 passed, 0 failed, 2 ignored
after.

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
Aleksey Selihov 9714dc2226 Merge pull request 'CI and release builds read the private VoelinProtocol repository' (#1) from phase0/ci-private-dependency into main
CI / Linux checks (push) Failing after 22m41s
2026-10-24 11:46:50 +00:00
faumarayandClaude Sonnet 5.5 c35bbb5ba8 Run the portal proxy test on a bus of its own, or say it checked nothing
voelin-platform's tests/proxy.rs says to run it under dbus-run-session, and
without DBUS_SESSION_BUS_ADDRESS it returned at once. With one set it ran on
the desktop's bus and failed at "the portal leaves the bus": the test has its
stand-in release org.freedesktop.portal.Desktop, and the first call afterwards
starts the real xdg-desktop-portal, which the bus can start by name; it
answers instead of the "missing" the test expects for a minute. A private bus
from plain dbus-run-session starts it the same way (the test failed the same
three times under it here), so the documented way did not work on a desktop
that has the portal installed.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:24:30 +03:00
faumarayandClaude Fable 5.1 b8ba43f0c9 Check each OpenSSH tool on its own and stop only an agent this job started
CI / Linux checks (pull_request) Failing after 21m18s
command -v with two names returns 0 when one resolves, so the guards were
weaker than they read. The release workflow's final step killed whatever agent
SSH_AGENT_PID named; it now needs the marker the start step writes after it
succeeded. Two documentation lines re-wrapped (the review's three minors).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:16:06 +03:00
faumarayandClaude Fable 5.1 c60acf9de0 Merge phase4/session-seam: the engine on voelin_proto::link::Session (plan Phase 4 step 7, first half)
CI / Linux checks (push) Failing after 49s
Slices 1 to 3 of docs/session-seam.md plus the merge of main ad20979 and the
minors round: SessionLink and the Backends registry put the engine on
Arc<dyn Session>; the TeamSpeak implementation is a Session under
voelin_core::ts; ServerLink, TsLink, LinkCmd, LinkEvent, LinkCtx and Remote are
private; VoiceOptions, QueryLogin and IdentityBlob are the public API changes.
Sonnet review accepted each slice; the Opus gate accepted the branch with one
minor (the TeamSpeak connector's refusal of an unreadable identity puts the
serde_json error, and so the key text, into the message: a follow-up).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 13:56:17 +03:00
faumarayandClaude Sonnet 5.5 e5956e40e9 Set CARGO_NET_GIT_FETCH_WITH_CLI in the CI workflow's own env as well
The checks action exports it through GITHUB_ENV, which depends on the runner
handing a composite action's environment file on to the later steps of the
job. If a runner did not, Cargo would silently go back to its built-in git
client, which cannot use the deploy key's IdentityFile, and fail with a
confusing authentication error in the first cargo command. The workflow-level
env does not depend on that, so both are set; the access check step still
exercises the key, the host key and the ssh configuration through git.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:45:56 +03:00
faumarayandClaude Sonnet 5.5 6e774873bf Document how CI and the release builds read the private VoelinProtocol repository
docs/ci.md gets a "VoelinProtocol access" section: why every cargo command
needs the access (Cargo resolves the whole workspace, so the gateway image
needs it too), the deploy key and the repository secret
VOELIN_PROTOCOL_DEPLOY_KEY, what the checks action, the release workflow and
the Dockerfiles do with it, why Cargo is told to use the system git, the
committed host key line with its fingerprint and the two commands that
re-check it, the effect on fork pull requests, and what each failure message
means. The runner setup no longer says that a fresh checkout does not build
there. docs/building.md says that the Docker builds need an ssh-agent with a
key that can read VoelinProtocol (--ssh default) and summarises the CI setup;
the plain docker build commands in it and in docs/gateway-admin.md gain
--ssh default, without which they would now stop at the cargo step.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:44:44 +03:00
faumarayandClaude Sonnet 5.5 b89116c0f4 Let the Docker builds fetch the private VoelinProtocol repository with an ssh-agent
Every cargo command in the images (linux, windows, android and the gateway
image) failed for the same reason as the CI job: Cargo resolves the whole
workspace, which includes the git dependency voelin-identity on the private
Voelin/VoelinProtocol repository, and the images had no SSH access to it. The
crates that depend on voelin-identity are voelin-store and, through it,
voelin-core, voelin-ui, voelin-ui-vm, voelin-android and voelinctl; the
gateway crate does not, but `cargo build -p voelin-gateway` fails without
access too (checked with an empty CARGO_HOME), so its Dockerfile needs the
same.

Each cargo RUN gets --mount=type=ssh,required=true: the build is handed the
caller's ssh-agent (docker build --ssh default), the key stays in the agent
and never reaches a layer or the build context, and a build without --ssh
fails at that step with "unset ssh forward key default". The build stage
copies the host key committed in .gitea/known_hosts to
/etc/ssh/ssh_known_hosts and sets CARGO_NET_GIT_FETCH_WITH_CLI=true, so that
Cargo uses the system git and ssh. The toolchain stages install git and
openssh-client where they were missing; the gateway Dockerfile gets the
syntax directive the others already have. scripts/docker-build.sh passes
--ssh default and stops early, with a message, when ssh-add -l shows no agent
or no key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:43:12 +03:00
faumarayandClaude Sonnet 5.5 437b508047 Start an ssh-agent with the VoelinProtocol deploy key in the release workflow
The Docker builds run cargo, which has to fetch the private VoelinProtocol
repository over SSH. After checkout the workflow now loads the deploy key
(secret VOELIN_PROTOCOL_DEPLOY_KEY) into a new ssh-agent through stdin, so
the key is never written to the runner's disk and never reaches an image
layer, and exports SSH_AUTH_SOCK and SSH_AGENT_PID for the later steps. The
agent is started with a nine hour key lifetime and stopped by a last step
that runs even after a failure, because the release runner is a persistent
host. The gateway image, which is built with a plain docker build and not
through scripts/docker-build.sh, gets --ssh default; the Dockerfiles use it
in the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:34:08 +03:00
faumarayandClaude Sonnet 5.5 8b6dcbf442 Give the Linux checks read access to the private VoelinProtocol repository
The workspace depends on voelin-identity from Voelin/VoelinProtocol over SSH,
and the job container had no key and no known_hosts, so the first cargo
command failed with "unknown SSH host key" (runs 1037 and 1050).

The checks action takes the private half of a read-only deploy key as the
input protocol-deploy-key (secrets are not visible inside a composite action,
so ci.yml passes ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}). Its first step
fails at once, with a message that names the secret, when the input is empty
or not a private key; it writes the key to ~/.ssh/voelin_protocol (0600),
appends the host key line committed in .gitea/known_hosts, writes a Host
block for git.faumaray.com (User gitea, IdentityFile, IdentitiesOnly,
StrictHostKeyChecking yes) and sets CARGO_NET_GIT_FETCH_WITH_CLI=true and
GIT_SSH_COMMAND for the rest of the job: Cargo's built-in git client cannot
use an IdentityFile, the system git and ssh can. The key reaches the step
through the environment only, is never echoed, and only the public
fingerprint is printed. A second step, after the system packages, runs
git ls-remote against VoelinProtocol, so a wrong key or a changed host key
fails there and not minutes later inside a cargo command.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:34:08 +03:00
faumarayandClaude Sonnet 5.5 5afa5a9740 Commit the SSH host key of git.faumaray.com for the CI and release builds
Cargo reaches the private VoelinProtocol repository over SSH and, in a fresh
job container or image, has no known_hosts: every cargo command failed with
"unknown SSH host key" (runs 1037 and 1050). The server (Gitea's built-in SSH,
SSH-2.0-Go) offers an RSA host key only; the line is committed here, after
checking its fingerprint (SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A)
against ssh-keyscan and Cargo's own report, so that jobs trust the reviewed
key instead of fetching one while they run. The next commits use it in the
checks action, the release workflow and the Dockerfiles.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+109
View File
@@ -1,9 +1,118 @@
name: Linux checks
description: Shared Linux validation for Gitea CI and release packaging.
inputs:
protocol-deploy-key:
description: >
Private half of the read-only deploy key registered on the private
Voelin/VoelinProtocol repository (the repository secret
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
visible inside a composite action). The action fails when it is empty.
required: true
runs:
using: composite
steps:
# The workspace depends on the private VoelinProtocol repository over SSH
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
# in seconds and before anything runs cargo.
- name: Install the VoelinProtocol deploy key
# The key reaches this step through the environment only: never in the
# script text, never echoed, no `set -x`.
env:
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
run: |
set -euo pipefail
umask 077
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
exit 1
fi
for tool in ssh ssh-keygen; do
command -v "$tool" > /dev/null || {
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
exit 1
}
done
ssh_dir="$HOME/.ssh"
key_file="$ssh_dir/voelin_protocol"
mkdir -p "$ssh_dir"
chmod 700 "$ssh_dir"
# Whatever the secret store did to the line ends and the final newline,
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
unset PROTOCOL_DEPLOY_KEY
chmod 600 "$key_file"
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
rm -f "$key_file"
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
exit 1
fi
# The fingerprint of the public half, to compare with the deploy key in
# the VoelinProtocol settings.
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
# The reviewed host key from the repository, never one fetched now.
known_hosts="$ssh_dir/known_hosts"
touch "$known_hosts"
chmod 600 "$known_hosts"
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
exit 1
}
while IFS= read -r line; do
case "$line" in '' | '#'*) continue ;; esac
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
# Use this key, and only this one, for the Gitea server; fail rather than
# ask when its host key is unknown or changed. The block goes first: ssh
# takes the first value it finds for each option.
config="$ssh_dir/config"
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
touch "$config"
if ! grep -qxF -- "$marker" "$config"; then
{
cat << EOF
$marker
Host git.faumaray.com
User gitea
IdentityFile $key_file
IdentitiesOnly yes
UserKnownHostsFile $known_hosts
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 30
EOF
cat "$config"
} > "$config.new"
mv "$config.new" "$config"
fi
chmod 600 "$config"
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
# system git runs ssh, which reads the config above. `-F` names it
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
# in $HOME, and a job image may set the two apart.
{
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
echo "GIT_SSH_COMMAND=ssh -F '$config'"
} >> "$GITHUB_ENV"
shell: bash
- uses: ./.github/actions/system-deps
- name: Check read access to VoelinProtocol
# The first thing cargo does, with the same git and ssh configuration, so
# that a wrong key or a changed host key fails here with a clear message
# and not minutes later inside a cargo command.
run: |
set -euo pipefail
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "Voelin/VoelinProtocol is readable with the deploy key."
shell: bash
- name: Install pinned Rust toolchain
run: |
set -euo pipefail
+10
View File
@@ -0,0 +1,10 @@
# SSH host key of git.faumaray.com (Gitea's built-in SSH server, which offers an
# RSA host key only). Fingerprint SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A,
# recorded on 2026-10-24 with `ssh-keyscan -t rsa git.faumaray.com`.
#
# Committed, never fetched while a job runs, so a CI or release build trusts the
# key reviewed here and not whatever answers on the network at that moment.
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
+10
View File
@@ -20,6 +20,11 @@ on:
env:
CARGO_TERM_COLOR: always
# Cargo fetches the private VoelinProtocol dependency with the system git and
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
# too; set here as well, it does not depend on the runner handing a composite
# action's GITHUB_ENV on to the later steps.
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
jobs:
linux:
@@ -32,3 +37,8 @@ jobs:
steps:
- uses: https://github.com/actions/checkout@v4
- uses: ./.gitea/actions/checks
with:
# A repository secret is not visible inside the composite action, so
# it is passed in. Pull requests from forks get no secrets: the
# action then fails at once with a message that says so.
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
+39 -1
View File
@@ -32,6 +32,38 @@ jobs:
docker info >/dev/null
# Remove only output owned by this workflow in its checkout.
rm -rf dist
# The workspace depends on the private VoelinProtocol repository over SSH
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
# this agent (`docker build --ssh default`): the key lives in the agent's
# memory, never on disk and never in an image layer. Stopped by the last
# step; the lifetime below ends the key anyway if the runner dies first.
- name: Start ssh-agent with the VoelinProtocol deploy key
env:
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
run: |
set -euo pipefail
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The repository secret VOELIN_PROTOCOL_DEPLOY_KEY is missing or empty. It holds the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
for tool in ssh-agent ssh-add; do
command -v "$tool" > /dev/null || { echo "::error::The runner needs the OpenSSH client: $tool is missing." >&2; exit 1; }
done
eval "$(ssh-agent -s -t 32400)" > /dev/null
started=
trap '[[ -n "$started" ]] || ssh-agent -k > /dev/null' EXIT
# LF lines and one final newline, whatever the secret store did.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' | ssh-add -q -
unset PROTOCOL_DEPLOY_KEY
# The fingerprint of the public half, to compare with the deploy key.
ssh-add -l
{
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
echo "SSH_AGENT_PID=$SSH_AGENT_PID"
# Only an agent this job started is stopped at the end.
echo "VOELIN_AGENT_STARTED=1"
} >> "$GITHUB_ENV"
started=1
- name: Linux packages
run: scripts/docker-build.sh linux --progress=plain
- name: Windows packages (MinGW)
@@ -77,7 +109,7 @@ jobs:
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
test -n "$version"
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
mkdir -p dist/gateway
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
- name: Collect packages and checksums
@@ -104,3 +136,9 @@ jobs:
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: scripts/gitea-release.sh dist/release
- name: Stop the ssh-agent
if: always()
run: |
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
ssh-agent -k > /dev/null || true
fi
+2
View File
@@ -2,3 +2,5 @@
/dev/.state/
/dist/
/.cargo/
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
/.scratch/
+11 -7
View File
@@ -69,13 +69,17 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The view models, the app's state and the decisions of the settings pages and
of the Stream Studio moved out of `voelin-ui` into a new crate,
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
the Bridge writes and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Nothing changes on screen. See
docs/ui.md, "Two crates".
- The view models, the app's state, the state change of every engine event and
the decisions of the settings pages, the Stream Studio, the streams, the chat,
the servers, the audio settings page, the friends and the development
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
depends on no UI toolkit (a second front end can use it); `voelin-ui`
converts its plain rows into Slint's and keeps the window, the Bridge writes
and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Two things change on screen: the chat of
a server that is gone takes the colour of its title instead of opaque
black, and a cached avatar file cut after a valid header shows the
initials instead of a broken picture. See docs/ui.md, "Two crates".
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
key, the signed-in account) with the account each belongs to, as a
`voelin-identity` key store, in two database migrations. Existing
Generated
+26 -25
View File
@@ -1774,9 +1774,9 @@ dependencies = [
[[package]]
name = "crypto-bigint"
version = "0.7.5"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"
checksum = "cc907c45bb7e9ef8fc3778defd0f3cd8c81288f1b4e748eba064948f20c47122"
dependencies = [
"cpubits",
"ctutils",
@@ -1817,7 +1817,7 @@ version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"
dependencies = [
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"rand_core 0.10.1",
]
@@ -1871,9 +1871,9 @@ dependencies = [
[[package]]
name = "ctutils"
version = "0.4.2"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"
dependencies = [
"cmov",
"subtle",
@@ -2400,7 +2400,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65"
dependencies = [
"base16ct 1.0.0",
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"crypto-common 0.2.2",
"digest 0.11.3",
"ff 0.14.0",
@@ -2512,7 +2512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5676,7 +5676,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.45.0",
]
[[package]]
@@ -6271,7 +6271,7 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4"
dependencies = [
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"crypto-common 0.2.2",
"ff 0.14.0",
"rand_core 0.10.1",
@@ -6467,7 +6467,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6842,7 +6842,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"
dependencies = [
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"hmac 0.13.0",
]
@@ -6898,7 +6898,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf"
dependencies = [
"const-oid 0.10.2",
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"crypto-primes",
"digest 0.11.3",
"pkcs1",
@@ -6996,7 +6996,7 @@ dependencies = [
"bytes",
"cbc",
"cipher 0.5.2",
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"ctr 0.10.1",
"curve25519-dalek 5.0.0",
"data-encoding",
@@ -7144,7 +7144,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7201,7 +7201,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7212,9 +7212,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"aws-lc-rs",
"ring",
@@ -8061,7 +8061,7 @@ checksum = "7b54d0ed0498daf3f78d82e00e28c8eec9d75a067c4cfbcc7a0f7d0f4077749e"
dependencies = [
"base64ct",
"bytes",
"crypto-bigint 0.7.5",
"crypto-bigint 0.7.7",
"ctutils",
"digest 0.11.3",
"pem-rfc7468 1.0.0",
@@ -8405,10 +8405,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8589,9 +8589,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.53.1"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
@@ -9768,6 +9768,7 @@ dependencies = [
"image",
"miniz_oxide 0.8.9",
"png",
"roxmltree",
"serde",
"serde_json",
"unicode-segmentation",
@@ -10082,9 +10083,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
dependencies = [
"rustls-pki-types",
]
@@ -10279,7 +10280,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
+12 -5
View File
@@ -175,7 +175,7 @@ the crate's authors are listed as its copyright holders.
| License | Crates |
|---|---|
| MIT License | 660 |
| MIT License | 667 |
| Apache License 2.0 | 31 |
| Unicode License v3 | 26 |
| BSD 3-Clause "New" or "Revised" License | 22 |
@@ -2611,7 +2611,7 @@ THIS SOFTWARE.
````
Used by: rustls-webpki 0.103.15
Used by: rustls-webpki 0.103.16
````text
Except as otherwise noted, this project is licensed under the following
@@ -7308,7 +7308,7 @@ DEALINGS IN THE SOFTWARE.
````
Used by: argon2 0.6.0, crypto-bigint 0.7.5, pkcs5 0.8.1, scrypt 0.12.0, sec1 0.8.1, spki 0.8.0, ssh-encoding 0.3.0, ssh-key 0.7.0-rc.11
Used by: argon2 0.6.0, crypto-bigint 0.7.7, pkcs5 0.8.1, scrypt 0.12.0, sec1 0.8.1, spki 0.8.0, ssh-encoding 0.3.0, ssh-key 0.7.0-rc.11
````text
Copyright (c) 2021-2026 The RustCrypto Project Developers
@@ -7930,7 +7930,7 @@ DEALINGS IN THE SOFTWARE.
````
Used by: ctutils 0.4.2
Used by: ctutils 0.4.5
````text
Copyright (c) 2025-2026 The RustCrypto Project Developers
@@ -9833,15 +9833,22 @@ Standard text, used by:
- windows-result 0.4.1 (https://github.com/microsoft/windows-rs)
- windows-strings 0.4.2: Microsoft (https://github.com/microsoft/windows-rs)
- windows-strings 0.5.1 (https://github.com/microsoft/windows-rs)
- windows-sys 0.45.0: Microsoft (https://github.com/microsoft/windows-rs)
- windows-sys 0.48.0: Microsoft (https://github.com/microsoft/windows-rs)
- windows-sys 0.52.0: Microsoft (https://github.com/microsoft/windows-rs)
- windows-sys 0.61.2 (https://github.com/microsoft/windows-rs)
- windows-targets 0.42.2: Microsoft (https://github.com/microsoft/windows-rs)
- windows-targets 0.48.5: Microsoft (https://github.com/microsoft/windows-rs)
- windows-targets 0.52.6: Microsoft (https://github.com/microsoft/windows-rs)
- windows-threading 0.1.0: Microsoft (https://github.com/microsoft/windows-rs)
- windows-threading 0.2.1 (https://github.com/microsoft/windows-rs)
- windows-version 0.1.7 (https://github.com/microsoft/windows-rs)
- windows 0.61.3: Microsoft (https://github.com/microsoft/windows-rs)
- windows 0.62.2 (https://github.com/microsoft/windows-rs)
- windows_x86_64_gnu 0.48.5: Microsoft (https://github.com/microsoft/windows-rs)
- windows_x86_64_gnu 0.52.6: Microsoft (https://github.com/microsoft/windows-rs)
- windows_x86_64_msvc 0.42.2: Microsoft (https://github.com/microsoft/windows-rs)
- windows_x86_64_msvc 0.48.5: Microsoft (https://github.com/microsoft/windows-rs)
- windows_x86_64_msvc 0.52.6: Microsoft (https://github.com/microsoft/windows-rs)
````text
@@ -9881,7 +9888,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
````
Used by: tokio-stream 0.1.19, tokio-util 0.7.19, tokio 1.53.1
Used by: tokio-stream 0.1.19, tokio-util 0.7.19, tokio 1.54.1
````text
MIT License
+7 -2
View File
@@ -453,10 +453,15 @@ mod tests {
lookups
}
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
/// connected to through the system's resolver, except `localhost`: the
/// servers of the tests listen on 127.0.0.1, and some machines resolve
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
/// the name `localhost`, not what the resolver makes of it.)
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
});
lookups
}
+14 -11
View File
@@ -199,19 +199,22 @@ async fn receive<R: AsyncRead + Unpin>(
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
// The directory and the file are made in one step, without a pause in
// which the task could be stopped: a cancel stops the task, waits for
// it and then removes the part file, so what the task made must be
// there by then (a pending open on the blocking pool would not be).
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let mut file = tokio::fs::File::from_std(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.map_err(|e| format!("{}: {e}", part.display()))?,
);
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
+7 -3
View File
@@ -166,9 +166,13 @@ impl Backends {
self.register_local(Arc::new(connector));
}
/// The device's Voelin account, for the connectors that use it (the QUIC
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
/// None is the default: nothing uses an account yet.
/// The device's Voelin account, which every connect hands the connector as
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
/// connector takes the myTeamSpeak account it presents from its own setters
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
/// proof from those setters to this hook. None is the default.
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
self.account = agent;
}
+8
View File
@@ -64,6 +64,10 @@ pub struct VoiceOptions {
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
/// client name on a TeamSpeak server (which may refuse or change it). When
/// it is empty, the `nickname` parameter of an `address` that is a
/// TeamSpeak link applies.
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
@@ -76,6 +80,10 @@ pub struct VoiceOptions {
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
/// The password of the server (`Hello.password`), for one that has a
/// password. When it is `None` or empty, the `password` parameter of an
/// `address` that is a TeamSpeak link applies. Not the password of
/// `channel` (that is `channel_password`).
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
+19 -13
View File
@@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
use voelin_audio::EncodedVoice;
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
@@ -325,7 +325,7 @@ async fn drive(
/// A transfer a user can cancel.
struct Running {
task: AbortHandle,
task: JoinHandle<()>,
part: Option<PathBuf>,
report: Report,
/// The server has opened it (a part file may exist).
@@ -1479,7 +1479,7 @@ impl Conn {
receive.await;
}
});
self.running(transfer, Running { task: task.abort_handle(), part, report, started });
self.running(transfer, Running { task, part, report, started });
}
fn upload(
@@ -1560,7 +1560,7 @@ impl Conn {
let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) };
files::upload_to(body, stored, from, size, offset, progress, task_report).await;
});
self.running(transfer, Running { task: task.abort_handle(), part: None, report, started });
self.running(transfer, Running { task, part: None, report, started });
}
fn running(&mut self, transfer: Option<TransferId>, running: Running) {
@@ -1572,15 +1572,21 @@ impl Conn {
fn cancel(&mut self, id: TransferId) {
match self.transfers.remove(&id) {
Some(running) if !running.task.is_finished() => {
running.task.abort();
// A part file exists once the server has opened the transfer.
if running.started.load(Ordering::Acquire)
&& let Some(part) = running.part
{
let _ = std::fs::remove_file(part);
}
(running.report)(TransferState::Cancelled);
Some(Running { task, part, report, started }) if !task.is_finished() => {
task.abort();
// The part file goes once the task has stopped, not at once: the task
// opens it in one step (files::download), so it is there or it never
// will be, and a removal that came before the open would leave it.
tokio::spawn(async move {
let _ = task.await;
// A part file exists once the server has opened the transfer.
if started.load(Ordering::Acquire)
&& let Some(part) = part
{
let _ = std::fs::remove_file(part);
}
report(TransferState::Cancelled);
});
}
_ => debug!(id, "cancel: no such transfer (finished?)"),
}
+98 -41
View File
@@ -607,6 +607,12 @@ async fn a_file_is_downloaded_through_the_connection_the_link_opens() {
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(
states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })),
"the transfer started: {:?}",
states.lock().unwrap()
);
// Cancelled the moment it is Started, when its part file may be opening.
rig.give(LinkCmd::CancelTransfer(3));
assert_eq!(final_state(&states).await, TransferState::Cancelled);
rig.quiet();
@@ -981,6 +987,32 @@ async fn a_connect_that_fails_is_a_disconnect_with_the_reason() {
);
}
/// An identity that cannot be read ends the connect with a disconnect whose
/// text says where it is wrong and holds none of the key: the JSON reader's
/// own message quotes a key that does not import, and the engine shows this
/// text as the error of the connection.
#[tokio::test(flavor = "multi_thread")]
async fn an_identity_that_cannot_be_read_is_a_disconnect_without_the_key() {
let (json, cut) = crate::ts::identity::json_with_a_cut_key();
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
let link = SessionLink::new(Backends::default());
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(options, LocalCtx::standalone().link, cmd_rx, event_tx);
let event = within("the end", events.recv()).await;
let LinkEvent::Disconnected(Some(text)) = event else {
panic!("a disconnect with the reason of the refusal")
};
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
crate::ts::identity::assert_holds_no_piece_of(&text, &cut);
}
// ---- the TeamSpeak side alone ---------------------------------------------------
/// A `LinkSession` over a recorder, made the way a connector makes it.
@@ -1930,20 +1962,38 @@ async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() {
const CHANNELS: u64 = 5_000;
let (conns, mut seen) = mpsc::unbounded_channel();
let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]);
let (mut params, _media) = connect_params("ts3server://fake.test?port=9987");
let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987");
params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() };
params.push_capacity = 1;
let connecting = tokio::spawn(connector.connect(params));
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(connected(everything())).unwrap();
// Made before the link is told it is connected: the connector waits only
// 250 ms for the first snapshot, and making 5,000 channels can take longer
// than that on a busy machine, which left the session without them.
let mut big = presence();
for id in 100..100 + CHANNELS {
let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() };
big.channels.insert(id, channel);
}
inner.events.send(connected(everything())).unwrap();
inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap();
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
let (session, mut pushes) = (connected.session, connected.pushes);
// The scope is sent whole only if the presence is in the host's state when
// it is asked for. The link takes its events in order, and a voice packet
// of one of the presence's clients comes through only once the presence
// is in: the packet says it is.
inner
.events
.send(LinkEvent::Audio(VoicePacket {
talker: TalkerId(8),
seq: 1,
codec: VoiceCodec::Voice,
whisper: false,
payload: OPUS_20_MS.to_vec(),
}))
.unwrap();
within("the voice", media.recv()).await;
let server = ScopeId::Server(1);
session.request(subscribe(server)).await.unwrap();
@@ -2152,12 +2202,48 @@ async fn event_of<T>(
.await
}
/// Asks for the file list of the lobby until the answer is one `wanted` takes,
/// one question at a time: the next goes out only when the last is answered.
/// Asked every few milliseconds instead, the answers fell behind the 16
/// events the bus holds (and the host's work), and the one that counted was
/// lost in the backlog.
async fn ask_files_until(
cmd_tx: &mpsc::UnboundedSender<LinkCmd>,
bus: &mut broadcast::Receiver<Event>,
request: &mut crate::files::RequestId,
wanted: impl Fn(&Result<Vec<FileEntry>, String>) -> bool,
) {
within("the file list to be answered as wanted", async {
loop {
*request += 1;
let dir = remote(10, None, "/");
cmd_tx.send(LinkCmd::ListFiles { request: *request, dir }).ok()?;
let result = loop {
match bus.recv().await {
Ok(Event::FileList { request: answered, result, .. })
if answered == *request =>
{
break result;
}
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => return None,
}
};
if wanted(&result) {
return Some(());
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await;
}
/// `Server.features` narrows what the host offers (protocol 1.3,
/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed.
#[tokio::test(flavor = "multi_thread")]
async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
use v1::entity::Kind;
use voelin_proto::test_util::{FakeConnector, eventually};
use voelin_proto::test_util::FakeConnector;
let connector = FakeConnector::new();
let host = connector.host();
@@ -2209,55 +2295,26 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
})
.count()
};
let ask = |request| {
let dir = remote(10, None, "/");
cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap();
};
let refusal = "not offered by this server: files";
let refused =
|event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal);
|result: &Result<Vec<FileEntry>, String>| matches!(result, Err(why) if why == refusal);
let mut request = 0;
// Refused here: nothing reaches the host.
ask(1);
loop {
let event = within("the refusal", async { bus.recv().await.ok() }).await;
if refused(&event) {
break;
}
}
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
assert_eq!(file_lists(), 0);
// The server lifts its list (an empty one keeps all the host's): files work.
put_server(&[]);
let mut request = 1;
eventually(WAIT, "a file list to reach the host", || {
request += 1;
ask(request);
file_lists() > 0
})
.await;
ask_files_until(&cmd_tx, &mut bus, &mut request, |result| !refused(result)).await;
assert!(file_lists() > 0, "the answer did not come from the host");
// The host narrows what it offers this user. A refusal counts only for a
// request made after the update: the earlier ones were answered by the host's
// wider set (or, before the server lifted its list, refused for that).
// The host narrows what it offers this user. Every question is answered
// before the next is asked, so those asked from here on are the ones the
// update can refuse; the earlier ones were answered by the host's wider set.
let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None };
handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap();
let after = request;
within("the narrower set to apply", async {
loop {
request += 1;
ask(request);
tokio::time::sleep(Duration::from_millis(20)).await;
while let Ok(event) = bus.try_recv() {
if matches!(&event, Event::FileList { request, .. } if *request > after)
&& refused(&event)
{
return Some(());
}
}
}
})
.await;
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
}
/// A port that is no port is refused in words, not dropped: the connection
+136 -43
View File
@@ -3257,9 +3257,13 @@ impl LocalPreview {
}
/// The first and last column of the rectangle in the middle row of a
/// decoded test pattern. Checks that pixels further than two columns from
/// its edges (which the codec blurs) have the colour of the rectangle or
/// the background.
/// decoded test pattern, after checking the row's structure: background, one
/// run of the rectangle, background. A pixel is whichever of the pattern's two
/// colours it is nearer to; it is not asked to be within some distance of one,
/// because an encoder that falls behind lowers its quality (the VP8 speed
/// control of the streamer does) and then moves a flat colour by 30 and more
/// per channel, still nowhere near the other colour. The two columns at each
/// edge, which the codec blurs, may be either.
#[cfg(all(test, feature = "media-desktop"))]
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
@@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
let i = ((y * picture.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
};
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
for x in 0..picture.width {
if x + 2 < a || x > b + 2 {
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
}
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
};
let rectangle = |x: u32| {
let p = pixel(x);
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
};
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
// One run: everything between its ends, but the blurred edges, is the
// rectangle's. Whatever is outside is the background by the choice of a and b.
for x in a + 2..=b.saturating_sub(2) {
assert!(
rectangle(x),
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
pixel(x)
);
}
(a, b)
}
@@ -3410,7 +3422,14 @@ mod tests {
assert!(all.is_hardware(backend), "{codec} offered in software");
}
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
// H.264 in software only (so not in `offer`): it leads the same
// codecs as with VP8 as the stream codec, whichever hardware
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
// before VP8, so VP8 is not always second).
let h264 = offer_codecs(&all, Codec::H264);
assert_eq!(h264[0], Codec::H264, "{h264:?}");
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
}
// Whatever this machine has: codecs every TeamSpeak client decodes
// come before H.264, HEVC last, and the automatic stream codec is
@@ -3423,10 +3442,23 @@ mod tests {
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
assert!(ranks.is_sorted(), "{offer:?}");
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
assert_eq!(
preferred_codec(&all, Some(Codec::H264)).is_some(),
all.encoder_codecs().contains(&Codec::H264)
);
// A configured codec is the stream codec when this machine can encode
// it; otherwise the result is the automatic choice,
// `preferred_codec(&all, None)` (some codec on any machine that
// encodes anything). Whether H.264 is encodable depends on the
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
// runner has none), so the expectation follows `all.encoder_codecs()`.
let h264 = preferred_codec(&all, Some(Codec::H264));
if all.encoder_codecs().contains(&Codec::H264) {
assert_eq!(h264, Some(Codec::H264), "{all:?}");
} else {
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
}
// The built-in codecs are the same everywhere (no OpenH264 loaded):
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
}
/// A sink whose viewers chose `codecs`; keeps every video frame with its
@@ -3516,11 +3548,30 @@ mod tests {
};
told(30).await;
assert_eq!(streamer.bitrate_kbps(), 1105);
// Not per frame.
let count = lock(&sink.formats).len();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(lock(&sink.formats).len(), count);
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
// Not per frame. The sink is told when it is attached and again by the
// encoder before its first frame (the same format twice), so the count is
// taken once a frame has been handed over and compared after more have;
// the frames, not a pause, are what "per frame" counts.
let frames_by = |frames: u64| {
let streamer = &streamer;
async move {
let deadline = Instant::now() + Duration::from_secs(30);
while streamer.stats().layers[0].frames < frames {
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
};
frames_by(1).await;
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
frames_by(seen + 5).await;
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
// The stats follow the sink's being told, not the other way round.
let deadline = Instant::now() + Duration::from_secs(10);
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
streamer.reconfigure(&codecs, update).unwrap();
told(15).await;
@@ -3691,15 +3742,35 @@ mod tests {
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
}
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
let stats = preview.stats();
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
assert_eq!(stats.codec, Some(Codec::Vp8));
let (before_first, first) = (Instant::now(), preview.stats());
let after_first = Instant::now();
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
assert_eq!(first.codec, Some(Codec::Vp8));
assert_eq!(preview.streamer().backend(), "synthetic");
// Rates over the second since: the pattern's rate, its bitrate.
// The rates are the counters over the time since the call before. How
// long that was the test does not say (a busy machine stretches a second,
// and the rate of pictures it manages is not what is tested), but it lies
// between the two spans the test timed around it.
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = preview.stats();
assert!((20..=40).contains(&stats.fps), "{stats:?}");
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
let before_second = Instant::now();
let second = preview.stats();
let after_second = Instant::now();
let longest = after_second.duration_since(before_first).as_secs_f64();
let shortest = before_second.duration_since(after_first).as_secs_f64();
let frames = (second.decoded - first.decoded) as f64;
let bits = (second.bytes - first.bytes) as f64 * 8.0;
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
// (The pictures per second are rounded, the bits per second cut off.)
let fps = f64::from(second.fps);
assert!(
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
);
let bitrate = second.bitrate as f64;
assert!(
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
);
}
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
@@ -4123,7 +4194,8 @@ mod tests {
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
let deadline = Instant::now() + Duration::from_secs(5);
// What is waited for is a state; the deadline only ends a hang.
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let stats = streamer.stats();
if done(&stats) {
@@ -4133,15 +4205,18 @@ mod tests {
std::thread::sleep(Duration::from_millis(20));
}
};
// The SineSource tone is 0.05; the second at half gain.
// The SineSource tone is 0.05; the second at half gain. The sources are metered
// before the mixer has made anything of them: the mix and the state of the
// sources are waited for too, not taken to be there with the meters.
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
let stats = wait("both tones", &|s| {
let stats = wait("both tones, mixed", &|s| {
s.audio_sources.len() == 2
&& near(s.audio_sources[0].level.peak, 0.05)
&& near(s.audio_sources[1].level.peak, 0.025)
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
&& s.audio_level.peak > 0.05
&& s.audio_limiter == 1.0
});
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
let first = stats.audio_sources[0].id;
// Mute the first (kept: same id), drop the second, add the
@@ -4157,19 +4232,31 @@ mod tests {
streamer.reconfigure(&codecs, update).unwrap();
assert_eq!(streamer.audio_sources().len(), 3);
let publisher = tap::publisher_id();
let speak = std::thread::spawn(move || {
// 20 ms of a 0.2 tone every 20 ms, for a second.
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
for _ in 0..50 {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
let heard = Arc::new(AtomicBool::new(false));
let speak = std::thread::spawn({
let heard = heard.clone();
move || {
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
// source takes what is published only from when it runs, which a
// busy machine delays by any time (the cap ends a thread whose test
// failed first).
let cap = Instant::now() + Duration::from_secs(120);
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
}
}
});
let stats = wait("microphone in, tone muted", &|s| {
s.audio_sources.len() == 3
&& s.audio_sources[1].level.peak > 0.15
&& s.audio_level.peak > 0.15
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
// Muted, and still metered: the tone's own level is read again.
&& near(s.audio_sources[0].level.peak, 0.05)
});
heard.store(true, Ordering::Relaxed);
speak.join().unwrap();
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
assert!(stats.audio_sources[0].spec.muted);
@@ -4201,9 +4288,15 @@ mod tests {
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
let mut source = EncodedSource::new(streamer);
let mut frames = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
assert!(Instant::now() < deadline, "no audio");
// Ten frames of audio and one of video, whichever the encoders make first:
// 20 ms of audio is quickly made, and a busy machine can keep the video
// encoder from its first frame for longer than that. The deadline only ends
// a hang.
let deadline = Instant::now() + Duration::from_secs(30);
let count =
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
tokio::time::sleep(Duration::from_millis(20)).await;
source.poll_frames(Instant::now(), &mut frames);
}
+39 -6
View File
@@ -1295,9 +1295,21 @@ mod tests {
// Before the viewer asks: its offer is made after this.
sink.layer_format(0, format(60_000_000));
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
// Connected for the viewer and for the streamer, in either order: the
// streamer asks for a keyframe when its viewer connects, a moment after
// the viewer has seen the connection.
let (mut watching, mut served) = (false, false);
wait(&mut rx, |e| {
match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
watching = true;
}
Event::StreamViewers { session: 1, viewers } => {
served |= viewers.iter().any(|v| v.state == ViewerState::Connected);
}
_ => {}
}
(watching && served).then_some(())
})
.await;
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
@@ -1312,7 +1324,15 @@ mod tests {
sink.take_layer_keyframes(&mut layers);
layers.contains(0)
};
keyframes();
// What asked for a keyframe so far (going live, the viewer's connecting
// and its first picture request) is done when a moment longer than the
// merging interval of requests (250 ms) passes with none.
for _ in 0..50 {
tokio::time::sleep(Duration::from_millis(300)).await;
if !keyframes() {
break;
}
}
sink.layer_format(0, format(9_000_000));
timeout(Duration::from_secs(5), async {
while !keyframes() {
@@ -1322,7 +1342,11 @@ mod tests {
.await
.expect("the layer did not change");
sink.layer_format(0, format(9_000_000));
tokio::time::sleep(Duration::from_millis(200)).await;
// The stream task takes its commands in order: its answer to this one
// (an error, nobody is viewer 65535) comes after all that the format
// above set going, and nothing is left to wait out.
handles[0].send(StreamCmd::Kick { viewer: u16::MAX });
wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await;
assert!(!keyframes(), "nothing changed");
handles[0].send(StreamCmd::Stop);
}
@@ -1701,7 +1725,16 @@ mod tests {
let stats = pipeline.stats();
assert_eq!(stats.codec, Some(Codec::Vp8));
assert!(stats.error.is_none(), "{stats:?}");
let sent = streamer.stats();
// The encoder counts a frame once the sink has taken it, so the picture
// can be at the viewer before the count has moved.
let mut sent = streamer.stats();
for _ in 0..500 {
if sent.video_frames >= 15 && sent.audio_frames > 0 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
sent = streamer.stats();
}
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
handles[0].send(StreamCmd::Stop);
+64 -5
View File
@@ -255,8 +255,21 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
blob.kind
)));
}
serde_json::from_str(&blob.json).map_err(|e| {
// Where the JSON is wrong, not what it says: it holds a private key.
from_json(&blob.json)
}
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
/// store keeps; voelin-core reads that text only through here (voelin-store
/// parses it too, for its own checks of a stored row).
///
/// What does not read is refused in words that say how it is wrong
/// (malformed, cut short, not an identity, unreadable) and where (line and
/// column), and never what it holds: the text holds a private key, and the
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
/// key that does not import as an invalid value, the key string and all), so
/// that message is never shown, not in an error, an event or a log.
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
serde_json::from_str(json).map_err(|e| {
let what = match e.classify() {
serde_json::error::Category::Syntax => "malformed",
serde_json::error::Category::Eof => "cut short",
@@ -271,6 +284,27 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
})
}
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
#[cfg(test)]
pub(crate) fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
#[cfg(test)]
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
/// and every other tool reads.
pub fn export(nickname: &str, identity: &Identity) -> String {
@@ -615,18 +649,43 @@ mod tests {
}
}
/// The JSON reader's own message quotes a key that does not import, so the
/// refusal is worded by `from_json` and holds none of the key.
#[test]
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
let (json, cut) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
for error in [
from_json(&json).unwrap_err().to_string(),
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
] {
assert!(
error.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
assert_holds_no_piece_of(&error, &cut);
}
}
#[test]
fn improve_level_keeps_the_key() {
let identity = synthetic();
// A fresh identity stops at the first counter whose level is 8 or more,
// and about one in 32 has 13 or more already, which `improve_level`
// returns as it is: ask for more than this one has, whatever it has.
let target = identity.level() + 3;
let levels = std::sync::Mutex::new(Vec::new());
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
levels.lock().unwrap().push(l);
})
.unwrap();
assert!(better.level() >= 13);
assert!(better.level() >= target);
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
assert!(better.counter() > identity.counter());
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
// Cancelled: nothing.
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
// Already there: the same identity.
+36 -4
View File
@@ -43,7 +43,7 @@ use voelin_proto::link::{
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use super::{ConnectOptions, ServerLink, TsLink, versions};
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
use crate::BackendInfo;
use crate::link::{
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
@@ -82,9 +82,14 @@ fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOption
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
Some(serde_json::from_slice(blob).map_err(|e| {
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
})?)
// The refusal never quotes the JSON: it holds the private key, and the
// JSON reader's own message would show a key that does not import.
let json = std::str::from_utf8(blob).map_err(|_| {
SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is not text".into(),
)
})?;
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
}
_ => {
return Err(SessionError::Protocol(
@@ -754,6 +759,33 @@ mod tests {
assert!(!futures::executor::block_on(confirm));
}
/// An identity that cannot be read ends the connect with words that say
/// where it is wrong and hold none of the key: the JSON reader's own
/// message quotes a key that does not import, and this text reaches the
/// event bus and the status line.
#[test]
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
let (json, cut) = identity::json_with_a_cut_key();
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
identity::assert_holds_no_piece_of(&text, &cut);
// Not even text.
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
+9 -4
View File
@@ -1650,8 +1650,10 @@ mod account_tests {
events,
));
let mut packet = [0; 2048];
let (_, first) =
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet))
.await
.expect("the first handshake packet within 5 s")
.unwrap();
// A logout/clear notification must cancel the old socket and restart.
account.send_replace(None);
let second = timeout(Duration::from_secs(5), async {
@@ -1663,11 +1665,14 @@ mod account_tests {
}
})
.await
.unwrap();
.expect("a handshake packet from a new socket within 5 s of the account change");
assert_ne!(first, second);
// Losing the account authority fails closed immediately, not after connect timeout.
drop(account);
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
timeout(Duration::from_secs(2), task)
.await
.expect("the connection to end within 2 s of the account source closing")
.unwrap();
assert!(
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
);
+71 -10
View File
@@ -960,11 +960,27 @@ pub(crate) mod tests {
/// What `f` logs at info (and above) on this thread: each line its
/// message, then its fields (` name=value`).
///
/// One recording subscriber is installed for the whole test process, the
/// first time this is called, and each call records into a buffer of its
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
/// lines: while it is the only subscriber alive, a callsite that another
/// test's thread meets first is registered against that thread's own
/// default, which is none, and stays disabled for every thread, so the
/// lines of the test that reads them are gone
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
/// failed with no lines at all, once in about thirty runs of the suite).
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
use std::cell::RefCell;
use std::sync::Once;
use tracing::field::{Field, Visit};
use tracing::span;
struct Lines(Arc<Mutex<Vec<String>>>);
thread_local! {
/// The lines of the `info_lines` running on this thread, if any.
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
#[derive(Default)]
struct Line(String, String);
impl Visit for Line {
@@ -975,7 +991,8 @@ pub(crate) mod tests {
}
}
}
impl tracing::Subscriber for Lines {
struct Recorder;
impl tracing::Subscriber for Recorder {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
*metadata.level() <= tracing::Level::INFO
}
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut line = Line::default();
event.record(&mut line);
self.0.lock().unwrap().push(line.0 + &line.1);
LINES.with(|lines| {
if let Some(lines) = lines.borrow_mut().as_mut() {
let mut line = Line::default();
event.record(&mut line);
lines.push(line.0 + &line.1);
}
});
}
fn enter(&self, _: &span::Id) {}
fn exit(&self, _: &span::Id) {}
}
let lines = Arc::new(Mutex::new(Vec::new()));
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
let lines = lines.lock().unwrap().clone();
/// Ends the recording of this thread, also when `f` panics.
struct Recording;
impl Drop for Recording {
fn drop(&mut self) {
LINES.with(|lines| lines.borrow_mut().take());
}
}
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
tracing::subscriber::set_global_default(Recorder)
.expect("no other global tracing subscriber in the tests");
// Makes every callsite decide again with the subscriber in place, also
// one that a thread was registering while it was being installed
// (creating a `Dispatch` rebuilds the cached interest of all of them).
drop(tracing::Dispatch::new(Recorder));
});
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
let _recording = Recording;
let result = f();
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
(result, lines)
}
/// The lines of `info_lines` do not depend on which thread met a callsite
/// first: this one is met on another thread, which records nothing, before
/// the thread that reads the lines meets it.
#[test]
fn info_lines_see_a_callsite_another_thread_met_first() {
fn log() {
tracing::info!("met");
}
let ((), lines) = info_lines(|| {
std::thread::spawn(log).join().unwrap();
log();
});
assert_eq!(lines, ["met"]);
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
};
let mut port = [0u8; 2];
client.read_exact(&mut port).await.unwrap();
let target = format!("{host}:{}", u16::from_be_bytes(port));
let port = u16::from_be_bytes(port);
let target = format!("{host}:{port}");
targets.send(target.clone()).unwrap();
let mut server = TcpStream::connect(target).await.unwrap();
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
// `::1` only, and the servers of the tests listen on 127.0.0.1.
let dial =
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
let mut server = TcpStream::connect(dial).await.unwrap();
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
});
+28
View File
@@ -0,0 +1,28 @@
//! What more than one integration test of this crate needs (a test binary
//! that uses it declares `mod common;`).
use std::path::{Path, PathBuf};
use std::time::Duration;
/// Wait until nothing has the SQLite database at `path` open any more, as when
/// the process that had it has ended: SQLite deletes the write-ahead log
/// (`<path>-wal`) when the last connection closes.
///
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
/// is joined there, and closing the connection checkpoints the log under an
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
/// lock only as long as the busy timeout (5 s) and then fails with
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
/// 6 s it happens every time).
pub async fn closed(path: &Path) {
let mut wal = path.as_os_str().to_owned();
wal.push("-wal");
let wal = PathBuf::from(wal);
tokio::time::timeout(Duration::from_secs(120), async {
while wal.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the engine's database connection closed");
}
+14 -1
View File
@@ -24,6 +24,8 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
mod common;
const LOBBY: ChatTarget = ChatTarget::Channel(1);
const ME: &str = "me-uid";
@@ -529,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
history.flush();
drop((engine, history));
// Dropping the engine does not close the database yet (see `closed`).
common::closed(&path).await;
// After a restart, with the gateway down: the stored page, found by the
// gateway's URL, which is remembered with the server's id.
@@ -812,7 +816,16 @@ async fn not_found_proxy() -> String {
#[tokio::test(flavor = "multi_thread")]
async fn the_next_published_gateway_is_used_when_one_fails() {
let proxy = not_found_proxy().await;
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
// A port that is taken and never listened on: connecting is refused at once,
// and no other test of this process can be given it meanwhile (one that was
// only free for a moment could be, the listeners of the others bind port 0).
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
let closed = reserved.local_addr().unwrap().port();
assert!(
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
"something listens on port {closed}"
);
let gw = FakeGateway::start().await;
let path = temp_db("fallback");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
+17
View File
@@ -1,8 +1,10 @@
//! Engine against the development servers (dev/docker-compose.yml).
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use voelin_core::{
@@ -15,6 +17,17 @@ fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
/// unsets them there. While it does, whatever else connects to the server is
/// told the addresses of those banners, and an engine fetches what it is told
/// (as it should): the requests of such an engine reached the HTTP server of
/// `ts6_banners`, which counts the requests of the engine under test, and the
/// test failed on `disabled policy must prevent HTTP requests` in every run
/// that had the tests of this file run side by side (as they do). The tests
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
/// runs with the server to itself, and the others before or after it.
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for(
rx: &mut Receiver<Event>,
@@ -131,6 +144,7 @@ async fn ts6_engine() {
if !live() {
return;
}
let _server = TS6.read().await;
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
.await;
}
@@ -258,6 +272,7 @@ async fn ts6_channel_joins() {
if !live() {
return;
}
let _server = TS6.read().await;
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
}
@@ -329,6 +344,7 @@ async fn ts6_banners() {
if !live() {
return;
}
let _server = TS6.write().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let query_addr =
@@ -512,6 +528,7 @@ async fn ts6_avatars() {
if !live() {
return;
}
let _server = TS6.read().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
+52 -1
View File
@@ -10,7 +10,9 @@
//! dedup of a message that comes twice, history, transfers, offline messages,
//! the features of a host, a reconnect and the media of a session are the
//! engine's own behaviour; nothing here needs a TeamSpeak server or a
//! TeamSpeak type.
//! TeamSpeak type, except `a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`,
//! which runs the engine's own TeamSpeak connector up to its refusal of an
//! identity.
use std::path::PathBuf;
use std::sync::Arc;
@@ -163,6 +165,12 @@ impl Harness {
fn on(connector: FakeConnector) -> Self {
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
Self::with_backends(backends, connector)
}
/// The engine on `backends`; `connector` is the fake host the test may
/// have registered in them (a test that registers none leaves it unused).
fn with_backends(backends: Backends, connector: FakeConnector) -> Self {
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
@@ -1502,3 +1510,46 @@ async fn a_teamspeak_identity_without_json_is_refused_and_no_session_is_made() {
assert!(handle.close_reason().is_none());
assert_eq!(h.connector.connects().len(), 1);
}
/// A TeamSpeak identity whose key does not import ends the connect with words
/// that say where the JSON is wrong and never show the key: the JSON reader's
/// own message quotes it, and the text is the reason of the disconnect, the
/// `Error` event and the status line the UI makes of it. This is the one test
/// of the file that runs the engine's own TeamSpeak connector
/// (`Backends::default()`): the refusal is that connector's and comes before
/// any network.
#[tokio::test(flavor = "multi_thread")]
async fn a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key() {
let mut json = serde_json::to_value(tsclientlib::Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
// The key lost its last two characters.
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json.to_string()));
let mut h = Harness::with_backends(Backends::default(), FakeConnector::new());
h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
assert_eq!((state.own_channel, state.own_client), (None, None));
let error = h.error().await;
assert!(
error.starts_with(
"voice: the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
// Nothing the engine reported afterwards holds a piece of the key either.
let mut shown = vec![error];
while let Ok(Ok(event)) =
tokio::time::timeout(Duration::from_millis(300), h.events.recv()).await
{
shown.push(format!("{event:?}"));
}
for text in &shown {
for piece in cut.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
}
@@ -10,6 +10,10 @@ use voelin_core::settings::Settings;
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
use voelin_model::FileRef;
mod common;
use common::closed;
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
@@ -165,6 +169,7 @@ async fn contacts_are_kept_in_the_database() {
engine.history().flush();
}
// A new engine attaches the database later: the contacts come back.
closed(&path).await;
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
+18 -3
View File
@@ -1,4 +1,9 @@
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
# syntax=docker/dockerfile:1
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
# (--ssh default hands the build your ssh-agent, which must hold a key that
# can read the private VoelinProtocol repository: docs/building.md,
# "Depending on VoelinProtocol". The gateway itself does not use it, but
# Cargo resolves the whole workspace, which includes voelin-identity.)
# Run: docker run -d --name tsgw --init --restart unless-stopped \
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
@@ -6,9 +11,19 @@
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
FROM rust:1.94-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
# voelin-identity comes from the private VoelinProtocol repository, fetched
# over SSH by Cargo through the system git, with the agent that
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# every cargo command needs this, although this crate does not use
# voelin-identity.
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
RUN --mount=type=ssh,required=true \
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /tsgw /usr/local/bin/tsgw
+36 -19
View File
@@ -1180,19 +1180,32 @@ mod tests {
scenes
}
/// The first preview frame that `wanted` takes. The preview keeps the latest
/// frame only, so few older ones are waiting or on their way: the number of
/// frames looked at is the bound (the work), and the wait for each, which a
/// busy machine can stretch, only ends a hang.
fn preview_until(
preview: &Handoff<VideoFrame>,
wanted: impl Fn(&VideoFrame) -> bool,
) -> Arc<VideoFrame> {
for _ in 0..20 {
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
if wanted(&frame) {
return frame;
}
}
panic!("the preview never showed what was asked for");
}
#[tokio::test]
async fn it_composes_into_the_preview_and_follows_commands() {
let studio = Studio::start(one_colour_scene()).await.unwrap();
let preview = studio.preview();
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
let started = Instant::now();
let frame = loop {
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
};
assert_eq!((frame.width, frame.height), (32, 24));
// The studio composes from the moment it starts, at the size and rate the
// preview has then (480x270, 15 fps): a frame of that size can be the
// first one there is.
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
@@ -1211,15 +1224,12 @@ mod tests {
.unwrap();
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
assert_eq!(studio.status().active_scene, break_id);
// The new scene's source draws.
let frame = loop {
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
if p.data[..3] == [1, 2, 3] {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
};
// The new scene's source draws, from the first frame composed after the
// command.
let frame = preview_until(
&preview,
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
);
drop(frame);
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
@@ -1402,9 +1412,16 @@ mod tests {
assert_eq!((listed[0].width, listed[0].height), (64, 48));
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
let mut frames = frames;
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
// (The wait only ends a hang.)
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
assert_eq!((frame.width, frame.height), (64, 48));
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
// A frame is counted once it has been handed over, so the count can still be
// behind when the frame is in the hands of the test.
let deadline = Instant::now() + Duration::from_secs(30);
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
assert!(Instant::now() < deadline, "the frame handed over was never counted");
std::thread::sleep(Duration::from_millis(5));
}
capture.stop();
std::fs::remove_dir_all(&dir).ok();
}
@@ -350,7 +350,22 @@ mod tests {
#[test]
fn an_unwritable_path_fails_at_once() {
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
let dir = dir("unwritable");
// A path below a regular file fails for every user, root included
// (ENOTDIR). A directory that is merely missing would be created, and
// a read-only one is written to by root.
let file = dir.join("not-a-directory");
std::fs::write(&file, b"x").unwrap();
assert!(Recorder::start(file.join("x").join("clip.webm"), 0, 2).is_err());
// The directory is there and the file cannot be created because the
// path names a directory (EISDIR, again for every user).
let named_like_a_file = dir.join("clip.webm");
std::fs::create_dir(&named_like_a_file).unwrap();
assert!(Recorder::start(&named_like_a_file, 0, 2).is_err());
// A name that asks for no known container is refused before any file
// is created.
assert!(Recorder::start(dir.join("clip.mp4"), 0, 2).is_err());
assert!(!dir.join("clip.mp4").exists());
std::fs::remove_dir_all(&dir).ok();
}
}
+74 -7
View File
@@ -1,8 +1,10 @@
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
//! session bus. Run it on a private bus:
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
//! without a session bus it checks nothing. Its own test binary: answers
//! are kept process-wide.
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
//! own that starts no services: on a desktop's bus the real portal is running
//! or startable, and when the stand-in leaves the bus (as the test has it do)
//! the real one is started and answers instead. Without `dbus-run-session`,
//! or a bus daemon for it, the test says so and checks nothing. Its own test
//! binary: answers are kept process-wide.
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
@@ -11,6 +13,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
use voelin_platform::proxy::proxy_for;
/// Set for the run on the bus of its own.
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
/// others.
struct Resolver {
@@ -34,10 +39,72 @@ impl Resolver {
}
}
/// The configuration of the bus of its own: a session bus without the service
/// directories, so that nothing on it can be started by name. Its socket is
/// made in `dir`.
fn bus_config(dir: &std::path::Path) -> String {
format!(
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:tmpdir={}</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
"#,
dir.display()
)
}
/// Run this test again under `dbus-run-session` on a bus of its own, and say
/// nothing was checked when that bus cannot be had.
fn on_a_bus_of_its_own() {
let dir = std::env::temp_dir();
let config = dir.join(format!("voelin-proxy-test-bus-{}.conf", std::process::id()));
std::fs::write(&config, bus_config(&dir)).unwrap();
let run = std::process::Command::new("dbus-run-session")
.arg(format!("--config-file={}", config.display()))
.arg("--")
.arg(std::env::current_exe().unwrap())
.args(["--exact", "the_portal_names_the_proxy", "--nocapture", "--test-threads=1"])
.env(ON_ITS_OWN_BUS, "1")
.output();
let _ = std::fs::remove_file(&config);
let run = match run {
Ok(run) => run,
Err(e) => {
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
return;
}
};
let text =
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
if run.status.success() {
// A child that ran no test (its filter matched nothing) exits 0 as well.
assert!(
text.contains("test result: ok. 1 passed;"),
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
);
return;
}
// The test ran and failed, or the bus never came up.
assert!(
!text.contains("running 1 test"),
"the test failed on its own bus ({}):\n{text}",
run.status
);
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
}
#[tokio::test]
async fn the_portal_names_the_proxy() {
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
eprintln!("no session bus: run under dbus-run-session");
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own();
return;
}
let lookups = Arc::new(AtomicU32::new(0));
+7 -5
View File
@@ -16,24 +16,26 @@ path = "src/lib.rs"
# must show neither. The front ends convert these types (docs/ui.md).
[dependencies]
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
# Picture sizes (the header of a file); PNG and JPEG are listed as the
# front end's toolkit used to bring them.
# Whether a picture file decodes, and its size; PNG and JPEG are listed as
# the front end's toolkit used to bring them.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
serde = { version = "1", features = ["derive"] }
# JSON values of the settings and the gateway's configuration keys.
serde_json = "1"
# Whether an SVG document is XML with an svg root (the vector renderers read
# it with this parser too).
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
# The Twemoji archive's blocks (raw deflate).
miniz_oxide = "0.8"
# Grapheme clusters for emoji in chat text.
unicode-segmentation = "1.13"
# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests.
png = "0.18"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { workspace = true }
voelin-store = { path = "../voelin-store" }
[dev-dependencies]
png = "0.18"
[lints]
workspace = true
+15 -1
View File
@@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500;
/// How a span of text looks.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Style {
/// Bold (`[b]`).
pub bold: bool,
/// Italic (`[i]`).
pub italic: bool,
/// Underlined (`[u]`).
pub underline: bool,
/// Struck through (`[s]`).
pub strike: bool,
/// Code: on a background.
pub code: bool,
@@ -51,12 +55,16 @@ pub struct Style {
/// A piece of a block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Span {
/// Text with one style.
Text {
/// The characters.
text: String,
/// How they look.
style: Style,
},
/// A picture at an address (`[img]…[/img]`).
Image {
/// Where the picture is.
url: String,
},
}
@@ -68,7 +76,10 @@ pub enum BlockKind {
Text,
/// A line of a quote; the first names who said it (`[quote=Name]`), when
/// the quote does.
Quote { author: String },
Quote {
/// Who said it, empty when the quote does not say.
author: String,
},
/// Code: all its lines in one span.
Code,
/// An item of a list.
@@ -80,13 +91,16 @@ pub enum BlockKind {
/// A line, a quote's line, code, a list item or a rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
/// What the block is.
pub kind: BlockKind,
/// Its pieces, left to right.
pub spans: Vec<Span>,
}
/// A message's text: its blocks, top to bottom.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Doc {
/// The lines, quotes, code and rules in order.
pub blocks: Vec<Block>,
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,9 @@
//! Chat lines: one [`ChatLine`] per message, with its text in blocks of
//! styled runs (`vm::bbcode`), its reactions and the files and pictures it
//! links.
//! links; [`logic`] has what happens to a session's chats when the engine
//! tells something.
pub mod logic;
use std::borrow::Cow;
use std::cell::RefCell;
@@ -9,7 +12,7 @@ use std::path::PathBuf;
use unicode_segmentation::UnicodeSegmentation;
use voelin_core::HistoryMessage;
use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence};
use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails};
use crate::avatar;
use crate::bbcode::{self, BlockKind, Doc, Span, Style};
@@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
use crate::color::Rgb;
use crate::emoji;
use crate::image::ImageRef;
use crate::state::{SessionView, Tab};
/// Where the server's welcome and host message keep what their lines were
/// built from (`LineCache`), apart from the messages' ids.
pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1];
/// What the server says to everyone who connects, with where its line keeps
/// its parts: its welcome message, and its host message when that goes to
/// the chat log.
pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> {
let host = details.host_message_mode == HostMessageMode::Log;
[Some(&details.welcome_message), host.then_some(&details.host_message)]
.into_iter()
.zip(SERVER_LINES)
.filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id)))
.collect()
}
/// The text of the server's line `key` (-1, -2, ...) of a server chat, if
/// `tab` is one.
pub fn server_text<'a, L>(view: &'a SessionView<L>, tab: &Tab<L>, key: i32) -> Option<&'a str> {
if tab.target != ChatTarget::Server || key >= 0 {
return None;
}
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
}
/// Lines of the same author within this time are grouped (no header).
const GROUP_MS: i64 = 5 * 60 * 1000;
@@ -24,7 +53,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000;
/// The author and time of the line before, for grouping.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Previous {
/// Who wrote it.
pub author: String,
/// When, in milliseconds since the epoch.
pub ts_ms: i64,
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
//! The sample data of `VOELIN_DEMO_UI` and the helpers of the development
//! switches that only look at the state. [`logic`] has the sample servers,
//! people, chats, contacts, notices and pictures as plain values and as the
//! events a server would send.
pub mod logic;
+2
View File
@@ -298,7 +298,9 @@ pub fn first_key(text: &str) -> Option<String> {
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
/// The text: the word with its space, or the emoji's own characters.
pub text: String,
/// The key of the Twemoji picture, none for plain text.
pub emoji: Option<String>,
}
+103
View File
@@ -0,0 +1,103 @@
//! What a server's gateway tells besides chat: its events (the events page,
//! RSVP, reminders), the stream directory and the activity feed (the home
//! page), our permissions there, its configuration (gateway administration).
//! The pins, reactions and topics are in `chat::logic`.
use voelin_core::{GatewayRequest, GatewayUpdate};
use voelin_gateway_proto::{EventQuery, feature};
use crate::host::Cx;
use crate::social::{NoticeKind, NoticeRequest, NoticeTarget, server_name};
use crate::state::{AppState, Lines};
/// Keep what a gateway update tells the home, events and administration
/// screens (before the chat handles its part), and ask for what a new
/// connection needs.
pub fn extra<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, update: &GatewayUpdate) {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
let has = |f: &str| capabilities.iter().any(|c| c == f);
ask.push(GatewayRequest::Permissions { channel: None });
if has(feature::EVENTS) {
ask.push(GatewayRequest::Events { query: EventQuery::default() });
}
if has(feature::STREAMS) {
ask.push(GatewayRequest::Streams);
}
if has(feature::ACTIVITY) {
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
}
}
U::Disconnected { .. } => {
extra.directory.clear();
extra.events.clear();
extra.events_loaded = false;
extra.activity.clear();
extra.actions.clear();
extra.config.clear();
extra.perms.clear();
}
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
U::Events { events } => {
extra.events = events.clone();
extra.events.sort_by_key(|e| e.spec.start_ms);
extra.events_loaded = true;
}
U::Event { event } => {
match extra.events.iter().position(|e| e.id == event.id) {
Some(i) => extra.events[i] = event.clone(),
None => extra.events.push(event.clone()),
}
extra.events.sort_by_key(|e| e.spec.start_ms);
}
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
U::EventReminder { event, starts_in_ms } => remind = Some((event.clone(), *starts_in_ms)),
U::Streams { streams } => extra.directory = streams.clone(),
U::StreamStarted { stream }
| U::StreamUpdated { stream }
| U::StreamRegistered { stream } => {
extra.directory.retain(|e| e.id != stream.id);
extra.directory.push(stream.clone());
}
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
U::Activity { entries, .. } => extra.activity = entries.clone(),
U::ActivityAdded { entry } => {
extra.activity.insert(0, entry.clone());
extra.activity.truncate(100);
}
U::Config { entries } => extra.config = entries.clone(),
U::ConfigValue { entry } => match extra.config.iter().position(|e| e.key == entry.key) {
Some(i) => extra.config[i] = entry.clone(),
None => extra.config.push(entry.clone()),
},
U::PermRules { rules } => extra.perms = rules.clone(),
_ => return,
}
for request in ask {
cx.gateway_to(id, request);
}
if let Some((event, starts_in_ms)) = remind {
let minutes = starts_in_ms / 60_000;
let title = if minutes <= 0 {
format!("{} starts now", event.spec.title)
} else {
format!("{} starts in {minutes} min", event.spec.title)
};
cx.update.notices.push(NoticeRequest {
kind: NoticeKind::Event,
title,
body: format!("on {}", server_name(state, id)),
target: NoticeTarget::Event(id, event.id),
name: event.creator.name.clone(),
uid: Some(event.creator.uid.clone()),
});
}
cx.update.refresh.home = true;
cx.update.refresh.events = true;
cx.update.refresh.gateways = true;
}
+531
View File
@@ -0,0 +1,531 @@
//! What the engine's events do to the client's state. [`handle`] takes an
//! [`Event`], changes the [`AppState`] and the [`Social`] state and returns
//! an [`Update`]: what to draw again, the status line, the commands for the
//! engine, what to keep. A front end calls it for every event and then does
//! what the update says; it has no dispatch of its own, so the Slint client
//! and a GPUI one change the state the same way. [`apply`] is the part that
//! changes the [`AppState`] alone; [`handle`] first lets
//! [`crate::social::logic::event`] look at the event (the friends, the
//! pokes, the notices and the offline messages), which has to see the state
//! as it was before the event.
//!
//! In [`Update::rest`] come back the events whose state is not in the
//! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a
//! setting that changed (the settings service), and the answers to the
//! offline message requests (the list that failed, a request that is done),
//! which the messages page keeps (docs/ui.md, "Controllers still to split").
//! A front end handles them before it draws what the update says is to be
//! drawn again. The text of an offline message is not among them: it is
//! state of the [`Social`], changed by [`handle`].
mod gateway;
use voelin_core::{BackendInfo, Command, Event, GatewayUpdate, JoinFailure, Source, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::Bookmark;
use crate::chat::logic::{
add_message, gateway_update, history_batch, load_reads, open_chat, save_reads, track_reading,
transfer_progress,
};
use crate::host::{Cx, Host, Persist, Update};
use crate::previews::fetch_previews;
use crate::servers::{AfterConnect, JoinStep, after_connect, join_password};
use crate::settings::LastVoice;
use crate::social::logic::Social;
use crate::state::{AppState, Lines, SessionView};
use crate::streams::logic as streams;
/// Apply an event to the [`AppState`]; see the [module](self).
pub fn apply<L: Lines>(state: &mut AppState<L>, host: &dyn Host, event: Event) -> Update {
let mut cx = Cx::new(host);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// Take an event in: what the social screens make of it first
/// ([`crate::social::logic::event`]), then [`apply`]. The one entry point
/// of a front end.
pub fn handle<L: Lines, D>(
state: &mut AppState<L>,
social: &mut Social<D>,
host: &dyn Host,
event: Event,
) -> Update {
let mut cx = Cx::new(host);
crate::social::logic::event(state, social, &mut cx, &event);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// The status line shows what the update says.
fn finish<L>(state: &mut AppState<L>, cx: Cx<'_>) -> Update {
if let Some(text) = &cx.update.status {
state.status.clone_from(text);
}
cx.update
}
fn dispatch<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, event: Event) {
// The Stream Studio's stream is the studio's.
if let Event::StreamState { session, .. } | Event::StreamViewers { session, .. } = &event
&& cx.host.studio_streams_to(*session as i64)
{
cx.update.rest = Some(event);
return;
}
match event {
Event::State { session, state: now } => session_state(state, cx, session as i64, now),
Event::ServerInfo { session, name, backend, capabilities } => {
let id = session as i64;
state.sessions.entry(id).or_default().capabilities = capabilities;
adopt_server_name(state, cx, id, &name);
if state.current == Some(id) {
cx.status(connected_status(&name, &backend));
}
cx.update.refresh.streams = true;
cx.update.autoshare = true;
}
Event::Presence { session, presence } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
// The server chat shows its welcome and host message, with their
// pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection), or
// renamed.
let path = |v: &SessionView<L>| {
v.state.own_channel.map(|c| crate::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
apply_client_playback(state, cx, id);
join_after_connect(state, cx, id);
if renamed && remember_voice(state, cx, id) {
cx.update.refresh.servers = true;
}
if state.current == Some(id) {
if said {
fetch_previews(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true);
cx.update.first_client = true;
}
}
Event::Talking { session, client, talking } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => state.current == Some(s as i64),
None => state.mic_test,
};
if shown {
cx.update.input_level = Some((level_db, sending));
}
}
Event::MicrophoneTestError { message } => {
cx.status(format!("Microphone test: {message}"));
}
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !state.sessions.entry(id).or_default().has_history() {
add_message(state, cx, id, message);
}
}
Event::ChatHistory { session, target, messages, source, complete } => {
history_batch(state, cx, session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
let id = session as i64;
if let GatewayUpdate::Connected { url, .. } = &update {
gateway_in_use(state, cx, id, url);
}
gateway::extra(state, cx, id, &update);
gateway_update(state, cx, id, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::ServerDetails { session, address, details } => {
remember_server_icon(state, cx, session as i64, &address, details.icon);
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let id = session as i64;
// A file that arrives again is decoded again if it changed.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().avatars.insert(client_uid, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.tree, r.chat, r.toolbar, r.member_card, r.streams) =
(true, true, true, true, true);
}
}
Event::IconReady { session, icon, path } => {
let id = session as i64;
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().icons.insert(icon, path);
cx.update.refresh.servers = true;
if state.current == Some(id) {
cx.update.refresh.tree = true;
cx.update.refresh.toolbar = true;
}
}
Event::PictureReady { session, url, path } => {
let id = session as i64;
// The host banner reloads into the same file.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().pictures.insert(url, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.member_card) = (true, true, true, true);
}
}
Event::Transfer { session, transfer, state: progress } => {
transfer_progress(state, cx, session as i64, transfer, progress);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if cx.host.demo_ui() && !state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
cx.update.refresh.member_card = true;
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if cx.host.demo_ui() => {}
Event::Error { message, .. } => cx.status(message),
Event::JoinFailed { session, channel, reason } => {
join_failed(state, cx, session as i64, channel, reason);
}
Event::SettingRejected { key, message } => {
cx.status(format!("Setting {key}: {message}"));
}
Event::StreamsChanged { session, streams } => {
let id = session as i64;
// Development switch: watch the first stream that shows up.
let autowatch = cx.host.autowatch() && !cx.host.watching() && state.current == Some(id);
// A client whose stream was asked for while it was looked up.
let pending = state
.pending_watch
.filter(|(s, _)| *s == id)
.and_then(|(_, client)| streams.iter().find(|s| s.streamer == client))
.map(|s| s.id.clone());
let view = state.sessions.entry(id).or_default();
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer))
.map(|s| s.id.clone());
view.streams = streams;
cx.update.refresh.streams = true;
cx.update.refresh.servers = true;
if let Some(stream) = pending {
state.pending_watch = None;
cx.update.watch = Some(stream);
} else if autowatch && let Some(stream) = first {
cx.update.watch = Some(stream);
}
}
// The streams we share and watch.
Event::StreamState { session, state: now } => {
streams::share_state(state, cx, session as i64, now);
}
Event::StreamViewerRequest { session, viewer, .. } => {
streams::viewer_request(state, cx, session as i64, viewer);
}
Event::StreamViewers { session, viewers } => {
streams::viewers(state, cx, session as i64, viewers);
}
Event::WatchState { session, stream_id, state: now } => {
streams::watch_state(state, cx, session as i64, &stream_id, now);
}
Event::WatchLayers { session, stream_id, layers, layer } => {
streams::watch_layers(state, cx, session as i64, &stream_id, layers, layer);
}
// Also flagged on the sink, which the encoder reads.
Event::StreamKeyframeRequest { .. } | Event::StreamLayerBitrate { .. } => {}
// The text of an offline message is in the `Social` state, which
// `handle` has changed before (`social::logic::event`).
Event::OfflineMessage { .. } => {}
// What the settings service and the offline messages' requests make
// of the rest, the front end keeps (see the module's note).
event => cx.update.rest = Some(event),
}
}
/// A session's connections changed.
fn session_state<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
now: voelin_core::SessionState,
) {
let view = state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = now.clone();
if now.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if now.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected {
view.channel_passwords.clear();
view.join_after_connect = None;
}
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept when the
// session ends.
load_reads(state, cx, id);
let off = |voice: VoiceState, observe: voelin_core::ObserveState| {
voice == VoiceState::Disconnected && observe == voelin_core::ObserveState::Off
};
if off(now.voice, now.observe) && !off(was_voice, was_observe) {
save_reads(state, cx, id);
}
let focus = !state.sessions.entry(id).or_default().focused_own_channel;
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
cx.status("Connected");
}
if state.current == Some(id) {
if track_reading(state, cx) {
cx.update.refresh.chat = true;
}
// The voice channel's chat is always at hand, and focused once per
// connection.
if let (Some(cid), VoiceState::Connected) = (now.own_channel, now.voice) {
open_chat(state, cx, ChatTarget::Channel(cid), focus);
state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last place,
// which the rail's refresh shows (voice on another server does not take
// it back at each of its events).
if (now.voice, now.own_channel) != (was_voice, was_channel) {
remember_voice(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.streams) = (true, true, true, true);
cx.update.autoshare = true;
if state.current == Some(id) {
cx.update.first_client = true;
}
join_after_connect(state, cx, id);
}
/// The status line once a server answered: "Connected to Nightfall Guild
/// (TeamSpeak 6 6.0.0-beta13.1)".
pub fn connected_status(name: &str, backend: &BackendInfo) -> String {
format!("Connected to {name} ({})", backend.label())
}
/// The gateway logged in at `url`: it is the one in use from now on.
fn gateway_in_use<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, url: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if b.gateway_in_use(url) {
cx.persist(Persist::Bookmark { id, what: "gateway in use" });
}
}
/// The server told its name: a server still named by its address takes it,
/// so the address is all a user has to type.
fn adopt_server_name<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, name: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
return;
};
if name.trim().is_empty() || cx.host.demo_ui() {
return;
}
b.name = name.trim().to_owned();
cx.persist(Persist::Bookmark { id, what: "server named" });
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
pub fn apply_server_icon<L>(
bookmark: &mut Bookmark,
view: &mut SessionView<L>,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
/// Keep only metadata supplied by the bookmark's current server.
fn remember_server_icon<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
address: &str,
icon: u32,
) {
let Some(bookmark) = state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed = apply_server_icon(bookmark, state.sessions.entry(id).or_default(), address, icon);
if changed && !cx.host.demo_ui() {
cx.persist(Persist::Bookmark { id, what: "server icon" });
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub fn remember_voice<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) -> bool {
if cx.host.demo_ui() {
return false;
}
let Some(view) = state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = crate::tree::channel_path(&view.presence, cid);
let Some(b) = state.bookmarks.iter().find(|b| b.id == session).filter(|_| !channel.is_empty())
else {
return false;
};
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
state.settings.last_voice = Some(last);
cx.persist(Persist::Settings);
true
}
/// Send the stored volumes of clients that appeared in a voice session.
pub fn apply_client_playback<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| state.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
cx.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume });
if playback.muted {
cx.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
/// Connected into another channel than the one asked for
/// (`SessionView::join_after_connect`): the server says nothing when, for
/// one, the password was wrong, so it is joined again, and that move says
/// why. Once the channel shows in the voice connection's presence, which
/// can come after the own channel.
pub fn join_after_connect<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect) else {
return;
};
let known = view.presence.channels.contains_key(&asked);
match after_connect(view.state.own_channel, asked, known) {
AfterConnect::Wait => {}
AfterConnect::Joined => view.join_after_connect = None,
AfterConnect::JoinAgain => {
view.join_after_connect = None;
move_into(state, cx, session, asked);
}
}
}
/// Move into a channel of a session connected with voice: with its
/// password, or asking for one when it is locked and none was given this
/// connection.
fn move_into<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64, channel: ChannelId) {
let Some(view) = state.sessions.get(&session) else { return };
let Some(info) = view.presence.channels.get(&channel) else { return };
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match join_password(info, remembered) {
JoinStep::Send(password) => {
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
}
JoinStep::Ask => ask_password(state, cx, session, channel, false),
}
}
/// Open the password dialog for a locked channel; `wrong`: the one given
/// was refused.
pub fn ask_password<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
wrong: bool,
) {
let Some(info) = state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
else {
return;
};
let name = crate::tree::channel_title(info).0.to_owned();
state.join_target = Some((session, channel));
cx.ask_password(name, wrong);
}
/// The server refused a move ([`Event::JoinFailed`]): a password asks again
/// (the one given is forgotten), the rest is a toast.
pub fn join_failed<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
reason: JoinFailure,
) {
match reason {
JoinFailure::Password => {
let given = state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
.is_some();
ask_password(state, cx, session, channel, given);
}
JoinFailure::Full => cx.status("The channel is full"),
JoinFailure::Other(text) => cx.status(text),
}
}
#[cfg(test)]
mod tests;
+725
View File
@@ -0,0 +1,725 @@
//! Tapes of engine events replayed through [`apply`] against a fake host:
//! the state they leave, and what each update asks of a front end.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use voelin_core::StreamState;
use voelin_core::gateway::Pin;
use voelin_core::stream::StreamInfo;
use voelin_core::{
BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
JoinFailure, TransferState, VoiceState,
};
use voelin_gateway_proto::{UserRef, feature};
use voelin_model::{Capabilities, ChatMessage, ChatTarget};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget};
use super::*;
use crate::host::Refresh;
use crate::host::testing::Fake;
use crate::settings::{ClientPlayback, LastVoice};
use crate::host::testing::{State, presence, said, session, state};
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
Event::ChatHistory {
session: 1,
target: ChatTarget::Channel(2),
messages,
source,
complete: true,
}
}
fn run(state: &mut State, host: &Fake, tape: Vec<Event>) -> Vec<Update> {
tape.into_iter().map(|event| apply(state, host, event)).collect()
}
fn gateway(update: GatewayUpdate) -> Event {
Event::Gateway { session: 1, update }
}
fn open_chats(update: &Update) -> Vec<ChatTarget> {
update
.commands
.iter()
.filter_map(|c| match c {
Command::OpenChat { target, .. } => Some(target.clone()),
_ => None,
})
.collect()
}
/// A first connection to a server, event by event: what the session knows
/// after each, and what the front end is told to do.
#[test]
fn a_first_connection() {
let mut st = state();
let host = Fake {
reads: HashMap::from([(
"srv=".to_owned(),
vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })],
)]),
..Default::default()
};
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() };
let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() };
// Connecting: the rail and the bar change, nothing is sent.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }],
);
assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting);
assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree);
assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare);
// The server answers: it gives its name to a bookmark that has only the
// address, and says what it runs.
let ups = run(
&mut st,
&host,
vec![Event::ServerInfo {
session: 1,
name: " Nightfall Guild ".into(),
backend,
capabilities: caps,
}],
);
assert_eq!(st.bookmarks[0].name, "Nightfall Guild");
assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]);
assert_eq!(
ups[0].status.as_deref(),
Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)")
);
assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)");
assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams);
// Its presence: the bar, the tree and the chat are drawn; the stored
// volume of Alice is sent once voice is connected, not before.
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
assert_eq!(st.sessions[&1].presence.clients.len(), 2);
assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client);
assert!(ups[0].commands.is_empty());
// Voice connected into Games: its chat opens and is shown, with the
// store's read marker; the place is remembered.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
let view = &st.sessions[&1];
assert_eq!(view.reads_of.as_deref(), Some("srv="));
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
assert_eq!(view.tabs[view.current_tab].read, Some((200, 7)));
assert_eq!(view.channel_tab, ChatTarget::Channel(2));
assert!(view.focused_own_channel);
assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]);
assert_eq!(ups[0].status.as_deref(), Some("Connected"));
assert_eq!(
st.settings.last_voice,
Some(LastVoice {
bookmark: 1,
address: "ts.example".into(),
channel: vec!["Games".into()]
})
);
assert!(ups[0].persist.contains(&Persist::Settings));
assert!(ups[0].refresh.chat && ups[0].refresh.servers);
// The presence again, now that voice is connected: Alice's volume goes
// to the engine, once.
let ups = run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::Presence { session: 1, presence: presence() },
],
);
assert!(matches!(
ups[0].commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume },
Command::SetClientMuted { session: 1, client: 11, muted: true },
] if *volume == 0.5
));
assert!(ups[1].commands.is_empty());
}
/// The messages of a chat: a stored page, then live ones, with the chat on
/// screen or not, and what is kept of how far it was read.
#[test]
fn messages_are_counted_read_and_kept() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
// The stored page: two read before, one new. (Its marker came from the
// store: nothing here, so what the tab held when the page came counts as
// read.)
let ups = run(
&mut st,
&host,
vec![games(
vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")],
HistorySource::Local,
)],
);
let tab = &st.sessions[&1].tabs[1];
assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::<Vec<_>>(), [6, 7, 8]);
assert!(tab.complete && !tab.loading);
assert_eq!(tab.unread, 0, "a first page is what was read");
assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]);
assert!(ups[0].refresh.chat);
// A live message while the chat is not on screen is new.
let ups =
run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
assert!(ups[0].refresh.servers, "the rail counts it");
// Our own is not.
st.own_uids.insert("me=".into());
run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
// The chat comes on screen: read up to its end, a divider over the new.
host.shown.set(true);
let mut cx = Cx::new(&host);
assert!(crate::chat::logic::track_reading(&mut st, &mut cx));
let tab = &st.sessions[&1].tabs[1];
assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10))));
assert_eq!(st.reading, Some((1, ChatTarget::Channel(2))));
// A live one now is read at once.
run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 0);
assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11)));
// The session ends: where the chats were read is stored, and what the
// store has is what the tab then says it has.
let mut ended = session(VoiceState::Disconnected, None);
ended.server_uid = Some("srv=".into());
let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]);
let written = host.written.borrow();
assert_eq!(written.len(), 1, "{written:?}");
assert_eq!(written[0].0, "srv=");
assert_eq!(written[0].1, StoredTarget::Channel(2));
assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11));
assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11)));
assert!(ups[0].refresh.servers);
}
/// Where the chat lines go when the engine keeps no history (it does not
/// know the server yet): one row appended per message.
#[test]
fn a_session_without_history_appends_lines() {
let mut st = state();
let host = Fake::default();
let message = |text: &str| ChatMessage {
target: ChatTarget::Server,
author_name: "Alice".into(),
author_uid: Some("alice=".into()),
author_id: Some(11),
text: text.into(),
ts_ms: 1000,
via_relay: false,
blocked: false,
};
let ups = run(
&mut st,
&host,
vec![
Event::Chat { session: 1, message: message("one") },
Event::Chat { session: 1, message: message("two") },
],
);
let tab = &st.sessions[&1].tabs[0];
assert_eq!(tab.lines.len(), 2);
assert_eq!(tab.unread, 2);
assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]);
assert!(ups[1].refresh.chat && ups[1].refresh.servers);
// With a server unique id the engine has the history, and the live
// message arrives as `ChatHistory`.
st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into());
run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]);
assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2);
}
/// What a gateway brings: capabilities, requests for what the screens
/// show, pins, the stream directory, reminders for the bell.
#[test]
fn a_gateway_connects_and_tells() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
let caps: Vec<String> = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS]
.map(String::from)
.into();
st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()];
let ups = run(
&mut st,
&host,
vec![gateway(GatewayUpdate::Connected {
url: "wss://gw.example/v1".into(),
gateway_id: "g".into(),
server_uid: "srv=".into(),
server_name: "Nightfall Guild".into(),
uid: "me=".into(),
capabilities: caps,
})],
);
let view = &st.sessions[&1];
assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS));
assert_eq!(view.extra.gateway_uid.as_deref(), Some("me="));
assert_eq!(
st.bookmarks[0].gateway_url.as_deref(),
Some("wss://gw.example/v1"),
"the gateway in use is kept"
);
assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" }));
// The permissions, the events and the directory, then the current
// chat's pins and topics.
let asked: Vec<&GatewayRequest> = ups[0]
.commands
.iter()
.filter_map(|c| match c {
Command::Gateway { session: 1, request } => Some(request),
_ => None,
})
.collect();
assert!(matches!(
asked.as_slice(),
[
GatewayRequest::Permissions { channel: None },
GatewayRequest::Events { .. },
GatewayRequest::Streams,
GatewayRequest::Pins { target: ChatTarget::Channel(2) },
GatewayRequest::Topics { target: ChatTarget::Channel(2), .. },
]
));
assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways);
// The answers: pins (newest first), the directory's viewer counts, a
// failed request of the user.
let pin = |id: i64, ts_ms: i64| Pin {
message: said(id, ts_ms, false, "pinned"),
by: UserRef { uid: "alice=".into(), name: "Alice".into() },
ts_ms,
};
let ups = run(
&mut st,
&host,
vec![
gateway(GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
pins: vec![pin(3, 10), pin(4, 20)],
}),
gateway(GatewayUpdate::Failed {
request: "pin".into(),
code: Some(voelin_gateway_proto::ErrorCode::Forbidden),
message: "no".into(),
}),
],
);
let tab = &st.sessions[&1].tabs[1];
assert!(tab.pins_loaded);
assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [4, 3]);
assert!(ups[0].refresh.chat);
assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server."));
// Gone: nothing of the gateway stays.
run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]);
let view = &st.sessions[&1];
assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded);
}
/// A password that was refused asks again, and says so the second time.
#[test]
fn a_locked_channel_asks_for_its_password() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password };
let ups = run(&mut st, &host, vec![failed()]);
let prompt = ups[0].password.clone().unwrap();
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(st.join_target, Some((1, 1)));
// A password was given and refused: it is forgotten, the prompt says so.
st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into());
let ups = run(&mut st, &host, vec![failed()]);
assert!(ups[0].password.as_ref().unwrap().wrong);
assert!(st.sessions[&1].channel_passwords.is_empty());
// The others are a toast.
let ups = run(
&mut st,
&host,
vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }],
);
assert_eq!(ups[0].status.as_deref(), Some("The channel is full"));
}
/// Connected into another channel than the one asked for: joined again,
/// with the password given this connection.
#[test]
fn a_channel_asked_for_and_not_entered_is_joined_again() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let view = st.sessions.get_mut(&1).unwrap();
view.join_after_connect = Some(1);
view.channel_passwords.insert(1, "pw".into());
// Connected into Games, not the Lobby that was asked for.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(ups[0].commands.iter().any(|c| matches!(
c,
Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw"
)));
assert_eq!(st.sessions[&1].join_after_connect, None);
// The sample sessions send nothing to the engine.
let mut demo = state();
let host = Fake { demo: true, ..Default::default() };
run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]);
demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1);
let ups = run(
&mut demo,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(open_chats(&ups[0]).is_empty());
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. })));
}
/// Pictures and files: the engine's cache, an upload from the composer, a
/// download that runs, the contacts, errors.
#[test]
fn pictures_files_contacts_and_errors() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let path = PathBuf::from("/cache/avatars/ab");
let ups = run(
&mut st,
&host,
vec![
Event::AvatarReady {
session: 1,
client_uid: "alice=".into(),
path: path.clone(),
hash: "ab".into(),
},
Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() },
Event::PictureReady {
session: 1,
url: "https://e.com/a.png".into(),
path: "/cache/pictures/a".into(),
},
],
);
let view = &st.sessions[&1];
assert_eq!(view.avatars.get("alice="), Some(&path));
assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png"));
assert_eq!(ups[0].reloaded, [path]);
assert_eq!(
ups[0].refresh,
Refresh {
tree: true,
chat: true,
toolbar: true,
member_card: true,
streams: true,
..Refresh::default()
}
);
assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat);
// An upload from the composer posts its link once it is up.
st.uploads.insert(7, (1, 2, "notes.txt".into()));
let done = TransferState::Done { size: 12, data: None, path: None };
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]);
assert!(st.uploads.is_empty());
assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared"));
assert!(matches!(
ups[0].commands.as_slice(),
[Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt")
));
st.uploads.insert(8, (1, 2, "big.iso".into()));
let failed = TransferState::Failed("full".into());
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]);
assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full"));
// Errors and rejected settings reach the status line, but not the sample
// sessions' (the engine does not know them).
let ups = run(
&mut st,
&host,
vec![
Event::Error { session: 1, message: "kicked".into() },
Event::SettingRejected { key: "audio".into(), message: "no".into() },
Event::MicrophoneTestError { message: "no device".into() },
],
);
assert_eq!(ups[0].status.as_deref(), Some("kicked"));
assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no"));
assert_eq!(st.status, "Microphone test: no device");
let demo = Fake { demo: true, ..Default::default() };
let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]);
assert!(ups[0].status.is_none());
}
/// A client that talks, the meter, the groups in the order TeamSpeak sorts
/// them.
#[test]
fn talking_the_meter_and_groups() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let ups = run(
&mut st,
&host,
vec![
Event::Talking { session: 1, client: 11, talking: true },
Event::Talking { session: 1, client: 11, talking: false },
Event::InputLevel { session: Some(1), level_db: -20.0, sending: true },
Event::InputLevel { session: None, level_db: -30.0, sending: false },
Event::InputLevel { session: Some(2), level_db: -10.0, sending: true },
],
);
assert!(st.sessions[&1].talking.is_empty());
assert!(ups[0].refresh.tree);
assert_eq!(ups[2].input_level, Some((-20.0, true)));
assert_eq!(ups[3].input_level, None, "no microphone test is running");
assert_eq!(ups[4].input_level, None, "another server's");
st.mic_test = true;
let ups = run(
&mut st,
&host,
vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }],
);
assert_eq!(ups[0].input_level, Some((-30.0, false)));
let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() };
run(
&mut st,
&host,
vec![Event::Groups {
session: 1,
server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]),
channel_groups: Arc::new(vec![group(5, 0)]),
}],
);
let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect();
assert_eq!(ids, [9, 6, 7]);
}
/// The streams the voice connection lists: the one a lookup waited for is
/// to be watched; the rest of the stream events are the front end's.
#[test]
fn streams_are_listed_and_a_lookup_is_watched() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let stream = |id: &str, streamer| StreamInfo {
id: id.into(),
streamer,
name: "screen".into(),
kind: voelin_core::stream::StreamKind::Screen,
bitrate: 0,
viewer_limit: 0,
audio: false,
viewers: Some(1),
};
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }],
);
assert_eq!(st.sessions[&1].streams.len(), 1);
assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none());
// A client's stream was asked for before the list knew it.
st.pending_watch = Some((1, 11));
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s2"));
assert_eq!(st.pending_watch, None);
// The development switch watches the first stream that is not ours.
let host = Fake { autowatch: true, ..Default::default() };
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s3"));
// Keyframe requests are the encoder's, read from the sink; a setting that
// changed is the settings service's: the front end keeps it.
let ups = run(
&mut st,
&host,
vec![
Event::StreamKeyframeRequest { session: 1, layer: 0 },
Event::SettingChanged { key: "audio".into() },
],
);
assert!(ups[0].rest.is_none() && ups[0].refresh.is_empty() && ups[0].commands.is_empty());
assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio"));
}
/// The streams of the events: the studio's stream is the studio's; ours and
/// the one we watch change the state and say what the capture and the
/// decoder are to do.
#[test]
fn the_streams_we_share_and_watch_follow_the_events() {
use crate::streams::logic::{Sharing, Watching, demo_viewers};
use voelin_core::WatchState;
use voelin_core::stream::EndReason;
let mut st = state();
run(&mut st, &Fake::default(), vec![Event::Presence { session: 1, presence: presence() }]);
st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false });
st.watch = Some(Watching {
session: Some(1),
stream_id: "s1".into(),
title: "Speedrun".into(),
streamer: "Alice".into(),
status: String::new(),
connected: true,
ended: false,
has_frame: true,
shown: true,
since: None,
layers: Vec::new(),
layer: None,
});
// The studio streams to the server: its events are handed back as they
// are, and our share is not touched.
let studio = Fake { studio: Some(1), ..Default::default() };
let ups = run(
&mut st,
&studio,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) },
],
);
assert!(matches!(ups[0].rest, Some(Event::StreamViewers { .. })));
assert!(matches!(ups[1].rest, Some(Event::StreamState { .. })));
assert!(st.share.as_ref().unwrap().viewers.is_empty() && st.share.as_ref().unwrap().live);
// Elsewhere they are ours.
let host = Fake::default();
let ups = run(
&mut st,
&host,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamViewerRequest { session: 1, viewer: 11, message: "hi".into() },
Event::WatchState {
session: 1,
stream_id: "s1".into(),
state: WatchState::Ended(EndReason::Stopped),
},
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) },
],
);
assert!(ups[0].refresh.streams && ups[0].rest.is_none());
assert_eq!(ups[1].status.as_deref(), Some("Alice wants to watch your stream"));
let watch = st.watch.as_ref().unwrap();
assert!(watch.ended && ups[2].stream.drop_decoder);
assert_eq!(watch.status, "The stream has ended.");
assert!(st.share.is_none() && ups[3].stream.drop_share && ups[3].stream.mixer);
assert_eq!(ups[3].status.as_deref(), Some("You stopped sharing"));
}
/// Pictures linked in a chat are downloaded once, up to the limit.
#[test]
fn linked_pictures_are_fetched_once() {
let mut st = state();
let host = Fake { limit: 100 * 1024, ..Default::default() };
let mut connected = session(VoiceState::Connected, Some(2));
connected.server_uid = Some("srv=".into());
run(
&mut st,
&host,
vec![
Event::ServerInfo {
session: 1,
name: "S".into(),
backend: BackendInfo::default(),
capabilities: Capabilities { file_transfer: true, ..Default::default() },
},
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: connected },
],
);
let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]";
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
let downloads: Vec<_> =
ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect();
assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands);
// Asked once: the same page again asks for nothing.
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. })));
}
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)");
}
#[test]
fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(
&path,
r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#,
)
.unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
// Details from another address, queued before an edit, change nothing.
assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77));
assert_eq!(view.server_icon, 1234);
std::fs::remove_file(path).unwrap();
}
+2
View File
@@ -18,9 +18,11 @@ pub enum ResumeAction {
/// The card: the server, the channel and the button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resume {
/// The id of the server's bookmark.
pub bookmark: i64,
/// The channel's path, its names from the top as the server has them.
pub path: Vec<String>,
/// What the button does.
pub action: ResumeAction,
}
+444
View File
@@ -0,0 +1,444 @@
//! What the transitions of the client's state need from the front end and
//! tell it. A transition (`events::apply`, the functions of `chat::logic`)
//! changes the [`AppState`](crate::state::AppState) it is given and puts
//! everything else into an [`Update`]: what to redraw, the status line, the
//! engine commands to send, what to keep; the little it must ask a front end
//! for while it runs (is the chat on screen, what the store knows) goes
//! through [`Host`]. Neither the engine nor the store nor a toolkit is
//! touched here, so the transitions are tested with a fake host
//! (`events::tests`).
use std::path::PathBuf;
use voelin_core::{Command, Event, GatewayRequest, StreamSink};
use voelin_model::ChatTarget;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use crate::social::NoticeRequest;
/// What a transition asks of its front end while it runs.
pub trait Host {
/// The sample data of `VOELIN_DEMO_UI` is shown: nothing is sent to the
/// engine or kept in the store.
fn demo_ui(&self) -> bool;
/// The current chat's messages are on screen (a page shows the chat).
fn chat_shown(&self) -> bool;
/// A stream is in the viewer.
fn watching(&self) -> bool;
/// The development switch `VOELIN_AUTOWATCH=1`: watch the first stream
/// that shows up.
fn autowatch(&self) -> bool;
/// The Stream Studio streams to this session: the events of that stream
/// are its own.
fn studio_streams_to(&self, session: i64) -> bool;
/// The largest picture previewed in chats, in bytes (0: none), from
/// `ui.image_preview_kb`.
fn preview_limit(&self) -> u64;
/// Pictures on the web are fetched and shown (`cache.fetch_images`).
fn fetch_images(&self) -> bool;
/// The private chat with this peer (unique id) of this session is on
/// screen, in the messages page.
fn dm_shown(&self, session: i64, uid: &str) -> bool;
/// Now, in milliseconds since the epoch.
fn now_ms(&self) -> i64 {
crate::social::now_ms()
}
/// How far the chats of a server were read, from the store.
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String>;
/// Keep how far a chat of a server was read.
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String>;
}
/// The parts of the screen to draw again. Each is a function of the state,
/// so a front end draws each flagged part once, however many events set it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Refresh {
/// The server rail.
pub servers: bool,
/// The top bar of the server page.
pub toolbar: bool,
/// The channel tree and the members.
pub tree: bool,
/// The chat tabs, the lines and what belongs to them (pins, topics).
pub chat: bool,
/// The streams panel and the voice card's streams.
pub streams: bool,
/// The stream viewer's header.
pub viewer: bool,
/// The open member card.
pub member_card: bool,
/// The home page.
pub home: bool,
/// The events page.
pub events: bool,
/// The gateway pages of the settings.
pub gateways: bool,
/// The friends page, home's friends and activity, the block list.
pub people: bool,
/// The lists of direct messages and the offline messages (asked for
/// again when a voice connection came up).
pub conversations: bool,
/// The peer card of the open direct message.
pub dm: bool,
}
impl Refresh {
/// Every part.
pub const ALL: Self = Self {
servers: true,
toolbar: true,
tree: true,
chat: true,
streams: true,
viewer: true,
member_card: true,
home: true,
events: true,
gateways: true,
people: true,
conversations: true,
dm: true,
};
/// Whether nothing is to be drawn.
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
}
/// What a transition wants kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Persist {
/// The bookmark with this id changed (the store has the old one).
Bookmark {
/// The bookmark.
id: i64,
/// What it was changed for, for the log.
what: &'static str,
},
/// The UI's own settings changed (`AppState::settings`).
Settings,
/// The audio settings changed (`AppState::audio`).
Audio,
/// The clients' local volumes changed (`AppState::playback`).
Playback,
}
/// The password dialog of a locked channel is to open
/// (`AppState::join_target` names the channel).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordPrompt {
/// The channel's name as the tree shows it.
pub name: String,
/// The password given before was refused.
pub wrong: bool,
}
/// What the streams we share and watch need of the front end, which owns the
/// capture and the decoder.
#[derive(Debug, Default)]
pub struct StreamEffects {
/// Encode into the live stream: the sink of our stream.
pub attach: Option<StreamSink>,
/// Our stream is over: the capture stops.
pub drop_share: bool,
/// The watched stream is over, or left: its decoder stops.
pub drop_decoder: bool,
/// The audio mixer's rows follow the capture again.
pub mixer: bool,
/// The player leaves full screen.
pub leave_fullscreen: bool,
}
/// What a transition tells its front end, besides the changed state.
#[derive(Debug, Default)]
pub struct Update {
/// What to draw again.
pub refresh: Refresh,
/// The status line's new text.
pub status: Option<String>,
/// Commands for the engine, in order.
pub commands: Vec<Command>,
/// What to keep, in order.
pub persist: Vec<Persist>,
/// Pictures the engine wrote again: a front end drops what it decoded
/// of them.
pub reloaded: Vec<PathBuf>,
/// The microphone meter: level in dBFS, and whether voice is sent.
pub input_level: Option<(f32, bool)>,
/// Open the password dialog.
pub password: Option<PasswordPrompt>,
/// Notices for the bell, in order.
pub notices: Vec<NoticeRequest>,
/// What went wrong that nothing else shows, for the log.
pub warnings: Vec<String>,
/// Chats whose messages changed (session, chat): the Stream Studio
/// follows the chat of its channel.
pub chats: Vec<(i64, ChatTarget)>,
/// A stream to watch (its id): the one a lookup was waiting for, or the
/// development switch's.
pub watch: Option<String>,
/// The capture and the decoder.
pub stream: StreamEffects,
/// A server connected or answered: the development switch that shares
/// the test pattern may start now.
pub autoshare: bool,
/// The session on screen got its state or its presence: the development
/// switch that opens the volume dialog of the first client may act.
pub first_client: bool,
/// The event, when its state is not in the [`AppState`]: the Stream
/// Studio's stream (`Host::studio_streams_to`), a setting that changed (the
/// settings service) and the answers to the offline message requests, which
/// the messages page keeps. The watched and shared streams are not among
/// them: they are state here and go through the stream effects. The front
/// end handles these itself ([`crate::events`] lists them), before it draws
/// what `refresh` names, as what it keeps may be on screen.
pub rest: Option<Event>,
}
/// The host and the update of a transition in progress.
pub struct Cx<'a> {
/// What the front end answers.
pub host: &'a dyn Host,
/// What is collected.
pub update: Update,
}
impl<'a> Cx<'a> {
/// A transition that starts with nothing to tell.
pub fn new(host: &'a dyn Host) -> Self {
Self { host, update: Update::default() }
}
/// The status line says this from now on.
pub fn status(&mut self, text: impl Into<String>) {
self.update.status = Some(text.into());
}
/// A command for the engine.
pub fn send(&mut self, command: Command) {
self.update.commands.push(command);
}
/// A command for the engine, but not for the sample sessions of
/// `VOELIN_DEMO_UI`: the engine would open them for real.
pub fn send_real(&mut self, command: Command) {
if !self.host.demo_ui() {
self.send(command);
}
}
/// A request to a session's gateway (not for the sample sessions).
pub fn gateway_to(&mut self, session: i64, request: GatewayRequest) {
self.send_real(Command::Gateway { session: session as u64, request });
}
/// Something went wrong that nothing else shows: it is logged.
pub fn warn(&mut self, text: impl Into<String>) {
self.update.warnings.push(text.into());
}
/// Keep this.
pub fn persist(&mut self, what: Persist) {
self.update.persist.push(what);
}
/// The password dialog of a locked channel opens.
pub fn ask_password(&mut self, channel_name: String, wrong: bool) {
self.update.password = Some(PasswordPrompt { name: channel_name, wrong });
}
/// The chat `target` of session `id` changed.
pub fn chat_changed(&mut self, id: i64, target: &ChatTarget) {
self.update.chats.push((id, target.clone()));
}
}
/// A front end for the tests of the transitions.
#[cfg(test)]
pub(crate) mod testing {
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use super::Host;
use std::sync::Arc;
use voelin_core::{
AudioSettings, HistoryMessage, ObserveState, SessionState, Source, VoiceState,
};
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails};
use voelin_store::{Bookmark, MessageSource};
use crate::bridge::ChatLine;
use crate::settings::{ClientPlaybackMap, UiSettings};
use crate::state::AppState;
/// The front end of the tests: answers what the transitions ask and keeps
/// what they store.
#[derive(Default)]
pub(crate) struct Fake {
pub(crate) demo: bool,
pub(crate) shown: Cell<bool>,
pub(crate) watching: bool,
pub(crate) autowatch: bool,
/// The session the Stream Studio streams to.
pub(crate) studio: Option<i64>,
pub(crate) limit: u64,
/// The private chat on screen: session and peer.
pub(crate) dm: Option<(i64, String)>,
/// What time it is.
pub(crate) now: Cell<i64>,
/// What the store has: server unique id, its chats' reads.
pub(crate) reads: HashMap<String, Vec<(StoredTarget, ChatRead)>>,
/// What was stored.
pub(crate) written: RefCell<Vec<(String, StoredTarget, ChatRead)>>,
}
impl Host for Fake {
fn demo_ui(&self) -> bool {
self.demo
}
fn chat_shown(&self) -> bool {
self.shown.get()
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
self.autowatch
}
fn studio_streams_to(&self, session: i64) -> bool {
self.studio == Some(session)
}
fn preview_limit(&self) -> u64 {
self.limit
}
fn fetch_images(&self) -> bool {
false
}
fn dm_shown(&self, session: i64, uid: &str) -> bool {
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
}
fn now_ms(&self) -> i64 {
self.now.get()
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
Ok(self.reads.get(server_uid).cloned().unwrap_or_default())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read));
Ok(())
}
}
pub(crate) type State = AppState<Vec<ChatLine>>;
pub(crate) fn state() -> State {
let bookmark = Bookmark {
id: 1,
name: "ts.example".into(),
address: "ts.example".into(),
nickname: "Me".into(),
..Default::default()
};
AppState::new(
vec![bookmark],
UiSettings::default(),
AudioSettings::default(),
ClientPlaybackMap::new(),
)
}
pub(crate) fn session(voice: VoiceState, own_channel: Option<u64>) -> SessionState {
let connected = voice == VoiceState::Connected;
SessionState {
voice,
observe: ObserveState::Off,
presence_source: connected.then_some(Source::Voice),
own_channel,
own_client: connected.then_some(10),
server_uid: connected.then(|| "srv=".to_owned()),
..Default::default()
}
}
/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in
/// Games).
pub(crate) fn presence() -> Arc<Presence> {
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] {
p.channels
.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() });
}
for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] {
p.clients.insert(
id,
ClientInfo {
id,
channel: 2,
nickname: name.into(),
uid: Some(uid.into()),
..Default::default()
},
);
}
p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() };
Arc::new(p)
}
/// A message of Games, by Alice unless `mine`.
pub(crate) fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage {
HistoryMessage {
id,
message: ChatMessage {
target: ChatTarget::Channel(2),
author_name: if mine { "Me" } else { "Alice" }.into(),
author_uid: Some(if mine { "me=" } else { "alice=" }.into()),
author_id: Some(if mine { 10 } else { 11 }),
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(id + 1000),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 0,
}
}
}
+209 -74
View File
@@ -4,6 +4,8 @@
use std::collections::HashMap;
use std::fmt;
use std::hash::{DefaultHasher, Hasher};
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
@@ -28,15 +30,8 @@ pub enum ImageSource {
/// What the file was when the reference was made.
stamp: Stamp,
},
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
Rgba {
/// Width in pixels.
w: u32,
/// Height in pixels.
h: u32,
/// `w * h * 4` bytes.
bytes: Arc<[u8]>,
},
/// Decoded pixels; [`ImageSource::rgba`] makes them.
Rgba(Pixels),
/// An SVG document.
Svg(Arc<[u8]>),
/// A picture file held in memory (a chat picture downloaded for its
@@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource {
match self {
Self::None => f.write_str("None"),
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()),
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
}
@@ -88,6 +83,39 @@ pub struct Size {
pub height: u32,
}
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
/// The length always fits the size (`width * height * 4`), so a front end
/// can hand the bytes to its toolkit without checking them.
#[derive(Clone, PartialEq, Eq)]
pub struct Pixels {
w: u32,
h: u32,
bytes: Arc<[u8]>,
}
impl Pixels {
/// The pixels `bytes` hold, if there are `w * h * 4` of them.
pub fn new(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> Option<Self> {
let bytes = bytes.into();
(bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes })
}
/// Width in pixels.
pub fn width(&self) -> u32 {
self.w
}
/// Height in pixels.
pub fn height(&self) -> u32 {
self.h
}
/// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row.
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
impl ImageSource {
/// A reference to no picture.
pub fn none() -> ImageRef {
@@ -104,27 +132,24 @@ impl ImageSource {
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
/// alpha); no picture if the length does not fit.
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
let bytes = bytes.into();
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
Arc::new(Self::Rgba { w, h, bytes })
} else {
Self::none()
}
Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels)))
}
/// The size the picture shows with; 0 by 0 when there is none or it can
/// not be shown: a file that is missing, is not a picture, or is too
/// large to decode (a front end drops those, as it would show nothing).
/// A file's size is read from its header, once while it stays as it is;
/// a vector picture has none of its own: its stated width and height,
/// else 1 by 1.
/// not be shown: a file that is missing, does not decode, or is too large
/// to decode (a front end drops those, as it would show nothing). So a
/// picture that has a size shows: a raster picture is decoded to tell
/// (its first frame, as a front end would show it), an SVG document must
/// parse. A file or a downloaded picture is checked once while it stays
/// as it is; a vector picture has no size of its own: its stated width
/// and height, else 1 by 1.
pub fn size(&self) -> Size {
match self {
Self::None => Size::default(),
Self::File { path, stamp } => file_size(path, *stamp),
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() },
Self::Svg(bytes) => svg_size(bytes),
Self::Memory { bytes, .. } => bytes_size(bytes),
Self::Memory { key, bytes } => memory_size(key, bytes),
}
}
@@ -138,24 +163,38 @@ impl ImageSource {
const MAX_DECODED_BYTES: u64 = 128 << 20;
fn checked(width: u32, height: u32) -> Size {
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
let bytes = u128::from(width) * u128::from(height) * 4;
if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) {
Size::default()
} else {
Size { width, height }
}
}
/// The size of a picture file's bytes, told by content.
/// What a picture file's bytes show as, told by content: a raster picture is
/// decoded (its first frame; the size comes from the header, the decoding
/// tells whether the rest of the file is a picture too), an SVG document
/// must parse. Anything else, or anything that does not decode, shows
/// nothing.
fn bytes_size(bytes: &[u8]) -> Size {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
else {
let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else {
return Size::default();
};
if reader.format().is_none() {
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
}
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
// What a front end allows itself: 16 bits a channel take twice the bytes.
let mut limits = image::Limits::default();
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
reader.limits(limits);
let Ok(decoder) = reader.into_decoder() else { return Size::default() };
let (width, height) = image::ImageDecoder::dimensions(&decoder);
let size = checked(width, height);
if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() {
return Size::default();
}
size
}
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
@@ -164,34 +203,25 @@ fn number(value: &str) -> Option<u32> {
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
}
/// The value of `name="…"` in the root tag of an SVG.
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let mut rest = tag;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = &rest[at + name.len()..];
let after = after.trim_start();
if before.is_none_or(char::is_whitespace)
&& let Some(value) = after.strip_prefix('=')
{
let value = value.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
return value[1..].split(quote).next();
}
rest = &rest[at + name.len()..];
}
None
}
/// The size of an SVG document: none unless it is XML (as the vector
/// renderers read it, a doctype allowed) whose root is an `svg` element.
fn svg_size(bytes: &[u8]) -> Size {
let text = String::from_utf8_lossy(bytes);
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
let tag = &text[start..];
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
const NAMESPACE: &str = "http://www.w3.org/2000/svg";
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() };
let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
let Ok(document) = roxmltree::Document::parse_with_options(text, options) else {
return Size::default();
};
let root = document.root_element();
let name = root.tag_name();
if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) {
return Size::default();
}
let stated =
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number));
let boxed = || {
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
number(w).zip(number(h))
};
@@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size {
checked(width, height)
}
/// What a probe of a file found, and what the file was then.
type Probe = (Stamp, Size);
/// What identifies the bytes a probe looked at.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Seen {
/// A file as it was (length and time).
File(Stamp),
/// A picture in memory: its length and a hash of its bytes.
Bytes(usize, u64),
}
/// Probed files, so a picture shown in many rows is read once; entries are
/// checked against the file's length and time before use.
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
/// Where a probed picture is.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Probed {
File(PathBuf),
Memory(Arc<str>),
}
/// Probed pictures with what they were then, so a picture shown in many
/// rows is decoded once; an entry is checked against the picture's length
/// and time (or bytes) before use.
static PROBES: Mutex<Option<HashMap<Probed, (Seen, Size)>>> = Mutex::new(None);
/// Probes kept at most; the picture cache is far smaller than this.
const MAX_PROBES: usize = 4096;
/// The size of the picture at `at`, from the cache when it is still the
/// same, else from `probe` (run without the lock: it decodes).
fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size {
{
let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at))
&& *was == seen
{
return *size;
}
}
let size = probe();
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(at, (seen, size));
size
}
fn file_size(path: &Path, stamp: Stamp) -> Size {
if stamp == Stamp::default() {
return Size::default();
}
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if let Some((was, size)) = probes.get(path)
&& *was == stamp
{
return *size;
}
// The file is read with the lock held; probes are short and rare.
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(path.to_owned(), (stamp, size));
size
probed(Probed::File(path.to_owned()), Seen::File(stamp), || {
std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes))
})
}
fn memory_size(key: &Arc<str>, bytes: &[u8]) -> Size {
let mut hasher = DefaultHasher::new();
hasher.write(bytes);
probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || {
bytes_size(bytes)
})
}
#[cfg(test)]
@@ -239,7 +301,15 @@ mod tests {
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
encoder.set_color(::png::ColorType::Rgba);
encoder.set_depth(::png::BitDepth::Eight);
let pixels = vec![200; width as usize * height as usize * 4];
// Pixels that do not compress to nothing, so cutting the file short
// cuts into the picture.
let mut seed = 0x2545_f491_u32;
let pixels: Vec<u8> = (0..width as usize * height as usize * 4)
.map(|_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
})
.collect();
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
bytes
}
@@ -257,8 +327,13 @@ mod tests {
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
assert!(!pixels.is_empty());
// The wrong length is no picture.
// The wrong length is no picture, and no pixels either.
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty());
assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none());
assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none());
let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") };
assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24));
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
}
@@ -284,6 +359,48 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_file_that_does_not_decode_shows_nothing() {
let dir = temp("corrupt");
let whole = png(32, 32);
// The header is fine, the picture is cut short (a download that
// stopped, a cache file written halfway).
let cut = dir.join("cut");
std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap();
assert!(ImageSource::file(&cut).is_empty());
// The header is fine, the data is not: flipped bytes in the image
// data, from the middle of the file to its end.
let mut flipped = whole.clone();
let from = flipped.len() / 2;
for byte in &mut flipped[from..] {
*byte = !*byte;
}
let garbled = dir.join("garbled");
std::fs::write(&garbled, &flipped).unwrap();
assert!(ImageSource::file(&garbled).is_empty());
// The whole file shows, and the answer is kept while it stays so.
let good = dir.join("good");
std::fs::write(&good, &whole).unwrap();
assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 });
// A file that is made whole shows (another stamp: another answer).
std::fs::write(&cut, &whole).unwrap();
assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 });
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_downloaded_picture_is_checked_too() {
let whole = png(16, 16);
let memory =
|key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() };
assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 });
assert!(memory("cut", &whole[..whole.len() / 2]).is_empty());
// The same key with other bytes is another picture.
assert!(memory("same", &whole[..whole.len() / 2]).is_empty());
assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 });
assert!(memory("none", b"").is_empty());
}
#[test]
fn vector_pictures() {
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
@@ -296,6 +413,24 @@ mod tests {
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
.is_empty()
);
// Not an SVG document: cut off, a sibling of the root, other roots,
// not text.
assert!(size("<svg width=\"8\" height=\"8\"").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"><g>").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"/><svg/>").width == 0);
assert!(size("<html width=\"8\" height=\"8\"/>").width == 0);
assert!(size("<svg xmlns='urn:other' width='8' height='8'/>").width == 0);
assert_eq!(
size("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='9'/>").height,
9
);
assert!(
ImageSource::Svg(b"<svg width='8' height='8'>\xff</svg>".as_slice().into()).is_empty()
);
// A doctype, as editors write it.
let doctype = "<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"5\" height=\"6\"/>";
assert_eq!(size(doctype), Size { width: 5, height: 6 });
// An SVG file with a byte order mark and a prolog, and in memory.
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
let dir = temp("svg");
+10 -1
View File
@@ -3,17 +3,26 @@
//! Neither Slint nor GPUI is a dependency; each front end converts these
//! types (docs/ui.md, "Two crates").
// Every public item is documented, the 559 fields of the two mirror modules
// (`bridge`, `studio_bridge`) included.
#![warn(missing_docs)]
pub mod avatar;
pub mod bbcode;
pub mod bridge;
pub mod chat;
pub mod color;
pub mod dev;
pub mod emoji;
pub mod events;
pub mod home;
pub mod host;
pub mod image;
pub mod list;
pub mod previews;
pub mod servers;
pub mod settings;
pub mod settings_page;
pub mod settings_pages;
pub mod social;
pub mod state;
@@ -23,4 +32,4 @@ pub mod studio_bridge;
pub mod tree;
pub use color::Rgb;
pub use image::{ImageRef, ImageSource, Size};
pub use image::{ImageRef, ImageSource, Pixels, Size};
+172
View File
@@ -0,0 +1,172 @@
//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or
//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into
//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`,
//! voice connections only) and the chat shows it as a picture card, and a
//! click opens it larger. A picture on the web a message shows (`[img]`)
//! comes the way banners do, into the engine's cache (`Command::FetchPicture`,
//! up to the same size, only with `cache.fetch_images`), and until it is
//! there the message shows its address.
use std::sync::Arc;
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::host::Cx;
use crate::image::{ImageRef, ImageSource};
use crate::state::{AppState, Preview, SessionView};
/// Whether a file name is a picture the chat shows inline.
pub fn is_previewable(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
}
/// The key of a link: where the file is.
pub fn link_key(file: &FileRef) -> String {
format!(
"{}/{}{}{}",
file.server_uid.as_deref().unwrap_or(""),
file.channel,
file.path,
file.name
)
}
/// The picture of a link, if it is there and shows.
pub fn image_of<L>(view: &SessionView<L>, file: &FileRef) -> Option<ImageRef> {
let key = link_key(file);
match view.extra.previews.get(&key)? {
Preview::Ready(bytes) => {
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
}
/// Download the pictures linked in the current chat of `session` that are
/// not there yet.
pub fn fetch_previews<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
if cx.host.demo_ui() {
return;
}
let limit = cx.host.preview_limit();
if limit == 0 {
return;
}
fetch_web_pictures(state, cx, session, limit);
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// Channel chats only: a link names its channel's file browser.
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
return;
}
let wanted: Vec<FileRef> = tab
.messages
.iter()
.rev()
.take(200)
.flat_map(|m| m.message.message.file_refs())
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
.collect();
for file in wanted {
let transfer = view.next_transfer;
view.next_transfer += 1;
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
cx.send(Command::DownloadChatFile {
session: session as u64,
transfer,
file,
password: None,
to: DownloadTo::Memory,
});
}
}
/// Ask the engine for the pictures on the web (`[img]`) of the current chat
/// of `session` that it has not reported; it fetches each once.
fn fetch_web_pictures<L>(state: &AppState<L>, cx: &mut Cx<'_>, session: i64, limit: u64) {
if !cx.host.fetch_images() {
return;
}
let Some(view) = state.sessions.get(&session) else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// The server chat starts with the server's messages.
let server = match tab.target {
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
_ => Vec::new(),
};
let wanted: Vec<String> = tab
.messages
.iter()
.rev()
.take(200)
.map(|m| m.message.message.text.as_str())
.chain(server.into_iter().map(|(text, _)| text))
.flat_map(crate::chat::web_pictures)
.filter(|url| !view.pictures.contains_key(url))
.collect();
for url in wanted {
cx.send(Command::FetchPicture { session: session as u64, url, max_bytes: limit });
}
}
/// A transfer of a picture: `true` if it was one.
pub fn preview_progress<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
transfer: u64,
progress: &TransferState,
) -> bool {
let limit = cx.host.preview_limit();
let current = state.current == Some(session);
let Some(view) = state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
.iter()
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
.map(|(k, _)| k.clone())
else {
return false;
};
match progress {
TransferState::Started { size, .. } if *size > limit => {
view.extra.previews.insert(key, Preview::Failed);
cx.send_real(Command::CancelTransfer { session: session as u64, transfer });
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if current {
cx.update.refresh.chat = true;
}
}
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
view.extra.previews.insert(key, Preview::Failed);
}
_ => {}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previewable_names() {
assert!(is_previewable("Banner.PNG"));
assert!(is_previewable("a.webp"));
assert!(!is_previewable("notes.svg"));
assert!(!is_previewable("route.pdf"));
let file =
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
assert_eq!(link_key(&file), "/2/a.png");
}
}
+956
View File
@@ -0,0 +1,956 @@
//! Servers: what the rail, the server card and the channel tree show, which
//! server is shown and how it is observed, the gateway found for it, and
//! joining a channel. The functions change the [`AppState`] and say in the
//! [`Cx`]'s update what to draw and send; the store, the secrets, the identity
//! and the sockets are the front end's.
use voelin_core::ts::identity::LaunchImport;
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::{Bookmark, QueryConfig};
use super::{JoinStep, item, join_password, tints};
use crate::bridge::{BookmarkForm, MemberItem, ServerItem, TreeItem};
use crate::chat::logic::{open_chat, prefetch_counts, save_reads, track_reading};
use crate::host::{Cx, Persist};
use crate::image::ImageRef;
use crate::state::{AppState, Lines, SessionView};
/// The name of the identity the app creates when it has none.
pub const CREATED_IDENTITY: &str = "Default";
/// What to tell the user about the identities imported from the official
/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything.
pub fn imported_status(report: &LaunchImport) -> Option<String> {
let n = report.added.len();
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() };
Some(match &report.default {
Some(f) if report.replaced => format!(
"You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}",
f.nickname
),
Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname),
None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"),
None => return None,
})
}
/// The bookmark the form describes, over `old` (what the form does not show,
/// like the identity, the default channel or the client version, stays; a
/// new server has none of it). Only the address is needed: the name is the
/// address until the server tells its own, the nickname `default_nickname`,
/// the gateway is looked up in DNS. A new address drops the gateway and the
/// query login found or set for the old one.
pub fn bookmark_from_form(
old: Option<&Bookmark>,
form: &BookmarkForm,
default_nickname: impl FnOnce() -> String,
) -> Bookmark {
let mut bookmark = old.cloned().unwrap_or_default();
bookmark.id = form.id as i64;
bookmark.address = form.address.trim().to_string();
if old.is_some_and(|old| old.address != bookmark.address) {
bookmark.cached_server_icon = None;
bookmark.gateway_url = None;
bookmark.gateway_urls.clear();
bookmark.query = None;
}
bookmark.name = match form.name.trim() {
"" => bookmark.address.clone(),
name => name.to_string(),
};
bookmark.nickname = match form.nickname.trim() {
"" => default_nickname(),
nickname => nickname.to_string(),
};
bookmark
}
/// Whether observing goes on as it is when discovery changed the gateways
/// kept from `previous` to `found`: the same ones (an older version kept
/// only the one in use), or logged in through `in_use`, still published.
/// What was found is kept for the next start, without a new login now.
pub fn observing_stays(
previous: &[String],
found: &[String],
in_use: Option<&str>,
observe: ObserveState,
) -> bool {
found == previous
|| (observe == ObserveState::Observing
&& in_use.is_some_and(|url| found.iter().any(|u| u == url)))
}
/// The options of a voice connection to `bookmark`, into `channel` (a path,
/// or `/<id>`, with its password) if given, with a privilege key if given;
/// the reason when the bookmark's client version is not one. The identity,
/// the server's password and the stream peer are the front end's to add.
pub fn voice_options(
bookmark: &Bookmark,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> Result<VoiceOptions, String> {
let mut options = VoiceOptions::new(&bookmark.address, &bookmark.nickname);
if let Some(spec) = &bookmark.client_version {
// The engine resolves the spec when it connects; asking now tells the
// user at once.
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
return Err(format!("Invalid client compatibility version: {error}"));
}
options.client_version = Some(spec.clone());
}
options.channel = channel;
options.channel_password = channel_password;
options.token = token;
options.audio = true;
Ok(options)
}
// Which server is shown, and how it is observed.
/// Show a server (the front end then observes it).
pub fn select_server<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
state.current = Some(id);
prefetch_counts(state, cx);
track_reading(state, cx);
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
}
/// A server was removed from the list (the store has the rest now): its
/// session goes, and the first server is shown.
pub fn forget_server<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
bookmarks: Vec<Bookmark>,
) {
save_reads(state, cx, id);
state.sessions.remove(&id);
state.gateways_looked_up.remove(&id);
state.bookmarks = bookmarks;
state.current = state.bookmarks.first().map(|b| b.id);
prefetch_counts(state, cx);
track_reading(state, cx);
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
}
/// What observing a server invisibly comes to ([`observe_plan`]).
#[derive(Clone, Debug, PartialEq)]
pub enum ObservePlan {
/// Nothing to do: it is observed already, or there is no server.
Nothing,
/// The gateway is still being connected to: the engine tries it again
/// now.
Retry(Vec<String>),
/// Observe through these gateways (best first), and look the gateway up
/// again; the status line says so.
Gateway(Vec<String>),
/// Observe through the server's own query login; the status line says so.
Query(QueryConfig),
/// There is neither: the gateway is looked up, and observing starts
/// when it is found.
Discover,
}
/// How to observe server `id` invisibly, unless it is already: through its
/// gateway, else its own query login. Without either the gateway is looked
/// up first, and observing starts when it is found. Asked while still
/// connecting, the engine tries the gateway again sooner.
pub fn observe_plan<L>(state: &AppState<L>, cx: &Cx<'_>, id: i64) -> ObservePlan {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else { return ObservePlan::Nothing };
if cx.host.demo_ui() {
return ObservePlan::Nothing;
}
let observing = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let urls = b.gateways();
match observing {
ObserveState::Observing => return ObservePlan::Nothing,
// The engine decides: the same gateways are not started over, at most
// tried again now.
ObserveState::Connecting => {
return if urls.is_empty() { ObservePlan::Nothing } else { ObservePlan::Retry(urls) };
}
ObserveState::Off => {}
}
if !urls.is_empty() {
ObservePlan::Gateway(urls)
} else if let Some(q) = &b.query {
ObservePlan::Query(q.clone())
} else {
ObservePlan::Discover
}
}
/// The address of server `id` to look the gateway up for, once a run (not
/// for the sample sessions).
pub fn discover_wanted<L>(state: &mut AppState<L>, cx: &Cx<'_>, id: i64) -> Option<String> {
if cx.host.demo_ui() || !state.gateways_looked_up.insert(id) {
return None;
}
state.bookmarks.iter().find(|b| b.id == id).map(|b| b.address.clone())
}
/// What finding the gateways of a server comes to.
#[derive(Clone, Debug, PartialEq)]
pub enum GatewayFound {
/// Nothing changed, or the server is another one now.
Same,
/// Kept, and observing goes on as it is; `observe` when the server on
/// screen is not observed yet.
Kept {
/// Observe the server now.
observe: bool,
},
/// Kept, and the old ones are left: observing was through them. The
/// server on screen is observed through the new ones.
Changed {
/// The gateways observed through before (the engine stops them).
stop: bool,
/// Observe the server now.
observe: bool,
/// Every URL the server publishes, best first, for the log.
urls: Vec<String>,
},
}
/// Gateways were found for the server at `address` (best first); they are
/// kept unless the server changed meanwhile. Users never hear of them
/// (logged only).
pub fn gateway_found<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
address: &str,
urls: Vec<String>,
) -> GatewayFound {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
return GatewayFound::Same;
};
let previous = b.gateways();
let in_use = b.gateway_url.clone();
if !b.set_gateways(urls) {
return GatewayFound::Same;
}
cx.persist(Persist::Bookmark { id, what: "gateway found" });
let found = b.gateways();
let observe = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let kept = observing_stays(&previous, &found, in_use.as_deref(), observe);
cx.update.refresh.toolbar = true;
let current = state.current == Some(id);
if kept {
return GatewayFound::Kept { observe: current && observe == ObserveState::Off };
}
// Observed through the old ones: through these now.
let stop = !previous.is_empty();
if stop && let Some(view) = state.sessions.get_mut(&id) {
view.state.observe = ObserveState::Off;
}
GatewayFound::Changed { stop, observe: current, urls: found }
}
// Joining a channel.
/// Join a channel of a session (a double-click in the tree, joining a
/// friend): move there with voice, or the password to connect into it with
/// when there is no voice on that server. A locked channel asks for its
/// password first, unless it was given this connection.
pub fn join_channel<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
) -> Option<Option<String>> {
let view = state.sessions.get(&session)?;
let info = view.presence.channels.get(&channel)?;
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match join_password(info, remembered) {
JoinStep::Send(password) => enter_channel(state, cx, session, channel, password),
JoinStep::Ask => {
crate::events::ask_password(state, cx, session, channel, false);
None
}
}
}
/// The password dialog's Join: the same, with that password.
pub fn join_with_password<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
password: String,
) -> Option<(i64, ChannelId, Option<String>)> {
let (session, channel) = state.join_target.take()?;
if password.is_empty() {
return None;
}
if let Some(view) = state.sessions.get_mut(&session) {
view.channel_passwords.insert(channel, password.clone());
}
enter_channel(state, cx, session, channel, Some(password)).map(|p| (session, channel, p))
}
/// Move into a channel; without voice on its server the front end connects
/// into it, with the password returned.
pub fn enter_channel<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
password: Option<String>,
) -> Option<Option<String>> {
let view = state.sessions.get_mut(&session)?;
if view.state.voice != VoiceState::Disconnected {
// Chosen while connecting: no longer the one to join after.
view.join_after_connect = None;
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
return None;
}
Some(password)
}
/// Voice is being connected into `channel` of session `session`: once
/// connected, it is joined again if the server put us elsewhere.
pub fn join_after_connect<L>(state: &mut AppState<L>, session: i64, channel: ChannelId) {
if let Some(view) = state.sessions.get_mut(&session) {
view.join_after_connect = Some(channel);
}
}
/// Fold or unfold a channel of the current session.
pub fn toggle_collapse<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, channel: ChannelId) {
if let Some(id) = state.current {
let view = state.sessions.entry(id).or_default();
if !view.collapsed.remove(&channel) {
view.collapsed.insert(channel);
}
}
cx.update.refresh.tree = true;
}
/// The members panel's search.
pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String) {
if state.member_filter != text {
state.member_filter = text;
cx.update.refresh.tree = 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) {
state.voice_view = on;
let channel =
state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| v.state.own_channel);
if on && let Some(channel) = channel {
open_chat(state, cx, ChatTarget::Channel(channel), true);
}
cx.update.refresh.tree = true;
}
/// A link to the voice channel we are in, for the Invite button (which
/// copies it, and the copy's toast names the channel); the reason without
/// one.
pub fn invite_link<L>(state: &mut AppState<L>) -> Result<String, &'static str> {
let address = state
.current
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
.map(|b| b.address.clone());
let path = state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| {
let cid = v.state.own_channel?;
let own = v.presence.channels.get(&cid)?;
// The link names the channels as the server has them; the toast as
// the tree shows them.
Some((
crate::tree::channel_path(&v.presence, cid),
crate::tree::channel_title(own).0.to_owned(),
))
});
let (Some(address), Some((path, title))) = (address, path) else {
return Err("Join a voice channel to invite others to it");
};
let path: Vec<&str> = path.iter().map(String::as_str).collect();
let link = super::invite_link(&address, &path);
state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
Ok(link)
}
// What is shown.
/// The rail: servers with their state, unread count (without private chats)
/// and streams. `icon` gives a server's icon (what its session fetched, else
/// what was cached).
pub fn rail<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> Vec<ServerItem> {
state
.bookmarks
.iter()
.zip(tints(&state.bookmarks))
.map(|(b, tint)| {
let view = state.sessions.get(&b.id);
let session = view.map(|v| v.state.clone()).unwrap_or_default();
let unread = view.map_or(0, SessionView::channel_unread);
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
let detail = view
.filter(|v| !v.presence.channels.is_empty())
.map(|v| crate::tree::stats(&v.presence))
.unwrap_or_default();
let product = view.map(|v| v.extra.product.clone()).unwrap_or_default();
item(b, &session, unread, live, detail, product, icon(b), tint)
})
.collect()
}
/// A server's colour, as the rail shows it; none for a server that is not
/// in the list (a chat that outlived its bookmark).
pub fn server_tint<L>(state: &AppState<L>, id: i64) -> Option<crate::color::Rgb> {
let position = state.bookmarks.iter().position(|b| b.id == id)?;
Some(tints(&state.bookmarks)[position])
}
/// The colour of a chat's avatar in a list: the server's own colour, as the
/// rail shows it, for the chat of a server (`kind` 0 of a
/// [`ConversationItem`](crate::bridge::ConversationItem)) that is still in
/// the list; for every other chat, and for a server chat that outlived its
/// bookmark, the colour of the `title`, never black.
pub fn conversation_tint<L>(
state: &AppState<L>,
kind: i32,
session: Option<i64>,
title: &str,
) -> crate::color::Rgb {
match (kind, session) {
(0, Some(session)) => server_tint(state, session),
_ => None,
}
.unwrap_or_else(|| crate::avatar::tint(title))
}
/// The server card, the voice controls and who we are.
pub struct ToolbarView {
/// The server's icon.
pub server_icon: ImageRef,
/// Its name.
pub server_title: String,
/// "9 online · 7 channels", once its presence is known.
pub server_stats: String,
/// Our nickname there.
pub nickname: String,
/// Our avatar.
pub own_avatar: ImageRef,
/// The server's banner.
pub server_banner: ImageRef,
/// How it is drawn.
pub server_banner_mode: i32,
/// The channel we are in.
pub own_channel: String,
/// Its topic.
pub own_channel_topic: String,
/// Its banner.
pub own_channel_banner: ImageRef,
/// How it is drawn.
pub own_channel_banner_mode: i32,
/// Its client limit, -1 without one.
pub own_channel_limit: i32,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice is transmitted.
pub transmitting: bool,
/// Where the presence comes from, for people to read.
pub presence_source: &'static str,
}
/// The server card for the current server; `icon` is its icon.
pub fn toolbar<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> ToolbarView {
let bookmark = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id));
let view = state.current.and_then(|id| state.sessions.get(&id));
let session = view.map(|v| v.state.clone()).unwrap_or_default();
let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty())
&& (session.voice == VoiceState::Connected || session.observe == ObserveState::Observing);
let own = view.zip(session.own_client).and_then(|(v, c)| v.avatar(c));
let banner =
|url: Option<&str>| view.map(|v| crate::tree::banner(&v.pictures, url)).unwrap_or_default();
let details = view.map(|v| &v.presence.server);
let own_channel =
view.and_then(|v| session.own_channel.and_then(|c| v.presence.channels.get(&c)));
ToolbarView {
server_icon: bookmark.map(&icon).unwrap_or_default(),
server_title: bookmark.map_or("No server selected".into(), |b| b.name.clone()),
server_stats: view
.filter(|_| has_presence)
.map(|v| crate::tree::stats(&v.presence))
.unwrap_or_default(),
nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default(),
own_avatar: crate::avatar::image(own),
server_banner: banner(details.map(|d| d.banner_gfx_url.as_str())),
server_banner_mode: details.map_or(0, |d| crate::tree::banner_mode(d.banner_mode)),
own_channel: own_channel
.map(|c| crate::tree::channel_title(c).0.to_owned())
.unwrap_or_default(),
own_channel_topic: own_channel.and_then(|c| c.topic.clone()).unwrap_or_default(),
own_channel_banner: banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())),
own_channel_banner_mode: own_channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)),
own_channel_limit: own_channel
.and_then(|c| c.max_clients)
.filter(|m| *m >= 0)
.unwrap_or(-1),
voice_connected: session.voice == VoiceState::Connected,
voice_connecting: session.voice == VoiceState::Connecting,
observing: session.observe != ObserveState::Off,
input_muted: session.input_muted,
output_muted: session.output_muted,
transmitting: session.transmitting,
presence_source: match session.presence_source {
Some(Source::Voice) => "live (voice)",
Some(Source::Gateway) => "invisible (gateway)",
Some(Source::Query) => "invisible (query)",
None => "",
},
}
}
/// The channel tree and the members.
pub struct TreeView {
/// The channels and clients, as the tree lists them.
pub rows: Vec<TreeItem>,
/// The members of our channel (while voice is connected).
pub members: Vec<MemberItem>,
/// Everyone on the server, filtered by the panel's search.
pub server_members: Vec<MemberItem>,
/// How many are on the server (without query clients).
pub member_total: i32,
}
/// The channel tree, the members of our channel and everyone on the server;
/// none when no server is shown. `popped_out`: the stream plays in a window
/// of its own.
pub fn tree_view<L>(state: &AppState<L>, popped_out: bool) -> Option<TreeView> {
let view = state.current.and_then(|id| state.sessions.get(&id))?;
let input = crate::tree::TreeInput {
presence: &view.presence,
collapsed: &view.collapsed,
talking: &view.talking,
playback: &state.playback,
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: "",
avatars: &view.avatars,
icons: &view.icons,
pictures: &view.pictures,
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
let rows = crate::tree::rows(&input);
let connected = view.state.voice == VoiceState::Connected;
let members = if connected { crate::tree::members(&input) } else { Vec::new() };
// The people in our channel first while their view is shown (not while
// the stream plays in a window of its own).
let watching = state.watch.as_ref().is_some_and(|w| w.shown) && !popped_out;
let voice_first = connected && (state.voice_view || watching);
let everyone = crate::tree::server_members(&input, voice_first);
let filter = state.member_filter.trim().to_lowercase();
let server_members =
if filter.is_empty() { everyone } else { crate::tree::matching(everyone, &filter) };
Some(TreeView {
rows,
members,
server_members,
member_total: view.presence.clients.values().filter(|c| !c.is_query).count() as i32,
})
}
#[cfg(test)]
mod tests {
use voelin_core::SessionState;
use voelin_model::ChannelInfo;
use super::*;
use crate::host::testing::{Fake, State, presence, session, state};
fn bookmark(id: i64, name: &str, address: &str) -> Bookmark {
Bookmark { id, name: name.into(), address: address.into(), ..Default::default() }
}
#[test]
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
use crate::events::apply_server_icon;
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-edited-{}.svg", std::process::id()));
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
bookmark = bookmark_from_form(
Some(&bookmark),
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|| "Me".into(),
);
// Connecting does not retag received imagery. A failed B connection
// must not make A's image appear under B's name.
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
view.state.voice = state;
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
}
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
assert_eq!(view.server_icon, 1234);
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
assert!(bookmark.server_icon_id().is_none());
// Equal icon IDs on the next server still need new provenance.
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
assert!(bookmark.server_icon_id().is_none());
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_address_alone_makes_a_server() {
let form =
BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() };
let b = bookmark_from_form(None, &form, || "Nick".into());
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
assert_eq!(b.nickname, "Nick");
assert_eq!(
(b.gateway_url, b.query, b.identity, b.default_channel),
(None, None, None, None)
);
}
#[test]
fn editing_keeps_what_the_form_does_not_show() {
let old = Bookmark {
id: 7,
name: "Old".into(),
address: "old.example.test".into(),
nickname: "Me".into(),
identity: Some(2),
default_channel: Some("Lobby/Sub".into()),
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
client_version: Some("linux".into()),
cached_server_icon: Some(voelin_store::CachedServerIcon {
address: "old.example.test".into(),
id: 1234,
}),
};
// Same address: the gateway found and the query login stay.
let same = BookmarkForm {
id: 7,
name: "Mine".into(),
address: "old.example.test".into(),
nickname: "Other".into(),
..Default::default()
};
let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given"));
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
assert_eq!(b.gateway_url, old.gateway_url);
assert_eq!(b.query, old.query);
assert_eq!(b.cached_server_icon, old.cached_server_icon);
// Another address: looked up again, for the new server.
let form = BookmarkForm { address: "new.example.test:9988".into(), ..same };
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
assert_eq!(b.address, "new.example.test:9988");
assert!(b.cached_server_icon.is_none());
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
assert_eq!(b.client_version.as_deref(), Some("linux"));
assert_eq!((b.gateway_url, b.query), (None, None));
assert!(b.gateway_urls.is_empty());
}
#[test]
fn a_gateway_found_again_is_not_logged_in_again() {
let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1");
let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::<Vec<_>>();
let stays = |previous: &[&str], found: &[&str], observe| {
observing_stays(&urls(previous), &urls(found), Some(plain), observe)
};
// The same ones (an older version kept only the one in use).
assert!(stays(&[plain], &[plain], ObserveState::Connecting));
assert!(stays(&[plain], &[plain], ObserveState::Observing));
// Logged in through one still published.
assert!(stays(&[plain], &[tls, plain], ObserveState::Observing));
// Not logged in yet: through the new ones.
assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting));
// The one in use is no longer published.
assert!(!stays(&[plain], &[tls], ObserveState::Observing));
assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off));
}
/// How a server is observed: through its gateway, its query login, or
/// after the gateway was looked up; not twice, not for sample servers.
#[test]
fn a_server_is_observed_through_what_it_has() {
let mut st = state();
let host = Fake::default();
let cx = Cx::new(&host);
assert_eq!(observe_plan(&st, &cx, 9), ObservePlan::Nothing, "no such server");
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Discover);
st.bookmarks[0].query = Some(QueryConfig::default());
assert!(matches!(observe_plan(&st, &cx, 1), ObservePlan::Query(_)));
st.bookmarks[0].gateway_urls = vec!["wss://gw/v1".into()];
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Gateway(vec!["wss://gw/v1".into()]));
let view = st.sessions.entry(1).or_default();
view.state.observe = ObserveState::Connecting;
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Retry(vec!["wss://gw/v1".into()]));
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Nothing);
let demo = Fake { demo: true, ..Default::default() };
assert_eq!(observe_plan(&st, &Cx::new(&demo), 1), ObservePlan::Nothing);
// The gateway is looked up once a run.
assert_eq!(discover_wanted(&mut st, &cx, 1).as_deref(), Some("ts.example"));
assert_eq!(discover_wanted(&mut st, &cx, 1), None);
}
/// What finding the gateways does to a server.
#[test]
fn found_gateways_are_kept_and_observed_through() {
let mut st = state();
let host = Fake::default();
let found = |st: &mut State, urls: &[&str], address: &str| {
let mut cx = Cx::new(&host);
let result = gateway_found(
st,
&mut cx,
1,
address,
urls.iter().map(|s| s.to_string()).collect(),
);
(result, cx.update.persist.len(), cx.update.refresh.toolbar)
};
// Another address now: nothing.
assert_eq!(found(&mut st, &["wss://gw/v1"], "other.example").0, GatewayFound::Same);
// First found, the server is shown and not observed: observe.
let (result, kept, toolbar) = found(&mut st, &["wss://gw/v1"], "ts.example");
assert_eq!(
result,
GatewayFound::Changed { stop: false, observe: true, urls: vec!["wss://gw/v1".into()] }
);
assert!(kept == 1 && toolbar);
// The same again: nothing changed.
assert_eq!(found(&mut st, &["wss://gw/v1"], "ts.example").0, GatewayFound::Same);
// Observing through the old: a different gateway list leaves them.
st.sessions.entry(1).or_default().state.observe = ObserveState::Observing;
let (result, ..) = found(&mut st, &["wss://new/v1"], "ts.example");
assert_eq!(
result,
GatewayFound::Changed { stop: true, observe: true, urls: vec!["wss://new/v1".into()] }
);
assert_eq!(st.sessions[&1].state.observe, ObserveState::Off);
// One that still lists the one in use keeps observing.
st.bookmarks[0].gateway_url = Some("wss://new/v1".into());
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
let (result, ..) = found(&mut st, &["wss://new/v1", "wss://more/v1"], "ts.example");
assert_eq!(result, GatewayFound::Kept { observe: false });
}
/// Joining a channel: a free one at once (or connecting into it), a locked
/// one asks, the password dialog's Join goes on.
#[test]
fn joining_a_channel_moves_asks_or_connects() {
let mut st = state();
let host = Fake::default();
let mut locked = ChannelInfo { id: 3, name: "Vault".into(), ..Default::default() };
locked.has_password = true;
let mut p = (*presence()).clone();
p.channels.insert(3, locked);
st.sessions.entry(1).or_default().presence = std::sync::Arc::new(p);
// Connected: moving.
st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2));
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), None);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::MoveToChannel { session: 1, channel: 1, password: None }]
));
// A locked one asks.
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 3), None);
assert_eq!(cx.update.password.as_ref().map(|p| p.name.as_str()), Some("Vault"));
assert_eq!(st.join_target, Some((1, 3)));
let mut cx = Cx::new(&host);
assert_eq!(join_with_password(&mut st, &mut cx, "".into()), None);
st.join_target = Some((1, 3));
assert_eq!(join_with_password(&mut st, &mut cx, "pw".into()), None);
assert_eq!(st.sessions[&1].channel_passwords.get(&3).map(String::as_str), Some("pw"));
assert!(matches!(
cx.update.commands.as_slice(),
[Command::MoveToChannel { channel: 3, password: Some(p), .. }] if p == "pw"
));
// Not connected: the front end connects into it.
st.sessions.get_mut(&1).unwrap().state = SessionState::default();
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), Some(None));
join_after_connect(&mut st, 1, 1);
assert_eq!(st.sessions[&1].join_after_connect, Some(1));
assert!(cx.update.commands.is_empty());
}
/// The server card, the rail and the tree for the server shown.
#[test]
fn the_rail_the_card_and_the_tree() {
let mut st = state();
let no_icon = |_: &Bookmark| ImageRef::default();
// Nothing connected yet.
let rail_rows = rail(&st, no_icon);
assert_eq!(rail_rows.len(), 1);
assert_eq!((&*rail_rows[0].status, &*rail_rows[0].detail), ("offline", "ts.example"));
let card = toolbar(&st, no_icon);
assert_eq!((card.server_title.as_str(), card.nickname.as_str()), ("ts.example", "Me"));
assert!(!card.voice_connected && card.presence_source.is_empty());
assert!(tree_view(&st, false).is_none(), "no session yet");
// Connected into Games.
let host = Fake::default();
for event in [
voelin_core::Event::Presence { session: 1, presence: presence() },
voelin_core::Event::State {
session: 1,
state: session(VoiceState::Connected, Some(2)),
},
] {
crate::events::apply(&mut st, &host, event);
}
let rail_rows = rail(&st, no_icon);
assert_eq!(
(&*rail_rows[0].status, &*rail_rows[0].detail),
("connected", "2 online · 2 channels")
);
assert_eq!(server_tint(&st, 1), Some(tints(&st.bookmarks)[0]));
assert_eq!(server_tint(&st, 9), None);
let card = toolbar(&st, no_icon);
assert!(card.voice_connected && card.own_channel == "Games");
assert_eq!(card.presence_source, "live (voice)");
assert_eq!(card.own_channel_limit, -1);
let tree = tree_view(&st, false).unwrap();
assert_eq!(tree.rows.len(), 4, "two channels and their clients");
assert_eq!(tree.members.len(), 2);
assert_eq!(tree.member_total, 2);
// The members' search filters the server's people only.
let mut cx = Cx::new(&host);
search_members(&mut st, &mut cx, "ali".into());
assert!(cx.update.refresh.tree);
let tree = tree_view(&st, false).unwrap();
assert_eq!(
tree.server_members
.iter()
.filter(|m| !m.group.is_empty() && &*m.name == "Alice")
.count(),
1
);
assert!(tree.server_members.iter().all(|m| &*m.name != "Me"));
// Folding a channel; the tree is drawn again.
let mut cx = Cx::new(&host);
toggle_collapse(&mut st, &mut cx, 1);
assert!(st.sessions[&1].collapsed.contains(&1) && cx.update.refresh.tree);
toggle_collapse(&mut st, &mut cx, 1);
assert!(st.sessions[&1].collapsed.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
/// is what a missing colour would be (`Rgb::default()`).
#[test]
fn a_chat_takes_its_servers_colour_or_that_of_its_title() {
let st = state();
let server = tints(&st.bookmarks)[0];
let titled = |title: &str| crate::avatar::tint(title);
// Titles whose own colour is not the server's, so that the chat
// below can tell the two apart.
assert_ne!(titled("Old Server"), server);
assert_ne!(titled("Alice"), server);
assert_ne!(titled("Alice"), crate::color::Rgb::default());
// The server's chat, the server in the list: its colour, not the
// title's.
assert_eq!(conversation_tint(&st, 0, Some(1), "Old Server"), server);
// The server is gone from the list: the title's colour.
assert_eq!(conversation_tint(&st, 0, Some(9), "Old Server"), titled("Old Server"));
// Not a server chat of a known server: the title's colour, whether
// the server is in the list or not, or not known at all.
assert_eq!(conversation_tint(&st, 1, Some(1), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 2, Some(1), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 2, Some(9), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 0, None, "Alice"), titled("Alice"));
}
/// The Invite button's link and note; the voice view's chat.
#[test]
fn invite_and_voice_view() {
let mut st = state();
let host = Fake::default();
assert_eq!(invite_link(&mut st), Err("Join a voice channel to invite others to it"));
for event in [
voelin_core::Event::Presence { session: 1, presence: presence() },
voelin_core::Event::State {
session: 1,
state: session(VoiceState::Connected, Some(2)),
},
] {
crate::events::apply(&mut st, &host, event);
}
let link = invite_link(&mut st).unwrap();
assert!(link.contains("ts.example") && link.contains("Games"), "{link}");
assert_eq!(st.copy_note.as_deref(), Some(&*format!("Copied an invite to Games: {link}")));
let mut cx = Cx::new(&host);
show_voice_view(&mut st, &mut cx, true);
assert!(st.voice_view && cx.update.refresh.tree && cx.update.refresh.chat);
}
/// A server leaves the list; the first one that is left is shown.
#[test]
fn forgetting_a_server_shows_the_first_left() {
let mut st = state();
st.bookmarks.push(bookmark(2, "Other", "other.example"));
let host = Fake::default();
st.sessions.entry(1).or_default();
st.gateways_looked_up.insert(1);
let mut cx = Cx::new(&host);
forget_server(&mut st, &mut cx, 1, vec![bookmark(2, "Other", "other.example")]);
assert_eq!(st.current, Some(2));
assert!(st.sessions.is_empty() && st.gateways_looked_up.is_empty());
let r = cx.update.refresh;
assert!(r.servers && r.toolbar && r.tree && r.chat && r.streams);
let mut cx = Cx::new(&host);
select_server(&mut st, &mut cx, 2);
assert_eq!(st.current, Some(2));
}
#[test]
fn the_voice_options_follow_the_bookmark() {
let mut b = bookmark(1, "G", "ts.example");
b.nickname = "Me".into();
let options =
voice_options(&b, Some("/5".into()), Some("pw".into()), Some("key".into())).unwrap();
assert_eq!(options.channel.as_deref(), Some("/5"));
assert_eq!(options.channel_password.as_deref(), Some("pw"));
assert_eq!(options.token.as_deref(), Some("key"));
assert!(options.audio);
// A bookmark without a version spec leaves the engine's default.
assert_eq!(options.client_version, None);
// A spec that resolves goes on as the spec: the engine resolves it
// when it connects.
b.client_version = Some("default".into());
let options = voice_options(&b, None, None, None).unwrap();
assert_eq!(options.client_version.as_deref(), Some("default"));
b.client_version = Some("no such version".into());
let error = voice_options(&b, None, None, None).err().unwrap();
assert!(error.starts_with("Invalid client compatibility version"), "{error}");
}
}
@@ -1,4 +1,8 @@
//! The server rail, the server dialog, and joining a channel.
//! The server rail, the server dialog, and joining a channel; [`logic`] has
//! which server is shown, how it is observed, and the rail, the server card
//! and the channel tree as plain data.
pub mod logic;
use std::sync::Arc;
@@ -126,6 +130,7 @@ pub fn form(
pub struct ConnectTo {
/// A channel path, or `/<id>`.
pub channel: Option<String>,
/// The channel's password, if the form has one.
pub channel_password: Option<String>,
/// A privilege key.
pub token: Option<String>,
+15
View File
@@ -31,8 +31,10 @@ pub static CLIENT_PLAYBACK: Key<ClientPlaybackMap> = Key::new(
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeChoice {
/// The dark palette.
#[default]
Dark,
/// The light palette.
Light,
/// The system's light or dark scheme.
System,
@@ -128,8 +130,11 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyLevel {
/// Nothing.
Off,
/// The bell in the app.
App,
/// The bell and a desktop notification.
#[default]
Desktop,
}
@@ -294,6 +299,7 @@ pub struct UiSettings {
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
/// The last choices in the share dialog.
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
@@ -321,8 +327,11 @@ impl Default for UiSettings {
/// path, its names from the top as the server has them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastVoice {
/// The id of the server's bookmark.
pub bookmark: i64,
/// The address the bookmark had then.
pub address: String,
/// The channel's names from the top.
pub channel: Vec<String>,
}
@@ -333,9 +342,13 @@ pub struct LastVoice {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
/// The frame rate's position in the old list ([`LEGACY_FPS_CHOICES`]).
pub fps_index: usize,
/// The bitrate's position in the old list ([`LEGACY_BITRATE_CHOICES`]).
pub bitrate_index: usize,
/// Share the sound too.
pub audio: bool,
/// Accept the viewers that ask to watch without asking us.
pub auto_accept: bool,
}
@@ -350,6 +363,7 @@ impl Default for ShareDefaults {
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
/// Not played at all.
pub muted: bool,
}
@@ -372,6 +386,7 @@ pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
/// What the list shows, by index.
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
@@ -0,0 +1,412 @@
//! The audio settings page and the local volume of clients: the device
//! lists and the form, what a change of the form sends to the engine, the
//! microphone test, the push-to-talk and H.264 switches, the crash notice
//! and the volume dialog. The functions change the
//! [`AppState`] and say in the [`Cx`]'s update what
//! to send and keep; the devices, the hotkey, the store and the window are
//! the front end's.
use voelin_core::Command;
use crate::bridge::{AudioForm, ClientAudio};
use crate::host::{Cx, Persist};
use crate::settings::{ClientPlayback, DeviceChoices, apply_audio_form, audio_form};
use crate::state::AppState;
/// What the settings page shows when it opens ([`open_settings`]).
#[derive(Clone, Debug, PartialEq)]
pub struct SettingsView {
/// The input devices' names, the system default first.
pub input_devices: Vec<String>,
/// The output devices' names, the system default first.
pub output_devices: Vec<String>,
/// The form of the audio settings.
pub audio: AudioForm,
/// The push-to-talk key works in every window.
pub global_ptt: bool,
/// The push-to-talk key.
pub ptt_key: String,
/// H.264 through the downloaded OpenH264 is on.
pub h264_enabled: bool,
}
/// An audio device the system lists: its id, its name and whether it is the
/// system's default of its direction.
pub type Device = (String, String, bool);
/// The settings page opens: the devices the system lists become the choices
/// (a device that is stored but not there stays in the list), and the form
/// and the switches are those of the state.
pub fn open_settings<L>(
state: &mut AppState<L>,
inputs: &[Device],
outputs: &[Device],
) -> SettingsView {
state.inputs = DeviceChoices::new(inputs, state.audio.input_device.as_deref());
state.outputs = DeviceChoices::new(outputs, state.audio.output_device.as_deref());
SettingsView {
input_devices: state.inputs.names.clone(),
output_devices: state.outputs.names.clone(),
audio: audio_form(&state.audio, &state.inputs, &state.outputs),
global_ptt: state.settings.global_ptt,
ptt_key: state.settings.ptt_key.clone(),
h264_enabled: state.settings.openh264,
}
}
/// The form changed: the engine gets the new audio settings, and they are
/// kept later ([`save_audio`]), if the form changed anything.
pub fn audio_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &AudioForm) {
let audio = apply_audio_form(form, &state.audio, &state.inputs, &state.outputs);
if audio == state.audio {
return;
}
state.audio = audio;
state.audio_dirty = true;
cx.send(Command::SetAudioSettings(Box::new(state.audio.clone())));
}
/// Keep the audio settings, if they changed since they were kept.
pub fn save_audio<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
if state.audio_dirty {
state.audio_dirty = false;
cx.persist(Persist::Audio);
}
}
/// The settings page closes: the microphone test stops and the audio
/// settings are kept. Whether the test was on.
pub fn close_settings<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) -> bool {
let was_on = set_mic_test(state, cx, false);
save_audio(state, cx);
was_on
}
/// Start or stop the microphone test: whether that changed anything.
pub fn set_mic_test<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) -> bool {
if state.mic_test == on {
return false;
}
state.mic_test = on;
cx.send(Command::TestMicrophone { on });
true
}
/// The push-to-talk switch and key: kept, and the key to register as a
/// hotkey of the whole desktop, none to unregister it. A blank key leaves
/// the one that was set.
pub fn apply_ptt<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
enabled: bool,
key: &str,
) -> Option<String> {
let key = key.trim().to_owned();
state.settings.global_ptt = enabled;
if !key.is_empty() {
state.settings.ptt_key = key.clone();
}
cx.persist(Persist::Settings);
(enabled && !key.is_empty()).then_some(key)
}
/// The H.264 switch: kept; the front end tells the encoder.
pub fn set_h264<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
state.settings.openh264 = enabled;
cx.persist(Persist::Settings);
}
/// What the H.264 rows show ([`h264_view`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct H264View {
/// The library is loaded.
pub loaded: bool,
/// It is being downloaded.
pub busy: bool,
/// What the front end's codec says.
pub status: String,
}
/// The H.264 rows for the codec's state: `loaded`, and its `status` text
/// ("Downloading …" while it is being fetched).
pub fn h264_view(loaded: bool, status: String) -> H264View {
H264View { loaded, busy: status.starts_with("Downloading"), status }
}
/// The crash reports switch: kept (the front end also tells the crash
/// handler and the settings service).
pub fn set_crash_reports<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
state.settings.crash_reports = enabled;
// Also in the blob, for older versions.
cx.persist(Persist::Settings);
}
/// The notice while crash reports are on disk: `summaries` are the first
/// lines of their panic messages, oldest first. Empty without reports.
pub fn crash_notice(summaries: &[String]) -> String {
let Some(newest) = summaries.last() else { return String::new() };
let saved = match summaries.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({newest}). {saved} on this device.")
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session; none when
/// there is no such client.
pub fn open_client<L>(state: &mut AppState<L>, client: u16) -> Option<ClientAudio> {
let id = state.current?;
let info = state.sessions.get(&id)?.presence.clients.get(&client)?.clone();
let playback =
info.uid.as_ref().and_then(|uid| state.playback.get(uid)).copied().unwrap_or_default();
state.playback_dialog = Some((id, client, info.uid.clone()));
Some(ClientAudio {
id: i32::from(client),
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
streaming: info.streaming == Some(true),
})
}
/// The volume dialog changed: the engine plays the client so, and the
/// choice is kept by the client's unique id (a client without one only for
/// this connection), the default as no choice. The tree shows who is muted.
pub fn client_playback_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &ClientAudio) {
let Some((session, client, uid)) = state.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
cx.send(Command::SetClientVolume { session, client, volume: playback.volume });
cx.send(Command::SetClientMuted { session, client, muted: playback.muted });
if let Some(uid) = uid {
if playback.is_default() {
state.playback.remove(&uid);
} else {
state.playback.insert(uid, playback);
}
cx.persist(Persist::Playback);
}
cx.update.refresh.tree = true;
}
/// The first client of the current session that is not us nor a query
/// client (`VOELIN_OPEN=client`): its id, when we are in the session.
pub fn first_client<L>(state: &AppState<L>) -> Option<u16> {
let view = state.current.and_then(|id| state.sessions.get(&id))?;
let own = view.state.own_client?;
view.presence.clients.values().filter(|c| c.id != own && !c.is_query).map(|c| c.id).min()
}
#[cfg(test)]
mod tests {
use voelin_core::VoiceState;
use super::*;
use crate::host::testing::{Fake, State, presence, session, state};
fn device(id: &str, name: &str, default: bool) -> Device {
(id.into(), name.into(), default)
}
#[test]
fn the_page_opens_with_the_devices_and_a_stored_one_stays() {
let mut st = state();
st.audio.input_device = Some("gone".into());
st.settings.global_ptt = true;
st.settings.ptt_key = "F9".into();
let inputs = [device("a", "Built-in", true), device("b", "Headset", false)];
let outputs = [device("a", "Built-in", false), device("b", "Headset", true)];
let view = open_settings(&mut st, &inputs, &outputs);
// The system default first, named after the one that is the default.
assert_eq!(
view.input_devices,
["System default (Built-in)", "Built-in", "Headset", "gone (not connected)"]
);
// Outputs have the other as the default, and no stored device.
assert_eq!(view.output_devices, ["System default (Headset)", "Built-in", "Headset"]);
assert_eq!(view.audio.input_index, 3, "the stored device is selected");
assert_eq!(view.audio.output_index, 0, "no stored output: the default");
assert!(view.global_ptt && view.ptt_key == "F9" && !view.h264_enabled);
assert_eq!(st.inputs.names, view.input_devices);
}
#[test]
fn a_change_of_the_form_goes_to_the_engine_once_and_is_kept_later() {
let mut st = state();
let host = Fake::default();
open_settings(&mut st, &[], &[]);
let mut form = audio_form(&st.audio, &st.inputs, &st.outputs);
// Nothing changed: nothing sent.
let mut cx = Cx::new(&host);
audio_changed(&mut st, &mut cx, &form);
assert!(cx.update.commands.is_empty() && !st.audio_dirty);
form.output_volume = 50.0;
audio_changed(&mut st, &mut cx, &form);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::SetAudioSettings(audio)] if audio.output_volume == 0.5
));
assert!(st.audio_dirty);
// The same form again changes nothing.
audio_changed(&mut st, &mut cx, &form);
assert_eq!(cx.update.commands.len(), 1);
// Kept once, when the page closes or the clock ticks.
save_audio(&mut st, &mut cx);
save_audio(&mut st, &mut cx);
assert_eq!(cx.update.persist, [Persist::Audio]);
assert!(!st.audio_dirty);
}
#[test]
fn the_microphone_test_stops_with_the_page() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
assert!(!close_settings(&mut st, &mut cx), "it was not on");
assert!(cx.update.commands.is_empty());
assert!(set_mic_test(&mut st, &mut cx, true));
assert!(!set_mic_test(&mut st, &mut cx, true), "already on");
st.audio_dirty = true;
assert!(close_settings(&mut st, &mut cx), "it was on");
assert!(!st.mic_test);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::TestMicrophone { on: true }, Command::TestMicrophone { on: false }]
));
assert_eq!(cx.update.persist, [Persist::Audio]);
}
#[test]
fn the_push_to_talk_key_is_registered_when_it_is_on_and_set() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
assert_eq!(apply_ptt(&mut st, &mut cx, true, " F9 ").as_deref(), Some("F9"));
assert!(st.settings.global_ptt);
assert_eq!(st.settings.ptt_key, "F9");
// Off: unregistered, the key stays for later.
assert_eq!(apply_ptt(&mut st, &mut cx, false, "F10"), None);
assert_eq!(st.settings.ptt_key, "F10");
// A blank key leaves the one that was set, and registers nothing.
assert_eq!(apply_ptt(&mut st, &mut cx, true, " "), None);
assert_eq!(st.settings.ptt_key, "F10");
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings, Persist::Settings]);
}
#[test]
fn the_switches_are_kept() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
set_h264(&mut st, &mut cx, true);
set_crash_reports(&mut st, &mut cx, true);
assert!(st.settings.openh264 && st.settings.crash_reports);
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings]);
assert_eq!(
h264_view(false, "Downloading OpenH264… 40%".into()),
H264View { loaded: false, busy: true, status: "Downloading OpenH264… 40%".into() }
);
assert!(!h264_view(true, "Loaded".into()).busy);
}
#[test]
fn the_crash_notice_counts_the_reports() {
assert_eq!(crash_notice(&[]), "");
assert_eq!(
crash_notice(&["index out of bounds".into()]),
"The app crashed earlier (index out of bounds). 1 crash report is saved on this device."
);
assert_eq!(
crash_notice(&["old".into(), "new".into()]),
"The app crashed earlier (new). 2 crash reports are saved on this device."
);
}
/// Connected, with Alice (11) in Games next to us (10), a query client
/// (12) and Zed (9, a lower id).
fn with_clients() -> State {
let mut st = state();
let mut p = (*presence()).clone();
p.clients.get_mut(&11).unwrap().streaming = Some(true);
for (id, name, query) in [(12, "serveradmin", true), (9, "Zed", false)] {
p.clients.insert(
id,
voelin_model::ClientInfo {
id,
channel: 2,
nickname: name.into(),
is_query: query,
..Default::default()
},
);
}
let view = st.sessions.entry(1).or_default();
view.presence = std::sync::Arc::new(p);
view.state = session(VoiceState::Connected, Some(2));
st
}
#[test]
fn the_volume_dialog_fills_from_what_was_kept() {
let mut st = with_clients();
assert_eq!(open_client(&mut st, 99), None, "no such client");
let form = open_client(&mut st, 11).unwrap();
assert_eq!((form.id, &*form.name, form.volume, form.muted), (11, "Alice", 100.0, false));
assert!(form.streaming);
assert_eq!(st.playback_dialog, Some((1, 11, Some("alice=".into()))));
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let form = open_client(&mut st, 11).unwrap();
assert_eq!((form.volume, form.muted), (50.0, true));
st.current = None;
assert_eq!(open_client(&mut st, 11), None, "no server shown");
}
#[test]
fn a_client_is_played_as_the_dialog_says_and_the_default_is_forgotten() {
let mut st = with_clients();
let host = Fake::default();
let mut cx = Cx::new(&host);
// No dialog open: nothing.
client_playback_changed(&mut st, &mut cx, &ClientAudio::default());
assert!(cx.update.commands.is_empty());
let mut form = open_client(&mut st, 11).unwrap();
form.volume = 900.0;
form.muted = true;
client_playback_changed(&mut st, &mut cx, &form);
// Clamped to four times, sent, kept by unique id, the tree shows it.
assert!(matches!(
cx.update.commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume: 4.0 },
Command::SetClientMuted { session: 1, client: 11, muted: true },
]
));
assert_eq!(st.playback["alice="], ClientPlayback { volume: 4.0, muted: true });
assert_eq!(cx.update.persist, [Persist::Playback]);
assert!(cx.update.refresh.tree);
// Back to the default: no entry.
form.volume = 100.0;
form.muted = false;
client_playback_changed(&mut st, &mut cx, &form);
assert!(st.playback.is_empty());
// A client without a unique id is played so only for now.
st.playback_dialog = Some((1, 9, None));
let before = cx.update.persist.len();
client_playback_changed(&mut st, &mut cx, &form);
assert!(st.playback.is_empty());
assert_eq!(cx.update.persist.len(), before);
}
#[test]
fn the_first_client_is_the_lowest_id_that_is_not_us() {
let mut st = with_clients();
assert_eq!(first_client(&st), Some(9), "not us (10), not the query client");
st.sessions.get_mut(&1).unwrap().state.own_client = None;
assert_eq!(first_client(&st), None, "not in the session");
st.current = None;
assert_eq!(first_client(&st), None);
}
}
@@ -0,0 +1,6 @@
//! The settings page of the audio devices and the voice controls, the push
//! to talk key, the H.264 switch, the crash reports and the volume of a
//! client. [`logic`] has what the page shows and what its controls change;
//! the engine, the store, the hotkey and the window are the front end's.
pub mod logic;
@@ -118,7 +118,7 @@ pub fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option<LayerSetting> {
}
/// The layers of quality preset `quality` (0: none, the source's size;
/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and
/// then `PRESETS`) at `kbps` (0: automatic, for the preset's size and
/// `fps`); `None` for no preset (layers of one's own).
pub fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option<Vec<LayerSetting>> {
match usize::try_from(quality).ok()? {
File diff suppressed because it is too large. Load diff
@@ -3,9 +3,232 @@
//! `vm::bbcode`), mentions, event dates, a poke's message, the private
//! chats of the home sidebar; pure, so they are tested here.
pub mod logic;
use std::collections::HashSet;
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use voelin_core::HistoryMessage;
use voelin_model::ChatTarget;
use voelin_core::{HistoryMessage, VoiceState};
use voelin_model::{ChatMessage, ChatTarget};
use crate::state::AppState;
/// Now, in milliseconds since the epoch.
pub fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
/// What a notification of the bell is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NoticeKind {
/// Someone mentioned us.
Mention,
/// Someone poked us.
Poke,
/// A private message.
Message,
/// A scheduled event starts soon.
Event,
/// A friend came online.
Friend,
}
impl NoticeKind {
/// The name the bell's rows carry.
pub fn name(self) -> &'static str {
match self {
Self::Mention => "mention",
Self::Poke => "poke",
Self::Message => "message",
Self::Event => "event",
Self::Friend => "friend",
}
}
}
/// Where a notification leads.
#[derive(Clone, Debug, PartialEq)]
pub enum NoticeTarget {
/// A chat of a session.
Chat(i64, ChatTarget),
/// A private chat with someone, in a session.
Dm(i64, String),
/// An event of a session's gateway (session, event id).
Event(i64, i64),
/// A contact, by unique id.
Contact(String),
}
/// A notification a transition asks for; the front end adds it to the bell
/// as the setting of its kind says.
#[derive(Clone, Debug, PartialEq)]
pub struct NoticeRequest {
/// What it is about.
pub kind: NoticeKind,
/// The headline.
pub title: String,
/// The line under it.
pub body: String,
/// Where it leads.
pub target: NoticeTarget,
/// Whose avatar it shows (initials from the name).
pub name: String,
/// Whose avatar picture it shows.
pub uid: Option<String>,
}
/// Whether a message is ours: by one of our unique ids, or by our client in
/// its session (`own_client`).
pub fn own_message(
own_uids: &HashSet<String>,
own_client: Option<u16>,
message: &ChatMessage,
) -> bool {
message.author_uid.as_ref().is_some_and(|u| own_uids.contains(u))
|| (own_client.is_some() && message.author_id == own_client)
}
/// A poke we got.
#[derive(Clone, Debug, PartialEq)]
pub struct Poke {
/// The session it came in.
pub session: i64,
/// Who poked, by unique id, when known.
pub uid: Option<String>,
/// Who poked, by name.
pub name: String,
/// What they wrote with it.
pub message: String,
/// When, in milliseconds since the epoch.
pub ts_ms: i64,
}
/// The avatar picture of someone by unique id, from any session.
pub fn avatar_of<L>(state: &AppState<L>, uid: &str) -> crate::image::ImageRef {
crate::avatar::image(state.sessions.values().find_map(|v| v.avatars.get(uid)))
}
/// Pokes from `uid` as lines of their private chat, among its messages
/// (with the time of each, oldest first).
pub fn poke_lines<L>(
state: &AppState<L>,
pokes: &[Poke],
session: i64,
uid: &str,
) -> Vec<(i64, crate::bridge::ChatLine)> {
pokes
.iter()
.enumerate()
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
.map(|(i, p)| {
let text = if p.message.is_empty() {
"👋 poked you".to_owned()
} else {
format!("👋 poked you: {}", p.message)
};
let message = ChatMessage {
target: ChatTarget::Private(uid.to_owned()),
author_name: p.name.clone(),
author_uid: p.uid.clone(),
author_id: None,
text,
ts_ms: p.ts_ms,
via_relay: false,
blocked: false,
};
let mut line = crate::chat::line(&message, None);
line.key = -1_000_000 - i as i32;
line.avatar = avatar_of(state, uid);
(p.ts_ms, line)
})
.collect()
}
/// Whether a message of a session is ours.
pub fn is_own<L>(state: &AppState<L>, session: i64, message: &ChatMessage) -> bool {
let own_client = state.sessions.get(&session).and_then(|v| v.state.own_client);
own_message(&state.own_uids, own_client, message)
}
/// Where someone is in one session.
#[derive(Clone, Debug, PartialEq)]
pub struct Spot {
/// The session.
pub session: i64,
/// The server's name.
pub server: String,
/// The client's id there.
pub client: u16,
/// The channel it is in.
pub channel: u64,
/// The channel's name as shown (a spacer's text).
pub channel_title: String,
/// Its away message, if it is away.
pub away: Option<String>,
/// It streams.
pub streaming: bool,
/// We are connected with voice there (messages, pokes, moving).
pub voice: bool,
}
/// A server's name: its bookmark's, else what the session calls it.
pub fn server_name<L>(state: &AppState<L>, session: i64) -> String {
state.bookmarks.iter().find(|b| b.id == session).map(|b| b.name.clone()).unwrap_or_else(|| {
state.sessions.get(&session).map(|v| v.presence.server_name.clone()).unwrap_or_default()
})
}
/// Every session where the client with this unique id is, in bookmark
/// order.
pub fn spots_of<L>(state: &AppState<L>, uid: &str) -> Vec<Spot> {
let mut ids: Vec<i64> = state.sessions.keys().copied().collect();
ids.sort_by_key(|id| state.bookmarks.iter().position(|b| b.id == *id).unwrap_or(usize::MAX));
let mut spots = Vec::new();
for id in ids {
let view = &state.sessions[&id];
let Some(c) = view.presence.clients.values().find(|c| c.uid.as_deref() == Some(uid)) else {
continue;
};
let channel = view.presence.channels.get(&c.channel);
spots.push(Spot {
session: id,
server: server_name(state, id),
client: c.id,
channel: c.channel,
channel_title: channel
.map(|ch| crate::tree::channel_title(ch).0.to_owned())
.unwrap_or_default(),
away: c.away.clone(),
streaming: c.streaming == Some(true),
voice: view.state.voice == VoiceState::Connected,
});
}
spots
}
/// What we call the peer of a private chat: its contact's nickname, the name
/// it has where it is now, the name on a message of theirs (`last`, or one in
/// any open chat), else the start of its unique id.
pub fn peer_name<L>(state: &AppState<L>, uid: &str, last: Option<&HistoryMessage>) -> String {
if let Some(c) = state.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
return c.nickname.clone();
}
if let Some(s) = spots_of(state, uid).first() {
return state.sessions[&s.session].nickname(s.client);
}
let from_peer = |m: &HistoryMessage| {
(m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone())
};
last.and_then(from_peer)
.or_else(|| {
state.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
(t.target == ChatTarget::Private(uid.to_owned()))
.then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message)))
.flatten()
})
})
.unwrap_or_else(|| uid.chars().take(8).collect())
}
/// A chat of any server.
#[derive(Clone, Debug, PartialEq)]
@@ -218,6 +441,18 @@ mod tests {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
/// The bell's rows carry the kind's name and the Slint side picks the
/// colour and the icon by it (`ui/screens/overlays.slint`; the message is
/// what no other name matches), so a renamed kind must fail here.
#[test]
fn notice_kinds_are_named_as_the_bell_keys_them() {
use NoticeKind::{Event, Friend, Mention, Message, Poke};
assert_eq!(
[Mention, Poke, Message, Event, Friend].map(NoticeKind::name),
["mention", "poke", "message", "event", "friend"]
);
}
#[test]
fn times() {
let now = 1_800_000_000_000;
+32 -6
View File
@@ -21,9 +21,11 @@ use voelin_gateway_proto::{
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
use voelin_store::Bookmark;
use crate::bridge::ChatLine;
use crate::chat::{LineCache, Previous};
use crate::image::ImageRef;
use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings};
use crate::streams::logic::{Sharing, Watching};
/// The store's name of a chat.
pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
@@ -34,6 +36,20 @@ pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
}
}
/// The lines of a chat tab, in the front end's own list type (a Slint model
/// kept in step with them, or a plain `Vec`): what a message that arrives
/// without stored history appends.
pub trait Lines: Default {
/// Append a line.
fn push(&mut self, line: ChatLine);
}
impl Lines for Vec<ChatLine> {
fn push(&mut self, line: ChatLine) {
Vec::push(self, line);
}
}
/// A file being downloaded from a chat message.
pub struct Download {
/// The message's handle.
@@ -283,21 +299,21 @@ pub struct SessionView<L> {
/// Clients whose stored volume was sent for this voice connection.
pub applied_playback: HashSet<u16>,
/// Avatar pictures in the engine's cache, by unique id
/// ([`Event::AvatarReady`]).
/// ([`voelin_core::Event::AvatarReady`]).
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
/// Icons in the engine's cache, by icon id ([`voelin_core::Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address
/// ([`Event::PictureReady`]).
/// ([`voelin_core::Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
/// ([`voelin_core::Event::ServerDetails`]); kept while disconnected, for the rail.
pub server_icon: u32,
/// Bookmark address that supplied this session's icon.
pub icon_address: Option<String>,
/// The server groups in display order ([`Event::Groups`]).
/// The server groups in display order ([`voelin_core::Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// The channel groups ([`Event::Groups`]).
/// The channel groups ([`voelin_core::Event::Groups`]).
pub channel_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
@@ -550,6 +566,13 @@ pub struct AppState<L> {
/// Files being uploaded to a channel from the composer: session,
/// channel and name, so the link can be posted when they are up.
pub uploads: HashMap<u64, (i64, u64, String)>,
/// Our unique ids (TeamSpeak 3 and 6 of every identity): messages by
/// them are ours ([`crate::social::own_message`]).
pub own_uids: HashSet<String>,
/// Our stream (the capture that feeds it is the front end's).
pub share: Option<Sharing>,
/// The stream in the viewer (its decoder is the front end's).
pub watch: Option<Watching>,
}
impl<L> AppState<L> {
@@ -589,6 +612,9 @@ impl<L> AppState<L> {
stream_volume: 100.0,
gateways_looked_up: HashSet::new(),
uploads: HashMap::new(),
own_uids: HashSet::new(),
share: None,
watch: None,
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,8 @@
//! Streams on the voice view, the phone's Activity tab and Home: what is
//! shared, and who shares it.
//! shared, and who shares it; [`logic`] has the state of the streams we
//! share and watch, and what happens to them.
pub mod logic;
use std::path::PathBuf;
+3
View File
@@ -117,6 +117,7 @@ pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static s
pub struct AudioLive {
/// Peak in dBFS.
pub level: f32,
/// What went wrong with the source, if something did.
pub error: Option<String>,
}
@@ -502,7 +503,9 @@ pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform {
/// (`None`: switched off, so it is removed).
#[derive(Clone, Debug, PartialEq)]
pub struct Overlay {
/// The source's name.
pub name: &'static str,
/// What it shows, none to remove it.
pub text: Option<String>,
}
+62 -1
View File
@@ -1,6 +1,6 @@
//! The Stream Studio's structs: the plain counterparts of
//! `crates/voelin-ui/ui/studio-bridge.slint`, as [`crate::bridge`] has those of
//! `bridge.slint`.
//! `bridge.slint`. As there, every field is documented.
use std::sync::Arc;
@@ -9,7 +9,9 @@ use crate::image::ImageRef;
/// A scene of the studio.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioScene {
/// The scene's id.
pub id: i32,
/// The scene's name.
pub name: Arc<str>,
/// Its sources, front first: "Screen + Camera + Text".
pub detail: Arc<str>,
@@ -22,11 +24,15 @@ pub struct StudioScene {
/// A source of the live scene, front first.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSource {
/// The source's id in its scene.
pub id: i32,
/// The source's name.
pub name: Arc<str>,
/// screen, window, portal, camera, image, text, colour, pattern
pub kind: Arc<str>,
/// It is shown in the output.
pub visible: bool,
/// It cannot be moved, resized or cropped.
pub locked: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
@@ -36,18 +42,22 @@ pub struct StudioSource {
pub info: Arc<str>,
/// At the front or the back (cannot move further).
pub front: bool,
/// At the back; it cannot move further.
pub back: bool,
}
/// An audio source of the stream (`stream.audio_sources`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioAudio {
/// The source's name.
pub name: Arc<str>,
/// "Elgato Wave:3", the application...
pub detail: Arc<str>,
/// microphone, desktop, app, window, tone
pub kind: Arc<str>,
/// Its gain in dB.
pub gain_db: f32,
/// It is muted in the mix.
pub muted: bool,
/// The meter in dBFS, after the gain.
pub level: f32,
@@ -60,6 +70,7 @@ pub struct StudioAudio {
pub struct StudioLayer {
/// "1280x720"; empty: `scale` of the output.
pub size: Arc<str>,
/// The factor on the output's size when `size` is empty.
pub scale: Arc<str>,
/// Frame-rate cap; empty: the output's.
pub fps: Arc<str>,
@@ -72,7 +83,9 @@ pub struct StudioLayer {
/// A viewer of the studio's stream.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioViewer {
/// The viewer's client id.
pub client: i32,
/// The viewer's name.
pub name: Arc<str>,
/// requested, connecting, connected
pub state: Arc<str>,
@@ -81,7 +94,9 @@ pub struct StudioViewer {
/// An entry of a picker (screens, windows, cameras, audio sources).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioPick {
/// The entry's name.
pub name: Arc<str>,
/// The line under the name.
pub detail: Arc<str>,
/// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
pub kind: Arc<str>,
@@ -100,48 +115,70 @@ pub struct StudioStatus {
pub destination: Arc<str>,
/// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent.
pub quality: i32,
/// The words for `quality`.
pub quality_text: Arc<str>,
/// "1080p • 60 FPS • 8,250 kbps"
pub format: Arc<str>,
/// The numbers behind it, for the info button.
pub details: Arc<str>,
/// The stream is live.
pub live: bool,
/// Going live: waiting for the server.
pub starting: bool,
/// "00:12:34"
pub elapsed: Arc<str>,
/// How many watch the stream.
pub viewers: i32,
/// How many viewers the stream has, those who only asked included.
pub participants: i32,
/// Go Live is possible.
pub can_go_live: bool,
/// Why Go Live is off, or what goes wrong.
pub hint: Arc<str>,
/// A recording runs.
pub recording: bool,
/// How long the recording runs: "00:12:34".
pub recorded: Arc<str>,
/// The replay buffer's window (0: off) and what it holds now.
pub replay_seconds: i32,
/// What the replay buffer holds now: "30 s".
pub replay_held: Arc<str>,
/// The output's width in pixels.
pub output_width: i32,
/// The output's height in pixels.
pub output_height: i32,
/// The output's frame rate.
pub fps: i32,
/// The studio is in a window of its own.
pub detached: bool,
/// A window of its own is possible (not on Android).
pub can_detach: bool,
/// The live scene shows a screen, a camera, a window (the phone's cards).
pub screen_shown: bool,
/// The live scene shows a camera.
pub camera_shown: bool,
/// The live scene shows a window.
pub window_shown: bool,
}
/// The stream settings panel (`studio.stream`, `stream.bitrate_kbps`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioForm {
/// Index into the destinations offered (channels to stream to); -1: none.
pub destination: i32,
/// The stream's title.
pub title: Arc<str>,
/// Game or category: it follows the title in the stream's name.
pub game: Arc<str>,
/// Sent to the channel's chat when the stream goes live.
pub message: Arc<str>,
/// The viewers are an overlay in the live scene.
pub show_viewers: bool,
/// The stream chat's last lines are an overlay.
pub show_chat: bool,
/// The title and the game are an overlay.
pub show_now_playing: bool,
/// The stream carries the mixer's sources; off: none.
pub audio: bool,
/// kbit/s of the stream without layers, as typed.
pub bitrate: Arc<str>,
@@ -151,45 +188,69 @@ pub struct StudioForm {
/// sources: `id` -1). Numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSourceForm {
/// The source's id; -1: a new one.
pub id: i32,
/// The source's name.
pub name: Arc<str>,
/// screen, window, portal, camera, image, text, colour or pattern.
pub kind: Arc<str>,
/// The left edge in output pixels.
pub x: Arc<str>,
/// The top edge in output pixels.
pub y: Arc<str>,
/// Empty: the source's own size times `scale`.
pub width: Arc<str>,
/// As `width`, for the height.
pub height: Arc<str>,
/// The factor on the source's own size, where `width` or `height` is empty.
pub scale: Arc<str>,
/// contain, cover, stretch
pub fit: Arc<str>,
/// Pixels cut off the source's left edge.
pub crop_left: Arc<str>,
/// Pixels cut off its top edge.
pub crop_top: Arc<str>,
/// Pixels cut off its right edge.
pub crop_right: Arc<str>,
/// Pixels cut off its bottom edge.
pub crop_bottom: Arc<str>,
/// Percent.
pub opacity: f32,
/// It cannot be moved, resized or cropped.
pub locked: bool,
/// It is shown in the output.
pub visible: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
/// Blur radius in percent of the picture's height.
pub blur: Arc<str>,
/// The picture behind the source, for the background `image`.
pub background_path: Arc<str>,
/// The colour behind the source, for the background `colour`.
pub background_colour: Arc<str>,
/// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources.
pub text: Arc<str>,
/// The text's size in pixels.
pub text_size: Arc<str>,
/// The text's or the colour source's colour.
pub colour: Arc<str>,
/// The image source's file.
pub path: Arc<str>,
/// The camera picture is mirrored.
pub mirror: bool,
}
/// The studio settings dialog (`studio.*` keys and the preview).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSettingsForm {
/// Seconds the replay buffer keeps; 0: off.
pub replay_seconds: Arc<str>,
/// MiB of the replay buffer kept in memory.
pub replay_memory: Arc<str>,
/// The folder of recordings and clips; empty: the default.
pub recording_dir: Arc<str>,
/// The preview's width in pixels.
pub preview_width: Arc<str>,
/// The preview's frame rate.
pub preview_fps: Arc<str>,
}
+6
View File
@@ -56,11 +56,17 @@ pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
/// The channels and clients of the server.
pub presence: &'a Presence,
/// The channels folded shut.
pub collapsed: &'a HashSet<ChannelId>,
/// The clients that are talking.
pub talking: &'a HashSet<u16>,
/// Local volume and mute of the clients we changed.
pub playback: &'a ClientPlaybackMap,
/// The channel we are in.
pub own_channel: Option<ChannelId>,
/// Our own client.
pub own_client: Option<u16>,
/// Search text: only matching channels and clients (and the channels
/// above them) are shown. Empty: everything.
+30 -282
View File
@@ -2,11 +2,12 @@
//! event loop glue and the state the screens share.
//!
//! The screens' logic is elsewhere: servers and the channel tree in
//! `servers.rs`, chat in `chat.rs`, streams in `streams.rs`, the settings
//! page in `settings_page.rs` and `appearance.rs`, the settings pages in
//! `settings_pages/`, the Stream Studio in `studio/`, the view models in the
//! `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, development switches in
//! `dev.rs`.
//! `servers/`, chat in `chat/`, streams in `streams/`, the people, the bell
//! and the search in `social/`, the settings page in `settings_page/` and
//! `appearance.rs`, the settings pages in `settings_pages/`, the Stream
//! Studio in `studio/`, what the screens show and what a move or an event
//! does in the `voelin-ui-vm` crate (`vm`), callbacks in `bind/`,
//! development switches in `dev/`.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
@@ -23,18 +24,15 @@ use voelin_core::settings::{
AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING,
Settings,
};
use voelin_core::{
AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState,
};
use voelin_model::ChatTarget;
use voelin_core::{AudioSettings, Command, Engine, Event, History};
use voelin_platform::crash;
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
use crate::bind::rows::Rows;
use crate::hotkey::GlobalPtt;
use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys};
use crate::streams::{Share, Watch};
use crate::video::Video;
use crate::streams::Share;
use crate::video::{Decoder, Video};
use crate::vm;
slint::include_modules!();
@@ -119,6 +117,12 @@ impl Secrets for FallbackSecrets {
/// The lines of a chat as the chat view shows them.
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
impl vm::state::Lines for ChatRows {
fn push(&mut self, line: vm::bridge::ChatLine) {
Rows::push(self, line);
}
}
/// A chat of a session (see `voelin_ui_vm::state`).
pub(crate) type Tab = vm::state::Tab<ChatRows>;
@@ -225,13 +229,13 @@ pub(crate) struct App {
pub prefs: Settings,
pub ptt: GlobalPtt,
pub video: Video,
/// Our stream.
/// The capture of our stream (`state.share` has the rest of it).
pub share: Option<Share>,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// The decoder of the stream in the viewer (`state.watch` has the rest).
pub decoder: Option<Decoder>,
/// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev/).
pub demo_ui: bool,
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
@@ -347,7 +351,7 @@ pub fn run(options: RunOptions) -> Result<()> {
let HostedEngine { engine, runtime, mut events } = hosted;
// VOELIN_DATA_DIR isolates the database; the other development
// switches are in dev.rs.
// switches are in dev/.
// A host that names the data directory (Android) has no platform cache
// directory either: avatars and icons go next to the database.
if let Some(dir) = &options.data_dir {
@@ -386,7 +390,7 @@ pub fn run(options: RunOptions) -> Result<()> {
// Creating an identity takes a moment (security level 8).
let identity = tsclientlib::Identity::create();
let origin = voelin_store::IdentityOrigin::Created;
store.add_identity(crate::servers::CREATED_IDENTITY, &identity, origin)?;
store.add_identity(vm::servers::logic::CREATED_IDENTITY, &identity, origin)?;
identity
}
};
@@ -438,7 +442,7 @@ pub fn run(options: RunOptions) -> Result<()> {
ptt,
video,
share: None,
watch: None,
decoder: None,
demo: switches.demo_stream,
demo_ui: switches.demo_ui,
autoshare: switches.autoshare,
@@ -473,7 +477,7 @@ pub fn run(options: RunOptions) -> Result<()> {
if app.demo {
app.start_demo();
}
if let Some(text) = crate::servers::imported_status(&imported) {
if let Some(text) = vm::servers::logic::imported_status(&imported) {
app.set_status(text);
}
});
@@ -512,7 +516,9 @@ pub fn run(options: RunOptions) -> Result<()> {
for id in ids {
app.save_reads(id);
}
app.watch = None;
app.state.watch = None;
app.decoder = None;
app.state.share = None;
app.share = None;
if own && !app.demo_ui {
for id in app.state.sessions.keys() {
@@ -627,7 +633,7 @@ impl App {
/// A setting changed, maybe elsewhere (a command, another window): take
/// the values the window keeps copies of. The engine applies audio
/// settings itself.
fn setting_changed(&mut self, key: &str) {
pub(crate) fn setting_changed(&mut self, key: &str) {
if key == AUDIO.name() && !self.state.audio_dirty {
self.state.audio = self.prefs.get(&AUDIO);
// The voice controls follow the transmit mode.
@@ -644,7 +650,7 @@ impl App {
} else if appearance_keys().iter().any(|k| k.name() == key) {
self.apply_appearance();
} else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() {
// A running share mixes the new sources (streams.rs).
// A running share mixes the new sources (streams/bind.rs).
self.share_audio_changed();
} else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() {
self.video.set_decoder_preference(decoder_preference(&self.prefs));
@@ -652,239 +658,6 @@ impl App {
self.page_setting_changed(key);
}
pub(crate) fn handle_event(&mut self, event: Event) {
let touched = self.social_event(&event);
self.dispatch(event);
self.social_refresh(touched);
}
fn dispatch(&mut self, event: Event) {
match event {
Event::State { session, state } => {
let id = session as i64;
let view = self.state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = state.clone();
if state.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if state.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected
{
view.channel_passwords.clear();
view.join_after_connect = None;
}
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept
// when the session ends.
self.load_reads(id);
let off = |voice: VoiceState, observe: ObserveState| {
voice == VoiceState::Disconnected && observe == ObserveState::Off
};
if off(state.voice, state.observe) && !off(was_voice, was_observe) {
self.save_reads(id);
}
let view = self.state.sessions.entry(id).or_default();
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
}
if self.state.current == Some(id) {
if self.track_reading() {
self.refresh_chat();
}
// The voice channel's chat is always at hand, and focused
// once per connection.
if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) {
self.open_chat(ChatTarget::Channel(cid), focus);
self.state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last
// place, which `refresh_servers` shows (voice on another
// server does not take it back at each of its events).
if (state.voice, state.own_channel) != (was_voice, was_channel) {
self.remember_voice(id);
}
self.refresh_servers();
self.refresh_toolbar();
self.refresh_tree();
self.refresh_streams();
self.autoshare();
if self.open_client_pending && self.state.current == Some(id) {
self.open_first_client();
}
self.join_after_connect(id);
}
Event::ServerInfo { session, name, backend, capabilities } => {
self.state.sessions.entry(session as i64).or_default().capabilities = capabilities;
self.adopt_server_name(session as i64, &name);
if self.state.current == Some(session as i64) {
self.set_status(connected_status(&name, &backend));
}
self.refresh_streams();
self.autoshare();
}
Event::Presence { session, presence } => {
let view = self.state.sessions.entry(session as i64).or_default();
// The server chat shows its welcome and host message, with
// their pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection),
// or renamed.
let path = |v: &SessionView| {
v.state.own_channel.map(|c| crate::vm::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
self.apply_client_playback(session as i64);
self.join_after_connect(session as i64);
if renamed && self.remember_voice(session as i64) {
self.refresh_servers();
}
if self.state.current == Some(session as i64) {
if said {
self.fetch_previews(session as i64);
}
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
self.refresh_streams();
if self.open_client_pending {
self.open_first_client();
}
}
}
Event::Talking { session, client, talking } => {
let view = self.state.sessions.entry(session as i64).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => self.state.current == Some(s as i64),
None => self.state.mic_test,
};
if shown && let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
}
Event::MicrophoneTestError { message } => {
self.set_status(format!("Microphone test: {message}"))
}
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !self.state.sessions.entry(id).or_default().has_history() {
self.add_message(id, message);
}
}
Event::ChatHistory { session, target, messages, source, complete } => {
self.history_batch(session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update {
self.gateway_in_use(session as i64, url);
}
self.gateway_extra(session as i64, &update);
self.gateway_update(session as i64, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let view = self.state.sessions.entry(session as i64).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::ServerDetails { session, address, details } => {
self.remember_server_icon(session as i64, &address, details.icon);
self.refresh_servers();
self.refresh_toolbar();
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.state.sessions.entry(session as i64).or_default();
// A file that arrives again is decoded again if it changed.
crate::images::reloaded(&path);
view.avatars.insert(client_uid, path);
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
self.refresh_toolbar();
self.refresh_member_card();
self.refresh_streams();
}
}
Event::IconReady { session, icon, path } => {
let view = self.state.sessions.entry(session as i64).or_default();
crate::images::reloaded(&path);
view.icons.insert(icon, path);
self.refresh_servers();
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_toolbar();
}
}
Event::PictureReady { session, url, path } => {
let view = self.state.sessions.entry(session as i64).or_default();
// The host banner reloads into the same file.
crate::images::reloaded(&path);
view.pictures.insert(url, path);
if self.state.current == Some(session as i64) {
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
self.refresh_member_card();
}
}
Event::Transfer { session, transfer, state } => {
self.transfer_progress(session as i64, transfer, state);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
self.state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
self.refresh_member_card();
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if self.demo_ui => {}
Event::Error { message, .. } => self.set_status(message),
Event::JoinFailed { session, channel, reason } => {
self.join_failed(session as i64, channel, reason);
}
Event::SettingChanged { key } => self.setting_changed(&key),
Event::SettingRejected { key, message } => {
self.set_status(format!("Setting {key}: {message}"));
}
// The Stream Studio's stream (studio/).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => {
self.studio_viewers(viewers);
}
event => self.stream_event(event),
}
}
/// Once a second.
fn tick(&mut self) {
self.tick_streams();
@@ -903,36 +676,11 @@ impl App {
}
}
/// The status line once a server answered: "Connected to Nightfall Guild
/// (TeamSpeak 6 6.0.0-beta13.1)".
fn connected_status(name: &str, backend: &BackendInfo) -> String {
format!("Connected to {name} ({})", backend.label())
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_model::ChatTarget;
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(
connected_status("Home", &backend("", "custom 9")),
"Connected to Home (custom 9)"
);
}
use super::*;
#[test]
fn channel_unread_ignores_private_tabs() {
+39 -2
View File
@@ -37,8 +37,14 @@ pub(crate) fn image(picture: &ImageRef) -> Image {
match &**picture {
ImageSource::None => Image::default(),
ImageSource::File { path, .. } => crate::images::file(path),
ImageSource::Rgba { w, h, bytes } => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
// `Pixels` holds `width * height * 4` bytes, which `clone_from_slice`
// needs (it panics otherwise).
ImageSource::Rgba(pixels) => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(
pixels.bytes(),
pixels.width(),
pixels.height(),
))
}
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
@@ -71,3 +77,34 @@ pub(crate) fn model<V, S: for<'a> From<&'a V> + Clone + 'static>(rows: &[V]) ->
pub(crate) fn rows<S: Clone + 'static, V: From<S>>(model: &ModelRc<S>) -> Vec<V> {
slint::Model::iter(model).map(V::from).collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// A picture of pixels shows as wide and as high as it was made, with
/// every pixel in its place: a width that is not the height tells the two
/// apart, and every pixel holds its column and its row.
#[test]
fn a_picture_of_pixels_keeps_its_size_and_its_places() {
let (w, h) = (3u32, 2u32);
let bytes: Vec<u8> = (0..h)
.flat_map(|y| (0..w).flat_map(move |x| [x as u8 + 1, y as u8 + 10, 7, 255]))
.collect();
let picture = image(&ImageSource::rgba(w, h, bytes));
let size = picture.size();
assert_eq!((size.width, size.height), (w, h));
let pixels = picture.to_rgba8().expect("a picture made of pixels");
let at = |x: u32, y: u32| {
let p = pixels.as_slice()[(y * w + x) as usize];
(p.r, p.g, p.b, p.a)
};
assert_eq!(at(0, 0), (1, 10, 7, 255));
assert_eq!(at(2, 0), (3, 10, 7, 255));
assert_eq!(at(0, 1), (1, 11, 7, 255));
assert_eq!(at(2, 1), (3, 11, 7, 255));
// Pixels of another length are no picture (and no panic).
let none = image(&ImageSource::rgba(w, h, vec![0u8; 23]));
assert_eq!((none.size().width, none.size().height), (0, 0));
}
}
File diff suppressed because it is too large. Load diff
+290
View File
@@ -0,0 +1,290 @@
//! The Slint side of the chat: the Bridge writes of the tabs, the lines and
//! the drawers, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::chat::logic`.
use slint::ComponentHandle;
use voelin_core::{HistoryMessage, HistorySource};
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{App, Bridge, Nav, SessionView, Tab};
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::bbcode::LinkKind;
use crate::vm::bridge::{ChatLine, ChatTab};
use crate::vm::chat::logic::{self as logic, LinesFacts};
use voelin_core::settings::CACHE_FETCH_IMAGES;
impl App {
/// Open the chat `target` of the current session, and with `focus` show
/// it ([`logic::open_chat`]).
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
self.transition(|state, cx| logic::open_chat(state, cx, target, focus));
}
/// The index of `target`'s tab in session `id`, opened if new (the
/// engine then sends its history).
pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize {
self.transition(|state, cx| logic::chat_tab(state, cx, id, target))
}
/// The session's tab that tab `index` of the chat strip is
/// (`Bridge.tabs`, [`vm::chat::strip`]).
pub(crate) fn strip_tab(&self, index: i32) -> Option<usize> {
self.models.strip.borrow().get(usize::try_from(index).ok()?).copied()
}
pub(crate) fn select_tab(&mut self, index: usize) {
self.transition(|state, cx| logic::select_tab(state, cx, index));
}
pub(crate) fn close_tab(&mut self, index: usize) {
self.transition(|state, cx| logic::close_tab(state, cx, index));
}
pub(crate) fn send_message(&mut self, text: String) {
self.transition(|state, cx| logic::send_message(state, cx, text));
}
/// A live message of a session without stored history.
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
self.transition(|state, cx| logic::add_message(state, cx, id, message));
}
/// Messages the engine stored: added or updated by their local id.
pub(crate) fn history_batch(
&mut self,
id: i64,
target: &ChatTarget,
messages: Vec<HistoryMessage>,
source: HistorySource,
complete: bool,
) {
self.transition(|state, cx| {
logic::history_batch(state, cx, id, target, messages, source, complete);
});
}
/// The page of messages before the oldest one shown.
pub(crate) fn load_older(&mut self) {
if let Some(sample) = self.transition(logic::load_older) {
// No engine answers in demo mode.
crate::dev::answer_older(sample.session, sample.target, sample.oldest);
}
}
/// What the lines of a chat need besides the state.
fn lines_facts(&self) -> LinesFacts<'_> {
LinesFacts {
// Pictures on the web show only while pictures are fetched and
// shown.
pictures_shown: self.prefs.get(&CACHE_FETCH_IMAGES)
&& self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0,
pokes: &self.social.pokes,
}
}
/// The lines of a tab's messages (`main`) or of its open topic, grouped
/// and with everything the row shows (also the stream chat of the
/// Stream Studio, studio/).
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
logic::lines_of(&self.state, view, tab, main, &self.lines_facts())
}
/// Tabs and the shown tab's messages.
pub(crate) fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(chat) = logic::chat_view(&self.state, &self.lines_facts()) else {
self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]);
*self.models.strip.borrow_mut() = vec![0];
bridge.set_current_tab(0);
bridge.set_current_chat(0);
let empty = self.models.no_chat.model();
if bridge.get_messages() != empty {
bridge.set_messages(empty);
}
bridge.set_unread_index(-1);
return;
};
self.models.tabs.sync(&chat.tabs);
*self.models.strip.borrow_mut() = chat.strip;
if bridge.get_current_tab() != chat.current {
bridge.set_current_tab(chat.current);
}
bridge.set_current_chat(chat.current_chat);
// The tab on screen: its lines are what the chat view shows.
if let Some(view) = self.view() {
let tab = &view.tabs[view.current_tab];
if let Some(lines) = &chat.lines {
tab.lines.sync(lines);
}
let lines = tab.lines.model();
if bridge.get_messages() != lines {
bridge.set_messages(lines);
}
}
bridge.set_unread_index(chat.unread_index);
bridge.set_unread_count(chat.unread_count);
bridge.set_unread_since(chat.unread_since.into());
bridge.set_more_history(chat.more_history);
bridge.set_loading_history(chat.loading_history);
bridge.set_local_history(chat.local_history);
bridge.set_has_pins(chat.has_pins);
bridge.set_has_reactions(chat.has_reactions);
bridge.set_has_topics(chat.has_topics);
bridge.set_pins_loading(chat.pins_loading);
bridge.set_topics_loading(chat.topics_loading);
bridge.set_pins_count(chat.pins_count);
bridge.set_topics_count(chat.topics_count);
self.models.pins.sync(&chat.pins);
self.models.topics.sync(&chat.topics);
bridge.set_current_topic(chat.current_topic);
bridge.set_topic_title(chat.topic_title.into());
self.models.topic_messages.sync(&chat.topic_lines);
}
/// A link in a message was clicked (`masked`: its text shows something
/// else, [`vm::bbcode::is_masked`]). A page on the web opens in the
/// browser, a masked one once the user saw where it goes (Nav.link-open);
/// a TeamSpeak link in Voelin ([`App::open_link`]).
pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) {
match vm::bbcode::classify_link(link) {
LinkKind::Web(url) if masked => {
if let Some(ui) = self.ui.upgrade() {
let nav = ui.global::<Nav>();
nav.set_link_host(vm::bbcode::link_host(&url).into());
nav.set_link_url(url.into());
nav.set_link_open(true);
}
}
LinkKind::Web(url) => {
if let Err(e) = self.open_url(&url) {
self.set_status(format!("Cannot open the link: {e}"));
}
}
LinkKind::Server(url) => self.open_link(&url),
// A file opens from its card.
LinkKind::File | LinkKind::Refused => {}
}
}
// What is read.
/// The current chat came on screen or left it (`Nav.chat-shown`).
pub(crate) fn chat_shown_changed(&mut self) {
self.transition(logic::chat_shown_changed);
}
/// The window gained or lost the focus (winit's events: the desktop
/// only).
#[cfg(not(target_os = "android"))]
pub(crate) fn window_focused(&mut self, focused: bool) {
self.transition(|state, cx| logic::window_focused(state, cx, focused));
}
/// The current chat is read (the bar over its messages): the divider
/// goes.
pub(crate) fn mark_read(&mut self) {
self.transition(logic::mark_read);
}
/// Store where every chat of session `id` was read (it ended, or the
/// app exits).
pub(crate) fn save_reads(&mut self, id: i64) {
self.transition(|state, cx| logic::save_reads(state, cx, id));
}
// Gateway features of a chat.
/// Add or remove our reaction to a message.
pub(crate) fn react(&mut self, key: i32, emoji: String) {
self.transition(|state, cx| logic::react(state, cx, key, emoji));
}
pub(crate) fn pin(&mut self, key: i32, on: bool) {
self.transition(|state, cx| logic::pin(state, cx, key, on));
}
/// Ask the gateway for the current chat's pins and topics until it sent
/// them, so the header counts them before their drawers are opened.
pub(crate) fn prefetch_counts(&mut self) {
self.transition(|state, cx| logic::prefetch_counts(state, cx));
}
/// Open the pins of the current chat (loading them once).
pub(crate) fn open_pins(&mut self) {
self.transition(|state, cx| logic::open_pins(state, cx));
}
/// Highlight a pinned message in the chat.
pub(crate) fn jump_to_pin(&mut self, key: i32) {
let row = self.transition(|state, cx| logic::jump_to_pin(state, cx, key));
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
let bridge = ui.global::<Bridge>();
bridge.set_jump_index(row as i32);
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
}
}
/// The topics drawer's search.
pub(crate) fn search_topics(&mut self, text: String) {
self.transition(|state, cx| logic::search_topics(state, cx, text));
}
pub(crate) fn open_topics(&mut self) {
self.transition(|state, cx| logic::open_topics(state, cx));
}
/// Show a topic's messages (`-1` goes back to the chat).
pub(crate) fn open_topic(&mut self, id: i32) {
self.transition(|state, cx| logic::open_topic(state, cx, id));
}
pub(crate) fn send_topic_message(&mut self, text: String) {
self.transition(|state, cx| logic::send_topic_message(state, cx, text));
}
/// Start a topic from a message (`key` < 0: a standalone topic).
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
self.transition(|state, cx| logic::create_topic(state, cx, key, title));
}
// Files in chat.
/// Download a file a message links, into the download folder.
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
let dir = dirs::download_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
self.transition(|state, cx| logic::download_file(state, cx, key, index, &dir));
}
/// Attach a file to the current channel chat: ask for one, upload it
/// into the channel and post its link.
pub(crate) fn attach_file(&mut self) {
let (id, channel) = match logic::attach_target(&self.state) {
Ok(Some(target)) => target,
Ok(None) => return,
Err(reason) => {
self.set_status(reason);
return;
}
};
if !voelin_platform::files::available() {
self.set_status("No file chooser on this platform.");
return;
}
let runtime = self.engine.runtime().clone();
runtime.spawn(async move {
let picked = voelin_platform::files::pick_file("Attach a file").await;
crate::app::later(move |app| match picked {
Ok(Some(path)) => app.upload(id, channel, path),
Ok(None) => {}
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
});
});
}
/// Upload a file into a channel and link it in the chat once it is up.
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: std::path::PathBuf) {
self.transition(|state, cx| logic::upload(state, cx, id, channel, from));
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Chat: tabs per session (server, channels, private chats), their
//! messages, and what a gateway adds to them (pins, reactions, topics).
//! What the state does is in `voelin_ui_vm::chat::logic`; `bind` has the
//! Bridge writes and the models.
//!
//! The chat strip shows the server's and the channels' tabs; a private chat
//! is the current tab only while the messages page shows it (messages.rs).
//! The engine keeps the history: a tab holds the messages it was given,
//! ordered by `(ts_ms, id)`, and the lines of the selected tab are rebuilt
//! from them and synced ([`crate::bind::rows::Rows::sync`]), which touches
//! only the rows that changed.
mod bind;
+506
View File
@@ -0,0 +1,506 @@
//! The Slint side of the development switches: the window's size, the
//! screenshot, the screens opened at start (`VOELIN_OPEN`), and the sample
//! data fed through the app's own events. The sample data itself is in
//! `voelin_ui_vm::dev::logic`.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use voelin_core::{Event, HistoryMessage, HistorySource, JoinFailure};
use voelin_model::ChatTarget;
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
use crate::social::now_ms;
use crate::vm::dev::logic::{self, DEMO};
/// The switches read at start.
#[derive(Clone, Debug, Default)]
pub(crate) struct Switches {
pub demo_stream: bool,
pub demo_ui: bool,
pub autoshare: bool,
pub open_client: bool,
open: Vec<String>,
autoconnect: Option<String>,
screenshot: Option<std::path::PathBuf>,
screenshot_delay: u64,
window_size: Option<(f32, f32)>,
}
fn flag(name: &str) -> bool {
std::env::var(name).is_ok_and(|v| v == "1")
}
/// `390x844` → (390, 844).
fn parse_size(text: &str) -> Option<(f32, f32)> {
let (w, h) = text.split_once(['x', 'X'])?;
Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
}
impl Switches {
pub fn from_env() -> Self {
let open: Vec<String> = std::env::var("VOELIN_OPEN")
.unwrap_or_default()
.split(',')
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.collect();
Self {
demo_stream: flag("VOELIN_DEMO_STREAM"),
demo_ui: flag("VOELIN_DEMO_UI"),
autoshare: std::env::var("VOELIN_AUTOSHARE").is_ok_and(|v| v == "test-pattern"),
open_client: open.iter().any(|o| o == "client"),
open,
autoconnect: std::env::var("VOELIN_AUTOCONNECT").ok(),
screenshot: std::env::var_os("VOELIN_SCREENSHOT").map(Into::into),
screenshot_delay: std::env::var("VOELIN_SCREENSHOT_DELAY")
.ok()
.and_then(|d| d.parse().ok())
.unwrap_or(4),
window_size: std::env::var("VOELIN_WINDOW_SIZE").ok().as_deref().and_then(parse_size),
}
}
}
fn section(name: &str) -> SettingsSection {
match name {
"1" | "keybinds" | "ptt" => SettingsSection::Keybinds,
"2" | "streaming" => SettingsSection::Streaming,
"3" | "privacy" => SettingsSection::Privacy,
"4" | "appearance" => SettingsSection::Appearance,
"5" | "account" => SettingsSection::Account,
"6" | "profiles" | "identities" => SettingsSection::Profiles,
"7" | "devices" => SettingsSection::Devices,
"8" | "notifications" => SettingsSection::Notifications,
"9" | "integrations" => SettingsSection::Integrations,
"10" | "advanced" => SettingsSection::Advanced,
_ => SettingsSection::Voice,
}
}
fn mobile_tab(name: &str) -> MobileTab {
match name {
"home" => MobileTab::Home,
"servers" => MobileTab::Servers,
"activity" => MobileTab::Activity,
"you" => MobileTab::You,
_ => MobileTab::Chat,
}
}
/// Timers that must live while the window runs.
pub(crate) struct Running {
_screenshot: Option<slint::Timer>,
_resize: Option<slint::Timer>,
_scroll: Option<slint::Timer>,
_more: Option<slint::Timer>,
}
/// Apply the switches once the app is set up.
pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
if let Some((w, h)) = switches.window_size {
ui.window().set_size(slint::LogicalSize::new(w, h));
}
if switches.demo_ui {
with_app(demo_ui);
}
match switches.autoconnect.as_deref() {
Some("voice") => {
with_app(|app| app.connect_voice());
}
Some("observe") => {
with_app(|app| {
if let Some(id) = app.state.current {
app.observe(id);
}
});
}
_ => {}
}
let nav = ui.global::<Nav>();
for open in &switches.open {
let (what, arg) = open.split_once(':').unwrap_or((open.as_str(), ""));
match what {
"home" => nav.invoke_show(Page::Home),
"server" => {
nav.invoke_show(Page::Server);
// The server chat, which starts with the welcome message.
if arg == "chat" {
with_app(|app| app.select_tab(0));
}
}
"settings" => nav.invoke_open_settings(section(arg)),
"about" => nav.invoke_open_about(),
"share" => {
nav.invoke_open_share();
// The sample share of the test pattern, live at once.
if arg == "live" && switches.demo_ui {
with_app(|app| app.demo_share());
}
}
// The current server's dialog, Advanced open.
"bookmark" if arg == "edit" => {
if let Some(id) = with_app(|app| app.state.current).flatten() {
nav.invoke_edit_server(id as i32);
}
}
// `join`: the same dialog (Join a server was one of its own).
"bookmark" | "join" => nav.invoke_add_server(),
"emoji" => nav.set_emoji_open(true),
"panel" => nav.set_right_panel_open(true),
"no-panel" => nav.set_right_panel_open(false),
"tab" => nav.set_mobile_tab(mobile_tab(arg)),
"voice" => {
nav.invoke_show_voice(true);
// The smaller stage, for this run only.
if arg == "compact" {
nav.set_voice_compact(true);
}
}
"pins" => nav.invoke_show_pins(true),
// Opened once laid out (below).
"more" => {}
// The phone's members page.
"members" => nav.set_members_open(true),
// What Android hands over: a tapped voice notification, text
// shared to the app.
"notification" => crate::inbox::request(crate::inbox::Request::ShowVoice),
"shared" => crate::inbox::request(crate::inbox::Request::Share {
text: Some(arg.to_owned()),
files: Vec::new(),
}),
"topics" => nav.invoke_show_topics(true),
"topic" => {
with_app(|app| {
app.open_topic(arg.parse().unwrap_or(1));
// No gateway answers in demo mode.
if switches.demo_ui {
app.handle_event(logic::topic_history(now_ms()));
}
});
}
"member" => {
with_app(|app| app.open_first_member());
}
// After `friends` the contact path (Kairo without a contact
// chosen), else the member card's.
"poke" => {
let friends = nav.get_page() == Page::Friends;
with_app(|app| {
if friends {
let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into());
app.contact_action(&uid, "poke");
} else {
app.open_first_member();
app.member_action("poke");
}
});
}
"channel-password" => {
with_app(|app| open_channel_password(app, arg == "wrong"));
}
// A screenshot cannot hover.
"actions" => nav.set_show_actions(true),
// Home as before the first server, over the sample data.
"first-run" => nav.set_first_run(true),
// `end`: further back, so the divider is above the view.
"unread" => {
with_app(|app| open_unread(app, if arg == "end" { 10 } else { 5 }));
}
"link-confirm" => {
let url = if arg.is_empty() { logic::DEMO_RAID_BOARD } else { arg };
with_app(|app| app.open_link_text(url, true));
}
// As a link from the platform comes.
"link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())),
"watch" | "popout" => {
with_app(|app| {
if switches.demo_ui {
app.demo_watch();
} else {
app.watch_first_stream();
}
if what == "popout" {
app.viewer_pop_out();
}
});
}
"theatre" => nav.set_theatre(true),
// Home, friends, messages, events, the bell, the search.
"friends" => {
with_app(|app| app.select_contact(arg.to_owned()));
nav.invoke_show(Page::Friends);
}
"messages" | "dm" => {
let uid = if arg.is_empty() { "demo-3" } else { arg };
with_app(|app| app.open_dm_with(Some(logic::DEMO), uid));
nav.invoke_show(Page::Messages);
}
"inbox" => {
nav.set_dm_tab(2);
with_app(|app| app.dm_tab(2));
nav.invoke_show(Page::Messages);
}
"library" => nav.invoke_show(Page::Library),
"events" => nav.invoke_show(Page::Events),
"event-form" => nav.invoke_create_event(),
"search" => nav.invoke_open_search(arg.into()),
"notifications" => nav.set_notifications_open(true),
"offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()),
"picture" => {
let picture = logic::demo_picture(1280, 720, 16);
let image = crate::images::picture("demo:lightbox", &picture);
nav.set_lightbox(image);
nav.set_lightbox_open(true);
}
// The camera preview of the settings (the test pattern).
"camera" => {
with_app(|app| {
app.start_camera();
app.refresh_pages();
});
}
"studio" => {
if arg != "window" {
nav.invoke_open_studio();
}
with_app(|app| app.studio_dev(arg));
}
// Opened once connected (settings_page/bind.rs).
"client" => {}
other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
}
}
// A window manager can refuse the size set before the window opened,
// so ask again once it is up. (Under `xvfb-run` in a Wayland session,
// remove WAYLAND_DISPLAY, or winit opens the window on the desktop.)
let resize = switches.window_size.map(|(w, h)| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 / 2),
move || {
if let Some(ui) = weak.upgrade() {
ui.window().set_size(slint::LogicalSize::new(w, h));
}
},
);
timer
});
// `unread`: up to the divider once the list is laid out (after the
// resize above).
let scroll = switches.open.iter().any(|o| o == "unread").then(|| {
late(ui, switches, |ui| {
let bridge = ui.global::<Bridge>();
bridge.set_jump_index(bridge.get_unread_index());
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
})
});
// `more`: the phone voice screen's More menu (a screenshot cannot tap).
let more = switches.open.iter().any(|o| o == "more").then(|| {
late(ui, switches, |ui| {
let nav = ui.global::<Nav>();
nav.set_more_requests(nav.get_more_requests().wrapping_add(1));
})
});
let screenshot = switches.screenshot.clone().map(|path| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_secs(switches.screenshot_delay),
move || {
if let Some(ui) = weak.upgrade() {
if let Err(e) = save_screenshot(&ui, &path) {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
// Also when the studio's or the stream's own window is
// open.
let _ = slint::quit_event_loop();
}
},
);
timer
});
Running { _screenshot: screenshot, _resize: resize, _scroll: scroll, _more: more }
}
/// A timer that runs `action` at three quarters of the screenshot delay, once
/// the window has its size and the screens are laid out.
fn late(
ui: &MainWindow,
switches: &Switches,
action: impl Fn(&MainWindow) + 'static,
) -> slint::Timer {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 * 3 / 4),
move || {
if let Some(ui) = weak.upgrade() {
action(&ui);
}
},
);
timer
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
let mut image = ui.window().take_snapshot()?;
let window = with_app(|app| app.studio_snapshot().or_else(|| app.viewer_snapshot())).flatten();
if let Some(window) = window {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
save_png(&window, &path.with_file_name(format!("{stem}-window.png")))?;
paste(&mut image, &window);
}
save_png(&image, path)
}
/// Draw `top` over the bottom right of `image` with a border, as a second
/// window sits on a desktop.
fn paste(image: &mut SharedPixelBuffer<Rgba8Pixel>, top: &SharedPixelBuffer<Rgba8Pixel>) {
let (w, h) = (image.width() as usize, image.height() as usize);
let (tw, th) = (top.width() as usize, top.height() as usize);
let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24));
let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff };
let pixels = image.make_mut_slice();
for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) {
for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) {
let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0));
pixels[y * w + x] =
if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border };
}
}
}
fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Result<()> {
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut encoder = png::Encoder::new(file, image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header()?.write_image_data(image.as_bytes())?;
Ok(())
}
/// The current chat's read marker `back` messages before its end
/// ([`logic::unread_from`]), its "New" divider shown (`VOELIN_OPEN=unread`).
fn open_unread(app: &mut App, back: usize) {
if logic::unread_from(&mut app.state, back) {
app.refresh_chat();
app.refresh_servers();
}
}
/// `VOELIN_OPEN=channel-password`: join the current server's first locked
/// channel, which asks for its password; `wrong` as if the server had
/// refused one.
fn open_channel_password(app: &mut App, wrong: bool) {
let Some((session, channel)) = logic::first_locked_channel(&app.state) else { return };
if wrong {
if let Some(view) = app.view_mut() {
view.channel_passwords.insert(channel, "guess".into());
}
app.join_failed(session, channel, JoinFailure::Password);
} else {
app.join_channel(session, channel);
}
}
/// Sample data through the same events a server would send.
fn demo_ui(app: &mut App) {
app.state.bookmarks = logic::bookmarks();
app.state.settings.last_voice = Some(logic::last_voice());
app.state.current = Some(DEMO);
for event in logic::server_events() {
app.handle_event(event);
}
demo_pictures(app);
for event in logic::chat_events(now_ms()) {
app.handle_event(event);
}
demo_social(app);
// No toast over the screenshots.
app.set_status("");
app.refresh_all();
}
/// Avatars, icons, banners and badges as the engine reports them once they
/// are in its cache (here a folder of synthetic pictures in the temporary
/// directory).
fn demo_pictures(app: &mut App) {
let dir = std::env::temp_dir().join("voelin-demo-pictures");
let _ = std::fs::create_dir_all(&dir);
let address = app.bookmark(DEMO).map(|b| b.address.clone()).unwrap_or_default();
let events = logic::pictures(&address, |name, png| {
let path = dir.join(name);
let _ = std::fs::write(&path, png);
path
});
for event in events {
app.handle_event(event);
}
}
/// Sample people, private chats, pokes, notifications, events, a picture
/// and recordings for the home, friends, messages, events and settings
/// screens (`VOELIN_DEMO_UI`).
fn demo_social(app: &mut App) {
let now = now_ms();
// The second sample server is observed: a few people there.
for event in logic::lounge_events() {
app.handle_event(event);
}
app.handle_event(Event::ContactsChanged { contacts: Arc::new(logic::contacts(now)) });
for (uid, since) in logic::online_since(now) {
app.social.online_since.insert(uid.into(), since);
}
for event in logic::private_chat_events(now) {
app.handle_event(event);
}
let (server_uid, chat, bookmark) = logic::stored_chat(now);
app.social.dm.stored.push((server_uid.into(), chat));
app.social.dm.bookmark_of.insert(server_uid.into(), bookmark);
logic::read_samples(&mut app.state);
let (poke, ts_ms) = logic::poke(now);
app.handle_event(poke);
if let Some(p) = app.social.pokes.last_mut() {
p.ts_ms = ts_ms;
}
app.handle_event(logic::offline_messages(now));
logic::link_previews(&mut app.state);
for event in logic::gateway_events(now) {
app.handle_event(event);
}
for n in logic::notices() {
app.notify(n.kind, n.title, n.body, n.target, n.name, n.uid);
}
logic::age_notices(&mut app.social, now);
app.refresh_notices();
app.models.social.recordings.sync(&logic::recordings());
app.refresh_chats();
app.refresh_people();
app.refresh_home();
}
/// Answer [`App::load_older`] in demo mode (no engine runs) with
/// [`logic::demo_older`], a moment later as a server would.
pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option<HistoryMessage>) {
slint::Timer::single_shot(Duration::from_millis(600), move || {
let now = now_ms();
let (messages, complete) = logic::demo_older(&target, oldest.as_ref(), now);
with_app(|app| {
app.handle_event(Event::ChatHistory {
session: session as u64,
target,
messages,
source: HistorySource::Gateway,
complete,
});
});
});
}
+67
View File
@@ -0,0 +1,67 @@
//! Development switches (environment variables), for trying screens and
//! taking screenshots without a server:
//!
//! - `VOELIN_DATA_DIR=<dir>`: the database (app.rs).
//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start.
//! - `VOELIN_SCREENSHOT=<png>`: save the window after
//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit.
//! - `VOELIN_WINDOW_SIZE=<w>x<h>`: the window's size (e.g. `390x844` for the
//! phone layout).
//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older
//! messages answer scrolling up) and streams, no server needed (nothing is
//! stored).
//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
//! - `VOELIN_OPEN=<what>[,<what>...]`: open screens on start: `home`,
//! `server` (`server:chat`: its server chat), `settings[:<section>]`
//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`,
//! `share`, `bookmark` (add a server, also `join`;
//! `bookmark:edit` the current one, Advanced open),
//! `emoji` (the picker), `client` (the volume dialog of the first other
//! client once connected), `panel` / `no-panel` (the members panel),
//! `voice` (the voice channel view; on the phone its own screen;
//! `voice:compact` with the smaller stage, not stored),
//! `more` (after `voice` on the phone: the voice screen's More menu,
//! opened once the screen is laid out),
//! `members` (the phone's members page), `notification` (a tapped voice
//! notification), `shared:<text>` (text shared to the app on Android),
//! `pins`, `topics` (the drawers),
//! `topic:<id>` (a topic's messages), `member` (the member card of the
//! first other client), `poke` (the poke dialog: for the contact shown
//! after `friends`, else for the first other client, its card open),
//! `channel-password` (the password dialog of the first locked channel,
//! the sample's Officers; `channel-password:wrong` as after a refused
//! one), `actions` (the last message's actions, as if hovered),
//! `first-run` (home's banner as before the first server, over the
//! sample data),
//! `unread` (the current chat read up to five messages before its end:
//! the "New" divider, scrolled up to; `unread:end` ten messages before,
//! at the list's end, under the bar that counts the new messages),
//! `link-confirm[:<url>]` (the question before a masked link opens, by
//! default the sample's raid board), `link:<url>` (a TeamSpeak link
//! opened: the server dialog filled in from it, or in voice on its
//! server a move into its channel), `watch` (the first stream; with
//! sample data the local test pattern in its place), `theatre` (after
//! `watch`: in theatre mode), `popout` (`watch` in a window of its own),
//! `tab:<home|servers|chat|activity|you>` (phone layout); `friends[:<uid>]`,
//! `messages[:<uid>]` (a private chat), `inbox` (offline messages),
//! `library`, `events`, `event-form`, `search[:<text>]`,
//! `notifications` (the bell), `offline` (an offline message), `picture`
//! (a chat picture opened large), `camera` (the settings' camera
//! preview); settings sections also `account`,
//! `profiles` (also `identities`), `devices`, `notifications`,
//! `integrations`, `advanced` (5-10);
//! `studio[:<what>]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
//! studio from synthetic sources), `studio:window` in a window of its own,
//! `studio:live` going live (also with a screen opened after it:
//! `studio:live,server,voice` shows our stream's card with the studio's
//! picture), `studio:record`, or a dialog: `studio:source`,
//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`.
//! A screenshot also saves the studio's window, or the stream's
//! (`<name>-window.png`), and draws it over the main window.
//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up.
//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting
//! everyone) once connected to a TeamSpeak 6 server.
mod bind;
pub(crate) use bind::{Switches, answer_older, start};
+3 -99
View File
@@ -1,16 +1,16 @@
//! What a server's gateway tells besides chat: its events (the events
//! page, RSVP, reminders), the stream directory and the activity feed (the
//! home page), our permissions there, its configuration (gateway
//! administration). The pins, reactions and topics are in `chat.rs`.
//! administration). The pins, reactions and topics are in `chat/`.
use std::sync::Arc;
use slint::{ComponentHandle, SharedString};
use voelin_core::{Command, GatewayRequest, GatewayUpdate};
use voelin_core::{Command, GatewayRequest};
use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature};
use crate::app::{App, Bridge};
use crate::social::{NoticeKind, NoticeTarget, now_ms};
use crate::social::now_ms;
use crate::vm;
use crate::vm::bridge::{EventForm, EventItem};
use crate::vm::social::{date_block, event_when, format_local, parse_local, soon};
@@ -23,102 +23,6 @@ impl App {
}
}
/// Keep what a gateway update tells these screens (before the chat
/// handles its part).
pub(crate) fn gateway_extra(&mut self, id: i64, update: &GatewayUpdate) {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut self.state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
let has = |f: &str| capabilities.iter().any(|c| c == f);
ask.push(GatewayRequest::Permissions { channel: None });
if has(feature::EVENTS) {
ask.push(GatewayRequest::Events { query: EventQuery::default() });
}
if has(feature::STREAMS) {
ask.push(GatewayRequest::Streams);
}
if has(feature::ACTIVITY) {
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
}
}
U::Disconnected { .. } => {
extra.directory.clear();
extra.events.clear();
extra.events_loaded = false;
extra.activity.clear();
extra.actions.clear();
extra.config.clear();
extra.perms.clear();
}
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
U::Events { events } => {
extra.events = events.clone();
extra.events.sort_by_key(|e| e.spec.start_ms);
extra.events_loaded = true;
}
U::Event { event } => {
match extra.events.iter().position(|e| e.id == event.id) {
Some(i) => extra.events[i] = event.clone(),
None => extra.events.push(event.clone()),
}
extra.events.sort_by_key(|e| e.spec.start_ms);
}
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
U::EventReminder { event, starts_in_ms } => {
remind = Some((event.clone(), *starts_in_ms))
}
U::Streams { streams } => extra.directory = streams.clone(),
U::StreamStarted { stream }
| U::StreamUpdated { stream }
| U::StreamRegistered { stream } => {
extra.directory.retain(|e| e.id != stream.id);
extra.directory.push(stream.clone());
}
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
U::Activity { entries, .. } => extra.activity = entries.clone(),
U::ActivityAdded { entry } => {
extra.activity.insert(0, entry.clone());
extra.activity.truncate(100);
}
U::Config { entries } => extra.config = entries.clone(),
U::ConfigValue { entry } => {
match extra.config.iter().position(|e| e.key == entry.key) {
Some(i) => extra.config[i] = entry.clone(),
None => extra.config.push(entry.clone()),
}
}
U::PermRules { rules } => extra.perms = rules.clone(),
_ => return,
}
for request in ask {
self.gateway_to(id, request);
}
if let Some((event, starts_in_ms)) = remind {
let minutes = starts_in_ms / 60_000;
let title = if minutes <= 0 {
format!("{} starts now", event.spec.title)
} else {
format!("{} starts in {minutes} min", event.spec.title)
};
let body = format!("on {}", self.server_name(id));
self.notify(
NoticeKind::Event,
title,
body,
NoticeTarget::Event(id, event.id),
event.creator.name.clone(),
Some(event.creator.uid.clone()),
);
}
self.refresh_home();
self.refresh_events();
self.refresh_gateways();
}
/// The events page of the current server was opened.
pub(crate) fn open_events(&mut self) {
let Some(id) = self.state.current else { return };
+1 -23
View File
@@ -1,7 +1,7 @@
//! The home page (design mockup 01): where we were with voice last, live
//! streams on our servers, what is happening there (events, scheduled
//! streams, server news), and the Library of recordings and clips.
//! Friends and the unread mentions are in `social.rs`, the recent chats in
//! Friends and the unread mentions are in `social/`, the recent chats in
//! `messages.rs`.
use std::path::{Path, PathBuf};
@@ -10,7 +10,6 @@ use slint::ComponentHandle;
use voelin_core::VoiceState;
use crate::app::{App, Bridge, Page};
use crate::settings::LastVoice;
use crate::vm;
use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem};
use crate::vm::home::ResumeAction;
@@ -269,27 +268,6 @@ impl App {
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub(crate) fn remember_voice(&mut self, session: i64) -> bool {
if self.demo_ui {
return false;
}
let Some(view) = self.state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = vm::tree::channel_path(&view.presence, cid);
let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false };
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if self.state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
self.state.settings.last_voice = Some(last);
self.store_settings();
true
}
/// The folder of recordings and clips.
fn recordings_dir(&self) -> PathBuf {
voelin_core::studio::recording_dir(&self.prefs)
+335
View File
@@ -0,0 +1,335 @@
//! The Slint side of the transitions of `voelin-ui-vm`: what they ask of
//! the front end while they run ([`SlintHost`]) and doing what their
//! [`Update`] says ([`App::perform`]). The state changes are in the view
//! model crate; this is where the engine, the store and the window are
//! touched for them.
use slint::ComponentHandle;
use tracing::{debug, warn};
use voelin_core::Event;
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_store::{ChatRead, ChatTarget as StoredTarget, Store};
use crate::app::{App, AppState, Bridge, MainWindow, Nav, Page};
use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB};
use crate::social::Social;
use crate::studio::StudioState;
use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
/// What the transitions ask while they run: the window, the store and the
/// settings, borrowed from the app besides its state.
pub(crate) struct SlintHost<'a> {
pub demo_ui: bool,
pub watching: bool,
/// The private chat the messages page has open: session and peer.
pub dm: Option<(i64, String)>,
pub ui: &'a slint::Weak<MainWindow>,
pub store: &'a Store,
pub prefs: &'a Settings,
pub studio: &'a StudioState,
}
impl Host for SlintHost<'_> {
fn demo_ui(&self) -> bool {
self.demo_ui
}
fn chat_shown(&self) -> bool {
self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_chat_shown())
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
std::env::var("VOELIN_AUTOWATCH").is_ok_and(|v| v == "1")
}
fn studio_streams_to(&self, session: i64) -> bool {
self.studio.streams_to(session)
}
fn preview_limit(&self) -> u64 {
u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024
}
fn fetch_images(&self) -> bool {
self.prefs.get(&CACHE_FETCH_IMAGES)
}
fn dm_shown(&self, session: i64, uid: &str) -> bool {
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
&& self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_page() == Page::Messages)
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
self.store.chat_reads(server_uid).map_err(|e| e.to_string())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.store.set_chat_read(server_uid, target, read).map_err(|e| e.to_string())
}
}
impl App {
/// Run `f` with the state and the host, and return what it returns.
pub(crate) fn with_host<R>(&mut self, f: impl FnOnce(&mut AppState, &SlintHost<'_>) -> R) -> R {
self.with_social(|state, _, host| f(state, host))
}
/// Run `f` with the state, the social state and the host.
pub(crate) fn with_social<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R,
) -> R {
let host = SlintHost {
demo_ui: self.demo_ui,
watching: self.state.watch.is_some(),
dm: self.social.dm.open.as_ref().and_then(|open| {
open.session.filter(|_| open.mail.is_none()).map(|s| (s, open.uid.clone()))
}),
ui: &self.ui,
store: &self.store,
prefs: &self.prefs,
studio: &self.studio,
};
f(&mut self.state, &mut self.social, &host)
}
/// An engine event: what it does to the state is in `voelin-ui-vm`
/// ([`crate::vm::events::handle`]), then the update is carried out.
pub(crate) fn handle_event(&mut self, event: Event) {
let update = self.with_social(|state, social, host| {
crate::vm::events::handle(state, social, host, event)
});
self.perform(update);
}
/// Run a transition of the view model on the state, and carry out what
/// it says.
pub(crate) fn transition<R>(&mut self, f: impl FnOnce(&mut AppState, &mut Cx<'_>) -> R) -> R {
let (result, update) = self.with_host(|state, host| {
let mut cx = Cx::new(host);
let result = f(state, &mut cx);
(result, cx.update)
});
self.perform(update);
result
}
/// Like [`App::transition`], for a transition that changes the social
/// state too.
pub(crate) fn social_transition<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &mut Cx<'_>) -> R,
) -> R {
let (result, update) = self.with_social(|state, social, host| {
let mut cx = Cx::new(host);
let result = f(state, social, &mut cx);
(result, cx.update)
});
self.perform(update);
result
}
/// Do what a transition asked for: tell the engine, keep what is to be
/// kept, draw what changed, and hand the rest back to the code that
/// still owns it.
pub(crate) fn perform(&mut self, update: Update) {
let Update {
refresh,
status,
commands,
persist,
reloaded,
input_level,
password,
notices,
warnings,
chats,
watch,
stream,
autoshare,
first_client,
rest,
} = update;
for text in warnings {
warn!("{text}");
}
// What the engine wrote again is decoded again, when it is drawn.
for path in &reloaded {
crate::images::reloaded(path);
}
for command in commands {
self.engine.send(command);
}
// The capture and the decoder.
if let Some(sink) = stream.attach
&& let Some(share) = &self.share
{
share.capture.attach(sink);
}
if stream.drop_share {
self.share = None;
}
if stream.drop_decoder {
self.decoder = None;
}
if stream.leave_fullscreen {
self.set_fullscreen(false);
}
if stream.mixer {
self.mixer_refresh();
}
if let Some(text) = status {
self.set_status(text);
}
for what in persist {
self.keep(what);
}
if let Some((level_db, sending)) = input_level
&& let Some(ui) = self.ui.upgrade()
{
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
if let Some(PasswordPrompt { name, wrong }) = password
&& let Some(ui) = self.ui.upgrade()
{
let nav = ui.global::<Nav>();
nav.set_channel_password_name(name.into());
nav.set_channel_password_error(wrong);
nav.set_channel_password_open(true);
}
for notice in notices {
self.notify(
notice.kind,
notice.title,
notice.body,
notice.target,
notice.name,
notice.uid,
);
}
// What the front end keeps itself comes before the drawing: what
// it changes is on screen then.
if let Some(event) = rest {
self.event_rest(event);
}
self.refresh_parts(refresh);
for (id, target) in chats {
self.studio_chat_changed(id, &target);
}
if let Some(stream) = watch {
self.watch_stream(stream);
}
if autoshare {
self.autoshare();
}
if first_client && self.open_client_pending {
self.open_first_client();
}
}
/// Keep what a transition changed.
fn keep(&mut self, what: Persist) {
match what {
Persist::Bookmark { id, what } => {
let Some(bookmark) = self.state.bookmarks.iter().find(|b| b.id == id) else {
return;
};
match self.store.update_bookmark(bookmark) {
Ok(()) => debug!(server = %bookmark.address, "{what}"),
Err(e) => warn!(%e, "could not keep the bookmark: {what}"),
}
}
Persist::Settings => self.store_settings(),
Persist::Audio => {
if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) {
warn!(%e, "could not store audio settings");
}
}
Persist::Playback => {
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) {
warn!(%e, "could not store client volumes");
}
}
}
}
/// Draw the parts of the window a transition changed.
pub(crate) fn refresh_parts(&mut self, parts: Refresh) {
if parts.servers {
self.refresh_servers();
}
if parts.toolbar {
self.refresh_toolbar();
}
if parts.tree {
self.refresh_tree();
}
if parts.chat {
self.refresh_chat();
}
if parts.streams {
self.refresh_streams();
}
if parts.viewer {
self.refresh_viewer();
}
if parts.member_card {
self.refresh_member_card();
}
if parts.people {
self.refresh_people();
}
if parts.conversations {
self.ask_inboxes();
self.refresh_chats();
}
if parts.home {
self.refresh_home();
}
if parts.dm {
self.refresh_dm();
}
if parts.events {
self.refresh_events();
}
if parts.gateways {
self.refresh_gateways();
}
}
/// The events whose state the view model does not hold: a setting that
/// changed, the studio's stream and the requests of the messages page.
/// [`App::perform`] runs this before it draws, so that what these change
/// is what is drawn.
fn event_rest(&mut self, event: Event) {
match event {
Event::SettingChanged { key } => self.setting_changed(&key),
// The Stream Studio's stream (studio/).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => {
self.studio_viewers(viewers);
}
// The messages page keeps the offline message requests
// (messages.rs); the text of a message is the view model's
// (`social::logic::event`).
Event::OfflineMessages { result: Err(e), .. } => debug!("offline messages: {e}"),
Event::RequestDone { session, request, result } => {
self.request_done(session as i64, request, result);
}
_ => {}
}
}
}
+1
View File
@@ -8,6 +8,7 @@ mod chat;
mod dev;
mod events;
mod home;
mod host;
mod hotkey;
mod identities;
mod images;
+7 -89
View File
@@ -17,11 +17,11 @@ use std::collections::HashMap;
use std::sync::Arc;
use slint::ComponentHandle;
use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, VoiceState};
use voelin_core::{Command, HistoryMessage, OfflineMessageInfo, VoiceState};
use voelin_model::ChatTarget;
use voelin_store::PageQuery;
use crate::app::{App, Bridge, Nav, Page, SessionView, later};
use crate::app::{App, Bridge, Page, SessionView, later};
use crate::vm;
use crate::vm::bridge::{ConversationItem, DmPeer, FileItem, OfflineForm};
use crate::vm::social::{ChatRef, ago, list_time, matches, plain, preview};
@@ -55,8 +55,6 @@ pub(crate) struct Dms {
pub tab: i32,
pub filter: String,
pub open: Option<Open>,
/// The text of the open offline message.
pub mail: Option<OfflineMessage>,
/// Offline message requests in flight: session and what for.
pub requests: HashMap<u64, (i64, &'static str)>,
pub next_request: u64,
@@ -106,24 +104,7 @@ impl App {
/// What we call the peer of a private chat.
pub(crate) fn peer_name(&self, uid: &str, last: Option<&HistoryMessage>) -> String {
if let Some(c) = self.state.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
return c.nickname.clone();
}
if let Some(s) = self.spots_of(uid).first() {
return self.state.sessions[&s.session].nickname(s.client);
}
let from_peer = |m: &HistoryMessage| {
(m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone())
};
last.and_then(from_peer)
.or_else(|| {
self.state.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
(t.target == ChatTarget::Private(uid.to_owned()))
.then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message)))
.flatten()
})
})
.unwrap_or_else(|| uid.chars().take(8).collect())
vm::social::peer_name(&self.state, uid, last)
}
/// Every chat, newest first; then the lists that show them.
@@ -220,11 +201,7 @@ impl App {
ago: ago(ts).into(),
unread: chat.unread,
initials: vm::avatar::initials(&title).into(),
// A server's chat in the server's colour.
tint: match (kind, session) {
(0, Some(s)) => self.server_tint(s),
_ => vm::avatar::tint(&title),
},
tint: vm::servers::logic::conversation_tint(&self.state, kind, session, &title),
avatar,
online,
selected: open.is_some_and(|o| {
@@ -454,7 +431,7 @@ impl App {
mail: None,
stored: !live,
});
self.social.dm.mail = None;
self.social.mail = None;
self.models.social.dm_lines.sync(&[]);
let target = ChatTarget::Private(uid.to_owned());
if let (true, Some(id)) = (live, session) {
@@ -501,18 +478,6 @@ impl App {
self.refresh_dm();
}
/// Whether the private chat with `uid` in `session` is on screen.
pub(crate) fn dm_shown(&self, session: i64, uid: &str) -> bool {
let page = self.ui.upgrade().map(|ui| ui.global::<Nav>().get_page());
page == Some(Page::Messages)
&& self
.social
.dm
.open
.as_ref()
.is_some_and(|o| o.mail.is_none() && o.uid == uid && o.session == Some(session))
}
/// Who the open conversation is with, and what can be done.
pub(crate) fn refresh_dm(&self) {
let Some(ui) = self.ui.upgrade() else { return };
@@ -584,7 +549,7 @@ impl App {
for m in tab.iter().flat_map(|t| t.messages.iter().rev()) {
let message = &m.message.message;
for f in message.file_refs() {
if let Some(image) = view.and_then(|v| crate::previews::image_of(v, &f)) {
if let Some(image) = view.and_then(|v| vm::previews::image_of(v, &f)) {
media.push(image);
continue;
}
@@ -672,7 +637,6 @@ impl App {
mail_subject: mail.as_ref().map(|m| m.subject.clone()).unwrap_or_default().into(),
mail_text: self
.social
.dm
.mail
.as_ref()
.map(|m| plain(&m.text))
@@ -790,7 +754,7 @@ impl App {
mail: Some((session, m.id)),
stored: false,
});
self.social.dm.mail = None;
self.social.mail = None;
let request = self.offline_request(session, "get");
if !self.demo_ui {
self.engine.send(Command::GetOfflineMessage {
@@ -802,20 +766,6 @@ impl App {
self.refresh_chats();
}
pub(crate) fn mail_arrived(&mut self, session: i64, result: Result<OfflineMessage, String>) {
match result {
Ok(m) => {
if let Some(view) = self.state.sessions.get_mut(&session)
&& let Some(info) = view.extra.inbox.iter_mut().find(|i| i.id == m.id)
{
info.read = true;
}
self.social.dm.mail = Some(m);
}
Err(e) => self.set_status(format!("Could not read the offline message: {e}")),
}
}
pub(crate) fn request_done(&mut self, session: i64, request: u64, result: Result<(), String>) {
let Some((_, what)) = self.social.dm.requests.remove(&request) else { return };
match (what, result) {
@@ -855,36 +805,4 @@ impl App {
self.engine.send(Command::ListOfflineMessages { session: id as u64, request });
}
}
/// Pokes from `uid` as lines of their private chat, among its messages
/// (`lines` and `times` in step, oldest first).
pub(crate) fn poke_lines(&self, session: i64, uid: &str) -> Vec<(i64, vm::bridge::ChatLine)> {
self.social
.pokes
.iter()
.enumerate()
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
.map(|(i, p)| {
let text = if p.message.is_empty() {
"👋 poked you".to_owned()
} else {
format!("👋 poked you: {}", p.message)
};
let message = voelin_model::ChatMessage {
target: ChatTarget::Private(uid.to_owned()),
author_name: p.name.clone(),
author_uid: p.uid.clone(),
author_id: None,
text,
ts_ms: p.ts_ms,
via_relay: false,
blocked: false,
};
let mut line = vm::chat::line(&message, None);
line.key = -1_000_000 - i as i32;
line.avatar = self.avatar_of(uid);
(p.ts_ms, line)
})
.collect()
}
}
+5 -3
View File
@@ -42,7 +42,8 @@ impl App {
/// The player into a window of its own.
pub(crate) fn viewer_pop_out(&mut self) {
// One window on Android.
if cfg!(target_os = "android") || self.popout.window.is_some() || self.watch.is_none() {
if cfg!(target_os = "android") || self.popout.window.is_some() || self.state.watch.is_none()
{
return;
}
// The main window's full screen was the player's.
@@ -86,7 +87,7 @@ impl App {
/// The player back into the main window, on the stream's server page.
pub(crate) fn viewer_dock(&mut self) {
let Some(window) = self.close_popout() else { return };
if let Some(watch) = &mut self.watch {
if let Some(watch) = &mut self.state.watch {
watch.shown = true;
}
if let Some(ui) = self.ui.upgrade() {
@@ -95,6 +96,7 @@ impl App {
// The main window may have gone to another server meanwhile: else
// the stream would play on, unseen.
let session = self
.state
.watch
.as_ref()
.and_then(|w| w.session)
@@ -127,7 +129,7 @@ impl App {
self.with_player(|_, window| crate::streams::show_cursor(window, shown));
}
/// A picture of the viewer's window (screenshots, dev.rs).
/// A picture of the viewer's window (screenshots, dev/).
pub(crate) fn viewer_snapshot(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
self.popout.window.as_ref()?.window().take_snapshot().ok()
}
+7 -167
View File
@@ -9,162 +9,16 @@
//! message shows its address.
use std::borrow::Cow;
use std::sync::Arc;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::app::{App, SessionView};
use crate::app::App;
use crate::bind::convert;
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::state::Preview;
use crate::vm::{ImageRef, ImageSource};
/// Whether a file name is a picture the chat shows inline.
pub(crate) fn is_previewable(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
}
/// The key of a link: where the file is.
pub(crate) fn link_key(file: &FileRef) -> String {
format!(
"{}/{}{}{}",
file.server_uid.as_deref().unwrap_or(""),
file.channel,
file.path,
file.name
)
}
/// The decoded picture of a link, if it is there (decoded once, kept by
/// the image cache).
pub(crate) fn image_of(view: &SessionView, file: &FileRef) -> Option<ImageRef> {
let key = link_key(file);
match view.extra.previews.get(&key)? {
Preview::Ready(bytes) => {
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
}
impl App {
/// Download the pictures linked in the current chat of `session` that
/// are not there yet.
/// are not there yet ([`vm::previews::fetch_previews`]).
pub(crate) fn fetch_previews(&mut self, session: i64) {
if self.demo_ui {
return;
}
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
if limit == 0 {
return;
}
self.fetch_web_pictures(session, limit);
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// Channel chats only: a link names its channel's file browser.
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
return;
}
let wanted: Vec<FileRef> = tab
.messages
.iter()
.rev()
.take(200)
.flat_map(|m| m.message.message.file_refs())
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
.collect();
for file in wanted {
let transfer = view.next_transfer;
view.next_transfer += 1;
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
self.engine.send(Command::DownloadChatFile {
session: session as u64,
transfer,
file,
password: None,
to: DownloadTo::Memory,
});
}
}
/// Ask the engine for the pictures on the web (`[img]`) of the current
/// chat of `session` that it has not reported; it fetches each once.
fn fetch_web_pictures(&self, session: i64, limit: u64) {
if !self.prefs.get(&CACHE_FETCH_IMAGES) {
return;
}
let Some(view) = self.state.sessions.get(&session) else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// The server chat starts with the server's messages.
let server = match tab.target {
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
_ => Vec::new(),
};
let wanted: Vec<String> = tab
.messages
.iter()
.rev()
.take(200)
.map(|m| m.message.message.text.as_str())
.chain(server.into_iter().map(|(text, _)| text))
.flat_map(vm::chat::web_pictures)
.filter(|url| !view.pictures.contains_key(url))
.collect();
for url in wanted {
self.engine.send(Command::FetchPicture {
session: session as u64,
url,
max_bytes: limit,
});
}
}
/// A transfer of a picture: `true` if it was one.
pub(crate) fn preview_progress(
&mut self,
session: i64,
transfer: u64,
state: &TransferState,
) -> bool {
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
let Some(view) = self.state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
.iter()
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
.map(|(k, _)| k.clone())
else {
return false;
};
match state {
TransferState::Started { size, .. } if *size > limit => {
view.extra.previews.insert(key, Preview::Failed);
if !self.demo_ui {
self.engine.send(Command::CancelTransfer { session: session as u64, transfer });
}
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if self.state.current == Some(session) {
self.refresh_chat();
}
}
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
view.extra.previews.insert(key, Preview::Failed);
}
_ => {}
}
true
self.transition(|state, cx| vm::previews::fetch_previews(state, cx, session));
}
/// The picture of link `index` of a message of the current chat (its
@@ -175,14 +29,16 @@ impl App {
let message = match tab.message(key) {
Some(message) => Cow::Borrowed(&message.message),
// A line of the server.
None => match crate::chat::server_text(view, tab, key) {
None => match vm::chat::server_text(view, tab, key) {
Some(text) => Cow::Owned(vm::chat::server_message("", text)),
None => return slint::Image::default(),
},
};
let index = index.max(0) as usize;
match message.file_refs().get(index) {
Some(file) => image_of(view, file).map(|i| convert::image(&i)).unwrap_or_default(),
Some(file) => {
vm::previews::image_of(view, file).map(|i| convert::image(&i)).unwrap_or_default()
}
None => vm::chat::picture_link(&message, index)
.and_then(|url| view.pictures.get(&url))
.map(|path| crate::images::file(path))
@@ -190,19 +46,3 @@ impl App {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previewable_names() {
assert!(is_previewable("Banner.PNG"));
assert!(is_previewable("a.webp"));
assert!(!is_previewable("notes.svg"));
assert!(!is_previewable("route.pdf"));
let file =
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
assert_eq!(link_key(&file), "/2/a.png");
}
}
-920
View File
@@ -1,920 +0,0 @@
//! Servers: bookmarks, connecting and observing, the rail, the sidebar's
//! server card and the channel tree.
use std::time::Instant;
use slint::ComponentHandle;
use tracing::{debug, info, warn};
use voelin_core::ts::identity::LaunchImport;
use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use crate::app::{App, Bridge, Nav, SessionView, later};
use crate::bind::convert;
use crate::vm;
use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::{AfterConnect, JoinStep};
/// The name of the identity the app creates when it has none.
pub(crate) const CREATED_IDENTITY: &str = "Default";
/// What to tell the user about the identities imported from the official
/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything.
pub(crate) fn imported_status(report: &LaunchImport) -> Option<String> {
let n = report.added.len();
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() };
Some(match &report.default {
Some(f) if report.replaced => format!(
"You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}",
f.nickname
),
Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname),
None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"),
None => return None,
})
}
/// The bookmark the form describes, over `old` (what the form does not show,
/// like the identity, the default channel or the client version, stays; a
/// new server has none of it). Only the address is needed: the name is the
/// address until the server tells its own (`adopt_server_name`), the
/// nickname `default_nickname`, the gateway is looked up in DNS
/// (`discover_gateway`). A new address drops the gateway and the query
/// login found or set for the old one.
fn bookmark_from_form(
old: Option<&Bookmark>,
form: &BookmarkForm,
default_nickname: impl FnOnce() -> String,
) -> Bookmark {
let mut bookmark = old.cloned().unwrap_or_default();
bookmark.id = form.id as i64;
bookmark.address = form.address.trim().to_string();
if old.is_some_and(|old| old.address != bookmark.address) {
bookmark.cached_server_icon = None;
bookmark.gateway_url = None;
bookmark.gateway_urls.clear();
bookmark.query = None;
}
bookmark.name = match form.name.trim() {
"" => bookmark.address.clone(),
name => name.to_string(),
};
bookmark.nickname = match form.nickname.trim() {
"" => default_nickname(),
nickname => nickname.to_string(),
};
bookmark
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
fn apply_server_icon(
bookmark: &mut Bookmark,
view: &mut SessionView,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
/// Whether observing goes on as it is when discovery changed the gateways
/// kept from `previous` to `found`: the same ones (an older version kept
/// only the one in use), or logged in through `in_use`, still published.
/// What was found is kept for the next start, without a new login now.
fn observing_stays(
previous: &[String],
found: &[String],
in_use: Option<&str>,
observe: ObserveState,
) -> bool {
found == previous
|| (observe == ObserveState::Observing
&& in_use.is_some_and(|url| found.iter().any(|u| u == url)))
}
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel = self
.state
.current
.and_then(|id| self.bookmark(id))
.and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None);
}
/// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for.
pub(crate) fn connect_voice_to(
&mut self,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
let mut options = VoiceOptions::new(&b.address, &b.nickname);
if let Some(spec) = &b.client_version {
// The engine resolves the spec when it connects; asking now tells the
// user at once.
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
self.set_status(format!("Invalid client compatibility version: {error}"));
return false;
}
options.client_version = Some(spec.clone());
}
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = channel;
options.channel_password = channel_password;
options.token = token;
options.audio = true;
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id);
true
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub(crate) fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
/// run: every one the server publishes is kept, best first, and tried in
/// turn; they take the place of a stored one that is no longer published
/// (a gateway that moved, or one typed into an older version, which
/// showed the field). Nothing found keeps what is stored.
pub(crate) fn discover_gateway(&mut self, id: i64) {
if self.demo_ui || !self.state.gateways_looked_up.insert(id) {
return;
}
let Some(b) = self.bookmark(id) else { return };
let address = b.address.clone();
self.engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
}
});
}
/// Gateways were found for the server at `address` (best first); they
/// are kept unless the server changed meanwhile, and the server is
/// observed through them if it is the one shown. Users never hear of
/// them (logged only).
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address)
else {
return;
};
let previous = b.gateways();
let in_use = b.gateway_url.clone();
if !b.set_gateways(urls) {
debug!(server = %b.address, urls = ?b.gateway_urls, elapsed_ms, "gateway found, as kept");
return;
}
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not keep the gateway found");
return;
}
let observe = self.state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let kept = observing_stays(&previous, &b.gateways(), in_use.as_deref(), observe);
info!(server = %b.address, urls = ?b.gateway_urls, ?previous, kept, elapsed_ms, "gateway found");
self.refresh_toolbar();
if kept {
if self.state.current == Some(id) && observe == ObserveState::Off {
self.observe(id);
}
return;
}
// Observed through the old ones: through these now.
if !previous.is_empty() {
self.engine.send(Command::StopObserving { session: id as u64 });
if let Some(view) = self.state.sessions.get_mut(&id) {
view.state.observe = ObserveState::Off;
}
}
if self.state.current == Some(id) {
self.observe(id);
}
}
/// The gateway logged in at `url`: it is the one in use from now on.
pub(crate) fn gateway_in_use(&mut self, id: i64, url: &str) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if !b.gateway_in_use(url) {
return;
}
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not keep the gateway in use");
return;
}
info!(server = %b.address, %url, "gateway in use");
}
/// The server told its name: a server still named by its address takes
/// it, so the address is all a user has to type.
pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address)
else {
return;
};
if name.trim().is_empty() || self.demo_ui {
return;
}
b.name = name.trim().to_owned();
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not name the server");
}
self.refresh_servers();
self.refresh_toolbar();
}
/// Observe the server invisibly, unless it is already: through its
/// gateway, else its own query login. Without either the gateway is
/// looked up first, and observing starts when it is found
/// (`gateway_found`). Asked while still connecting, the engine tries
/// the gateway again sooner.
pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return };
if self.demo_ui {
return;
}
let session = b.id as u64;
let state = self.state.sessions.get(&b.id).map(|v| v.state.observe).unwrap_or_default();
let urls = b.gateways();
match state {
ObserveState::Observing => return,
// The engine decides: the same gateways are not started over,
// at most tried again now.
ObserveState::Connecting => {
if !urls.is_empty() {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
}
return;
}
ObserveState::Off => {}
}
if !urls.is_empty() {
info!(server = %b.address, ?urls, "observing through the gateway");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
} else if let Some(q) = &b.query {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
} else {
self.discover_gateway(b.id);
return;
}
self.set_status("Observing invisibly…");
}
/// Show a server, and observe it.
pub(crate) fn select_server(&mut self, id: i64) {
self.state.current = Some(id);
self.prefetch_counts();
self.track_reading();
self.refresh_all();
self.observe(id);
}
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: self.default_nickname().into(),
..Default::default()
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
/// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned();
let mut bookmark = bookmark_from_form(old.as_ref(), form, || self.default_nickname());
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its
// gateway is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
}
/// The server dialog's Connect: save the server, then connect it with
/// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
/// shown after a failed save would connect the server shown before.
/// Whether it was saved.
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form);
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
return false;
};
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
}
pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
self.save_reads(id);
self.state.sessions.remove(&id);
self.state.gateways_looked_up.remove(&id);
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.state.current = self.state.bookmarks.first().map(|b| b.id);
self.prefetch_counts();
self.track_reading();
self.refresh_all();
}
/// Keep only metadata supplied by the bookmark's current server.
pub(crate) fn remember_server_icon(&mut self, id: i64, address: &str, icon: u32) {
let Some(bookmark) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed =
apply_server_icon(bookmark, self.state.sessions.entry(id).or_default(), address, icon);
if changed
&& !self.demo_ui
&& let Err(error) = self.store.update_bookmark(bookmark)
{
warn!(%error, "could not keep the server icon");
}
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
let current = self
.state
.sessions
.get(&bookmark.id)
.map(|view| view.server_icon_for(&bookmark.address))
.unwrap_or_default();
if current.size().width > 0 {
current
} else {
vm::servers::cached_icon(bookmark, &self.engine.cache())
}
}
/// A server's colour, as the rail shows it ([`vm::servers::tints`]).
pub(crate) fn server_tint(&self, id: i64) -> vm::Rgb {
let tints = vm::servers::tints(&self.state.bookmarks);
self.state.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]).unwrap_or_default()
}
/// The rail: servers with their state, unread count (without private
/// chats) and streams; what the chat strip and the private chats have
/// unread.
pub(crate) fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let tints = vm::servers::tints(&self.state.bookmarks);
let items: Vec<_> = self
.state
.bookmarks
.iter()
.zip(tints)
.map(|(b, tint)| {
let view = self.state.sessions.get(&b.id);
let state = view.map(|v| v.state.clone()).unwrap_or_default();
let unread = view.map_or(0, SessionView::channel_unread);
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
let detail = view
.filter(|v| !v.presence.channels.is_empty())
.map(|v| vm::tree::stats(&v.presence))
.unwrap_or_default();
let product = view.map(|v| v.extra.product.clone()).unwrap_or_default();
let icon = self.server_list_icon(b);
vm::servers::item(b, &state, unread, live, detail, product, icon, tint)
})
.collect();
self.models.servers.sync(&items);
bridge.set_last_place(self.last_place(&items).into());
bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32));
// Private chats count on the messages page (and the phone's Home).
bridge.set_unread_total(self.view().map_or(0, SessionView::channel_unread));
bridge.set_dm_unread(self.dm_unread());
}
/// The server card, the voice controls and who we are.
pub(crate) fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.state.current.and_then(|id| self.bookmark(id));
let view = self.view();
let state = view.map(|v| v.state.clone()).unwrap_or_default();
bridge.set_server_icon(convert::image(
&bookmark.map(|b| self.server_list_icon(b)).unwrap_or_default(),
));
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty())
&& (state.voice == VoiceState::Connected || state.observe == ObserveState::Observing);
bridge.set_server_stats(
view.filter(|_| has_presence)
.map(|v| vm::tree::stats(&v.presence))
.unwrap_or_default()
.into(),
);
bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into());
let own = view.zip(state.own_client).and_then(|(v, c)| v.avatar(c));
bridge.set_own_avatar(convert::image(&vm::avatar::image(own)));
let banner = |url: Option<&str>| {
view.map(|v| vm::tree::banner(&v.pictures, url)).unwrap_or_default()
};
let details = view.map(|v| &v.presence.server);
bridge
.set_server_banner(convert::image(&banner(details.map(|d| d.banner_gfx_url.as_str()))));
bridge.set_server_banner_mode(details.map_or(0, |d| vm::tree::banner_mode(d.banner_mode)));
let own_channel =
view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c)));
bridge.set_own_channel(
own_channel.map(|c| vm::tree::channel_title(c).0).unwrap_or_default().into(),
);
bridge.set_own_channel_topic(
own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
);
bridge.set_own_channel_banner(convert::image(&banner(
own_channel.and_then(|c| c.banner_gfx_url.as_deref()),
)));
bridge.set_own_channel_banner_mode(
own_channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)),
);
bridge.set_own_channel_limit(
own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1),
);
bridge.set_voice_connected(state.voice == VoiceState::Connected);
bridge.set_voice_connecting(state.voice == VoiceState::Connecting);
bridge.set_observing(state.observe != ObserveState::Off);
bridge.set_input_muted(state.input_muted);
bridge.set_output_muted(state.output_muted);
bridge.set_transmitting(state.transmitting);
bridge.set_presence_source(
match state.presence_source {
Some(Source::Voice) => "live (voice)",
Some(Source::Gateway) => "invisible (gateway)",
Some(Source::Query) => "invisible (query)",
None => "",
}
.into(),
);
if state.voice != VoiceState::Connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
/// The channel tree, the members of our channel and everyone on the
/// server.
pub(crate) fn refresh_tree(&self) {
let Some(view) = self.view() else {
self.models.tree.sync(&[]);
self.models.members.sync(&[]);
self.models.server_members.sync(&[]);
return;
};
let input = vm::tree::TreeInput {
presence: &view.presence,
collapsed: &view.collapsed,
talking: &view.talking,
playback: &self.state.playback,
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: "",
avatars: &view.avatars,
icons: &view.icons,
pictures: &view.pictures,
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
self.models.tree.sync(&vm::tree::rows(&input));
let connected = view.state.voice == VoiceState::Connected;
let members = if connected { vm::tree::members(&input) } else { Vec::new() };
self.models.members.sync(&members);
// The people in our channel first while their view is shown (not
// while the stream plays in a window of its own).
let watching = self.watch.as_ref().is_some_and(|w| w.shown) && self.popout.window.is_none();
let voice_first = connected && (self.state.voice_view || watching);
let everyone = vm::tree::server_members(&input, voice_first);
let filter = self.state.member_filter.trim().to_lowercase();
let shown =
if filter.is_empty() { everyone } else { vm::tree::matching(everyone, &filter) };
self.models.server_members.sync(&shown);
if let Some(ui) = self.ui.upgrade() {
let total = view.presence.clients.values().filter(|c| !c.is_query).count();
ui.global::<crate::app::Bridge>().set_member_total(total as i32);
}
}
/// The members panel's search.
pub(crate) fn search_members(&mut self, text: String) {
if self.state.member_filter != text {
self.state.member_filter = text;
self.refresh_tree();
}
}
/// The voice channel view was opened or closed: its chat is our
/// channel's, and its people lead the members panel.
pub(crate) fn show_voice_view(&mut self, on: bool) {
self.state.voice_view = on;
if on && let Some(channel) = self.view().and_then(|v| v.state.own_channel) {
self.open_chat(voelin_model::ChatTarget::Channel(channel), true);
}
self.refresh_tree();
}
/// A link to the voice channel we are in, for the Invite button (which
/// copies it, and the copy's toast names the channel); empty, with a
/// note, without one.
pub(crate) fn invite_link(&mut self) -> String {
let bookmark =
self.state.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone());
let path = self.view().and_then(|v| {
let cid = v.state.own_channel?;
let own = v.presence.channels.get(&cid)?;
// The link names the channels as the server has them; the
// toast as the tree shows them.
Some((
vm::tree::channel_path(&v.presence, cid),
vm::tree::channel_title(own).0.to_owned(),
))
});
let (Some(address), Some((path, title))) = (bookmark, path) else {
self.set_status("Join a voice channel to invite others to it");
return String::new();
};
let path: Vec<&str> = path.iter().map(String::as_str).collect();
let link = vm::servers::invite_link(&address, &path);
self.state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
link
}
/// Join a channel of a session (a double-click in the tree, joining a
/// friend): move there with voice, or connect into it. A locked channel
/// asks for its password first, unless it was given this connection.
pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) {
let Some(view) = self.state.sessions.get(&session) else { return };
let Some(info) = view.presence.channels.get(&channel) else { return };
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match vm::servers::join_password(info, remembered) {
JoinStep::Send(password) => self.enter_channel(session, channel, password),
JoinStep::Ask => self.ask_channel_password(session, channel, false),
}
}
/// The password dialog's Join.
pub(crate) fn join_with_password(&mut self, password: String) {
let Some((session, channel)) = self.state.join_target.take() else { return };
if password.is_empty() {
return;
}
if let Some(view) = self.state.sessions.get_mut(&session) {
view.channel_passwords.insert(channel, password.clone());
}
self.enter_channel(session, channel, Some(password));
}
/// Move into a channel; without voice on its server, connect into it.
fn enter_channel(&mut self, session: i64, channel: ChannelId, password: Option<String>) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Disconnected {
// Chosen while connecting: no longer the one to join after.
view.join_after_connect = None;
if !self.demo_ui {
self.engine.send(Command::MoveToChannel {
session: session as u64,
channel,
password,
});
}
return;
}
if self.state.current != Some(session) {
self.select_server(session);
}
// By id: by its name the server finds only a top-level channel (a
// subchannel's name connects into the default channel).
if self.connect_voice_to(Some(format!("/{channel}")), password, None)
&& let Some(view) = self.state.sessions.get_mut(&session)
{
view.join_after_connect = Some(channel);
}
}
/// Connected into another channel than the one asked for
/// (`SessionView::join_after_connect`): the server says nothing when,
/// for one, the password was wrong, so it is joined again, and that
/// move says why. Once the channel shows in the voice
/// connection's presence, which can come after the own channel.
pub(crate) fn join_after_connect(&mut self, session: i64) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect)
else {
return;
};
let known = view.presence.channels.contains_key(&asked);
match vm::servers::after_connect(view.state.own_channel, asked, known) {
AfterConnect::Wait => {}
AfterConnect::Joined => view.join_after_connect = None,
AfterConnect::JoinAgain => {
view.join_after_connect = None;
self.join_channel(session, asked);
}
}
}
/// Open the password dialog for a locked channel; `wrong`: the one
/// given was refused.
fn ask_channel_password(&mut self, session: i64, channel: ChannelId, wrong: bool) {
let Some(info) =
self.state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
else {
return;
};
let name = vm::tree::channel_title(info).0.to_owned();
self.state.join_target = Some((session, channel));
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_channel_password_name(name.into());
nav.set_channel_password_error(wrong);
nav.set_channel_password_open(true);
}
/// The server refused a move ([`voelin_core::Event::JoinFailed`]): a
/// password asks again (the one given is forgotten), the rest is a
/// toast.
pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) {
match reason {
JoinFailure::Password => {
let given = self
.state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
.is_some();
self.ask_channel_password(session, channel, given);
}
JoinFailure::Full => self.set_status("The channel is full"),
JoinFailure::Other(text) => self.set_status(text),
}
}
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
if let Some(view) = self.view_mut()
&& !view.collapsed.remove(&channel)
{
view.collapsed.insert(channel);
}
self.refresh_tree();
}
}
#[cfg(test)]
mod tests {
use voelin_core::ts::identity::Found;
use super::*;
use voelin_store::QueryConfig;
#[test]
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
bookmark = bookmark_from_form(
Some(&bookmark),
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|| "Me".into(),
);
// Connecting does not retag received imagery. A failed B connection
// must not make A's image appear under B's name.
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
view.state.voice = state;
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
}
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
assert_eq!(view.server_icon, 1234);
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
assert!(bookmark.server_icon_id().is_none());
// Equal icon IDs on the next server still need new provenance.
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
assert!(bookmark.server_icon_id().is_none());
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_address_alone_makes_a_server() {
let form =
BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() };
let b = bookmark_from_form(None, &form, || "Nick".into());
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
assert_eq!(b.nickname, "Nick");
assert_eq!(
(b.gateway_url, b.query, b.identity, b.default_channel),
(None, None, None, None)
);
}
#[test]
fn editing_keeps_what_the_form_does_not_show() {
let old = Bookmark {
id: 7,
name: "Old".into(),
address: "old.example.test".into(),
nickname: "Me".into(),
identity: Some(2),
default_channel: Some("Lobby/Sub".into()),
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
client_version: Some("linux".into()),
cached_server_icon: Some(voelin_store::CachedServerIcon {
address: "old.example.test".into(),
id: 1234,
}),
};
// Same address: the gateway found and the query login stay.
let same = BookmarkForm {
id: 7,
name: "Mine".into(),
address: "old.example.test".into(),
nickname: "Other".into(),
..Default::default()
};
let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given"));
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
assert_eq!(b.gateway_url, old.gateway_url);
assert_eq!(b.query, old.query);
assert_eq!(b.cached_server_icon, old.cached_server_icon);
// Another address: looked up again, for the new server.
let form = BookmarkForm { address: "new.example.test:9988".into(), ..same };
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
assert_eq!(b.address, "new.example.test:9988");
assert!(b.cached_server_icon.is_none());
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
assert_eq!(b.client_version.as_deref(), Some("linux"));
assert_eq!((b.gateway_url, b.query), (None, None));
assert!(b.gateway_urls.is_empty());
}
#[test]
fn the_import_is_told_by_nickname() {
let found = |nickname: &str| Found {
nickname: nickname.into(),
identity: tsclientlib::Identity::create(),
source: "settings.db".into(),
selected: false,
};
let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport {
added: added.iter().map(|n| found(n)).collect(),
default: default.map(found),
replaced,
};
assert_eq!(imported_status(&report(&[], None, false)), None);
assert_eq!(
imported_status(&report(&["Main"], Some("Main"), false)).unwrap(),
"Using your TeamSpeak identity \u{201c}Main\u{201d}"
);
assert_eq!(
imported_status(&report(&["Main", "Alt"], None, false)).unwrap(),
"Imported 2 identities from TeamSpeak: Main, Alt"
);
// Imported earlier, now ours instead of the one the app made.
assert_eq!(
imported_status(&report(&[], Some("Main"), true)).unwrap(),
"You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept"
);
}
#[test]
fn a_gateway_found_again_is_not_logged_in_again() {
let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1");
let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::<Vec<_>>();
let stays = |previous: &[&str], found: &[&str], observe| {
observing_stays(&urls(previous), &urls(found), Some(plain), observe)
};
// The same ones (an older version kept only the one in use).
assert!(stays(&[plain], &[plain], ObserveState::Connecting));
assert!(stays(&[plain], &[plain], ObserveState::Observing));
// Logged in through one still published.
assert!(stays(&[plain], &[tls, plain], ObserveState::Observing));
// Not logged in yet: through the new ones.
assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting));
// The one in use is no longer published.
assert!(!stays(&[plain], &[tls], ObserveState::Observing));
assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off));
}
}
+455
View File
@@ -0,0 +1,455 @@
//! The Slint side of the servers: connecting and observing (the store, the
//! secrets, the engine), the Bridge writes of the rail, the server card and
//! the channel tree, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::servers::logic`.
use std::time::Instant;
use slint::ComponentHandle;
use tracing::{debug, info, warn};
use voelin_core::{Command, JoinFailure, ObserveState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use crate::app::{App, Bridge, later};
use crate::bind::convert;
use crate::vm;
use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan};
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel = self
.state
.current
.and_then(|id| self.bookmark(id))
.and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None);
}
/// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for.
pub(crate) fn connect_voice_to(
&mut self,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
self.set_status(error);
return false;
}
};
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id);
true
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub(crate) fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![logic::CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
/// run ([`logic::discover_wanted`]): every one the server publishes is
/// kept, best first, and tried in turn; they take the place of a stored
/// one that is no longer published (a gateway that moved, or one typed
/// into an older version, which showed the field). Nothing found keeps
/// what is stored.
pub(crate) fn discover_gateway(&mut self, id: i64) {
let Some(address) = self.transition(|state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
self.engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
}
});
}
/// Gateways were found for the server at `address` (best first); they
/// are kept unless the server changed meanwhile ([`logic::gateway_found`]),
/// and the server is observed through them if it is the one shown. Users
/// never hear of them (logged only).
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
let found = self.transition(|state, cx| logic::gateway_found(state, cx, id, address, urls));
match found {
GatewayFound::Same => {
debug!(server = %address, elapsed_ms, "gateway found, as kept");
}
GatewayFound::Kept { observe } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if observe {
self.observe(id);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.engine.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id);
}
}
}
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its
/// gateway, else its own query login. Without either the gateway is
/// looked up first, and observing starts when it is found
/// (`gateway_found`).
pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return };
let session = b.id as u64;
match self.transition(|state, cx| logic::observe_plan(state, cx, id)) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
}
ObservePlan::Query(q) => {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id);
return;
}
}
self.set_status("Observing invisibly…");
}
/// Show a server, and observe it.
pub(crate) fn select_server(&mut self, id: i64) {
self.transition(|state, cx| logic::select_server(state, cx, id));
self.observe(id);
}
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: self.default_nickname().into(),
..Default::default()
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
/// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || self.default_nickname());
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its
// gateway is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
}
/// The server dialog's Connect: save the server, then connect it with
/// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
/// shown after a failed save would connect the server shown before.
/// Whether it was saved.
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form);
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
return false;
};
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
}
pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
let bookmarks = self.store.bookmarks().unwrap_or_default();
self.transition(|state, cx| logic::forget_server(state, cx, id, bookmarks));
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
let current = self
.state
.sessions
.get(&bookmark.id)
.map(|view| view.server_icon_for(&bookmark.address))
.unwrap_or_default();
if current.size().width > 0 {
current
} else {
vm::servers::cached_icon(bookmark, &self.engine.cache())
}
}
/// The rail: servers with their state, unread count (without private
/// chats) and streams; what the chat strip and the private chats have
/// unread.
pub(crate) fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let items = logic::rail(&self.state, |b| self.server_list_icon(b));
self.models.servers.sync(&items);
bridge.set_last_place(self.last_place(&items).into());
bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32));
// Private chats count on the messages page (and the phone's Home).
bridge.set_unread_total(self.view().map_or(0, crate::app::SessionView::channel_unread));
bridge.set_dm_unread(self.dm_unread());
}
/// The server card, the voice controls and who we are
/// ([`logic::toolbar`]).
pub(crate) fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let card = logic::toolbar(&self.state, |b| self.server_list_icon(b));
bridge.set_server_icon(convert::image(&card.server_icon));
bridge.set_server_title(card.server_title.into());
bridge.set_server_stats(card.server_stats.into());
bridge.set_nickname(card.nickname.into());
bridge.set_own_avatar(convert::image(&card.own_avatar));
bridge.set_server_banner(convert::image(&card.server_banner));
bridge.set_server_banner_mode(card.server_banner_mode);
bridge.set_own_channel(card.own_channel.into());
bridge.set_own_channel_topic(card.own_channel_topic.into());
bridge.set_own_channel_banner(convert::image(&card.own_channel_banner));
bridge.set_own_channel_banner_mode(card.own_channel_banner_mode);
bridge.set_own_channel_limit(card.own_channel_limit);
bridge.set_voice_connected(card.voice_connected);
bridge.set_voice_connecting(card.voice_connecting);
bridge.set_observing(card.observing);
bridge.set_input_muted(card.input_muted);
bridge.set_output_muted(card.output_muted);
bridge.set_transmitting(card.transmitting);
bridge.set_presence_source(card.presence_source.into());
if !card.voice_connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
/// The channel tree, the members of our channel and everyone on the
/// server ([`logic::tree_view`]).
pub(crate) fn refresh_tree(&self) {
let Some(tree) = logic::tree_view(&self.state, self.popout.window.is_some()) else {
self.models.tree.sync(&[]);
self.models.members.sync(&[]);
self.models.server_members.sync(&[]);
return;
};
self.models.tree.sync(&tree.rows);
self.models.members.sync(&tree.members);
self.models.server_members.sync(&tree.server_members);
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_member_total(tree.member_total);
}
}
/// The members panel's search.
pub(crate) fn search_members(&mut self, text: String) {
self.transition(|state, cx| logic::search_members(state, cx, text));
}
/// The voice channel view was opened or closed.
pub(crate) fn show_voice_view(&mut self, on: bool) {
self.transition(|state, cx| logic::show_voice_view(state, cx, on));
}
/// A link to the voice channel we are in, for the Invite button; empty,
/// with a note, without one ([`logic::invite_link`]).
pub(crate) fn invite_link(&mut self) -> String {
match logic::invite_link(&mut self.state) {
Ok(link) => link,
Err(why) => {
self.set_status(why);
String::new()
}
}
}
/// Join a channel of a session ([`logic::join_channel`]): the transition
/// moves there with voice or asks for the password; without voice on that
/// server we connect into it.
pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) {
if let Some(password) =
self.transition(|state, cx| logic::join_channel(state, cx, session, channel))
{
self.connect_into(session, channel, password);
}
}
/// The password dialog's Join.
pub(crate) fn join_with_password(&mut self, password: String) {
if let Some((session, channel, password)) =
self.transition(|state, cx| logic::join_with_password(state, cx, password))
{
self.connect_into(session, channel, password);
}
}
/// Connect voice into a channel of a server that has none.
fn connect_into(&mut self, session: i64, channel: ChannelId, password: Option<String>) {
if self.state.current != Some(session) {
self.select_server(session);
}
// By id: by its name the server finds only a top-level channel (a
// subchannel's name connects into the default channel).
if self.connect_voice_to(Some(format!("/{channel}")), password, None) {
logic::join_after_connect(&mut self.state, session, channel);
}
}
/// The server refused a move ([`voelin_core::Event::JoinFailed`]): a
/// password asks again (the one given is forgotten), the rest is a
/// toast.
pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) {
self.transition(|state, cx| vm::events::join_failed(state, cx, session, channel, reason));
}
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
self.transition(|state, cx| logic::toggle_collapse(state, cx, channel));
}
}
#[cfg(test)]
mod tests {
use voelin_core::ts::identity::{Found, LaunchImport};
use super::*;
/// The report is the engine's ([`LaunchImport`], with identities of
/// `tsclientlib`, which the view model crate does not have).
#[test]
fn the_import_is_told_by_nickname() {
let found = |nickname: &str| Found {
nickname: nickname.into(),
identity: tsclientlib::Identity::create(),
source: "settings.db".into(),
selected: false,
};
let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport {
added: added.iter().map(|n| found(n)).collect(),
default: default.map(found),
replaced,
};
let told = logic::imported_status;
assert_eq!(told(&report(&[], None, false)), None);
assert_eq!(
told(&report(&["Main"], Some("Main"), false)).unwrap(),
"Using your TeamSpeak identity \u{201c}Main\u{201d}"
);
assert_eq!(
told(&report(&["Main", "Alt"], None, false)).unwrap(),
"Imported 2 identities from TeamSpeak: Main, Alt"
);
// Imported earlier, now ours instead of the one the app made.
assert_eq!(
told(&report(&[], Some("Main"), true)).unwrap(),
"You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept"
);
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Servers: bookmarks, connecting and observing, the rail, the sidebar's
//! server card and the channel tree. What the state does (which server is
//! shown, how it is observed, the rail, the card and the tree as plain data,
//! joining a channel) is in `voelin_ui_vm::servers::logic`; `bind` has the
//! store and the secrets, the engine's commands and the Bridge and model
//! writes.
mod bind;
-308
View File
@@ -1,308 +0,0 @@
//! The settings page (audio, push-to-talk, H.264, crash reports), the
//! About page's notices, and the local volume of clients.
use slint::{ComponentHandle, SharedString};
use tracing::warn;
use voelin_core::settings::{AUDIO, CRASH_REPORTS};
use voelin_core::{Command, Source, VoiceState};
use voelin_platform::{crash, notices};
use crate::app::{App, Bridge, later, model};
use crate::settings::{self, CLIENT_PLAYBACK, ClientPlayback, DeviceChoices};
use crate::vm::bridge::{AudioForm, ClientAudio};
impl App {
pub(crate) fn open_settings(&mut self) {
let list = |devices: voelin_audio::Result<Vec<voelin_audio::device::DeviceInfo>>,
input: bool| {
let devices = devices.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
});
devices
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect::<Vec<_>>()
};
let inputs = list(voelin_audio::device::input_devices(), true);
let outputs = list(voelin_audio::device::output_devices(), false);
self.state.inputs = DeviceChoices::new(&inputs, self.state.audio.input_device.as_deref());
self.state.outputs =
DeviceChoices::new(&outputs, self.state.audio.output_device.as_deref());
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect());
bridge.set_input_devices(names(&self.state.inputs));
bridge.set_output_devices(names(&self.state.outputs));
bridge.set_audio(
settings::audio_form(&self.state.audio, &self.state.inputs, &self.state.outputs).into(),
);
bridge.set_global_ptt(self.state.settings.global_ptt);
bridge.set_ptt_key(self.state.settings.ptt_key.clone().into());
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_image_cache_usage(crate::images::usage_text().into());
self.refresh_h264();
self.refresh_identities();
}
pub(crate) fn close_settings(&mut self) {
self.set_mic_test(false);
self.save_audio();
}
pub(crate) fn audio_changed(&mut self, form: &AudioForm) {
let audio = settings::apply_audio_form(
form,
&self.state.audio,
&self.state.inputs,
&self.state.outputs,
);
if audio == self.state.audio {
return;
}
self.state.audio = audio;
self.state.audio_dirty = true;
self.engine.send(Command::SetAudioSettings(Box::new(self.state.audio.clone())));
}
pub(crate) fn save_audio(&mut self) {
if !self.state.audio_dirty {
return;
}
self.state.audio_dirty = false;
if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) {
warn!(%e, "could not store audio settings");
}
}
pub(crate) fn set_mic_test(&mut self, on: bool) {
if self.state.mic_test == on {
return;
}
self.state.mic_test = on;
self.engine.send(Command::TestMicrophone { on });
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(on);
if !on {
bridge.set_input_level(-100.0);
}
}
}
pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) {
let key = key.trim().to_owned();
self.state.settings.global_ptt = enabled;
if !key.is_empty() {
self.state.settings.ptt_key = key.clone();
}
self.store_settings();
self.ptt.set((enabled && !key.is_empty()).then_some(key));
}
pub(crate) fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
pub(crate) fn set_h264(&mut self, enabled: bool) {
self.state.settings.openh264 = enabled;
self.store_settings();
self.video.set_h264(enabled);
self.refresh_h264();
}
pub(crate) fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.state.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
bridge.set_h264_loaded(loaded);
bridge.set_h264_busy(status.starts_with("Downloading"));
bridge.set_h264_status(status.into());
}
/// Switches the About page and the settings show.
pub(crate) fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.state.settings.crash_reports);
}
/// The transmit mode for the voice controls (Hold to talk shows for
/// push-to-talk) before the settings page fills the whole form: only
/// `transmit` changes, as the device lists are not read yet.
pub(crate) fn refresh_transmit(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let mut form = bridge.get_audio();
form.transmit = settings::transmit_index(self.state.audio.transmit);
bridge.set_audio(form);
}
pub(crate) fn set_crash_reports(&mut self, enabled: bool) {
self.state.settings.crash_reports = enabled;
// Also in the blob, for older versions.
self.store_settings();
if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) {
warn!(%e, "could not store the crash report setting");
}
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk.
pub(crate) fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let text = match crash::pending_reports() {
Ok(reports) if !reports.is_empty() => {
let newest = &reports[reports.len() - 1];
let saved = match reports.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({}). {saved} on this device.", newest.summary)
}
_ => String::new(),
};
ui.global::<Bridge>().set_crash_notice(text.into());
}
pub(crate) fn open_crash_folder(&mut self) {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) =
result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string()))
{
self.set_status(format!("Cannot open the crash report folder: {e}"));
}
}
pub(crate) fn delete_crash_reports(&mut self) {
match crash::clear() {
Ok(n) => self.set_status(format!("Deleted {n} crash reports")),
Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")),
}
self.refresh_crash_notice();
}
/// The third-party notices, one model entry per line.
pub(crate) fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session.
pub(crate) fn open_client(&mut self, client: u16) -> bool {
let Some(id) = self.state.current else { return false };
let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else {
return false;
};
let playback = info
.uid
.as_ref()
.and_then(|uid| self.state.playback.get(uid))
.copied()
.unwrap_or_default();
self.state.playback_dialog = Some((id, client, info.uid.clone()));
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(
ClientAudio {
id: client as i32,
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
streaming: info.streaming == Some(true),
}
.into(),
);
}
true
}
pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) {
let Some((session, client, uid)) = self.state.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume });
self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted });
// Kept by unique id; clients without one only for this connection.
if let Some(uid) = uid {
if playback.is_default() {
self.state.playback.remove(&uid);
} else {
self.state.playback.insert(uid, playback);
}
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) {
warn!(%e, "could not store client volumes");
}
}
self.refresh_tree();
}
/// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us.
pub(crate) fn open_first_client(&mut self) {
let Some(view) = self.view().filter(|v| v.state.own_client.is_some()) else { return };
let own = view.state.own_client;
let mut others: Vec<_> =
view.presence.clients.values().filter(|c| Some(c.id) != own && !c.is_query).collect();
others.sort_by_key(|c| c.id);
let Some(id) = others.first().map(|c| c.id) else { return };
self.open_client_pending = false;
if self.open_client(id)
&& let Some(ui) = self.ui.upgrade()
{
ui.global::<crate::app::Nav>().set_client_open(true);
}
}
/// Send the stored volumes of clients that appeared in a voice session.
pub(crate) fn apply_client_playback(&mut self, session: i64) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| self.state.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
self.engine.send(Command::SetClientVolume {
session: s,
client: c,
volume: playback.volume,
});
if playback.muted {
self.engine.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
}
+222
View File
@@ -0,0 +1,222 @@
//! The Slint side of the settings page: the system's audio devices, the
//! hotkey, the codec download and the crash reports, the Bridge writes, and
//! the callbacks' ways into the transitions of
//! `voelin_ui_vm::settings_page::logic`.
use slint::{ComponentHandle, SharedString};
use tracing::warn;
use voelin_core::settings::CRASH_REPORTS;
use voelin_platform::{crash, notices};
use crate::app::{App, Bridge, Nav, later, model};
use crate::settings;
use crate::vm::bridge::{AudioForm, ClientAudio};
use crate::vm::settings_page::logic::{self, Device};
/// The audio devices the system lists in one direction, as `(id, name,
/// is the default)`; none, and a warning, when it cannot list them.
fn devices(
list: voelin_audio::Result<Vec<voelin_audio::device::DeviceInfo>>,
input: bool,
) -> Vec<Device> {
list.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
})
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect()
}
impl App {
pub(crate) fn open_settings(&mut self) {
let inputs = devices(voelin_audio::device::input_devices(), true);
let outputs = devices(voelin_audio::device::output_devices(), false);
let page = logic::open_settings(&mut self.state, &inputs, &outputs);
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |names: Vec<String>| model(names.into_iter().map(SharedString::from).collect());
bridge.set_input_devices(names(page.input_devices));
bridge.set_output_devices(names(page.output_devices));
bridge.set_audio(page.audio.into());
bridge.set_global_ptt(page.global_ptt);
bridge.set_ptt_key(page.ptt_key.into());
bridge.set_h264_enabled(page.h264_enabled);
bridge.set_image_cache_usage(crate::images::usage_text().into());
self.refresh_h264();
self.refresh_identities();
}
pub(crate) fn close_settings(&mut self) {
if self.transition(logic::close_settings) {
self.mic_test_stopped();
}
}
pub(crate) fn audio_changed(&mut self, form: &AudioForm) {
self.transition(|state, cx| logic::audio_changed(state, cx, form));
}
pub(crate) fn save_audio(&mut self) {
self.transition(logic::save_audio);
}
pub(crate) fn set_mic_test(&mut self, on: bool) {
if self.transition(|state, cx| logic::set_mic_test(state, cx, on)) {
if on {
self.mic_test_started();
} else {
self.mic_test_stopped();
}
}
}
/// The Bridge shows the microphone test running.
fn mic_test_started(&self) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_mic_test(true);
}
}
/// The Bridge shows the microphone test over, and its level gone.
fn mic_test_stopped(&self) {
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(false);
bridge.set_input_level(-100.0);
}
}
pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) {
let hotkey = self.transition(|state, cx| logic::apply_ptt(state, cx, enabled, &key));
self.ptt.set(hotkey);
}
pub(crate) fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
pub(crate) fn set_h264(&mut self, enabled: bool) {
self.transition(|state, cx| logic::set_h264(state, cx, enabled));
self.video.set_h264(enabled);
self.refresh_h264();
}
pub(crate) fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.state.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
let view = logic::h264_view(loaded, status);
bridge.set_h264_loaded(view.loaded);
bridge.set_h264_busy(view.busy);
bridge.set_h264_status(view.status.into());
}
/// Switches the About page and the settings show.
pub(crate) fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.state.settings.crash_reports);
}
/// The transmit mode for the voice controls (Hold to talk shows for
/// push-to-talk) before the settings page fills the whole form: only
/// `transmit` changes, as the device lists are not read yet.
pub(crate) fn refresh_transmit(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let mut form = bridge.get_audio();
form.transmit = settings::transmit_index(self.state.audio.transmit);
bridge.set_audio(form);
}
pub(crate) fn set_crash_reports(&mut self, enabled: bool) {
self.transition(|state, cx| logic::set_crash_reports(state, cx, enabled));
if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) {
warn!(%e, "could not store the crash report setting");
}
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk ([`logic::crash_notice`]).
pub(crate) fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let summaries: Vec<String> = crash::pending_reports()
.map(|reports| reports.into_iter().map(|r| r.summary).collect())
.unwrap_or_default();
ui.global::<Bridge>().set_crash_notice(logic::crash_notice(&summaries).into());
}
pub(crate) fn open_crash_folder(&mut self) {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) =
result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string()))
{
self.set_status(format!("Cannot open the crash report folder: {e}"));
}
}
pub(crate) fn delete_crash_reports(&mut self) {
match crash::clear() {
Ok(n) => self.set_status(format!("Deleted {n} crash reports")),
Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")),
}
self.refresh_crash_notice();
}
/// The third-party notices, one model entry per line.
pub(crate) fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session
/// ([`logic::open_client`]).
pub(crate) fn open_client(&mut self, client: u16) -> bool {
let Some(form) = logic::open_client(&mut self.state, client) else { return false };
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(form.into());
}
true
}
pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) {
self.transition(|state, cx| logic::client_playback_changed(state, cx, form));
}
/// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us.
pub(crate) fn open_first_client(&mut self) {
let Some(id) = logic::first_client(&self.state) else { return };
self.open_client_pending = false;
if self.open_client(id)
&& let Some(ui) = self.ui.upgrade()
{
ui.global::<Nav>().set_client_open(true);
}
}
}
@@ -0,0 +1,6 @@
//! The settings page (audio, push-to-talk, H.264, crash reports), the
//! About page's notices, and the local volume of clients. What the state
//! does is in `voelin_ui_vm::settings_page::logic`; `bind` has the devices,
//! the hotkey, the codec, the crash reports and the Bridge writes.
mod bind;
+1 -1
View File
@@ -423,7 +423,7 @@ impl App {
uids.insert(ids.ts6);
}
}
self.social.own_uids = uids;
self.state.own_uids = uids;
}
/// The identity servers see us as on `bookmark` (the one place that
File diff suppressed because it is too large. Load diff
+254
View File
@@ -0,0 +1,254 @@
//! The Slint side of the social screens: the Bridge writes of the friends,
//! the bell and the search, the desktop toasts, the navigation after a move,
//! and the callbacks' ways into the transitions of
//! `voelin_ui_vm::social::logic`.
use slint::ComponentHandle;
use tracing::debug;
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{App, Bridge, Nav, Page, SettingsSection};
use crate::settings::{
NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel,
};
use crate::vm;
use crate::vm::social::logic::{self, ContactMove, Found, SettingsPage};
use crate::vm::social::{NoticeRequest, Spot};
use super::{NoticeKind, NoticeTarget, now_ms};
/// The Slint enum for a page of the settings.
fn section(page: SettingsPage) -> SettingsSection {
match page {
SettingsPage::Account => SettingsSection::Account,
SettingsPage::Profiles => SettingsSection::Profiles,
SettingsPage::Appearance => SettingsSection::Appearance,
SettingsPage::Voice => SettingsSection::Voice,
SettingsPage::Streaming => SettingsSection::Streaming,
SettingsPage::Devices => SettingsSection::Devices,
SettingsPage::Notifications => SettingsSection::Notifications,
SettingsPage::Privacy => SettingsSection::Privacy,
SettingsPage::Keybinds => SettingsSection::Keybinds,
SettingsPage::Integrations => SettingsSection::Integrations,
SettingsPage::Advanced => SettingsSection::Advanced,
}
}
impl App {
/// The avatar picture of someone by unique id, from any session.
pub(crate) fn avatar_of(&self, uid: &str) -> vm::ImageRef {
vm::social::avatar_of(&self.state, uid)
}
/// A server's name: its bookmark's, else what the session calls it.
pub(crate) fn server_name(&self, session: i64) -> String {
vm::social::server_name(&self.state, session)
}
/// Every session where the client with this unique id is, in bookmark
/// order.
pub(crate) fn spots_of(&self, uid: &str) -> Vec<Spot> {
vm::social::spots_of(&self.state, uid)
}
/// Friends page, home's friends and activity, the block list
/// ([`logic::people`]).
pub(crate) fn refresh_people(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let m = &self.models.social;
let people = logic::people(&self.state, &self.social);
m.friends_online.sync(&people.online);
m.friend_activity.sync(&people.activity);
m.blocked.sync(&people.blocked);
bridge.set_contacts_online(people.online_count);
bridge.set_contacts_all(people.all_count);
bridge.set_contacts_blocked(people.blocked_count);
m.contacts.sync(&people.shown);
bridge.set_contact(people.selected.into());
}
pub(crate) fn friends_tab(&mut self, tab: i32) {
self.social_transition(|_, social, cx| logic::set_friends_tab(social, cx, tab));
}
pub(crate) fn search_contacts(&mut self, text: String) {
self.social_transition(|_, social, cx| logic::search_contacts(social, cx, text));
}
pub(crate) fn select_contact(&mut self, uid: String) {
self.social_transition(|_, social, cx| logic::select_contact(social, cx, uid));
}
/// The buttons of a contact: "message", "poke", "join", "watch",
/// "friend", "block", "neutral", "remove", "mute"
/// ([`logic::contact_action`]); what the move needs a window for is done
/// here.
pub(crate) fn contact_action(&mut self, uid: &str, action: &str) {
let next = self.social_transition(|state, social, cx| {
logic::contact_action(state, social, cx, uid, action)
});
match next {
Some(ContactMove::Message) => self.message_person(uid),
Some(ContactMove::Poke(session, client)) => self.ask_poke(session, client),
Some(ContactMove::Join(spot)) => {
self.show_server(spot.session);
self.join_channel(spot.session, spot.channel);
}
Some(ContactMove::Watch(spot)) => {
self.show_server(spot.session);
self.watch_client(spot.client);
}
None => {}
}
}
pub(crate) fn contact_note(&mut self, uid: &str, note: String) {
self.transition(|state, cx| logic::contact_note(state, cx, uid, note));
}
pub(crate) fn contact_volume(&mut self, uid: &str, percent: f32) {
self.transition(|state, cx| logic::contact_volume(state, cx, uid, percent));
}
/// The server page of a session.
pub(crate) fn show_server(&mut self, session: i64) {
if self.state.current != Some(session) {
self.select_server(session);
}
self.navigate(|nav| nav.invoke_show(Page::Server));
}
/// Navigate after the current callback: `Nav`'s functions call back
/// into the app (`Bridge.open-*`), which is borrowed now.
pub(crate) fn navigate(&self, f: impl FnOnce(&Nav) + Send + 'static) {
let weak = self.ui.clone();
let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = weak.upgrade() {
f(&ui.global::<Nav>());
}
});
}
// The bell.
/// Add a notification as the kind's setting says ([`logic::notify`]),
/// and show it on the desktop if the setting says so.
#[allow(clippy::too_many_arguments)]
pub(crate) fn notify(
&mut self,
kind: NoticeKind,
title: String,
body: String,
target: NoticeTarget,
name: String,
uid: Option<String>,
) {
let key = match kind {
NoticeKind::Mention => &NOTIFY_MENTIONS,
NoticeKind::Poke => &NOTIFY_POKES,
NoticeKind::Message => &NOTIFY_MESSAGES,
NoticeKind::Event => &NOTIFY_EVENTS,
NoticeKind::Friend => &NOTIFY_FRIENDS,
};
let level = self.prefs.get(key);
if level == NotifyLevel::Off {
return;
}
let request = NoticeRequest { kind, title, body, target, name, uid };
if let Some(toast) = logic::notify(&mut self.social, level, self.demo_ui, request, now_ms())
{
let n = voelin_platform::Notification {
urgent: toast.urgent,
..voelin_platform::Notification::new(toast.title, toast.body)
};
self.engine.runtime().spawn(async move {
if let Err(e) = voelin_platform::notify(&n).await {
debug!("no desktop notification: {e}");
}
});
}
self.refresh_notices();
}
/// The bell's notices, and home's unread mentions (the newest three).
pub(crate) fn refresh_notices(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let rows = logic::notice_rows(&self.state, &self.social);
self.models.social.notices.sync(&rows.notices);
self.models.social.mentions.sync(&rows.mentions);
ui.global::<Bridge>().set_notifications_unread(rows.unread);
}
pub(crate) fn mark_notices_read(&mut self) {
logic::mark_notices_read(&mut self.social);
self.refresh_notices();
}
pub(crate) fn clear_notices(&mut self) {
logic::clear_notices(&mut self.social);
self.refresh_notices();
}
/// Open what a notification is about.
pub(crate) fn open_notice(&mut self, key: i32) {
let Some(target) =
self.social_transition(|_, social, cx| logic::open_notice(social, cx, key))
else {
return;
};
self.refresh_notices();
match target {
NoticeTarget::Chat(session, chat) => {
self.show_server(session);
self.open_chat(chat, true);
}
NoticeTarget::Dm(session, uid) => self.open_dm_with(Some(session), &uid),
NoticeTarget::Event(session, _) => {
self.select_server(session);
self.navigate(|nav| nav.invoke_show(Page::Events));
}
NoticeTarget::Contact(_) => self.navigate(|nav| nav.invoke_show(Page::Friends)),
}
}
/// Whether a message is ours.
pub(crate) fn is_own(&self, session: i64, message: &ChatMessage) -> bool {
vm::social::is_own(&self.state, session, message)
}
// The search (Ctrl+K).
/// Fill the results for `text` ([`logic::search`]).
pub(crate) fn search(&mut self, text: String) {
let (items, found) = logic::search(&self.state, &text, |b| self.server_list_icon(b));
self.social.found = found;
self.models.social.search.sync(&items);
}
/// Open a search result.
pub(crate) fn search_activate(&mut self, index: i32) {
let Some(found) =
self.social_transition(|_, social, cx| logic::search_activate(social, cx, index))
else {
return;
};
match found {
Found::Server(id) => self.show_server(id),
Found::Channel(id, channel) => {
self.show_server(id);
self.open_chat(ChatTarget::Channel(channel), true);
}
Found::Person(id, _, Some(uid)) => self.open_dm_with(Some(id), &uid),
Found::Person(id, client, None) => {
self.show_server(id);
self.open_member(i32::from(client));
}
Found::Contact(_) => self.navigate(|nav| nav.invoke_show(Page::Friends)),
Found::Setting(page) => {
let section = section(page);
self.navigate(move |nav| nav.invoke_open_settings(section));
}
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! People across servers: contacts and where they are (Friends, home), the
//! bell's notifications, pokes, and the search (Ctrl+K). The direct
//! messages are in `messages.rs`, the home page in `home.rs`, a server's
//! events in `events.rs`.
//!
//! Every contact's whereabouts come from the sessions' presence (voice,
//! gateway or query), so they are current for friends and the others alike;
//! [`voelin_core::Event::FriendPresence`] adds when a friend came online, for
//! "12m ago" and the notification. What the screens show and what an event
//! or a move does to them is in `voelin_ui_vm::social::logic`; `bind` has
//! the Bridge writes, the desktop toasts and the navigation.
mod bind;
use crate::app::Bridge;
use crate::bind::rows::Rows;
use crate::vm;
pub(crate) use vm::social::{NoticeKind, NoticeTarget, now_ms};
/// State of the home, friends, messages, bell and search screens: the
/// view model's, with what the messages page keeps.
pub(crate) type Social = vm::social::logic::Social<crate::messages::Dms>;
/// The models of these screens, set on the Bridge once.
pub(crate) struct SocialModels {
pub friends_online: Rows<vm::bridge::ContactItem>,
pub friend_activity: Rows<vm::bridge::ContactItem>,
pub contacts: Rows<vm::bridge::ContactItem>,
pub blocked: Rows<vm::bridge::ContactItem>,
pub live: Rows<vm::bridge::LiveItem>,
pub recent: Rows<vm::bridge::ConversationItem>,
pub sidebar_dms: Rows<vm::bridge::ConversationItem>,
pub conversations: Rows<vm::bridge::ConversationItem>,
pub dm_lines: Rows<vm::bridge::ChatLine>,
pub happenings: Rows<vm::bridge::HappeningItem>,
pub recordings: Rows<vm::bridge::RecordingItem>,
pub notices: Rows<vm::bridge::NoticeItem>,
pub mentions: Rows<vm::bridge::NoticeItem>,
pub search: Rows<vm::bridge::SearchItem>,
pub events: Rows<vm::bridge::EventItem>,
}
impl SocialModels {
pub fn new(bridge: &Bridge) -> Self {
let m = Self {
friends_online: Rows::default(),
friend_activity: Rows::default(),
contacts: Rows::default(),
blocked: Rows::default(),
live: Rows::default(),
recent: Rows::default(),
sidebar_dms: Rows::default(),
conversations: Rows::default(),
dm_lines: Rows::default(),
happenings: Rows::default(),
recordings: Rows::default(),
notices: Rows::default(),
mentions: Rows::default(),
search: Rows::default(),
events: Rows::default(),
};
bridge.set_friends_online(m.friends_online.model());
bridge.set_friend_activity(m.friend_activity.model());
bridge.set_contacts(m.contacts.model());
bridge.set_blocked(m.blocked.model());
bridge.set_live_rooms(m.live.model());
bridge.set_recent_chats(m.recent.model());
bridge.set_sidebar_dms(m.sidebar_dms.model());
bridge.set_conversations(m.conversations.model());
bridge.set_dm_messages(m.dm_lines.model());
bridge.set_happenings(m.happenings.model());
bridge.set_recordings(m.recordings.model());
bridge.set_notifications(m.notices.model());
bridge.set_home_mentions(m.mentions.model());
bridge.set_search_results(m.search.model());
bridge.set_events(m.events.model());
m
}
}
File diff suppressed because it is too large. Load diff
+425
View File
@@ -0,0 +1,425 @@
//! The Slint side of the streams: the Bridge writes of the streams panel,
//! the share dialog and the viewer, the capture and the decoder, the
//! viewer's window. The state and its transitions are in
//! `voelin_ui_vm::streams::logic`.
use std::time::Duration;
use slint::{ComponentHandle, Model};
use tracing::warn;
use voelin_core::media::{Streamer, audio_source_specs};
use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS};
use voelin_core::stream::StreamSetup;
use super::Share;
use crate::app::{App, Bridge, later, with_app};
use crate::bind::convert;
use crate::video::{self, Capture, Decoder};
use crate::vm::bridge::{ShareForm, SourceItem};
use crate::vm::streams::logic::{
self as logic, CaptureFacts, CaptureStarted, SharePlan, StreamsFacts, viewer_view,
};
/// Show or hide the pointer over `window`. In full screen the player hides
/// it with its controls: Slint applies a TouchArea's cursor only when the
/// pointer moves, so the window is told directly. (No pointer on Android.)
pub(crate) fn show_cursor(window: &slint::Window, shown: bool) {
#[cfg(not(target_os = "android"))]
{
use slint::winit_030::WinitWindowAccessor;
window.with_winit_window(|w| w.set_cursor_visible(shown));
}
#[cfg(target_os = "android")]
let _ = (window, shown);
}
impl App {
/// The streams panel, the voice card's streams and the share card.
pub(crate) fn refresh_streams(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let current = self.state.current;
let capture = self.share.as_ref().map(|s| CaptureFacts {
status: s.capture.status(),
source_name: s.capture.source_name().to_owned(),
has_audio: s.capture.has_audio(),
});
let facts = StreamsFacts {
demo: self.demo,
studio_live_here: current.is_some_and(|c| self.studio_streams_to(c)),
capture: capture.as_ref(),
};
let view = logic::streams_view(&self.state, &facts);
bridge.set_streams_available(view.available);
self.models.streams.sync(&view.items);
bridge.set_can_share(video::AVAILABLE);
let share = view.share;
bridge.set_share_state(share.state.into());
bridge.set_share_busy(share.busy);
bridge.set_share_error(share.error.into());
bridge.set_share_audio(share.audio);
bridge.set_share_requests(share.requests);
self.models.viewers.sync(&share.viewers);
bridge.set_share_status(share.status.into());
}
/// The viewer in the main window and in its own: the same facts, but
/// the main window's player only while the stream is not popped out.
pub(crate) fn refresh_viewer(&self) {
let popped = self.popout.window.is_some();
let Some(watch) = &self.state.watch else {
self.viewer_each(|bridge| {
bridge.set_viewer_open(false);
bridge.set_viewer_popped(popped);
bridge.set_viewer_has_frame(false);
bridge.set_viewer_frame(slint::Image::default());
});
return;
};
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
let open = watch.shown && !popped && self.watch_here();
if !open && bridge.get_viewer_open() && bridge.get_viewer_fullscreen() {
// The player goes, still in full screen: it may have hidden the cursor.
show_cursor(ui.window(), true);
}
bridge.set_viewer_open(open);
}
if let Some(window) = &self.popout.window {
window.global::<Bridge>().set_viewer_open(true);
}
let decoded = self.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let view = viewer_view(&self.state, watch, &decoded);
// The members are the current server's.
let admin = self.watch_here()
&& self.models.members.rows().iter().any(|m| m.id == view.streamer_id && m.admin);
self.models.qualities.sync(&view.qualities);
let channel = slint::SharedString::from(view.channel.as_str());
let elapsed = slint::SharedString::from(view.elapsed.as_str());
self.viewer_each(|bridge| {
bridge.set_viewer_popped(popped);
bridge.set_viewer_title(view.title.as_str().into());
bridge.set_viewer_status(view.status.as_str().into());
bridge.set_viewer_ended(view.ended);
bridge.set_viewer_has_frame(view.has_frame);
bridge.set_viewer_volume(view.volume);
bridge.set_viewer_info(view.info.as_str().into());
bridge.set_viewer_streamer(view.streamer.as_str().into());
bridge.set_viewer_streamer_avatar(convert::image(&view.avatar));
bridge.set_viewer_streamer_initials(view.initials.as_ref().into());
bridge.set_viewer_streamer_tint(convert::color(view.tint));
bridge.set_viewer_streamer_admin(admin);
bridge.set_viewer_channel(channel.clone());
bridge.set_viewer_elapsed(elapsed.clone());
bridge.set_viewer_count(view.count);
if bridge.get_viewer_quality() != view.quality {
bridge.set_viewer_quality(view.quality);
}
bridge.set_viewer_quality_detail(view.detail.as_str().into());
});
}
/// The watched stream is on the server on screen (or is the local test
/// stream).
pub(crate) fn watch_here(&self) -> bool {
self.state.watch.as_ref().is_some_and(|w| w.here(self.state.current))
}
/// A simulcast layer of the watched stream (0: follow the bandwidth
/// estimate), asked of the streamer; the engine confirms with
/// `WatchLayers`.
pub(crate) fn set_stream_quality(&mut self, index: i32) {
self.transition(|state, cx| logic::set_quality(state, cx, index));
}
/// Once a second: statistics, a capture that ended, decoder problems.
pub(crate) fn tick_streams(&mut self) {
if self.share.as_ref().is_some_and(|s| s.capture.ended()) {
self.transition(logic::capture_ended);
}
if self.state.watch.as_ref().is_some_and(|w| w.connected && !w.has_frame)
&& let Some(error) = self.decoder.as_ref().and_then(Decoder::error)
{
logic::decoder_failed(&mut self.state, &error);
}
if self.state.share.is_some() {
self.refresh_streams();
}
// The share dialog's audio mixer (studio/).
self.mixer_tick();
if self.state.watch.is_some() {
self.refresh_viewer();
}
}
// Sharing.
/// Fill the share dialog: sources and the last choices.
pub(crate) fn open_share(&mut self) -> ShareForm {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1");
let restorable = self.state.settings.portal_restore_token.is_some();
let sources =
logic::sources_listed(&mut self.state, self.video.sources(test_pattern, restorable));
if let Some(ui) = self.ui.upgrade() {
let items: Vec<SourceItem> = sources
.into_iter()
.map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() })
.collect();
ui.global::<Bridge>().set_share_sources(convert::model(&items));
}
self.refresh_streams();
// Its audio: the Stream Studio's mixer rows and picker.
self.mixer_show();
let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS));
logic::share_form(&self.state, fps, bitrate)
}
/// The share dialog's form with the test pattern chosen.
fn test_pattern_form(&mut self) -> Option<ShareForm> {
let mut form = self.open_share();
let ui = self.ui.upgrade()?;
let sources = ui.global::<Bridge>().get_share_sources();
let pattern = (0..sources.row_count())
.find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"))?;
form.source = pattern as i32;
Some(form)
}
/// Development switch `VOELIN_AUTOSHARE`: share the test pattern once.
pub(crate) fn autoshare(&mut self) {
if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) {
return;
}
self.autoshare = false;
if let Some(form) = self.test_pattern_form() {
self.start_share(ShareForm { auto_accept: true, ..form });
}
}
/// `VOELIN_OPEN=share:live` with sample data: the test pattern shared
/// with the sample mixer's sources (live at once, `capture_ready`).
pub(crate) fn demo_share(&mut self) {
if let Some(form) = self.test_pattern_form() {
self.start_share(ShareForm { audio: true, ..form });
}
}
pub(crate) fn start_share(&mut self, form: ShareForm) {
let Some(session) = self.state.current else { return };
// The mixer's sources (the sample studio's with VOELIN_DEMO_UI).
let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES);
let studio_live_here = self.studio_streams_to(session);
let Some(plan) = self.transition(|state, cx| {
logic::plan_share(state, cx, &form, studio_live_here, &sources)
}) else {
return;
};
let SharePlan { session, source, fps, bitrate, request, setup, auto_accept } = plan;
// The next share starts from these.
for result in
[self.prefs.set(&STREAM_FPS, fps), self.prefs.set(&STREAM_BITRATE_KBPS, bitrate)]
{
if let Err(e) = result {
warn!(%e, "could not store the share settings");
}
}
let runtime = self.engine.runtime().clone();
self.video.start_capture(&runtime, source, request, move |result| {
later(move |app| app.capture_ready(session, setup, auto_accept, result));
});
}
/// The capture started (or not): go live.
fn capture_ready(
&mut self,
session: i64,
setup: StreamSetup,
auto_accept: bool,
result: Result<Capture, String>,
) {
let started = result.as_ref().map(started).map_err(Clone::clone);
let (keep, update) = self.with_host(|state, host| {
let mut cx = crate::vm::host::Cx::new(host);
let keep = logic::capture_ready(state, &mut cx, session, setup, auto_accept, started);
(keep, cx.update)
});
// The capture is kept before the update is carried out: the mixer's
// rows it asks for follow it.
if let (true, Ok(capture)) = (keep, result) {
let meters = slint::Timer::default();
meters.start(slint::TimerMode::Repeated, Duration::from_millis(66), || {
with_app(|app| app.studio_meters());
});
self.share = Some(Share { capture, _meters: meters });
}
self.perform(update);
}
pub(crate) fn stop_share(&mut self) {
self.transition(logic::stop_share);
}
/// The running share's streamer (the mixer's rows, studio/).
pub(crate) fn share_streamer(&self) -> Option<&Streamer> {
self.share.as_ref().map(|s| s.capture.streamer())
}
/// `stream.audio_sources` changed (the mixer, the settings, another
/// window): a running share mixes the new sources.
pub(crate) fn share_audio_changed(&mut self) {
if self.share.is_none() {
return;
}
let sources = audio_source_specs(&self.studio_settings().get(&STREAM_AUDIO_SOURCES));
let codecs = self.video.codecs();
let Some(share) = &self.share else { return };
if let Err(e) = share.capture.follow_audio(&codecs, sources) {
self.set_status(format!("Stream audio: {e}"));
}
self.mixer_refresh();
}
pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) {
self.transition(|state, cx| logic::respond_viewer(state, cx, viewer, accept));
}
pub(crate) fn kick_viewer(&mut self, viewer: u16) {
self.transition(|state, cx| logic::kick_viewer(state, cx, viewer));
}
// Watching.
pub(crate) fn watch_stream(&mut self, stream_id: String) {
if stream_id == "demo" && self.demo {
self.start_demo();
return;
}
let Some(session) = self.transition(|state, cx| logic::watch_stream(state, cx, &stream_id))
else {
return;
};
let wake = || later(|app| app.show_picture());
self.decoder = Some(self.video.watch(&self.engine, session as u64, &stream_id, wake));
self.refresh_viewer();
}
/// Watch the stream of `client` (a click on a streaming user in the
/// channel tree or the members): at once if it is known, else as soon as
/// the lookup brings it (it may have started in another channel or
/// before we joined).
pub(crate) fn watch_client(&mut self, client: u16) {
if let Some(id) = self.transition(|state, cx| logic::watch_client(state, cx, client)) {
self.watch_stream(id);
}
}
/// `VOELIN_OPEN=watch`: watch the first stream of our channel.
pub(crate) fn watch_first_stream(&mut self) {
if let Some(id) = logic::first_stream(&self.state) {
self.watch_stream(id);
}
}
/// The local test stream in the viewer (`VOELIN_DEMO_STREAM`).
pub(crate) fn start_demo(&mut self) {
self.transition(logic::start_demo);
let runtime = self.engine.runtime().clone();
let wake = || later(|app| app.show_picture());
self.video.demo(&runtime, wake, |result| {
later(move |app| {
let Some(watch) = app.state.watch.as_mut().filter(|w| w.session.is_none()) else {
return;
};
match result {
Ok(decoder) => app.decoder = Some(decoder),
Err(e) => watch.status = format!("The preview failed: {e}"),
}
app.refresh_viewer();
});
});
}
/// `VOELIN_OPEN=watch` with sample data: the local test pattern in the
/// viewer, dressed as the first stream of our channel.
pub(crate) fn demo_watch(&mut self) {
let sample = logic::demo_sample(&self.state);
self.start_demo();
if let (Some(watch), Some((id, title, streamer))) = (&mut self.state.watch, sample) {
(watch.stream_id, watch.title, watch.streamer) = (id, title, streamer);
}
self.refresh_viewer();
// Its card shows it as watched.
self.refresh_streams();
}
/// A decoded picture is waiting.
fn show_picture(&mut self) {
if self.state.watch.is_none() {
return;
}
let Some(image) = self.decoder.as_ref().and_then(Decoder::take_picture) else { return };
let first = logic::picture_shown(&mut self.state);
// Only the window with the player: each would scale it again.
self.with_player(|bridge, _| bridge.set_viewer_frame(image));
if first {
self.refresh_viewer();
}
}
pub(crate) fn show_viewer(&mut self, shown: bool) {
// Shown in the main window: from a window of its own, it comes back.
if shown && self.popout.window.is_some() {
self.viewer_dock();
return;
}
self.transition(|state, cx| logic::show_viewer(state, cx, shown));
}
/// Stop watching and close the viewer, its own window too.
pub(crate) fn leave_stream(&mut self) {
self.close_popout();
self.stop_watching();
}
/// Stop watching; a window of its own stays (for the next stream).
fn stop_watching(&mut self) {
self.transition(logic::stop_watching);
}
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
self.transition(|state, cx| logic::set_volume(state, cx, percent));
}
pub(crate) fn toggle_fullscreen(&mut self) {
let mut full = false;
self.with_player(|bridge, _| full = !bridge.get_viewer_fullscreen());
self.set_fullscreen(full);
}
/// The window with the player in full screen, or back.
pub(crate) fn set_fullscreen(&self, full: bool) {
self.with_player(|bridge, window| {
if bridge.get_viewer_fullscreen() == full {
return;
}
bridge.set_viewer_fullscreen(full);
window.set_fullscreen(full);
if !full {
// The player that hid the cursor may be gone already.
show_cursor(window, true);
}
});
}
}
/// What the state needs to know of a capture that started.
fn started(capture: &Capture) -> CaptureStarted {
CaptureStarted {
restore_token: capture.restore_token(),
automatic_bitrate: capture.streamer().bitrate_kbps(),
has_audio: capture.has_audio(),
audio_error: capture.audio_error(),
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the
//! viewer. The engine runs the stream sessions; `video.rs` captures,
//! encodes and decodes. What is state of the streams (what we share, what we
//! watch, the rows and texts) is in `voelin_ui_vm::streams::logic`; `bind`
//! has the Bridge writes, the capture and the decoder.
mod bind;
use crate::video::Capture;
pub(crate) use bind::show_cursor;
/// The capture that feeds our stream, while we share (`AppState::share` has
/// the rest): it stops when dropped.
pub(crate) struct Share {
pub capture: Capture,
/// The audio mixer's meters (the studio's rows), about 15 times a second.
_meters: slint::Timer,
}
+6 -6
View File
@@ -490,7 +490,7 @@ impl App {
if self.studio.run.is_some() {
return;
}
if self.share.is_some() {
if self.state.share.is_some() {
self.mixer_refresh();
}
if !self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_share_open()) {
@@ -566,7 +566,7 @@ impl App {
self.studio.models.chat.sync(&lines);
}
/// A chat of session `id` changed (chat.rs): follow it if it is the
/// A chat of session `id` changed (chat/): follow it if it is the
/// stream's.
pub(crate) fn studio_chat_changed(&mut self, id: i64, target: &ChatTarget) {
if self.studio.run.is_some()
@@ -596,7 +596,7 @@ impl App {
let sharing = st
.data
.destination
.is_some_and(|d| self.share.as_ref().is_some_and(|s| s.session == d));
.is_some_and(|d| self.state.share.as_ref().is_some_and(|s| s.session == d));
let session = st.data.stream.as_ref().map(|s| s.session);
let viewer_name = |v: &ViewerInfo| logic::viewer_name(&self.state, session, v.client);
let cx = logic::StatusContext {
@@ -1068,7 +1068,7 @@ impl App {
if self.studio.data.stream.is_some() || self.studio_streamer().is_none() {
return;
}
if self.share.as_ref().is_some_and(|s| s.session == session) {
if self.state.share.as_ref().is_some_and(|s| s.session == session) {
self.set_status("Stop sharing your screen first.");
return;
}
@@ -1253,12 +1253,12 @@ impl App {
});
}
/// A picture of the studio window (screenshots, dev.rs).
/// A picture of the studio window (screenshots, dev/).
pub(crate) fn studio_snapshot(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
self.studio.window.as_ref()?.window().take_snapshot().ok()
}
// Development switches and sample data (dev.rs).
// Development switches and sample data (dev/).
/// `VOELIN_OPEN=studio:<what>`: `window` (the window of its own), `live`,
/// `record`, or a dialog: `source`, `audio`, `camera`, `scene`, `settings`.
+8
View File
@@ -101,3 +101,11 @@ pub(crate) struct StudioState {
meters: Vec<Option<SourceHandle>>,
has_preview: bool,
}
impl StudioState {
/// The Stream Studio streams to `session`: the events of that stream
/// are its own.
pub(crate) fn streams_to(&self, session: i64) -> bool {
self.data.streams_to(session)
}
}
+1 -8
View File
@@ -509,14 +509,7 @@ fn share_rows(
}
/// Share settings from the dialog.
pub(crate) struct CaptureRequest {
pub fps: u32,
pub bitrate_kbps: u32,
pub audio: bool,
/// Mixed into the stream's audio (`stream.audio_sources`).
pub audio_sources: Vec<AudioSourceSpec>,
pub restore_token: Option<String>,
}
pub(crate) use crate::vm::streams::logic::CaptureRequest;
/// A running capture for our stream. Stops when dropped.
pub(crate) struct Capture {
+1 -1
View File
@@ -1,6 +1,6 @@
// Where the user is: the page, open dialogs, panel sizes. Any screen can
// navigate through these functions; Rust sets the same properties for the
// development switch VOELIN_OPEN (src/dev.rs).
// development switch VOELIN_OPEN (src/dev/mod.rs).
import { Bridge, BookmarkForm, ShareForm, EventForm, OfflineForm } from "bridge.slint";
import { StudioBridge } from "studio-bridge.slint";
+7
View File
@@ -7,6 +7,13 @@ all-features = false
# Unmaintained crates are reported but only fail for direct dependencies.
unmaintained = "workspace"
ignore = [
# TIME-LIMITED, remove by 2026-12-20 (entered 2026-10-25). `crypto-bigint` 0.5.5
# (through `elliptic-curve` 0.13 / `p256` 0.13 of `tsproto-types`) and 0.6.1
# (`tsproto` directly) have no fixed release on their lines; the fix is to move
# the tsclientlib fork to the `p256` 0.14 / `crypto-bigint` 0.7 line. The affected
# arithmetic serves the TeamSpeak identity (ECDH, ECDSA) in a client that holds
# only its own key, so the timing variability is a local concern.
{ id = "RUSTSEC-2026-0387", reason = "tsproto and tsproto-types pin crypto-bigint 0.5/0.6; fork upgrade to p256 0.14 is the follow-up" },
# Marvin attack: timing side channel in RSA *private-key* operations of the
# `rsa` crate, pulled in by russh. TeamSpeak SSH query servers use RSA host
# keys, so russh needs RSA to verify the server's signature (a public-key
+20 -8
View File
@@ -3,13 +3,15 @@
# Android APKs (docs/building.md, docs/android.md): a debug APK, installable
# as is, for arm64-v8a and x86_64 (emulators).
#
# docker build -f docker/android.Dockerfile -o dist/android .
# docker build -f docker/android.Dockerfile --build-arg ABIS=arm64-v8a -o dist/android .
# docker build --ssh default -f docker/android.Dockerfile -o dist/android .
# docker build --ssh default -f docker/android.Dockerfile --build-arg ABIS=arm64-v8a -o dist/android .
#
# or scripts/docker-build.sh android. A signed release APK needs your keystore
# (docs/release.md), passed as build secrets:
# or scripts/docker-build.sh android. --ssh default hands the build your
# ssh-agent, which must hold a key that can read the private VoelinProtocol
# repository (docs/building.md, "Depending on VoelinProtocol"). A signed
# release APK needs your keystore (docs/release.md), passed as build secrets:
#
# docker build -f docker/android.Dockerfile --build-arg APK=release \
# docker build --ssh default -f docker/android.Dockerfile --build-arg APK=release \
# --secret id=keystore,src=release.jks --secret id=signing,src=signing.env \
# -o dist/android .
#
@@ -21,8 +23,8 @@ FROM ubuntu:24.04 AS toolchain
ARG DEBIAN_FRONTEND=noninteractive
# JDK 17 (Gradle, the Android Gradle plugin), CMake + Ninja (the bundled libopus).
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl ninja-build openjdk-17-jdk-headless \
pkg-config python3 unzip \
build-essential ca-certificates cmake curl git ninja-build openjdk-17-jdk-headless \
openssh-client pkg-config python3 unzip \
&& rm -rf /var/lib/apt/lists/*
# Extra CA certificates (PEM, one or more), for building behind a
@@ -83,8 +85,18 @@ ARG APK=debug
# supplies a fresh non-secret nonce so a rotated key cannot reuse an old APK.
ARG SIGNING_CACHE_BUST=unsigned
WORKDIR /src
# voelin-identity comes from the private VoelinProtocol repository, fetched
# over SSH by Cargo through the system git, with the agent that
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# every cargo command needs this (Gradle's cargo-ndk inherits the agent and the
# variable below).
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-android,target=/src/target \
--mount=type=cache,id=voelin-gradle,target=/root/.gradle \
--mount=type=secret,id=keystore,required=false \
+17 -5
View File
@@ -5,17 +5,20 @@
# gateway (servers) as tsgw-<version>-linux-x86_64.tar.gz and
# tsgw_<version>_amd64.deb.
#
# docker build -f docker/linux.Dockerfile -o dist/linux .
# docker build --ssh default -f docker/linux.Dockerfile -o dist/linux .
#
# or scripts/docker-build.sh linux. The cargo registry and target directory
# live in cache mounts, so rebuilds are incremental.
# or scripts/docker-build.sh linux. --ssh default hands the build your
# ssh-agent, which must hold a key that can read the private VoelinProtocol
# repository (docs/building.md, "Depending on VoelinProtocol"). The cargo
# registry and target directory live in cache mounts, so rebuilds are
# incremental.
FROM ubuntu:24.04 AS toolchain
ARG DEBIAN_FRONTEND=noninteractive
# The same libraries as CI (.github/actions/system-deps), plus dpkg-dev for
# the .deb's dependencies and patchelf for the .tar.gz's bundled libraries.
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl dpkg-dev patchelf pkg-config \
build-essential ca-certificates cmake curl dpkg-dev git openssh-client patchelf pkg-config \
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
&& rm -rf /var/lib/apt/lists/*
@@ -37,8 +40,17 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
FROM toolchain AS build
WORKDIR /src
# voelin-identity comes from the private VoelinProtocol repository, fetched
# over SSH by Cargo through the system git, with the agent that
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# every cargo command needs this.
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-linux,target=/src/target \
cargo build --release --locked -p voelin-ui -p voelin-gateway \
&& scripts/package.sh linux /out
+20 -7
View File
@@ -4,11 +4,15 @@
# voelin-<version>-windows-x86_64.zip with voelin.exe, and the NSIS installer
# voelin-<version>-setup.exe.
#
# docker build -f docker/windows.Dockerfile -o dist/windows .
# docker build --ssh default -f docker/windows.Dockerfile -o dist/windows .
#
# or scripts/docker-build.sh windows. This builds for x86_64-pc-windows-gnu
# with mingw-w64; CI's Windows jobs build the MSVC target on Windows. Both run
# on Windows 10 and 11. Unsigned, like CI's (signing: docs/release.md).
# or scripts/docker-build.sh windows. --ssh default hands the build your
# ssh-agent, which must hold a key that can read the private VoelinProtocol
# repository (docs/building.md, "Depending on VoelinProtocol").
#
# This builds for x86_64-pc-windows-gnu with mingw-w64; CI's Windows jobs build
# the MSVC target on Windows. Both run on Windows 10 and 11. Unsigned, like
# CI's (signing: docs/release.md).
FROM ubuntu:24.04 AS toolchain
ARG DEBIAN_FRONTEND=noninteractive
@@ -16,8 +20,8 @@ ARG DEBIAN_FRONTEND=noninteractive
# assembly), CMake (the bundled libopus, aws-lc), Meson and Ninja (dav1d),
# NSIS (the installer), zip and unzip.
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl git meson mingw-w64 nasm ninja-build nsis perl \
pkg-config unzip zip \
build-essential ca-certificates cmake curl git meson mingw-w64 nasm ninja-build nsis \
openssh-client perl pkg-config unzip zip \
&& rm -rf /var/lib/apt/lists/* \
&& update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix \
&& update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix
@@ -89,9 +93,18 @@ ENV VPX_LIB_DIR=/opt/libvpx/lib VPX_INCLUDE_DIR=/opt/libvpx/include \
SYSTEM_DEPS_DAV1D_NO_PKG_CONFIG=1 SYSTEM_DEPS_DAV1D_SEARCH_NATIVE=/opt/dav1d/lib \
SYSTEM_DEPS_DAV1D_LIB=dav1d SYSTEM_DEPS_DAV1D_LINK=static
WORKDIR /src
# voelin-identity comes from the private VoelinProtocol repository, fetched
# over SSH by Cargo through the system git, with the agent that
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# every cargo command needs this.
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
# FFmpeg's LGPL DLLs go into the packages (scripts/fetch-ffmpeg-windows.sh).
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
RUN --mount=type=ssh,required=true \
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
--mount=type=cache,id=voelin-target-windows,target=/src/target \
cargo build --release --locked --target x86_64-pc-windows-gnu -p voelin-ui \
&& scripts/fetch-ffmpeg-windows.sh /tmp/ffmpeg \
+27 -8
View File
@@ -28,7 +28,8 @@ yet: Windows SmartScreen warns about the installer, and the debug APK is
signed with a debug key (fine for testing, not for the Play Store).
The gateway's image can also be built directly:
`docker build -f crates/voelin-gateway/Dockerfile -t tsgw .`.
`docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .`
(`--ssh default`: see [Locally with Docker](#locally-with-docker)).
Gitea at [git.faumaray.ru](https://git.faumaray.ru) builds the same package
types through `.gitea/workflows/release.yml`: manual runs produce one
@@ -80,7 +81,16 @@ scripts/docker-build.sh android # → dist/android/
scripts/docker-build.sh # all three
```
The same with plain Docker, e.g. `docker build -f docker/linux.Dockerfile -o dist/linux .`
The same with plain Docker, e.g. `docker build --ssh default -f docker/linux.Dockerfile -o dist/linux .`.
**The builds need an ssh-agent that holds a key able to read the private
VoelinProtocol repository** ([below](#depending-on-voelinprotocol)): Cargo
fetches it inside the image, through the agent that `--ssh default` hands to the
build. The key stays in the agent; it is not copied into the image or the build
cache. `scripts/docker-build.sh` passes `--ssh default` itself and stops with a
message when `ssh-add -l` shows no agent or no key (`eval "$(ssh-agent -s)"`,
then `ssh-add` your key). The server's host key comes from
`.gitea/known_hosts` ([ci.md](ci.md#voelinprotocol-access)).
Rebuilds are incremental: the cargo registry, `target/` and Gradle live in
BuildKit cache mounts (`docker builder prune` frees them).
@@ -153,13 +163,22 @@ set `net.git-fetch-with-cli = true` in `~/.cargo/config.toml`.
compiler (gcc or clang) and cmake.
`deny.toml` allows this one git source.
**CI and the Docker builds need read access to that repository too**: an SSH
deploy key (a repository secret written to `~/.ssh`, with the server's host key
in `known_hosts`) or an access token (rewrite the SSH URL to HTTPS with
**CI and the Docker builds read it with a read-only SSH deploy key.** The key
is registered on VoelinProtocol and stored as the repository secret
`VOELIN_PROTOCOL_DEPLOY_KEY`; the Gitea workflows write it to `~/.ssh` (CI) or
load it into an ssh-agent (release builds), the server's host key comes from the
committed `.gitea/known_hosts`, and Cargo is told to fetch with the system git
(`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because its built-in git client ignores
`~/.ssh/config`. The Docker builds use the same key through
`docker build --ssh default` (see above). What was set up, how to re-check the
host key's fingerprint and what each failure means:
[ci.md](ci.md#voelinprotocol-access). A runner of your own gets the same setup
from the workflows; the alternative to a deploy key is an access token (rewrite
the SSH URL to HTTPS with
`git config --global url."https://<token>@git.faumaray.com/".insteadOf ssh://gitea@git.faumaray.com/`
and set `CARGO_NET_GIT_FETCH_WITH_CLI=true`). Without it `cargo` cannot fetch
the dependency and a fresh checkout does not build; the details are in
VoelinProtocol's `docs/development.md` ("Depending on VoelinProtocol").
and set `CARGO_NET_GIT_FETCH_WITH_CLI=true`), which these workflows do not
use. More in VoelinProtocol's `docs/development.md` ("Depending on
VoelinProtocol").
### Working with a sibling VoelinProtocol checkout
+198 -16
View File
@@ -46,21 +46,25 @@ the separate `release.yml` workflow below.
this label (the left side must match the workflow's `runs-on`):
```text
ubuntu-24.04:docker://ghcr.io/catthehacker/ubuntu:act-24.04
ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04
```
Configure this in the runner's labels when registering/configuring it;
an `ubuntu-latest` label alone does not match. The job image must provide
Bash, Git, Node.js for checkout v4, and root or passwordless sudo for apt.
an `ubuntu-latest` label alone does not match. This is the image of the
runner that runs this repository's CI, and the one the tests are checked
against ([Tests under the job image](#tests-under-the-job-image)). The job
image must provide Bash, Git, the OpenSSH client, Node.js for checkout v4,
and root or passwordless sudo for apt.
3. Allow network access from the runner and job container to the Gitea
instance, GitHub (checkout action, dependencies and RustSec advisories),
GHCR (runner image), Ubuntu apt mirrors, rustup distribution servers,
crates.io and dependency/license sources used by cargo-about. The
`docker.gitea.com` (runner image), Ubuntu apt mirrors, rustup
distribution servers, crates.io and dependency/license sources used by
cargo-about. The
workspace also depends on the **private** VoelinProtocol repository
(`voelin-identity`, over SSH), so the job needs read access to it: an SSH
deploy key or an access token, set up as in
[building.md](building.md#depending-on-voelinprotocol). Until a runner has
it, a fresh checkout does not build there.
(`voelin-identity`, over SSH), so the job needs read access to it and the
server's SSH port. The workflows set that up themselves from a repository
secret: [VoelinProtocol access](#voelinprotocol-access). A runner needs
nothing for it beyond the network access and the image tools above.
4. Provision enough RAM, swap and free disk for a full Slint workspace build
plus cargo-deny/cargo-about compilation. These are large builds; monitor
the first run and size the runner accordingly. The workflow limits Cargo
@@ -93,14 +97,190 @@ No GitHub cache/artifact service or reusable-workflow support is required.
The job does not need a Docker socket mounted inside its container; the
runner itself still needs Docker access to start that container. Keep this
runner isolated from production services and credentials, particularly when
accepting untrusted pull requests. No release signing or publishing secrets
are needed.
accepting untrusted pull requests. CI needs one secret, the VoelinProtocol
deploy key below; it needs no release signing or publishing secrets.
After registering the runner, dispatch **CI** in Gitea Actions and inspect
all step results. Local YAML/shell checks do not prove that a particular
Gitea instance, runner registration, network policy or resource allocation
can complete this job.
### Tests under the job image
The test step runs as **root** in an Ubuntu 24.04 container of the
`ubuntu-24.04` label ([Runner setup](#runner-setup):
`docker.gitea.com/runner-images:ubuntu-24.04`, `HOME=/root`) to which only
the apt packages of the system-dependencies action are added. A test that
assumes a developer machine fails there, and a run takes about an hour, so
check a change to the tests the way CI runs them, with every failing test of
every crate listed in one go (`--no-fail-fast`):
```sh
# A bare clone of the private VoelinProtocol repository (see below the block):
# git clone --bare ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git <dir>
: "${PROTOCOL_GIT:?path of a bare clone of VoelinProtocol}"
# Root owns what the container writes: keep it in a directory of its own
# (.scratch/ is in .gitignore; see below the block for its removal).
mkdir -p .scratch
docker run --rm --init -v "$PWD":/src -w /src -e HOME=/root \
-v "$PROTOCOL_GIT":/protocol.git:ro -e CARGO_NET_GIT_FETCH_WITH_CLI=true \
-e CARGO_HOME=/src/.scratch/cargo -e RUSTUP_HOME=/src/.scratch/rustup \
-e CARGO_TARGET_DIR=/src/.scratch/target \
docker.gitea.com/runner-images:ubuntu-24.04 bash -c '
git -C / config --global url."file:///protocol.git".insteadOf \
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git
apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl git jq pkg-config python3 \
libasound2-dev libfontconfig1-dev libxkbcommon-dev libvpx-dev \
libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev xvfb xauth
curl --proto =https --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal --default-toolchain none
. "$CARGO_HOME/env" && rustup toolchain install
xvfb-run -a bash -c "VOELIN_X11_TEST_DISPLAY=\$DISPLAY \
cargo test --workspace --locked --no-fail-fast"'
```
`--init` is required: `bash -c` runs its last command, `xvfb-run`, as the
container's process 1, and that never gets to start `cargo` (the command
hangs). The runner starts its steps with `docker exec` in a container whose
process 1 is something else, so CI itself is not affected.
The private VoelinProtocol dependency needs the deploy key
([below](#voelinprotocol-access)). The block reads it from a local bare clone
instead: `PROTOCOL_GIT` is mounted at `/protocol.git` and git is told to use
it in place of the SSH URL (with `CARGO_NET_GIT_FETCH_WITH_CLI=true`, as in CI,
so that cargo runs the `git` command), which leaves `Cargo.lock` as it is.
The `git config` is run with `-C /` because a git worktree's `.git` file points
outside the mount, and `git config` in `/src` then fails with `fatal: not a git
repository: (null)` (exit 128). To use the deploy key instead, set it up as
described below and leave out the `PROTOCOL_GIT` lines and the `git config`
command. What the container wrote under `.scratch/` belongs to root; remove it
from a container as well:
```sh
docker run --rm -v "$PWD/.scratch":/s alpine:3.20 rm -rf /s/target /s/cargo /s/rustup
```
What the image lacks, and what the tests do about it. A test that is about
the missing piece returns without testing it, in most cases after printing a
line that says it skipped and names the piece (the wording differs from test
to test), or is `#[ignore]`d with the reason, and passes; any other test does
not need the piece.
| A test cannot count on | What the tests do |
|---|---|
| Regular user (root writes anywhere and creates missing directories) | Nothing relies on a permission bit or a missing directory failing. A path that cannot be written is built from something that fails for root too: below a regular file (`ENOTDIR`) or naming a directory (`EISDIR`), as `an_unwritable_path_fails_at_once` of the recorder does. |
| Sound card (`/dev/snd`), PipeWire and WirePlumber daemons | `libpipewire` and ALSA are there to build against only. `tests/pipewire_apps.rs` needs `pipewire`, `wireplumber` and `dbus-daemon` and, without them, prints a skipped line that names them. The camera tests are `#[ignore]`d (a camera and PipeWire). |
| D-Bus session bus | `voelin-platform`'s portal proxy test runs itself again under `dbus-run-session` on a bus of its own and, where that cannot be run, prints `skipped, nothing was checked: dbus-run-session cannot be run`; the notification and capture-portal tests run only where no bus is configured, and check that talking to a missing service fails cleanly. |
| GPU, `/dev/dri`, VA-API, `/dev/udmabuf` | The VA-API and DMA-BUF tests print a skipped line that names what is missing: a usable `h264_vaapi`, `/dev/udmabuf` or VA-API surfaces to export. |
| FFmpeg libraries, `ffmpeg` and `ffprobe` | The FFmpeg tests of `voelin-media` and `voelin-core` print a skipped line that names what is missing (the libraries, `ffmpeg`, `ffprobe`). The studio tests that read a recording back with `ffprobe` write and check the file themselves and skip only the `ffprobe` check; the RTMP tests need all three and skip. |
| H.264 encoder (no FFmpeg, no GPU, no OpenH264 library: `VOELIN_OPENH264_LIB` is unset and the download test is `#[ignore]`d) | Tests that need an H.264 encoder print a skipped line that says no H.264 encoder is there. Tests of codec choice state what `preferred_codec` promises with whatever the machine can encode. VP8 and VP9 (libvpx) are built in, so their round trips run. |
| X11 or Wayland display | `xvfb-run` supplies one X11 display and the step hands it over as `VOELIN_X11_TEST_DISPLAY` to the X11 capture and hotkey tests. `VOELIN_WLROOTS_TEST_DISPLAY` is unset, so the wlroots capture test prints `skipped`. |
| Playwright and Chromium (the image has Node) | The browser interop tests print `skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)`. |
| TeamSpeak dev servers | Without `VOELIN_LIVE=1` the live tests return at once (some print `skipped: set VOELIN_LIVE=1 with the dev servers running`); the gateway's live test is `#[ignore]`d (`needs a running tsgw and TeamSpeak server`). |
| DNS and internet while the tests run (the job needs the network for apt, rustup and crates before they start) | The tests use no DNS or internet; those that would are `#[ignore]`d with the reason: four resolver tests of `tsclientlib` (`needs DNS and the internet`) and the OpenH264 download test. |
`localhost` resolves to `::1` first in this image (it also has `127.0.0.1`).
The tests that reach a server of their own go to `127.0.0.1` by name, not
through `localhost`, so a machine where connections to `::1` hang (a
development machine with a VPN does that) changes nothing for them.
A test that passes in the image and fails now and then on a busy runner or
development machine is another kind of failure, a test of the machine's load:
[testing/load.md](testing/load.md) says how to make a machine busy to
reproduce one, what the tests that failed that way assert now, and which are
known and left alone.
### VoelinProtocol access
The workspace depends on `voelin-identity` from the **private** repository
`Voelin/VoelinProtocol`, as a git dependency over SSH
([building.md](building.md#depending-on-voelinprotocol)). Cargo resolves the
whole workspace before it builds anything, so *every* cargo command needs
that access: all of CI, all three package images and the gateway image (whose
crate does not use `voelin-identity` itself). Without it the first cargo
command fails with `unknown SSH host key` (runs 1037 and 1050 did).
What is set up:
- **The deploy key.** A read-only SSH deploy key is registered on
`Voelin/VoelinProtocol` (Settings → Deploy Keys, write access off). It has
no other use and no access to any other repository. Its private half is the
repository secret **`VOELIN_PROTOCOL_DEPLOY_KEY`** of `Voelin/VoelinClient`
(Settings → Actions → Secrets): the whole OpenSSH private key file, BEGIN
and END lines included, without a passphrase. To rotate it, make a new pair
(`ssh-keygen -t ed25519 -N '' -C voelin-client-ci -f key`), register
`key.pub` on VoelinProtocol, replace the secret with the contents of
`key`, run CI, then delete the old deploy key and `key`.
- **CI** (`ci.yml`). The workflow hands the secret to the checks action as its
input `protocol-deploy-key` (a repository secret is not visible inside a
composite action). The action's first step fails at once, naming the secret,
if the input is empty or is not a private key. Otherwise it writes the key to
`~/.ssh/voelin_protocol` (mode 0600, `~/.ssh` 0700), appends the host key
line to `~/.ssh/known_hosts`, writes a `Host git.faumaray.com` block to
`~/.ssh/config` (`User gitea`, that `IdentityFile`, `IdentitiesOnly yes`,
`StrictHostKeyChecking yes`) and exports `CARGO_NET_GIT_FETCH_WITH_CLI=true`
and `GIT_SSH_COMMAND` for the rest of the job (`ci.yml` sets the first one
in its own `env` as well). It prints only the key's
public fingerprint; the key is never echoed. After the system packages a
second step runs `git ls-remote` on VoelinProtocol, so a wrong key or host
key fails there, with the reason, and not inside a cargo command. The key
lives in the job container and goes with it.
- **Release** (`release.yml`). A step after checkout starts an `ssh-agent` on
the release host, loads the key into it from stdin (it is never written to
disk) and exports `SSH_AUTH_SOCK`; the agent forgets the key after nine
hours, and a last step, which also runs after a failure, stops it. The
builds pass the agent on with `docker build --ssh default`
(`scripts/docker-build.sh` does it for the three packages; the gateway image
step does it itself).
- **The images.** Each cargo `RUN` of `docker/*.Dockerfile` and
`crates/voelin-gateway/Dockerfile` has `--mount=type=ssh,required=true`, so
the key exists only inside that step, through the agent socket, and never
reaches a layer, a build argument or the cache; a build without `--ssh`
stops there with `unset ssh forward key default`. The build stage copies
`.gitea/known_hosts` to `/etc/ssh/ssh_known_hosts` and sets the same
`CARGO_NET_GIT_FETCH_WITH_CLI=true`; the toolchain stages install `git` and
`openssh-client`.
- **Cargo uses the system git** (`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because
Cargo's built-in git client does not read `~/.ssh/config` (so it cannot use
an `IdentityFile`), authenticates with an ssh-agent and checks the host
against `~/.ssh/known_hosts` and its own `net.ssh.known-hosts` setting. The
system git runs `ssh`, which reads the config above (and
`/etc/ssh/ssh_known_hosts` in the images), so the same files serve a plain
`git` call, Cargo and the access check.
- **The host key** is committed in [`.gitea/known_hosts`](../.gitea/known_hosts),
never fetched while a job runs. Gitea's built-in SSH server (`SSH-2.0-Go`)
offers an RSA host key only (`ssh-keyscan -t ed25519 git.faumaray.com`
prints nothing), so the line is `ssh-rsa`; its fingerprint is
`SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A`. Re-check it:
```sh
ssh-keygen -lf .gitea/known_hosts # the committed line
ssh-keyscan -t rsa git.faumaray.com | ssh-keygen -lf - # what the server offers now
```
Both print the fingerprint above. If the server's key is ever replaced on
purpose, confirm the new fingerprint with the server's administrator, put the
new `ssh-keyscan -t rsa` line and the date in `.gitea/known_hosts` and the
fingerprint here, and commit all of it in one change. Until then a changed key
makes every job stop with `Host key verification failed`, which is the point.
Pull requests from forks get no secrets: their CI run stops at the first step
with the message about the empty deploy key. Anyone who can change a workflow of
this repository, or run code in one of its jobs, can read the key; it can only
read VoelinProtocol, and it is replaced as above. That is one more reason to
keep the CI runner isolated, as said above.
If a run fails here:
| Message | Cause |
|---|---|
| `The VoelinProtocol deploy key is empty` | the secret is missing, empty or not visible (a fork's pull request) |
| `… is not an unencrypted OpenSSH or PEM private key` | the secret holds something else, or a key with a passphrase |
| `Permission denied (publickey)` in "Check read access to VoelinProtocol" | the key is valid but is not a deploy key of VoelinProtocol: compare the fingerprint "Deploy key installed" printed with the one in VoelinProtocol's deploy key settings |
| `Host key verification failed` | `.gitea/known_hosts` does not match the server: check as above before changing anything |
| `unset ssh forward key default` | a Docker build ran without `--ssh default`: a plain `docker build` (`scripts/docker-build.sh` passes it itself and stops earlier when the agent has no key) |
### Gitea release runner
The instance at `https://git.faumaray.ru` reported Gitea **1.25.4** on
@@ -114,9 +294,10 @@ host** runner with the label:
voelin-release:host
```
Provision Bash, Git, Node.js 20+, Python 3.11+, curl, tar, gzip and rootful
Docker 23+ with BuildKit. Use **act_runner 0.2.7 or newer** (prefer the latest
maintained release), or gitea-runner 2+. Older act_runner does not provide
Provision Bash, Git, the OpenSSH client (`ssh-agent` and `ssh-add`), Node.js
20+, Python 3.11+, curl, tar, gzip and rootful Docker 23+ with BuildKit. Use
**act_runner 0.2.7 or newer** (prefer the latest maintained release), or
gitea-runner 2+. Older act_runner does not provide
`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. Register the
runner against `https://git.faumaray.ru`, reachable from both the host and
build containers. Gitea 1.25.4 provides the required artifact-v4 API.
@@ -158,8 +339,9 @@ ENDLESS_TASK_TIMEOUT = 9h
Keep sufficient RAM/swap and free disk for all package builds and their
Docker caches. The package builds run one after another, each with as many
Cargo jobs as the host has CPUs. The workflow never prunes shared Docker
state or creates host swap. The token and optional Android signing secrets
are documented in
state or creates host swap. The secrets are the VoelinProtocol deploy key
([below](#voelinprotocol-access)), `RELEASE_TOKEN` and the optional Android
signing secrets, both documented in
[Gitea releases](release.md#gitea-releases).
The Gitea release job builds packages only: it runs no formatting, Clippy,
+1 -1
View File
@@ -240,7 +240,7 @@ the unit to `/etc/systemd/system/`.
**Container** (`tsgw-image.tar.gz`, or build it):
```sh
docker load -i tsgw-image.tar.gz # or: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
docker load -i tsgw-image.tar.gz # or: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
docker run -d --name tsgw --init --restart unless-stopped \
-v $PWD/tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
-e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
+206 -6
View File
@@ -3,8 +3,10 @@
Status: design (2026-10-20); slices 1, 2 and 3 are implemented (section 13
says how slice 1 differs from this text, sections 14 and 15 what its reviews
changed, section 16 what slice 2 built, found and corrected, section 17 what
slice 3 moved, changed and ran, and 17.7 the round after its review, which
brought the branch onto main `ad20979`); section 10 has the slices.
slice 3 moved, changed and ran, 17.7 the round after its review, which
brought the branch onto main `ad20979`, and 17.8 the round after the gate of the
merge; 17.6 has the complete edge list for the second half); section 10 has
the slices.
Design for the first half of plan step 7 (Phase 4): the engine consumes
`voelin_proto::link::Session`, `ServerLink` becomes an adapter over it, and
@@ -929,7 +931,7 @@ Nothing here blocks this half: each has a workaround above.
| H6 | Avatars and icons as attachments (`Image.attachment_id`, content-addressed cache) instead of channel-0 paths. |
| H7 | The UI on the replica (Phase 5): the old-model projection and F1-F10 go; `u16` client ids widen to `u32` participants. |
| H8 | Reconnect with backoff, resume tokens and persisted cursors move to `voelin-sdk` once it exists; the engine consumes the SDK. |
| H9 | Move `src/ts/` (with its live tests) to `voelin-gateway-ts` (features `basic`, `streams`), first behind a `ts` feature of `voelin-core`, then by git tag; the exit check of plan step 6, `cargo tree -p voelin-core -e normal \| grep -E 'tsclientlib\|tsproto'` empty, holds after H1-H3 and this. Two edges run from the engine into `src/ts/` and have to be cut first: `Backends::default` registers `ts::TsConnector` (the `ts` feature makes it optional), and `link/project.rs` and `link/session_link.rs` import `ts::ts_session::{entities::user_uid, ids}`, the id and uid rule that the projection undoes the synthetic ids with (it moves to the engine side, or into `voelin-model`'s replica conversion, which already has `uid_text`). |
| H9 | Move `src/ts/` (with its live tests) to `voelin-gateway-ts` (features `basic`, `streams`), first behind a `ts` feature of `voelin-core`, then by git tag; the exit check of plan step 6, `cargo tree -p voelin-core -e normal \| grep -E 'tsclientlib\|tsproto'` empty, holds after H1-H3, H5 and this (17.6 has the complete list of the edges between the engine and `src/ts/`, the stream split and the other crates that carry `tsclientlib`). The first two to cut run from the engine into `src/ts/`: `Backends::default` registers `ts::TsConnector` (the `ts` feature makes it optional), and `link/project.rs` and `link/session_link.rs` import `ts::ts_session::{entities::user_uid, ids}`, the id and uid rule that the projection undoes the synthetic ids with (it moves to the engine side, or into `voelin-model`'s replica conversion, which already has `uid_text`). |
### 11.3 Coordination
@@ -1634,9 +1636,112 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run.
### 17.6 Follow-ups
- **H9 gains two edges to cut** (11.2): `Backends::default` and the use of
`ts::ts_session::{entities::user_uid, ids}` in `link/project.rs` and
`link/session_link.rs`.
- **H9 starts from the complete edge list below.** The Opus gate of the merge
(2026-10-24) found that 11.2 names two edges and the tree has more. Each
line was checked with `rg` and `cargo tree` on the tree of the follow-up
round (`phase4/seam-followups`); file lines are given where the file did not
change in the round, items by name where it did.
1. **From the engine into `src/ts/`**: what has to be cut or moved before
`ts` can leave the crate.
| Where | What | Goes with |
|---|---|---|
| `link/backends.rs` | `use crate::ts::TsConnector`; `Backends::default` registers `TsConnector::new()`; `Backends::register_teamspeak(TsConnector)` is the only public way to register an in-process connector and goes through the crate-private `register_local(Arc<dyn LocalConnector>)` | H9: the `ts` feature makes `default` optional |
| `link/project.rs:20-21`, `link/session_link.rs:565, 973, 1328` | `ts::ts_session::entities::user_uid` and `ts::ts_session::ids::{self, FOREIGN_SYSTEM}`: the id and uid rule the projection undoes the synthetic ids with | H9: to the engine side, or into `voelin-model`'s replica conversion (`uid_text`) |
| `gateway.rs:98, 1209` | `ts::identity::{from_blob, to_blob}`: 98 is `login_identity` (the blob to the `tsclientlib::Identity` the gateway login is made of), 1209 is a test | H5: the gateway becomes a `Session` and takes the blob as a credential |
| `lib.rs:69` | `pub mod ts`: the public paths `voelin_core::ts::{identity, versions, TsConnector}` | H9: they move or are re-exported |
| outside the crate: `tools/voelinctl/src/{engine,identity,versions,client}.rs`, `crates/voelin-ui/src/{app,servers}.rs` and `settings_pages/bind.rs`, `crates/voelin-ui-vm/src/settings_pages/logic.rs`, `crates/voelin-core/tests/gateway.rs` | users of `voelin_core::ts::identity::*` and `ts::versions::*` (`to_blob`, `Found`, `import`, `import_new`, `discover`, `read`, `write_export`, `improve_level`, `LaunchImport`, `DEFAULT_NICKNAME`, `resolve`, `native_version`, `known_versions`, `client_metadata`) | H9: re-point to the new crate (`crates/voelin-ui*` belong to `phase5/ui-vm-2`) |
| docs: `lib.rs:8` (`ts::TsConnector`), `lib.rs:129` (`Command::ObserveGateway`: `ts::identity::to_blob`), `gateway.rs:103` (`to_blob`), `settings.rs:1138` (`import_new`); in `link/mod.rs` the module doc (`TsConnector`), `VoiceOptions::identity` (`to_blob`) and `VoiceOptions::client_version` (`ts::versions::resolve`) | intra-doc links into `ts`, which `cargo doc` with `-D warnings` resolves only while `ts` is in the crate | H9: reworded, or pointed at the new crate's docs |
A TeamSpeak connector in another crate has only
`Backends::register(Arc<dyn Connector>)`: `register_teamspeak` takes the
crate's own `TsConnector`, and `LocalConnector`, `LocalCtx`,
`LocalConnected` and `StreamPort` are crate-private. A plain `Connector`
is handed neither the `LocalCtx` (the event bus, `audio`, `stream_peer`)
nor a `StreamPort` (`Backends::connect` makes its `LocalConnected` with
`streams: None`), so its sessions have no TeamSpeak 6 streams. Streams
across the crate boundary need H2 first, or a public extension trait that
takes the place of `LocalConnector`.
*Test-only* edges, which move with the tests of each side:
`link/tests.rs` and `link/fake_link_tests.rs` (lines 30-31 of both) use
`ts::ts_session::LinkConnector` and `ts::{ConnectOptions, ServerLink}`;
the tests of `link/session_link.rs` use `ts_session::{backend_to_v1,
features_of}`; `link/tests.rs` uses the helpers
`ts::identity::{json_with_a_cut_key, assert_holds_no_piece_of}` and
`tests/session_fake.rs` builds a `tsclientlib::Identity` and runs
`Backends::default()` in one test (both from this round, with the gate's
minor).
2. **From `src/ts/` into engine-private items**: the reverse edges.
| Module of the engine | Items `src/ts/` uses |
|---|---|
| `crate::link` | `LinkCmd`, `LinkEvent`, `LinkCtx` (its `session`, `events`, `frames`, `settings`, `emit`, `done`), `Remote`, `BoxRead`, `BoxDuplex` (`ts/voice.rs`, `ts/ts_link.rs`, `ts/ts_session/driver.rs`); `LocalConnector`, `LocalCtx`, `LocalConnected`, `StreamPort`, `VERSION_PARAM`, `without_query` (`ts/ts_session/mod.rs`); `StreamEvent` (`driver.rs`) |
| `crate::stream` | `StreamCmd` (`voice.rs`, `driver.rs`), `StreamHandle`, `StreamInput` (`voice.rs`) |
| `crate::files` | `FileEntry`, `RequestId`, `TransferState`, and the functions `normalize_dir` and `join_path` (`voice.rs`, `driver.rs`) |
| `crate::offline` | `OfflineMessage`, `OfflineMessageInfo` (`voice.rs`, `driver.rs`) |
| the crate root | `Event`, `JoinFailure`, `BackendInfo`, `POKE_MESSAGE_MAX` |
| `crate::settings` | `SharedSettings`, through `LinkCtx.settings`, which `voice.rs` hands to the stream task |
| tests only | `crate::link::{Backends, VoiceOptions, connect_params}` (`ts_session/mod.rs`, `live_tests.rs`), `crate::link::media::TalkTracker` and `crate::link::project::{View, presence}` (`ts/book.rs`), `crate::settings::{SharedSettings, Settings}` and `crate::files::{Report, Sink}` (`ts/voice.rs`) |
Together with the first list this is a cycle: `voelin-core` would need
`voelin-gateway-ts` for `TsConnector` and the uid rule, and
`voelin-gateway-ts` needs `voelin-core` for every item above. So the "by
git tag" step of H9 needs **H1 and H2** (the TeamSpeak side speaks v1
through `Session`, which takes the place of `LinkCmd`, `LinkEvent`,
`LinkCtx`, `StreamPort` and the stream task's input) **or a shared
vocabulary crate** that holds the items above for both sides. Without
one of the two, only the first step, the `ts` feature of `voelin-core`,
is possible.
3. **What else keeps `tsclientlib` and `tsproto` in the tree.** The exit
check (`cargo tree -p voelin-core -e normal | grep -E 'tsclientlib|tsproto'`
empty) is not met by moving `src/ts/` alone:
- `voelin-core` itself: its four direct dependencies (`tsclientlib`,
`tsproto`, `tsproto-packets`, `tsproto-types`) leave with `src/ts/`,
but `gateway.rs` uses `tsclientlib::Identity` (`login_identity`,
`connect_watched`, `attempt`: H5) and `stream.rs` uses
`tsclientlib::ClientId` (item 4).
- Three more crates of `voelin-core`'s tree carry the dependency:
`voelin-store` (`store.rs` and `keystore.rs` take, read and check a
`tsclientlib::Identity`), `voelin-stream` (`proto.rs`, `session.rs`,
`discovery.rs`: `tsclientlib::{ClientId, InMessage, messages::c2s}` and
`tsproto_packets::packets::OutCommand`; H3 splits it) and
`voelin-gateway-proto` (`auth.rs`, `client.rs`:
`tsproto_types::crypto::EccKeyPrivP256`, the key of the gateway login;
H5). `cargo tree -p <crate> -e normal` shows it for each of the three.
- `voelin-query` and `voelin-observer` have none, so `query.rs` using
`voelin_query` is not an edge of the exit check; it goes with H5
because the query observer becomes a `Session` of a gateway daemon.
- So the exit check needs H1-H3, **H5**, a way for `voelin-store` to
handle a TeamSpeak identity without `tsclientlib`'s type, and H9.
4. **`stream.rs` must be split.** Stays with the engine: `StreamState`,
`WatchState`, `StreamFrame`, `StreamSink` and `LayerFormat` (public API),
`StreamCmd`, `OwnStreamEvent`, `kind_name`, `parse_kind` and
`parse_srtp_profiles` (`session.rs`), `media_codec` (`media.rs`) and the
re-exports of `stream_types` (`StreamInfo`, `StreamKind`, `StreamSetup`,
`ViewerInfo`, ...). Goes with the TeamSpeak 6 task: `StreamHandle`,
`StreamTask` and its helpers, `StreamInput`, the `StreamLookup` over the
gateway directory, and every use of `tsclientlib::ClientId` (the engine's
own ids are `u16`; `stream.rs` wraps them for `voelin-stream`).
5. **The engine API docs that link into `ts` move with it** (the last row of
the table of item 1): `VoiceOptions::identity` and
`Command::ObserveGateway` link `ts::identity::to_blob`,
`VoiceOptions::client_version` links `ts::versions::resolve`.
- **The same leak in `voelin-store`, not closed.** `Store::identity` and
`Store::identities` read the stored JSON of a TeamSpeak identity with `?`, so
an `Error::Json` whose text is the `serde_json` message, which quotes a key
that does not import, as the gate's minor did in the connector. The rows are
written from a `tsclientlib::Identity` (`add_identity`), so a damaged
database is the only way to such a row; the key store (`keystore.rs`) drops
the parse error for the same reason. `ts::identity::from_json` cannot be
used there (`voelin-core` depends on `voelin-store`); the fix is the same
classification in `voelin-store`, or `from_json` moved down.
- The bookmark tests of `link/connect.rs` that still sit in
`ts/ts_session/mod.rs` (17.2) belong next to it.
- `QueryLogin.allowlisted` goes with the query observer (H5), which becomes a
@@ -1720,3 +1825,98 @@ included.
The last bullet of 17.6 (documents that still name the old paths) is closed by
`76a884a`; the others stand.
### 17.8 The round after the gate (`phase4/seam-followups`)
The Opus gate of the merge (`c60acf9`) accepted it with one minor and notes for
H9. This round, on `phase4/seam-followups` from `c60acf9`, closes the minor,
writes the notes down (17.6) and deals with the five tests that failed on
their own on `main`. No history was rewritten. The `mao-*` agents were not
registered in the session, so a general-purpose agent played
`mao-implementer`, attempt 1.
| Commit | What |
|---|---|
| `a856f90` | The gate's minor. `ts::identity::from_json` is the classification `from_blob` had (malformed, cut short, not an identity, unreadable, with line and column, never the value), taking the JSON text; `from_blob` and `ts_session::inner_options` both use it. `inner_options` had put the `serde_json` error into the text, and `tsproto`'s key reader reports a key that does not import as `invalid_value(Unexpected::Str(key), ..)`, so the key reached `LinkEvent::Disconnected(Some(text))`, `Event::Error` and the status line. A credential that is not UTF-8 is "it is not text". Four tests, each with a key that lost its last two characters and none holding 8 characters in a row of the key: `identity::tests` (which also asserts that the reader's own message does quote it), `ts_session::tests` (`inner_options`), `link::tests` (the `Disconnected` text through `SessionLink` and the real connector) and `session_fake` (`ConnectVoice` through the engine with `Backends::default()`: the `Disconnected` state, the `Error` event and every event after it). The three connector-side ones fail with the `serde_json` text put back. |
| `563482d` | `VoiceOptions::nickname` and `server_password` have their docs; `Backends::set_account` says that no connector reads `ConnectParams.account` yet and that H4 moves the myTeamSpeak proof to it. |
| `96ff0e0` | The edge list of 17.6, and the H9 row of 11.2 pointing to it. |
| `9254e08` | `identity::tests::improve_level_keeps_the_key`. |
| `0d67dd7` | `voice_features::contacts_are_kept_in_the_database`. |
| `4be37e1` | `session::banner_tests::a_failing_banner_is_logged_once_with_its_address`, through `web::tests::info_lines`. |
| `e614a1c` | `discover::tests::without_records_the_gateway_itself_is_asked`. |
| `a90bb70` | `web::tests::pictures_go_through_the_proxy_named_for_each_hop`. |
| `c35bbb5` | `voelin-platform`'s `proxy::the_portal_names_the_proxy`. |
**The five flakes: all fixed, none recorded as known.** Two of the fixes are
rewrites of a test helper and a test, not one-line edits.
- `improve_level_keeps_the_key`: a fresh `Identity::create()` stops at the first
counter of level 8 or more and about one in 32 has 13 already, which
`improve_level` returns as it is. The test asks for three levels above what
its identity has. 8 failures in 300 runs of the single test before, 0 in 300
after.
- `contacts_are_kept_in_the_database`: dropping an `Engine` does not close the
history database. The engine task ends later, the history writer is joined
there, and closing the connection checkpoints the write-ahead log under an
exclusive lock with fsyncs; the second `History::open` waits for that lock
for the 5 s busy timeout only and fails with `DatabaseBusy` when a loaded
disk makes the close slower. A connection was still open (the `-wal` file
still there) in 23 of 24 instrumented runs, and 10 of those 24 (eight at a
time on a loaded machine) failed. The test now waits for the `-wal` file to
go (SQLite deletes it when the last connection closes) before it reopens.
With every fsync of the test process delayed by 6 s (`strace -f -e
inject=fsync,fdatasync:delay_enter=6000000`) the old test fails every time at
the reopen, and the new one passes.
- `a_failing_banner_is_logged_once_with_its_address` (`lines == []`):
`web::tests::info_lines` read the log with `tracing::subscriber::with_default`.
While that scoped subscriber is the only one alive, `tracing-core` registers
a callsite that another test's thread meets first against that thread's own
default (none) and the callsite stays disabled for every thread
(`callsite::Dispatchers::rebuilder`, `has_just_one`). Several tests of
`banner_tests` reach the same callsite through `image_finished`. The helper
now installs one recording subscriber as the global default the first time
and records into a buffer per thread. A new test (`info_lines_see_a_callsite_
another_thread_met_first`) fails with the old helper (`lines == []`, the
failure that was seen) and passes with the new one. The old helper failed 1 of
300 runs of `banner_tests`, the new one 0 of 600. The failure of the whole
suite did not occur in the twenty full runs below, so the evidence for this
fix is the mechanism, the new test and these rates.
- The two `localhost` tests fail where `localhost` resolves to `::1` only (the
servers of the tests listen on 127.0.0.1). The discovery test's `probing`
helper and the test SOCKS proxy dial `localhost` at 127.0.0.1; what the tests
check (the name the gateway is asked at, the name the proxy is given) is
unchanged.
- `the_portal_names_the_proxy` did not need `dbus-run-session` only: with a
session bus, on the desktop's or on a private one made by plain
`dbus-run-session`, it failed here three times out of three at "the portal
leaves the bus", because the bus can start the real `xdg-desktop-portal` by
name, which the first call after the stand-in has left does, and the real
one answers instead of the "missing for a minute" the test expects. The test
now runs itself again under `dbus-run-session` with a bus configuration of
its own, a session bus without service directories. Without
`dbus-run-session`, or when the bus does not come up, it prints "skipped,
nothing was checked" and the reason and passes. On the bus with the default
services the same test still fails (checked by hand).
**What ran.** The environment of 17.7, taken again: `nix shell` of `gcc cmake
gnumake pkg-config jq` and the `.dev` outputs of `alsa-lib openssl libvpx dav1d
pipewire fontconfig freetype libxkbcommon expat`, with `PKG_CONFIG_PATH` (the
`.dev` outputs), `LIBCLANG_PATH`, `BINDGEN_EXTRA_CLANG_ARGS` (`-isystem` the
`glibc.dev` headers: `libspa-sys` fails without) and, to run the binaries it
builds, `LD_LIBRARY_PATH` (the `.out` outputs of those: `libvpx.so.12`) set by
hand, and the 1.94 and nightly toolchains from their store paths in front of
`PATH`. The `dev rust-nightly` shell does not build here (`cargo-llvm-cov`).
With that, `cargo check --workspace --all-targets --locked` passes on 1.94, the
`voelin-ui`, `voelin-ui-vm`, `voelinctl`, `voelin-gateway` and `voelin-android`
targets included.
| Check | Result |
|---|---|
| `cargo fmt $(scripts/own-crates.sh) --check` | 1.94: clean at the head and at each of the nine commits, checked out detached one by one. `cargo fmt --all --check` as such is not clean at `c60acf9` on any toolchain: it includes the vendored `crates/proto`, which formats with upstream's nightly configuration, and the nightly `rustfmt` also reformats own files that 1.94's leaves alone (the CI runs the form above). |
| `cargo clippy -p voelin-core -p voelin-platform --all-targets --locked --no-deps -- -D warnings` | 1.94: clean at each of the nine commits, checked out detached one by one. |
| `cargo test -p voelin-core --locked --lib`, ten times in a row, no exclusions | Nightly: ten runs, each 252 passed, 2 ignored. 1.94: the same ten times. (The baseline of 17.5 and 17.7 had two failures in each run and needed `--skip`.) |
| `cargo test -p voelin-core --locked`, once | Both toolchains: green. Integration tests: `gateway` 9, `live` 6 and `stream_live` 3 (they skip without `VOELIN_LIVE`), `session_backends` 2, `session_fake` 20 passed and 2 ignored, `settings` 1, `voice_features` 3. |
| `cargo test -p voelin-platform --locked` | Both toolchains: 24 lib tests, `crash` 3, `proxy` 1 (on its own bus), `x11` 1 (skipped without a display), 2 doc tests. |
| `RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p voelin-core --locked` | 1.94 and nightly: clean. |
| `Cargo.lock`, `THIRD_PARTY_NOTICES.md` | Unchanged: `git diff c60acf9 -- Cargo.lock Cargo.toml` is empty, so there was nothing to regenerate. |
| `scripts/it-smoke.sh ts3 ts6`, on `c60acf9` (before) and at the head (after) | The stack of `VoelinGateWay/dev/docker-compose.yml` as a compose project of its own (`voelin-seam-followups`), the state directory under the scratch directory. On a fresh stack each (`down -v`, `up -d` before each): both pass every per-server scenario of ts3 and ts6 (connect and tree, server and channel chat, voice tone, invisible presence, relay, gateway, history, pins and reactions, the engine's voice features, the TeamSpeak 6 streams), the TeamSpeak session module stage (12 passed, 2 ignored; 16.38 s before, 16.73 s after) and fail in the same place, the engine stage at `ts6_banners` (`live.rs:396`, 5 passed, 1 failed), the failure 17.5 and 17.7 record. Two more runs on the first stack, which was no longer fresh (before, then after), gave the same: the outputs have 100 lines each and differ only in ids, counters, tone ratios and the number of tests filtered out of the module stage (236 before, 240 after: this round's four unit tests). The very first run, on `c60acf9` on the first stack, stopped earlier, at the first gateway request of the admin identity of ts3 (`config_set` not answered, observe stayed `Connecting`); it did not repeat on the fresh stack at `c60acf9`, nor in any later run, and was not chased. |
+261
View File
@@ -0,0 +1,261 @@
# Tests under load
A test that passes alone and fails one run in a hundred when the machine is
busy is a test of the machine. The runner shares its CPUs with other jobs, and
a developer's machine with whatever else runs on it, so the suite has to give
the same answer on a busy machine as on an idle one. This page says how to
make a machine busy, what the fixes of `phase5/test-hygiene` did about the
tests that failed only then, and what is known and left alone.
## The round of `phase5/test-hygiene`
The branch is `phase5/test-hygiene`, from `2ffe5ff` (main with the session
seam, its follow-ups, the CI deploy key and `phase5/tests-under-runner`). It
settles the left-overs of the review of the seam follow-ups and of the
tests-under-runner round. The `mao-*` agents were not registered in the
session, so a general-purpose agent played `mao-implementer` (Sonnet 5.5),
attempt 1; an earlier run of the same task was cut off by a restart of the
orchestrator, left four commits and an uncommitted tree, and this attempt
judged those, kept what was right and finished the rest. No history was
rewritten; `THIRD_PARTY_NOTICES.md` is untouched (`Cargo.lock` did not change).
| Commit | What | Whose |
|---|---|---|
| `e465a55` | Item 2: the fallback gateway test keeps its "closed" port bound | cut-off run, kept |
| `ac957a0` | Item 1: the history test of `gateway.rs` waits for the `-wal` file before it reopens (`tests/common/mod.rs`) | cut-off run, kept |
| `35408a3` | Item 5: the portal proxy test requires `1 passed` of its child | cut-off run, kept |
| `7e63092` | Item 4: `from_json`'s doc names voelin-core (voelin-store parses the text too: `keystore.rs` `check_teamspeak` and `level`, `store.rs` `list`) | cut-off run, kept |
| `0bc6aba` | Item 3: the account-change test names the step it timed out in | this attempt |
| `f9bfd5d` | Item 6: `rectangle_span` checks the pattern's structure | cut-off run's tree, committed |
| `25be433` | Item 6: the preview test checks its rates against its own timing | cut-off run's tree, committed |
| `81c40a4` | Item 6: `audio_sources_change_live` | cut-off run's tree, committed |
| `c5bb74f` | Item 6: the server-features test asks one question at a time | cut-off run's tree, committed |
| `7730460` | Item 6: the layer-format test waits for the stream task's answer | cut-off run's tree, committed |
| `9d04e01` | Item 6: the studio compose test waits for the frame it asks for | cut-off run's tree, committed |
| `92d02b0` | Beyond the list: the studio capture-backend test waits for the delivered count | cut-off run's tree, committed |
| `661a607` | Beyond the list: the scope test and `streamer_sends_opus` | cut-off run's tree, committed |
| `069fd2a` | Item 7: `ts6_banners` runs with the TeamSpeak 6 server to itself | cut-off run's tree, committed |
| `5c029a9` | Item 7: the smoke's `roundtrip` waits for its listener | cut-off run's tree, committed |
| `94195db` | rustfmt of four spots of the commits above | this attempt |
| `f508e5b` | Beyond the list: the automatic-bitrate test counts frames | this attempt |
| `ad80660` | The smoke script says which of its checks still flake | this attempt |
| `d4ccb8c`, `376925a` | `docs/testing/load.md` and the pointer in `docs/ci.md`; the record of the round, with the table of the checks | this attempt |
Two hunks of the cut-off run's tree were dropped: the timing instrumentation of
the account-change test (`Instant`s and an `eprintln!` of the steps, replaced
by the named `expect`s of `0bc6aba`; its numbers are below) and a
`#[cfg(test)] FIRST_SNAPSHOT` of 5 s in `ts_session` (it keeps the lib tests
from running the 250 ms the engine really has; see "Seen and left alone"). The
commits "beyond the list" are fixes of tests that failed in this round's own
runs, each in a commit of its own, and can be dropped without touching the
others.
What ran, on the final tree (the dev shell `dev rust-nightly -p cmake -p clang
-p pkg-config -p jq -p alsa-lib -p openssl -p libvpx -p dav1d -p pipewire -p
fontconfig -p freetype -p libxkbcommon -p expat -p dbus -p procps -p gnumake`
with the pinned 1.94 or the nightly of 2026-10-21 in front of `PATH`, and
`LIBCLANG_PATH`):
| Check | Result |
|---|---|
| `cargo fmt $(scripts/own-crates.sh) -- --check`, `cargo clippy $(scripts/own-crates.sh) --all-targets --locked --no-deps -- -D warnings` | 1.94: clean at the head |
| The same on nightly | clippy is blocked at sites of the baseline (none in a line of this branch): `chunks_exact_to_as_chunks` (voelin-core `audio.rs` and `media.rs:4057`, voelin-media), `manual_checked_ops`, `unnecessary_sort_by` (voelin-media), `result_large_err` (`ts/voice.rs:476`); with those four allowed the three touched crates are clean with all targets. voelin-platform is clean. `rustfmt` differs at `history.rs`, `ffmpeg/encoder.rs`, `discovery.rs`, `chat.rs` and `voelinctl/src/engine.rs`, none changed here |
| Clippy alone, at each of the 16 commits above that touch Rust, checked out detached | 1.94, `voelin-core`, `voelin-media`, `voelin-platform`, all targets, `media-desktop`: clean at each. `rustfmt` was not clean at seven commits from `c5bb74f` to `069fd2a` (the commits that wrote the four spots `94195db` formats, and the shell-only `5c029a9` that sits on that tree); per-commit rustfmt waived by the orchestrator, fixed forward, no history rewrite |
| `cargo test -p voelin-core -p voelin-platform -p voelin-media --locked --no-fail-fast`, ten times in a row | 516 tests passed and 13 ignored in each of ten runs, 33 test binaries each; load average 89 to 29 from other jobs |
| The same with `--features voelin-core/media-desktop` (the tests of this round's `media` fixes only exist there; `cargo test --workspace` has it on through `voelin-ui`) | 551 passed and 14 ignored in each of ten runs; load average 21 to 25 |
| `cargo check --workspace --all-targets --locked` | passes (1.94) |
| The tests of the tables below, 100 runs each of the binary of `2ffe5ff` and of the final tree, and the whole lib binaries | The tables below |
| `scripts/it-smoke.sh ts3 ts6` | Below, "The live smoke" |
## Making the machine busy
The recipe of that round: 32 busy loops beside the run (the machine had 32
threads), and the test binary started many times, a few at a time, so that
the tests of one binary also meet each other's load:
```sh
# 1. Build the test binaries once and note their paths (the "executable" of
# the lib and of each integration test); run those, not `cargo test`.
cargo test -p voelin-core --features media-desktop --lib --no-run --message-format=json
# 2. The busy loops, and 300 runs of one test, 8 at a time. (The
# whole binary, without --exact, is the better test of "under full
# load": every test of it runs at once.)
for _ in $(seq 32); do sh -c 'while :; do :; done' & done
trap 'kill $(jobs -p)' EXIT
seq 300 | xargs -P 8 -I{} sh -c '<executable> --exact <test> >/dev/null 2>&1 || echo FAIL' | sort | uniq -c
```
Compare a binary built before a change with one built after it, started
alternately in the same loop, so that both meet the same load. Write the load
average (`/proc/loadavg`) down with the result: other jobs on the shared
machine took it from the 32 loops' 32 to over 100 and, for minutes, to 250,
and some tests fail only above 150 (see below). A failure rate of one in a
hundred tests needs a few hundred runs to show; the whole binary shows its
flaky tests faster than each test alone, since its 275 tests compete.
## What the fixes assert
The rules the fixes of this round followed, in the order of preference:
1. **Wait for the state or event the test is about.** A deadline only ends a
hang (30 s), it never decides the result. A pause (`sleep`) is never what a
test waits for, and a "nothing happened" check waits for something that
comes after it (a command the same task answers in order, a count of
frames), not for time to pass.
2. **Derive a time from the work.** Where a rate is checked, the bounds come
from timestamps taken by the test around the calls, not from a constant.
3. **Check structure, not values within a tolerance**, where a lossy or
adaptive component is involved: an encoder that falls behind lowers its
quality, and a tolerance only moves the load at which the test fails.
4. **Keep what you reserved.** A port that is "free" because a listener was
bound and dropped can be handed to another test of the process at once;
a socket that stays bound and never listens refuses connections for the
whole test.
5. **A test that changes the state of a shared server runs with the server to
itself** (a lock in the test binary), however the harness schedules it.
## The load-only tests of the round
100 runs of each test alone, the binary of the commit before the round
(`2ffe5ff`) and the one after it, started alternately 8 at a time beside 32
busy loops (load average 34 to 81 during the runs), and 150 / 100 runs of the
whole lib binaries of `voelin-core` / `voelin-media`, 4 at a time beside the
same loops (load average 69 to 123). Failed runs, of the runs:
| Test | Why it failed | It checks now | Alone, before / after | Notes |
|---|---|---|---|---|
| `media::tests::local_preview_decodes_the_pattern`, `stream::tests::test_pattern_through_stream_tasks` (`media::rectangle_span`) | The VP8 speed control lowers the quality when the encoder falls behind; flat colours moved by 30 and more per channel and failed the tolerance of 24 (one of 40 was tried and reverted) | Each pixel is the nearer of the pattern's two colours; the middle row is background, one run of the rectangle, background; the span's width and movement as before. The preview's `fps` and `bitrate` are the counters' change over the time between the two stats calls, which the test timed | 1 / 0 and 1 / 0 of 100 | In the whole lib binary, before: 6 and 4 failures in 150 runs; after: 0 |
| `media::tests::audio_sources_change_live` | The state, mix and limiter were asserted when the meters showed, not waited for; the microphone thread published for one second, which a busy machine delayed past | Waits for the state, the mix and the limiter with the meters; the microphone is fed until the test has heard it | 0 / 0 of 100 | In the whole lib binary, before: 2 failures in 150 runs |
| `link::tests::the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list` | The file list was asked for every 20 ms and the answers fell behind the 16 events of the bus | One question at a time, the next after the answer (`ask_files_until`) | 0 / 0 of 100 | In the whole lib binary, before: 1 failure in 150 runs |
| `stream::tests::layer_formats_reach_the_live_stream` | "Nothing changed" was a 200 ms sleep, short of the stream task on a busy machine | A command the task answers with an event, sent after the format, and waited for: the task takes its commands in order | 0 / 0 of 100 | The "late streamer-side keyframe request" of the runner round was never seen and is not proven; a request the viewer's side makes late is not covered |
| `studio::tests::it_composes_into_the_preview_and_follows_commands` | The first frame after `SetPreview` can be one composed at the studio's start size (480x270) before the command applied | `preview_until`: the first frame of the size and scene asked for, out of at most 20 | 0 / 0 of 100 | In the whole lib binary of `voelin-media`, before: 0 of 100 runs; seen 2 in 150 earlier in the round |
| `gateway.rs`: `the_next_published_gateway_is_used_when_one_fails` | The "closed" port was bound and dropped; another test of the binary could be given it | A socket kept bound without listening, checked to refuse | 0 / 0 of 100 | |
| `gateway.rs`: `history_on_open_paging_and_offline_messages` | Dropping an `Engine` does not close its database; reopening waited 5 s for the exclusive lock of the closing connection (`DatabaseBusy`) | Waits for the `-wal` file to go (`tests/common/mod.rs`, shared with `voice_features.rs`) | 0 / 0 of 100 | The same as `contacts_are_kept_in_the_database`, fixed in `0d67dd7`. Beside the busy loops it did not fail; with every fsync of the process delayed by 6 s (`strace -f -qq -e trace=fsync,fdatasync -e inject=fsync,fdatasync:delay_enter=6s`) the old test fails every time at the reopen with `DatabaseBusy` (`gateway.rs:536`), the new one passes |
| `voelin-platform` `proxy.rs`: `the_portal_names_the_proxy` | A child that ran no test (its `--exact` name matches none) exits 0 | The wrapper requires `test result: ok. 1 passed;` in the child's output | 0 / 0 of 100 | |
Found by the same runs, beyond the list, and fixed in their own commits:
| Test | Why it failed | It checks now | Alone, before / after | Notes |
|---|---|---|---|---|
| `studio::tests::packets_reach_the_outputs_and_the_studio_is_a_capture_backend` | The studio counts a frame as delivered after handing it over, so the count could still be 0 | Waits for the count | 2 / 0 of 100 | Whole `voelin-media` binary, before: 11 of 150 runs (9 of them this test), then 2 of 100; after: 0 of 100 |
| `link::tests::a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks` | 5,000 channels were made after the connector's 250 ms wait for a first snapshot began; the scope was sent before the presence was in | The channels are made first; a voice packet through the link shows the presence is in | 0 / 0 of 100 | 3 failures of about 500 whole-binary runs before, 7 of 300 at a load average of 150 to 250 with the first half of the fix only (the channels first, no voice packet); too rare to count a rate after |
| `media::tests::streamer_sends_opus` | Ten frames of audio came before the first frame of video, which a busy machine delays | Waits for ten of audio and one of video | 0 / 0 of 100 | 2 failures of about 500 whole-binary runs before |
| `media::tests::an_automatic_bitrate_follows_the_stream` | The sink is told the format at `attach` and again by the encoder before its first frame; the test counted in between after a 200 ms pause | Counts after a frame has come and compares after five more | 2 of 900 before; 0 of 600 after | 1 of 150 in the final whole-binary run of the old test |
The whole `voelin-core` lib binary failed 12 of 150 runs before and 1 of 150
after (the last test of the table, fixed since), the `voelin-media` binary 2
of 100 before and 0 of 100 after.
## `ts::voice::account_tests::account_change_cancels_pending_handshake`
Seen once in about 130 runs of the whole suite under load by the review of the
seam follow-ups; the failure was not kept. It did not fail again in this round
(it does not touch the test's code or the code it drives), neither alone nor
in the whole lib binary:
- 600 runs alone, 8 at a time beside 32 busy loops (300 of the unchanged
binary, 300 of the timed one): 600 passed; 100 more before and 100 after
in the table above, 200 passed.
- It is in each whole-binary run of `voelin-core`: about 1,300 runs under
the busy loops in this round (150 of them of the final tree), in none of
which it failed (load average up to 250), and in the ten full runs of
`cargo test -p voelin-core -p voelin-platform -p voelin-media` of each kind
(with and without `media-desktop`) of the final tree.
- The test, timed (a throw-away build): the first handshake packet after
12.5 ms (median; 34 ms at most), the packet of the new socket after an
account change 6.9 ms (33 ms at most), the end of the connection after the
account source closed 0.2 ms (9 ms at most), in the 300 runs beside the 32
loops. Its deadlines are 5 s, 5 s and 2 s: 60 times or more the longest
step seen.
The test and the code were read for a race and none was found: the account
watch has seen its version before the connection is made, so a change after
the first packet always restarts the connection; the restart opens a socket of
its own, so a packet from another port is the new connection's; and dropping
the sender makes `changed()` fail, which ends the loop with the reason the test
expects. The only ways the test can fail are its three deadlines. That is the
evidence for "only load": a failure needs a stall of seconds in one step, and
the machine's, not the test's, is the likelier source. The three timeouts now
say which step it was, so the next failure is attributable; if it is seen
again, keep the output and the load average (`/proc/loadavg`) and see which
of the three it names.
## Seen and left alone
These failed in the runs of an intermediate tree of this round at load
averages of 150 to 250 (other jobs on the machine as well as the 32 loops),
and not in the runs of the final tree at 35 to 120. None of them is among the
tests this round changed.
- `link::tests::the_welcome_names_the_host_the_user_and_what_the_link_can_do`:
the test tells the connection that it is connected and, in the next
statement, gives it the snapshot; the session waits 250 ms for the snapshot
(`FIRST_SNAPSHOT` in `ts_session`), and at a load average of 250 the gap was
longer: the welcome had the user made up from the uid. Raising that constant
in test builds was tried and dropped: it stops the lib tests from running the
250 ms the engine really has.
- `link::tests::what_the_link_reports_comes_back_as_events` (3 of 300 runs of
the whole lib binary), `link::tests::the_stream_tasks_reports_are_not_held_for_ever`
(2 of 300) and `stream::tests::layers_through_stream_tasks` (3 of 500): timing
of reports against the machine, not looked into further. None failed in the
500 runs of the tree before the round, which ran at load averages up to 150.
- `media::tests::undecodable_video_is_noticed_through_the_pipeline` (1 of 100
runs of the whole `voelin-core` lib binary of the final tree, four at a time
beside 32 busy loops, load average 106 to 146; the review's run):
`DecodeWatch` called a real VP8 stream undecodable because no picture was
decoded within 400 ms and 10 frames. Untouched by this round; it did not fail
in 150 before or 150 after runs of the interleaved A/B.
`stream::tests::layers_through_stream_tasks` failed again in the same 100.
## The live smoke (`scripts/it-smoke.sh`)
The engine stage (`voelin-core`'s `tests/live.rs`, with `stream_live` and
`media_live`) failed on `disabled policy must prevent HTTP requests`
(`ts6_banners`) in every run that reached it, while the six tests passed
one after the other. The cause was the test: it sets the TeamSpeak 6 server's
banners and counts the requests that reach its own HTTP server for them, and
the other tests of the file, which cargo runs side by side, connect engines to
the same server; the server tells each of them the banners' addresses and an
engine fetches what it is told, so their requests were counted. With the tests
in pairs against the development servers: `ts6_banners` alone passes (62 s),
with `ts6_avatars`, `ts6_engine` or `ts6_channel_joins` it fails. It is not
the engine (it should fetch what the server announces) and not the order of the
script's stages (the tests of one binary run side by side whatever the stage
before). The tests that connect to the TeamSpeak 6 server now hold a lock of
the binary shared, and `ts6_banners` holds it exclusively.
Before the change, on `2ffe5ff`'s tests and script (the TeamSpeak 3 and 6
dev servers of `dev/docker-compose.yml`, as a compose project of their own):
the `live` binary failed `ts6_banners` in each run that reached it, with the
six tests side by side (5 passed, 1 failed); the smoke
stopped at `FAIL: private message: the action failed` in its TeamSpeak 3 stage
(`the client is not on the server`) and, in its TeamSpeak 6 stage, at
`FAIL: gateway request {"config_set":...} was not answered`. After it, at the
head of the branch: `scripts/it-smoke.sh ts3 ts6`, three times in a row, the
`live` binary passing 6 of 6 (66 s) in each run that reached the engine stage:
two runs passed every stage (`all smoke tests passed`), one failed in its
TeamSpeak 6 stage at `FAIL: the directory did not list the stream`, below.
What the smoke still does not do reliably, and was not changed for:
- Each step that starts a background client and then a second one
(`roundtrip`) used to wait a fixed 3 s; a dev server that takes 4 s to
13 s to let a client in made the action run before the listener was on the
server (`the client is not on the server`). It now waits for the listener's
`connected:` line. The server's own slowness is not removed.
- The stream directory check (step 10, TeamSpeak 6): the late viewer ends as
soon as it has 30 frames, and the `"title"` line the script looks for is
printed only if the viewer's own gateway session had connected and been
told of the directory by then. In the run that failed it had not (the
viewer's state stayed `observe=Connecting`): the stream was watched, 30
frames came, and the stream was listed through TeamSpeak 6's own listing
(`streams: ...`), which says nothing about the gateway's directory. A fix is
in `voelinctl engine` (end the viewer when it has both) and was left out of a
round about tests.
- The gateway stage (`voelinctl gateway --engine`, step 8) has failed in a run
with `expected output did not appear` while the engine was still
`observe=Connecting`, before the change as well. That may be the same wait
for a gateway session; it was not looked into.
- `ts6_banners` alone takes 62 s, so the engine stage takes more than a
minute longer than the sum of the others.
+153 -35
View File
@@ -22,11 +22,29 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
studio_bridge.rs the same for the Stream Studio
state.rs AppState, SessionView, Tab, Msg: what the client knows apart from
the window, generic over the list type of a chat tab's lines
servers.rs tree.rs chat.rs social.rs home.rs streams.rs avatar.rs studio/mod.rs
host.rs Host (what a transition asks of its front end), Update (what it
tells: Refresh, status, commands, Persist, ...), Cx
events/ events::apply: what an engine event does to the AppState
(mod.rs; gateway.rs: the gateway's events and directory)
previews.rs pictures linked in chat: which to fetch, the transfers
servers/mod.rs tree.rs chat/mod.rs social/mod.rs home.rs streams/mod.rs avatar.rs studio/mod.rs
pure view models (engine state → bridge structs), unit-tested
chat/logic.rs chat tabs, messages and what is read, pins and topics, files; the
chat view (tabs, lines, divider, drawers) and the user's moves
streams/logic.rs the streams we share and watch: their state, the events and the
user's choices, the streams panel's, the share card's and the
viewer's rows and texts
servers/logic.rs which server is shown and how it is observed, joining a channel;
the rail, the server card and the channel tree as plain data
settings.rs the UI's settings keys, the audio form
settings_pages/logic.rs, studio/logic.rs
the decisions of the settings pages and of the Stream Studio
dev/logic.rs the sample data of `VOELIN_DEMO_UI` as plain values and events
social/logic.rs the friends, the bell and the search as rows, what the user's moves on
them do, and what an event does to the friends, pokes and notices
settings_page/logic.rs
the audio settings page (devices, form, microphone test, push to
talk), the crash notice and the volume dialog of a client
bbcode.rs emoji.rs chat formatting; the Twemoji archive, text → runs of text and emoji
crates/voelin-ui/ the Slint front end
ui/
@@ -53,20 +71,32 @@ crates/voelin-ui/ the Slint front end
phone layout)
assets/ fonts/ (Inter, OFL), icons/ (Lucide, ISC), logo.svg
src/
app.rs setup, the Slint models (`Models`), event dispatch; `App` holds
app.rs setup, the Slint models (`Models`), the event loop; `App` holds
a `voelin_ui_vm::state::AppState` and the window
servers.rs chat.rs members.rs streams.rs settings_page.rs appearance.rs
home.rs social.rs messages.rs events.rs previews.rs popout.rs
the Slint side of each area (social.rs: contacts, the bell and the
search; previews.rs: pictures in chat; popout.rs: the stream's own
window)
host.rs SlintHost (the answers the transitions ask for), `App::handle_event`,
`transition` and `perform`: doing what an `Update` says
members.rs appearance.rs
home.rs messages.rs events.rs previews.rs popout.rs
the Slint side of each area (previews.rs: pictures in chat;
popout.rs: the stream's own window)
chat/ mod.rs, bind.rs: the chat view's Bridge writes and models
servers/ mod.rs, bind.rs: connecting and observing (store, secrets, engine),
the rail, the server card and the tree on the Bridge
social/ mod.rs (the models), bind.rs: contacts, the bell and the search on
the Bridge, the desktop toasts, the navigation after a move
settings_page/ mod.rs, bind.rs: the audio devices, the hotkey, the codec download,
the crash reports and the Bridge writes of the settings page
settings_pages/ mod.rs (Pages), bind.rs: the settings pages on the Bridge
streams/ mod.rs (Share: the capture), bind.rs: the streams panel, the share
dialog and the viewer on the Bridge, the capture and the decoder
studio/ mod.rs (StudioState), bind.rs: the Stream Studio's windows and engine
bind/ callbacks of each area, wired once; convert.rs, convert/items.rs
(plain values → Slint values), rows.rs (a Slint model kept in step
with a plain list)
images.rs the image cache (LRU, bounded by `ui.image_cache_mb`)
dev.rs development switches (screenshots, sample data)
dev/ mod.rs (the switches, listed), bind.rs: the window's size, the
screenshot, the screens opened at start, the sample data fed through
the app's own events
```
Models are created once (`app::Models`) and updated row by row with
@@ -87,12 +117,18 @@ this file is `voelin_ui_vm::chat`. The boundary:
- **Values.** A picture is an `ImageRef` (`Arc<ImageSource>`: a file of the
engine's cache with its stamp, decoded RGBA pixels, SVG or memory bytes,
or none; `size()` reads a file's header). A colour is an `Rgb(u32)`, a
or none; `size()` decodes a raster file once to tell it shows, and parses an SVG, so a
picture with a size is one a front end can draw). A colour is an `Rgb(u32)`, a
shared string an `Arc<str>`, a list a `Vec`. The bridge structs (51 in
`bridge.rs`, 10 in `studio_bridge.rs`) are plain `Clone + PartialEq + Debug`
structs with the field names of the Slint structs in `bridge.slint` and
`studio-bridge.slint`; `MytsBadge` and `MytsForm`, which have no data source
in this build, stay Slint-only.
in this build, stay Slint-only. The crate warns about undocumented public
items (`#![warn(missing_docs)]`) and has none, the mirror modules' 559
fields (460 in `bridge.rs`, 99 in `studio_bridge.rs`) included: 210 carry
the comments of the `.slint` files, and the other 349 (288 in `bridge.rs`,
61 in `studio_bridge.rs`), which had none there, were described from the
code that fills them. No module is exempt from the lint.
- **Lists.** `list::diff(old, new)` gives `Changes`: updates, removals and
insertions by index, in the order to apply them. `bind/rows.rs` applies
them to a `VecModel` and converts only the changed rows; a GPUI view
@@ -106,44 +142,124 @@ this file is `voelin_ui_vm::chat`. The boundary:
`voelin_ui_vm::state`, generic over the list type `L` of a chat tab's
lines: the Slint app plugs in `Rows<ChatLine>` (`app::ChatRows`), a front
end that re-renders can use a `Vec`. `App.state` is the one `AppState`.
- **Events.** `voelin_ui_vm::events::handle(state, social, host, event)` is
the one dispatch: it lets `social::logic::event` look at the event first
(the friends, pokes, offline messages and the notices, which need the state
as it was before the event), then `events::apply` changes the `AppState`,
and returns an `Update`, which says what the front end has to do: the parts
to draw again (`Refresh`, each once however many events set it), the status
line, the engine commands in order, what to keep (`Persist`: a bookmark,
the UI's settings, the audio settings, the clients' volumes), pictures to
decode again, the password dialog, notices for the bell, the chats that
changed and a stream to watch. `Host` is what the transitions ask while
they run: whether the chat or a private chat is on screen, the store's read
markers, the preview limit, the time. The Slint client's
`App::handle_event` is `handle` and then `perform`, which carries the update
out in `host.rs`; a GPUI client calls `handle` and draws what
`Update::refresh` names. The vm tests replay tapes of events against a fake
`Host` (`events/tests.rs`, `social/logic.rs`). `Update::rest` hands back the
events whose state is not in the `AppState`: the Stream Studio's stream
(`StreamState` and `StreamViewers` while `Host::studio_streams_to`),
`SettingChanged`, the answers to the offline message requests
(`RequestDone`, a list that failed; `messages.rs` keeps those for now), and
the rest that no screen looks at. `perform` handles `rest` before it draws
what `Update::refresh` names, as what the front end keeps may be on screen.
The text of an offline message is not in `rest`: `Event::OfflineMessage`
changes the `Social` state (`mail`, and the inbox row turns read) in
`social::logic::event`, so the redraw shows it (a tape test in
`social/logic.rs`). The streams we share and watch are in the `AppState`
(`share`, `watch`; the capture and the decoder are the front end's, and an
update says when to attach or drop them). The friends, the pokes, the
bell's notices, the text of the open
offline message and what the friends page and the search keep are in
`Social` (`social::logic`), which a front end passes to `handle` besides
the `AppState`.
- **Logic and bind.** An area that interleaves decisions with Bridge writes
is split into `<area>/logic.rs` in `voelin-ui-vm` (functions over the
settings service, the `AppState` and plain rows; they return rows,
commands or messages for the status line, and write no Bridge) and
`<area>/bind.rs` in `voelin-ui` (the Bridge and model writes, windows,
timers, threads, engine commands). Done: `settings_pages` and `studio`.
timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams`, `chat`, `servers`, `settings_page`, `social` and `dev`.
The pure code is tested in `voelin-ui-vm` (`cargo test -p voelin-ui-vm`,
no display); the Slint crate's tests are what needs the window types.
### Controllers still to split
Counted as `.set_` calls per file (`grep -c '\.set_'`, the status line's
`set_status` included) before this round's splits; Bridge writes alone are
about four fifths of each. Each one is a slice of the same shape as
`settings_pages` and `studio`: move the decisions into
`voelin-ui-vm/src/<area>/logic.rs`, keep the writes in
`voelin-ui/src/<area>/bind.rs`.
Plan section 6 step 2 (the toolkit-free `voelin-ui-vm` crate) is done: the
view models, the state, the state transition of every engine event and the
decisions of every area controller that interleaved them with Bridge writes
are in `voelin-ui-vm`, and the Slint crate keeps the writes. What is left
for step 3 (the GPUI front end) is the list at the end of this section.
Status at the merge of main 6e0df51 (2026-10-24): the branch carries the
session seam of main (c60acf9) and, since, the CI deploy key, the media codec
test and the seam follow-ups. None of them touches `voelin-ui` or
`voelin-ui-vm`, and the `.set_` counts below were counted again on the merged
tree and are as stated. The colour of a chat's avatar (the server's own for a
server's chat, the title's colour for any other and for a server that is
gone, never black) is `servers::logic::conversation_tint`, which `messages.rs`
calls and a test pins.
The measure is the number of `.set_` calls in the file (`grep -c '\.set_'`):
every setter counts, those of the Bridge, `Nav`, the window, models and the
engine, and the status line's `self.set_status(…)`, which writes the Bridge's
status text too. In the seven largest files before this round's splits
(230 calls: `streams.rs`, `chat.rs`, `app.rs`, `servers.rs`, `settings_page.rs`,
`social.rs` and `dev.rs`) 150 are direct writes to the Bridge (140 written as
`bridge.set_…`, ten as `ui.global::<Bridge>().set_…` or a chained setter;
one of the ten is `set_status_text`, the write inside `set_status`, so it is
not one of the 36) and 36 go through the status line, so Bridge writes are 186
of the 230, about four fifths of those files, and direct ones about two
thirds; the rest are `Nav`, window and engine setters (in `dev.rs` mostly
those). Each controller was a slice of the same shape as `settings_pages` and
`studio`: the decisions moved into
`voelin-ui-vm/src/<area>/logic.rs`, the writes stayed in
`voelin-ui/src/<area>/bind.rs`. The `.set_` calls of each file before and
after, every number counted with that command:
| Area | Before | After |
|---|---|---|
| Stream Studio | `studio.rs` 64 (62 once the view models had moved) | `studio/bind.rs` 58 |
| Settings pages | `settings_pages.rs` 52 | `settings_pages/bind.rs` 51 |
| Streams | `streams.rs` 45 | `streams/bind.rs` 38 |
| Chat | `chat.rs` 38 | `chat/bind.rs` 31 |
| Servers | `servers.rs` 37 | `servers/bind.rs` 31 |
| Audio settings page | `settings_page.rs` 26 | `settings_page/bind.rs` 26 |
| Friends, the bell, search | `social.rs` 23 | `social/bind.rs` 5 and `social/mod.rs` 15 (the models handed to the Bridge once) |
| Development switches | `dev.rs` 23 | `dev/bind.rs` 21 |
| Event dispatch and setup | `app.rs` 38 | `app.rs` 31 and `host.rs` 8 (carrying out an `Update`) |
The Bridge and model writes stay where the toolkit is, and what each write
says now comes from `logic.rs`, which has tests of its own.
Why the studio went before `streams.rs`: it had the most calls, and it is
self-contained. It has its own state (`StudioState`), windows and bridge
(`studio-bridge.slint`), so its decisions moved without touching the event
dispatch of `app.rs`. `streams.rs`, `chat.rs` and the rest of the list were
driven by that dispatch (the watch, share and history events), so they
followed it: the state transition of every engine event came first
(`events::apply`), then the controllers that show the result, `streams` first
as the one whose events were still the front end's.
Still to split before or while the GPUI front end is written (the files as they
stand):
| File | `.set_` calls | What it mixes |
|---|---|---|
| `streams.rs` | 45 | the streams panel, viewer and share dialog: what the voice card, the viewer header and the share form say, with the watch and share bookkeeping |
| `chat.rs` | 38 | the chat view: lines, the unread divider, pins, topics and downloads, with the engine's history batches |
| `app.rs` | 38 | event dispatch and the status line, the toolbar and tree refreshes |
| `servers.rs` | 37 | the rail, the server dialog and the channel tree's refresh |
| `settings_page.rs` | 26 | the audio settings page and the devices |
| `social.rs` | 23 | home's contacts, the bell and the search |
| `dev.rs` | 23 | development switches and the sample data (the switches stay with the window; the sample rows can move) |
| `app.rs` | 31 (4 in tests) | setup and the model hand-off, the status line, `setting_changed` (which setting touches what); the event dispatch itself is `vm::events::handle` and `events::apply`; the toolbar and tree refreshes are `servers/bind.rs` (`refresh_toolbar`, `refresh_tree`), which `app.rs` only calls |
| `images.rs` | 13 | the decoded-picture cache |
| `messages.rs` | 12 | direct messages |
| `messages.rs` | 11 | direct messages |
| `appearance.rs` | 11 | theme, font scale and breakpoints |
| `popout.rs` | 8 | the viewer's own window |
| `members.rs`, `links.rs`, `inbox.rs`, `home.rs`, `events.rs` | 6, 5, 5, 5, 4 | small; split with their neighbours |
Before this round: `studio.rs` had 62 and `settings_pages.rs` 52 (the two
with the most). Their `bind.rs` files still show 58 and 51 `.set_` calls: the
Bridge and model writes stay where the toolkit is, and what each write says
now comes from `logic.rs`, which has tests of its own.
The gate that accepted `voelin-ui-vm` asked for the `app.rs`/`events.rs` split
before the GPUI client. The dispatch is what moved (the `app.rs` part:
`handle` and `apply` in the crate, `host.rs` here); `events.rs` of
`voelin-ui` is no dispatch but the controller of the gateway's events page
(the event form, RSVP, the channels an event can be in), and it is not split.
Neither is the rest of `app.rs` named above: they are the next slices.
## Theme tokens
@@ -423,14 +539,16 @@ with the sample studio's sources, live at once with sample viewers.
## Adding a server
The add-server dialog (`BookmarkDialog` in `screens/dialogs.slint`, logic in
`servers.rs`) asks for the address (host, host:port, IP or server
`servers/`: the decisions in `voelin-ui-vm`'s `servers::logic`, the Slint side
in `servers/bind.rs`) asks for the address (host, host:port, IP or server
nickname; the resolver finds the port through SRV records and TSDNS) and
an optional server password. *Advanced* (open when editing) has the name
and the nickname, and empty fields there are filled in: the name is the
address until the first connection, then the server's own name
(`adopt_server_name`); the nickname is the default identity's (one imported
from TeamSpeak keeps its nickname there), else the system user's, else
"Voelin user"; the identity is the default one, there is no default channel.
(`adopt_server_name` in `voelin-ui-vm`'s `events`); the nickname is the
default identity's (one imported from TeamSpeak keeps its nickname there),
else the system user's, else "Voelin user"; the identity is the default one,
there is no default channel.
There are no gateway or ServerQuery fields: the gateway is looked up from
the address (DNS SRV records, else the gateway's `/.well-known/tsgw`) when
the server is saved, selected or connected
@@ -515,7 +633,7 @@ for importing the official clients' identities on start
the Slint side as `impl App` in `voelin-ui/src/<name>.rs`, with the
decisions in the view-model crate (`<name>/logic.rs`, [Two
crates](#two-crates)).
5. A development switch to open it (`dev.rs`, `VOELIN_OPEN=<name>`), a
5. A development switch to open it (`dev/bind.rs`, `VOELIN_OPEN=<name>`), a
screenshot (below) and a line in this file.
## Settings
@@ -601,7 +719,7 @@ notifications and the home's news show the text on one line
## Development switches and screenshots
Environment variables (see `src/dev.rs`):
Environment variables (see `src/dev/mod.rs`):
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with
formatting and emoji (and two pages of older messages, which load when
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more