Compare commits
144
Commits
No files matched your search
@@ -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
|
||||
|
||||
@@ -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==
|
||||
@@ -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 }}
|
||||
@@ -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
|
||||
@@ -16,7 +16,8 @@ runs:
|
||||
- name: apt packages
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
|
||||
# by the GPUI front end), libvpx + dav1d
|
||||
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
|
||||
# (bindgen), Xvfb (X11 tests).
|
||||
run: |
|
||||
@@ -27,7 +28,7 @@ runs:
|
||||
"${sudo[@]}" apt-get update
|
||||
"${sudo[@]}" apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates cmake curl git jq pkg-config python3 \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
|
||||
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
|
||||
xvfb xauth
|
||||
|
||||
|
||||
@@ -2,3 +2,5 @@
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
|
||||
/.scratch/
|
||||
+47
-7
@@ -8,6 +8,24 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Added
|
||||
|
||||
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
|
||||
window titled Voelin with one line of the app's state in it (the version,
|
||||
the voice connections that are up, the engine events handled, the seconds
|
||||
up), fed by the same engine and the same view models as the Slint app
|
||||
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
|
||||
radius, size and type token of the Slint app's `theme.slint`, light and dark
|
||||
(a test reads the Slint file and fails when the two differ), written into
|
||||
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
|
||||
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
|
||||
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
|
||||
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
|
||||
`scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a
|
||||
second: the CPU by group of threads, the memory and its own counters. A
|
||||
window that cannot open (no driver, no display server) ends the app with
|
||||
the reason and exit status 1. The Slint app (`voelin`) is unchanged and
|
||||
stays the app; both run on one engine until the GPUI one reaches parity
|
||||
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
|
||||
in software); no package ships it yet.
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
|
||||
opens the folder.
|
||||
@@ -69,13 +87,35 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- The view models, the app's state and the decisions of the settings pages and
|
||||
of the Stream Studio moved out of `voelin-ui` into a new crate,
|
||||
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
|
||||
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
|
||||
the Bridge writes and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Nothing changes on screen. See
|
||||
docs/ui.md, "Two crates".
|
||||
- The desktop portals (screen capture and camera through PipeWire, the push to
|
||||
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
|
||||
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
|
||||
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
|
||||
have both. Every D-Bus connection of the apps, the desktop notifications'
|
||||
included, now runs on an I/O thread of its own, whichever part of the app
|
||||
asks first.
|
||||
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
|
||||
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
|
||||
front end, which is being built, depends on a library that calls a function
|
||||
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
|
||||
builds from `rust:1.95-bookworm`.
|
||||
- The key store now keeps the device key when signing out of an account,
|
||||
unbound, whether it was in use before the account or was made for it; "Forget
|
||||
this device's identity" is the only way a key is deleted. The identity store
|
||||
also reports a damaged TeamSpeak identity by the kind of damage and never
|
||||
repeats its key in an error. Nothing changes on screen yet: accounts and
|
||||
sign-in are later steps.
|
||||
- The view models, the app's state, the state change of every engine event and
|
||||
the decisions of the settings pages, the Stream Studio, the streams, the chat,
|
||||
the servers, the audio settings page, the friends and the development
|
||||
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
|
||||
depends on no UI toolkit (a second front end can use it); `voelin-ui`
|
||||
converts its plain rows into Slint's and keeps the window, the Bridge writes
|
||||
and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Two things change on screen: the chat of
|
||||
a server that is gone takes the colour of its title instead of opaque
|
||||
black, and a cached avatar file cut after a valid header shows the
|
||||
initials instead of a broken picture. See docs/ui.md, "Two crates".
|
||||
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
|
||||
key, the signed-in account) with the account each belongs to, as a
|
||||
`voelin-identity` key store, in two database migrations. Existing
|
||||
|
||||
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
|
||||
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
|
||||
project's own crates (`scripts/own-crates.sh`) green.
|
||||
|
||||
Two front ends run on one engine until the second reaches parity:
|
||||
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
|
||||
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
|
||||
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
|
||||
view models and the state, with no UI toolkit (`docs/ui.md`).
|
||||
|
||||
## Hosting: Gitea, not GitHub
|
||||
|
||||
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
|
||||
|
||||
Generated
+3680
-142
File diff suppressed because it is too large.
Load diff
+14
-6
@@ -15,6 +15,7 @@ members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
@@ -36,6 +37,7 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
@@ -48,7 +50,7 @@ default-members = [
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
rust-version = "1.95"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Faumaray/Voelin"
|
||||
publish = false
|
||||
@@ -58,13 +60,19 @@ publish = false
|
||||
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
|
||||
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
|
||||
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
|
||||
# the three crates below are at one revision (main c8e0e5a: the account-bound
|
||||
# KeyStore of Phase 2 task 28, the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# the three crates below are at one revision (main c5bb6b9: the account-bound
|
||||
# KeyStore whose sign-out keeps every device key and the release of a device key,
|
||||
# Phase 2 task 34; the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# The UI-facing domain model and the client's replica of v1 entities.
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
|
||||
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
|
||||
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
|
||||
# "The version to pin").
|
||||
gpui-kit = "=0.8.1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
|
||||
@@ -48,6 +48,11 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
|
||||
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
|
||||
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
|
||||
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
|
||||
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
|
||||
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
|
||||
([docs/ui.md](docs/ui.md), "The GPUI front end")
|
||||
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
|
||||
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
|
||||
clients through a TS6 server
|
||||
@@ -79,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
|
||||
```sh
|
||||
# Desktop app
|
||||
cargo run -p voelin-ui --bin voelin
|
||||
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
|
||||
cargo run -p voelin-gpui --release
|
||||
|
||||
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
|
||||
docker compose -f dev/docker-compose.yml up -d
|
||||
|
||||
+3261
-45
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,13 @@ archive in crates/voelin-ui-vm):
|
||||
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
|
||||
Contributors, under the ISC License; the icons derived from Feather are
|
||||
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
|
||||
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
|
||||
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
|
||||
client's own set above), Copyright (c) Lucide Icons and Contributors, under
|
||||
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
|
||||
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
|
||||
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
|
||||
the crates).
|
||||
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
|
||||
contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
|
||||
|
||||
@@ -23,6 +23,10 @@ accepted = [
|
||||
"LicenseRef-Slint-Royalty-free-2.0",
|
||||
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
|
||||
"bzip2-1.0.6",
|
||||
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
|
||||
# (notify 8, tiny-keccak); see deny.toml.
|
||||
"0BSD",
|
||||
"CC0-1.0",
|
||||
]
|
||||
|
||||
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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())?;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -313,7 +313,7 @@ async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
}
|
||||
let report = conformance::run(&through_the_registry).await;
|
||||
assert_eq!(report.cases.len(), conformance::CASES.len());
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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?)"),
|
||||
}
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -255,8 +255,21 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
serde_json::from_str(&blob.json).map_err(|e| {
|
||||
// Where the JSON is wrong, not what it says: it holds a private key.
|
||||
from_json(&blob.json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; voelin-core reads that text only through here (voelin-store
|
||||
/// parses it too, for its own checks of a stored row).
|
||||
///
|
||||
/// What does not read is refused in words that say how it is wrong
|
||||
/// (malformed, cut short, not an identity, unreadable) and where (line and
|
||||
/// column), and never what it holds: the text holds a private key, and the
|
||||
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
|
||||
/// key that does not import as an invalid value, the key string and all), so
|
||||
/// that message is never shown, not in an error, an event or a log.
|
||||
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
|
||||
serde_json::from_str(json).map_err(|e| {
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax => "malformed",
|
||||
serde_json::error::Category::Eof => "cut short",
|
||||
@@ -271,6 +284,27 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
|
||||
}
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -615,18 +649,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON reader's own message quotes a key that does not import, so the
|
||||
/// refusal is worded by `from_json` and holds none of the key.
|
||||
#[test]
|
||||
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
|
||||
let (json, cut) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
|
||||
for error in [
|
||||
from_json(&json).unwrap_err().to_string(),
|
||||
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
|
||||
] {
|
||||
assert!(
|
||||
error.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
assert_holds_no_piece_of(&error, &cut);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn improve_level_keeps_the_key() {
|
||||
let identity = synthetic();
|
||||
// A fresh identity stops at the first counter whose level is 8 or more,
|
||||
// and about one in 32 has 13 or more already, which `improve_level`
|
||||
// returns as it is: ask for more than this one has, whatever it has.
|
||||
let target = identity.level() + 3;
|
||||
let levels = std::sync::Mutex::new(Vec::new());
|
||||
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
|
||||
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
|
||||
levels.lock().unwrap().push(l);
|
||||
})
|
||||
.unwrap();
|
||||
assert!(better.level() >= 13);
|
||||
assert!(better.level() >= target);
|
||||
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
|
||||
assert!(better.counter() > identity.counter());
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
|
||||
// Cancelled: nothing.
|
||||
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
|
||||
// Already there: the same identity.
|
||||
|
||||
@@ -333,7 +333,7 @@ enum Expect {
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
|
||||
/// Every case of the suite of the protocol repository at `c5bb6b9`, in its
|
||||
/// order, with what a TeamSpeak session does with it. A case the suite gains
|
||||
/// fails `the_suite_is_known` until it is listed here.
|
||||
///
|
||||
|
||||
@@ -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 ¶ms.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"));
|
||||
|
||||
@@ -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")
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
# 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
|
||||
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
FROM rust:1.95-bookworm AS build
|
||||
WORKDIR /src
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake 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
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
[package]
|
||||
name = "voelin-gpui"
|
||||
version = "0.0.1-alpha"
|
||||
description = "The GPUI front end of the desktop app, under construction: it runs on the same engine as the Slint front end (voelin-ui) until it reaches parity."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "voelin_gpui"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "voelin-gpui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
|
||||
gpui-kit = { workspace = true }
|
||||
# The engine's runtime and the channel of its events (a tokio receiver needs no
|
||||
# reactor, so GPUI's executor can await it).
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
|
||||
# commit that moved voelin-media and voelin-platform to it) lets this binary
|
||||
# hold both the portals and gpui-kit.
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
|
||||
# The app's name and id, the hotkeys and portals of the slices to come.
|
||||
voelin-platform = { path = "../voelin-platform" }
|
||||
# The Host trait's types (what the store knows of a chat's read marker).
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
# The view models and the state, shared with the Slint front end.
|
||||
voelin-ui-vm = { path = "../voelin-ui-vm" }
|
||||
|
||||
# The meter reads /proc/self (CPU ticks per second, the page size).
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { version = "1.1.5", features = ["param"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests
|
||||
# need no display. gpui-kit's own `test-support` feature is not used: it names
|
||||
# the optional `gpui-fast` backend in weak features, which puts gpui-fast and
|
||||
# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit
|
||||
# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does
|
||||
# not resolve).
|
||||
gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
|
||||
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
|
||||
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
|
||||
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
|
||||
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
|
||||
//! table written with `std`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let manifest =
|
||||
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
|
||||
let dir = manifest.join("../voelin-ui/ui/assets/icons");
|
||||
println!("cargo:rerun-if-changed={}", dir.display());
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
|
||||
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
|
||||
.filter(|name| name.ends_with(".svg"))
|
||||
.collect();
|
||||
names.sort();
|
||||
assert!(!names.is_empty(), "no icons in {}", dir.display());
|
||||
let mut table = String::from(
|
||||
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
|
||||
);
|
||||
for name in &names {
|
||||
let path = dir.join(name);
|
||||
let path = path.canonicalize().unwrap_or(path);
|
||||
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
|
||||
}
|
||||
table.push_str("];\n");
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
|
||||
std::fs::write(out, table).expect("write icons.rs");
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! The root state of the window, `Entity<AppState>`: everything the client
|
||||
//! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes
|
||||
//! beside it) and the three loops that keep it current on GPUI's thread:
|
||||
//!
|
||||
//! - the **engine's events**: a foreground task awaits the receiver of
|
||||
//! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so
|
||||
//! GPUI's executor can poll it), hands every event to
|
||||
//! [`events::handle`] and tells the entity to redraw (`cx.notify()`), the
|
||||
//! pattern of spike 3's hotkey task;
|
||||
//! - the **tick**, once a second, a loop of `background_executor().timer`
|
||||
//! (the Slint front end's `slint::Timer` calling `App::tick`);
|
||||
//! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the
|
||||
//! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a
|
||||
//! channel of jobs a third foreground task runs on GPUI's thread, as
|
||||
//! `later(|app| ...)` does in the Slint front end.
|
||||
//!
|
||||
//! What a transition asks for besides the state (`Update`: which parts to
|
||||
//! draw again, what to keep, the streams' capture and decoder) belongs to
|
||||
//! the slices that have those parts; today only the engine commands go out
|
||||
//! and the warnings are logged.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gpui_kit::Context;
|
||||
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
|
||||
use voelin_core::{AudioSettings, Command, Engine, Event, VoiceState};
|
||||
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
|
||||
use voelin_ui_vm::bridge::ChatLine;
|
||||
use voelin_ui_vm::events;
|
||||
use voelin_ui_vm::host::{Host, Update};
|
||||
use voelin_ui_vm::settings::UiSettings;
|
||||
use voelin_ui_vm::social::logic::Social;
|
||||
|
||||
use crate::meter::Counters;
|
||||
|
||||
/// The toolkit-free state of the client, with the chat lines of a tab as plain
|
||||
/// rows (what a front end that draws again from the list needs).
|
||||
pub type VmState = voelin_ui_vm::state::AppState<Vec<ChatLine>>;
|
||||
|
||||
/// A job for GPUI's thread, from any thread.
|
||||
type Job = Box<dyn FnOnce(&mut AppState, &mut Context<AppState>) + Send>;
|
||||
|
||||
/// How other threads reach the root state: `later.run(|app, cx| ...)` runs
|
||||
/// the closure on GPUI's thread with the entity (the Slint front end's
|
||||
/// `later`). Cloneable and `Send`; the closure must be `Send` too.
|
||||
#[derive(Clone)]
|
||||
pub struct Later(UnboundedSender<Job>);
|
||||
|
||||
impl Later {
|
||||
/// Run `job` on GPUI's thread soon. `false` once a job has found the
|
||||
/// window gone (the entity released): the loop that runs the jobs notices
|
||||
/// that only when a job reaches it, ends and drops the channel, so the
|
||||
/// first job sent after the window went answers `true` and is never run.
|
||||
/// `true` is a promise of nothing more than that the job was queued.
|
||||
pub fn run(
|
||||
&self,
|
||||
job: impl FnOnce(&mut AppState, &mut Context<AppState>) + Send + 'static,
|
||||
) -> bool {
|
||||
self.0.send(Box::new(job)).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the transitions of the state ask of this front end while they run.
|
||||
/// There is no store yet (the shell slice opens it): nothing was read, and
|
||||
/// nothing is kept.
|
||||
#[derive(Debug, Default)]
|
||||
struct ShellHost;
|
||||
|
||||
impl Host for ShellHost {
|
||||
fn demo_ui(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn chat_shown(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn watching(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn autowatch(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn studio_streams_to(&self, _session: i64) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn preview_limit(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn fetch_images(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn dm_shown(&self, _session: i64, _uid: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn chat_reads(&self, _server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn set_chat_read(
|
||||
&self,
|
||||
_server_uid: &str,
|
||||
_target: &StoredTarget,
|
||||
_read: &ChatRead,
|
||||
) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The root entity.
|
||||
pub struct AppState {
|
||||
/// What the client knows apart from the window.
|
||||
pub vm: VmState,
|
||||
/// The friends, pokes and notices the social screens keep.
|
||||
pub social: Social<()>,
|
||||
/// Engine events handled since the window opened.
|
||||
pub events_handled: u64,
|
||||
/// One-second ticks since the window opened.
|
||||
pub ticks: u64,
|
||||
engine: Option<Engine>,
|
||||
host: ShellHost,
|
||||
started: Instant,
|
||||
counters: Counters,
|
||||
later: Later,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// The state at start, with its three loops running: the engine's
|
||||
/// `events` (the engine is `None` in tests that need none), the tick and
|
||||
/// the jobs of [`Later`]. They end when the entity is released.
|
||||
pub fn new(
|
||||
engine: Option<Engine>,
|
||||
events: UnboundedReceiver<Event>,
|
||||
counters: Counters,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let (later, mut jobs) = mpsc::unbounded_channel::<Job>();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let mut events = events;
|
||||
while let Some(event) = events.recv().await {
|
||||
if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
loop {
|
||||
cx.background_executor().timer(Duration::from_secs(1)).await;
|
||||
if this.update(cx, |state, cx| state.tick(cx)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
while let Some(job) = jobs.recv().await {
|
||||
if this
|
||||
.update(cx, |state, cx| {
|
||||
state.counters.later_jobs.incr();
|
||||
job(state, cx);
|
||||
cx.notify();
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
Self {
|
||||
vm: VmState::new(
|
||||
Vec::new(),
|
||||
UiSettings::default(),
|
||||
AudioSettings::default(),
|
||||
Default::default(),
|
||||
),
|
||||
social: Social::default(),
|
||||
events_handled: 0,
|
||||
ticks: 0,
|
||||
engine,
|
||||
host: ShellHost,
|
||||
started: Instant::now(),
|
||||
counters,
|
||||
later: Later(later),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle other threads use to run something on GPUI's thread.
|
||||
pub fn later(&self) -> Later {
|
||||
self.later.clone()
|
||||
}
|
||||
|
||||
/// What an engine event does to the state ([`events::handle`], the one
|
||||
/// dispatch of both front ends), and what comes of it for the engine.
|
||||
pub fn handle_event(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||
self.events_handled += 1;
|
||||
self.counters.engine_events.incr();
|
||||
let update = events::handle(&mut self.vm, &mut self.social, &self.host, event);
|
||||
self.perform(update);
|
||||
self.counters.connections.set(self.connections() as u64);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Do what an update asks that this front end has the parts for: the
|
||||
/// engine's commands go out, the warnings are logged.
|
||||
fn perform(&mut self, update: Update) {
|
||||
if let Some(engine) = &self.engine {
|
||||
for command in update.commands {
|
||||
engine.send(command);
|
||||
}
|
||||
}
|
||||
for warning in update.warnings {
|
||||
tracing::warn!("{warning}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The once-a-second work: what the Slint front end's `App::tick` will be
|
||||
/// here (stream statistics, stored settings); today it counts.
|
||||
pub fn tick(&mut self, cx: &mut Context<Self>) {
|
||||
self.ticks += 1;
|
||||
self.counters.ticks.incr();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Voice connections that are up.
|
||||
pub fn connections(&self) -> usize {
|
||||
self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count()
|
||||
}
|
||||
|
||||
/// Seconds since the window opened.
|
||||
pub fn uptime(&self) -> Duration {
|
||||
self.started.elapsed()
|
||||
}
|
||||
|
||||
/// The one line of state the window shows: the version, how many voice
|
||||
/// connections are up, how many engine events came and how long the
|
||||
/// window has run. Each part moves by a loop above, so a line that
|
||||
/// changes shows that the loop runs.
|
||||
pub fn state_line(&self) -> String {
|
||||
let connections = self.connections();
|
||||
format!(
|
||||
"{} {} · {} connection{} · {} engine event{} · {} s up",
|
||||
voelin_platform::APP_NAME,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
connections,
|
||||
if connections == 1 { "" } else { "s" },
|
||||
self.events_handled,
|
||||
if self.events_handled == 1 { "" } else { "s" },
|
||||
self.ticks,
|
||||
)
|
||||
}
|
||||
|
||||
/// Leave the servers properly, so no ghost client stays behind until it
|
||||
/// times out (the window is closing): tell the engine to close every
|
||||
/// session. Returns how many it told, so that the caller can give the
|
||||
/// engine time to act on them before the runtime goes (none without an
|
||||
/// engine).
|
||||
pub fn shutdown(&self) -> usize {
|
||||
let Some(engine) = &self.engine else { return 0 };
|
||||
for id in self.vm.sessions.keys() {
|
||||
engine.send(Command::CloseSession { session: *id as u64 });
|
||||
}
|
||||
self.vm.sessions.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::AppContext as _;
|
||||
use voelin_core::{Command, Event, SessionState, VoiceState};
|
||||
|
||||
use super::*;
|
||||
use crate::engine::HostedEngine;
|
||||
|
||||
fn voice(voice: VoiceState) -> Event {
|
||||
Event::State { session: 1, state: SessionState { voice, ..Default::default() } }
|
||||
}
|
||||
|
||||
/// The entity of a test with no engine behind it: `tx` stands in for the
|
||||
/// engine's events.
|
||||
fn entity(
|
||||
cx: &mut TestAppContext,
|
||||
) -> (gpui_kit::Entity<AppState>, UnboundedSender<Event>, Counters) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let counters = Counters::default();
|
||||
let app = cx.new({
|
||||
let counters = counters.clone();
|
||||
move |cx| AppState::new(None, rx, counters, cx)
|
||||
});
|
||||
(app, tx, counters)
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
|
||||
let (app, tx, counters) = entity(cx);
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!(app.connections(), 0);
|
||||
assert!(app.state_line().contains("0 connections · 0 engine events"));
|
||||
});
|
||||
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!(app.events_handled, 1);
|
||||
assert_eq!(app.connections(), 1);
|
||||
assert_eq!(app.vm.status, "Connected", "the transition's status line");
|
||||
assert!(
|
||||
app.state_line().contains("1 connection · 1 engine event"),
|
||||
"{}",
|
||||
app.state_line()
|
||||
);
|
||||
});
|
||||
assert_eq!(counters.engine_events.get(), 1);
|
||||
assert_eq!(counters.connections.get(), 1);
|
||||
|
||||
tx.send(voice(VoiceState::Disconnected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!((app.events_handled, app.connections()), (2, 0));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) {
|
||||
let (app, tx, _) = entity(cx);
|
||||
let notified = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let _subscription = cx.update(|cx| {
|
||||
let notified = notified.clone();
|
||||
cx.observe(&app, move |_, _| notified.set(notified.get() + 1))
|
||||
});
|
||||
tx.send(voice(VoiceState::Connecting)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(notified.get(), 1);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tick_runs_once_a_second(cx: &mut TestAppContext) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.ticks), 0);
|
||||
for second in 1..=3 {
|
||||
cx.executor().advance_clock(Duration::from_secs(1));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.ticks), second);
|
||||
}
|
||||
assert_eq!(counters.ticks.get(), 3);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
let later = app.read_with(cx, |app, _| app.later());
|
||||
let sent = std::thread::spawn(move || {
|
||||
later.run(|app, _| app.vm.status = "from another thread".into())
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert!(sent);
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread");
|
||||
assert_eq!(counters.later_jobs.get(), 1);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_job_sent_after_the_window_went_is_dropped_and_the_next_one_is_refused(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
let later = app.read_with(cx, |app, _| app.later());
|
||||
drop(app);
|
||||
cx.update(|_| {});
|
||||
cx.run_until_parked();
|
||||
assert!(later.run(|_, _| {}), "queued: nothing has found the entity gone yet");
|
||||
cx.run_until_parked();
|
||||
assert_eq!(counters.later_jobs.get(), 0, "never run");
|
||||
assert!(!later.run(|_, _| {}), "the first job found the entity gone");
|
||||
}
|
||||
|
||||
/// What closing the window hands the runtime's shutdown: the number of
|
||||
/// sessions the engine was told to close, which `run` gives time to act
|
||||
/// on (the Slint front end does the same). The engine ignores a close for
|
||||
/// a session it never opened, so the sessions here are only the state's.
|
||||
#[gpui::test]
|
||||
fn closing_counts_the_sessions_the_engine_was_told_to_close(cx: &mut TestAppContext) {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let app =
|
||||
cx.new(|cx| AppState::new(Some(hosted.engine.clone()), rx, Counters::default(), cx));
|
||||
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 0, "no session open yet");
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 1);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn closing_without_an_engine_tells_nothing(cx: &mut TestAppContext) {
|
||||
let (app, tx, _) = entity(cx);
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| (app.connections(), app.shutdown())), (1, 0));
|
||||
}
|
||||
|
||||
/// The whole path with a real engine: a command makes the engine report a
|
||||
/// setting change, which its forwarder hands to the window's channel and
|
||||
/// the foreground task to the entity. The engine's tasks run on tokio
|
||||
/// threads, so the test looks again until the event is in (no bound on
|
||||
/// how long the loaded machine takes, a generous one on the whole wait);
|
||||
/// the test scheduler is told that other threads wake it
|
||||
/// (`allow_parking`), which it otherwise reports as a test that is not
|
||||
/// deterministic.
|
||||
#[gpui::test]
|
||||
fn a_real_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
|
||||
cx.executor().allow_parking();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let engine = hosted.engine.clone();
|
||||
let counters = Counters::default();
|
||||
let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, counters, cx));
|
||||
engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() });
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
while app.read_with(cx, |app, _| app.events_handled) == 0 {
|
||||
assert!(Instant::now() < deadline, "the engine's event never arrived");
|
||||
cx.run_until_parked();
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(app.read_with(cx, |app, _| app.events_handled) >= 1);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
|
||||
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
|
||||
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
|
||||
//! icons the client draws; anything else (the rest of gpui-kit-assets'
|
||||
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
|
||||
//! gpui-kit-assets.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::{AssetSource, Result, SharedString};
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||
|
||||
/// The client's icons first, then gpui-kit-assets'.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Assets;
|
||||
|
||||
/// The client's icon of a file name (`mic.svg`), if it has one.
|
||||
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
|
||||
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
|
||||
}
|
||||
|
||||
/// The names of the client's icons, sorted.
|
||||
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
|
||||
ICONS.iter().map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
|
||||
return Ok(Some(Cow::Borrowed(bytes)));
|
||||
}
|
||||
gpui_kit::assets::AllAssets.load(path)
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
|
||||
gpui_kit::assets::AllAssets.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_client_set_is_embedded_and_sorted() {
|
||||
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
|
||||
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
|
||||
for (name, bytes) in ICONS {
|
||||
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_icon_answers_before_gpui_kit_assets() {
|
||||
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
|
||||
let ours = client_icon(name).unwrap();
|
||||
let kit = gpui_kit::assets::AllAssets
|
||||
.load(&format!("icons/{name}"))
|
||||
.unwrap()
|
||||
.expect("gpui-kit-assets has a mic too");
|
||||
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
|
||||
assert_eq!(&*served, ours);
|
||||
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
|
||||
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
|
||||
let only_in_kit = kit
|
||||
.iter()
|
||||
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
|
||||
.expect("the catalogue has icons the client lacks");
|
||||
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
|
||||
// gpui-kit-assets answers a path it does not have with an error, so do we.
|
||||
assert!(Assets.load("icons/no-such-icon.svg").is_err());
|
||||
assert!(Assets.load("nothing/here").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! The development switches of the GPUI front end, read from the
|
||||
//! environment. They are the Slint front end's (docs/ui.md, "Development
|
||||
//! switches and screenshots") where the GPUI one has the same thing to
|
||||
//! switch, so that one recipe serves both; the rest are new.
|
||||
//!
|
||||
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
|
||||
//! components, the icons) in place of the shell. The Slint front end's
|
||||
//! other pages do not exist here yet; they are named in a warning and
|
||||
//! skipped.
|
||||
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
|
||||
//! one the settings will give (`ui.theme` in the Slint front end).
|
||||
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
|
||||
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
|
||||
//! - `VOELIN_METER=1`: the cost meter, one log line a second
|
||||
//! ([`crate::meter`]).
|
||||
|
||||
use crate::theme::Choice;
|
||||
|
||||
/// A page the window can be opened on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
/// The shell. Today an empty window with the state line.
|
||||
Shell,
|
||||
/// Every theme token, a few components and the icons.
|
||||
Swatch,
|
||||
}
|
||||
|
||||
/// What the environment switched.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Switches {
|
||||
/// The page to open on.
|
||||
pub open: Page,
|
||||
/// The theme mode, when the switch names one.
|
||||
pub theme: Option<Choice>,
|
||||
/// The text size factor, when the switch names one.
|
||||
pub font_scale: Option<f32>,
|
||||
/// The window's size in pixels, when the switch names one.
|
||||
pub window: Option<(f32, f32)>,
|
||||
/// Log the cost meter.
|
||||
pub meter: bool,
|
||||
}
|
||||
|
||||
impl Default for Switches {
|
||||
fn default() -> Self {
|
||||
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Switches {
|
||||
/// The switches of this process's environment.
|
||||
pub fn from_env() -> Self {
|
||||
Self::parse(|name| std::env::var(name).ok())
|
||||
}
|
||||
|
||||
/// The switches `get` answers for; what it does not understand is logged
|
||||
/// and left out.
|
||||
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let mut switches = Self::default();
|
||||
if let Some(list) = get("VOELIN_OPEN") {
|
||||
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
|
||||
match what {
|
||||
"swatch" => switches.open = Page::Swatch,
|
||||
other => tracing::warn!(
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(name) = get("VOELIN_DEV_THEME") {
|
||||
match Choice::parse(name.trim()) {
|
||||
Some(choice) => switches.theme = Some(choice),
|
||||
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_FONT_SCALE") {
|
||||
match text.trim().parse::<f32>() {
|
||||
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
|
||||
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
|
||||
match parse_size(&text) {
|
||||
Some(size) => switches.window = Some(size),
|
||||
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
|
||||
}
|
||||
}
|
||||
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
|
||||
switches
|
||||
}
|
||||
}
|
||||
|
||||
/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way.
|
||||
fn parse_size(text: &str) -> Option<(f32, f32)> {
|
||||
let (w, h) = text.trim().split_once('x')?;
|
||||
let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
|
||||
((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> Switches {
|
||||
let map: HashMap<String, String> =
|
||||
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
Switches::parse(|name| map.get(name).cloned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_switched_is_the_shell_in_the_settings_theme() {
|
||||
assert_eq!(env(&[]), Switches::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_switch_is_read() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "swatch"),
|
||||
("VOELIN_DEV_THEME", "light"),
|
||||
("VOELIN_FONT_SCALE", "1.25"),
|
||||
("VOELIN_WINDOW_SIZE", "1440x960"),
|
||||
("VOELIN_METER", "1"),
|
||||
]);
|
||||
assert_eq!(s.open, Page::Swatch);
|
||||
assert_eq!(s.theme, Some(Choice::Light));
|
||||
assert_eq!(s.font_scale, Some(1.25));
|
||||
assert_eq!(s.window, Some((1440.0, 960.0)));
|
||||
assert!(s.meter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_makes_no_sense_is_left_out() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "settings:voice,home"),
|
||||
("VOELIN_DEV_THEME", "blue"),
|
||||
("VOELIN_FONT_SCALE", "9"),
|
||||
("VOELIN_WINDOW_SIZE", "10x10"),
|
||||
("VOELIN_METER", "0"),
|
||||
]);
|
||||
assert_eq!(s, Switches::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! The engine this front end runs on, the same one the Slint front end
|
||||
//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started
|
||||
//! on a tokio runtime, its events forwarded into a channel the window reads.
|
||||
//! The Slint crate cannot be a dependency here (it brings Slint in), so the
|
||||
//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front
|
||||
//! end is retired.
|
||||
|
||||
use tokio::runtime::{Handle, Runtime};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_core::{Engine, Event};
|
||||
|
||||
/// An engine owned by the caller of [`crate::run`].
|
||||
pub struct HostedEngine {
|
||||
/// The handle: commands go in through it.
|
||||
pub engine: Engine,
|
||||
/// The runtime the engine runs on; the window's helpers run there too.
|
||||
pub runtime: Handle,
|
||||
/// The engine's events for the window: first those that rebuild the
|
||||
/// current state of every session, then new ones. Reading them needs no
|
||||
/// reactor, so the window's foreground executor can await it.
|
||||
pub events: mpsc::UnboundedReceiver<Event>,
|
||||
}
|
||||
|
||||
impl HostedEngine {
|
||||
/// A new engine on `runtime`, all of whose events go to the window.
|
||||
pub fn start(runtime: &Runtime) -> Self {
|
||||
let engine = runtime.block_on(async { Engine::start() });
|
||||
let (tx, events) = mpsc::unbounded_channel();
|
||||
let mut rx = engine.subscribe();
|
||||
runtime.spawn(async move {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(event) => {
|
||||
if tx.send(event).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { engine, runtime: runtime.handle().clone(), events }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Inter, the UI font, as the Slint front end bundles it
|
||||
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
|
||||
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
|
||||
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
|
||||
//! come later (the chat slice; docs/design/gpui-spikes.md, "Open choices for step 3").
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::App;
|
||||
|
||||
/// The files of the family: regular, medium, semibold, bold, italic.
|
||||
const INTER: [&[u8]; 5] = [
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
|
||||
];
|
||||
|
||||
/// Add Inter to GPUI's text system.
|
||||
pub fn load(cx: &mut App) {
|
||||
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
|
||||
if let Err(error) = cx.text_system().add_fonts(fonts) {
|
||||
tracing::warn!(%error, "cannot add Inter to the text system");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_files_are_fonts() {
|
||||
for bytes in INTER {
|
||||
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
|
||||
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The GPUI front end of the desktop app, under construction (plan section 6
|
||||
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
|
||||
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
|
||||
//! reaches parity; both run on the same engine.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod app;
|
||||
pub mod assets;
|
||||
pub mod dev;
|
||||
pub mod engine;
|
||||
pub mod fonts;
|
||||
pub mod meter;
|
||||
pub mod swatch;
|
||||
pub mod theme;
|
||||
pub mod view;
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
|
||||
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::assets::Assets;
|
||||
use crate::dev::Switches;
|
||||
use crate::engine::HostedEngine;
|
||||
use crate::meter::Counters;
|
||||
use crate::theme::{Choice, VoelinTheme};
|
||||
use crate::view::MainView;
|
||||
|
||||
/// How long the engine gets, after the window closed, to act on the
|
||||
/// `CloseSession` commands the close sent (the Slint front end waits as long):
|
||||
/// its tasks run on the runtime, and shutting the runtime down drops them.
|
||||
const CLOSE_GRACE: Duration = Duration::from_millis(500);
|
||||
|
||||
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
|
||||
/// crate, this front end's information, and what GPUI says about the display
|
||||
/// and the GPU adapter it picked (which device a run used). Two warnings are
|
||||
/// left out because they are harmless: zbus's, as in the Slint front end (it
|
||||
/// warns when a desktop portal's request object is gone before it reads its
|
||||
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
|
||||
/// asks for the platform's UI font, which Linux has no name for, before the
|
||||
/// theme names Inter; the text system falls back).
|
||||
const LOG_FILTER: &str =
|
||||
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
|
||||
|
||||
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
|
||||
/// GPUI logs through the `log` crate; the subscriber carries those records.
|
||||
pub fn init_logging() {
|
||||
let filter = EnvFilter::try_from_env("VOELIN_LOG")
|
||||
.or_else(|_| EnvFilter::try_from_default_env())
|
||||
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
|
||||
.try_init();
|
||||
}
|
||||
|
||||
/// The main window's options: titled with the app's name, grouped by its id,
|
||||
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
|
||||
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
|
||||
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
|
||||
WindowOptions {
|
||||
titlebar: Some(TitlebarOptions {
|
||||
title: Some(voelin_platform::APP_NAME.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
app_id: Some(voelin_platform::APP_ID.to_owned()),
|
||||
window_min_size: Some(size(px(640.0), px(480.0))),
|
||||
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the main window on the root state; closing it leaves the servers and
|
||||
/// ends the app. `closed_sessions` is set to how many sessions the close told
|
||||
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
|
||||
fn open_main_window(
|
||||
cx: &mut App,
|
||||
switches: &Switches,
|
||||
engine: HostedEngine,
|
||||
counters: Counters,
|
||||
closed_sessions: Rc<Cell<usize>>,
|
||||
) -> Result<()> {
|
||||
// Without a display server GPUI falls back to a headless platform, which
|
||||
// opens windows that draw nothing and runs until it is stopped.
|
||||
if cx.compositor_name() == "headless" {
|
||||
return Err(anyhow::anyhow!(
|
||||
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
|
||||
))
|
||||
.context("cannot open the main window");
|
||||
}
|
||||
let HostedEngine { engine, events, .. } = engine;
|
||||
let app = cx.new({
|
||||
let counters = counters.clone();
|
||||
move |cx| AppState::new(Some(engine), events, counters, cx)
|
||||
});
|
||||
let options = window_options(switches, cx);
|
||||
let page = switches.open;
|
||||
gpui_kit::open_window(options, cx, {
|
||||
let app = app.clone();
|
||||
move |window, cx| {
|
||||
// The window's own appearance, which may differ from the system's before
|
||||
// the window exists.
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
window.on_window_should_close(cx, {
|
||||
let app = app.clone();
|
||||
move |_, cx| {
|
||||
closed_sessions.set(app.read(cx).shutdown());
|
||||
cx.quit();
|
||||
true
|
||||
}
|
||||
});
|
||||
cx.new(|cx| MainView::new(app, page, counters, window, cx))
|
||||
}
|
||||
})
|
||||
.context("cannot open the main window")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the app on the current thread until its window closes.
|
||||
pub fn run() -> Result<()> {
|
||||
init_logging();
|
||||
let switches = Switches::from_env();
|
||||
tracing::info!(
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
os = std::env::consts::OS,
|
||||
"Voelin (GPUI) starting"
|
||||
);
|
||||
let counters = Counters::default();
|
||||
if switches.meter {
|
||||
meter::start(counters.clone());
|
||||
}
|
||||
// The engine runs on tokio threads of its own; the window is GPUI's.
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("cannot start the engine's runtime")?;
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
|
||||
let closed_sessions: Rc<Cell<usize>> = Rc::default();
|
||||
gpui_kit::application().with_assets(Assets).run({
|
||||
let failure = failure.clone();
|
||||
let closed_sessions = closed_sessions.clone();
|
||||
move |cx| {
|
||||
gpui_kit::init(cx);
|
||||
fonts::load(cx);
|
||||
// Until the settings are read here (the shell slice), the mode and
|
||||
// the text size are the development switches' or the defaults.
|
||||
VoelinTheme::init(
|
||||
cx,
|
||||
switches.theme.unwrap_or(Choice::System),
|
||||
cx.window_appearance(),
|
||||
switches.font_scale.unwrap_or(1.0),
|
||||
);
|
||||
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
|
||||
*failure.borrow_mut() = Some(e);
|
||||
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
|
||||
// before it starts its event loop, and the loop forgets a stop
|
||||
// asked for earlier (calloop clears its stop signal when it
|
||||
// starts), so the process would stay with no window and no
|
||||
// message. A task runs inside the loop.
|
||||
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
|
||||
}
|
||||
}
|
||||
});
|
||||
// The close told the engine to close the sessions; give its tasks time to
|
||||
// send that before the runtime drops them (`shutdown_timeout` waits for
|
||||
// blocking tasks only), as the Slint front end does, or ghost clients stay
|
||||
// on the servers until they time out. Any other way to end the app that
|
||||
// the slices add must call `AppState::shutdown` too.
|
||||
if closed_sessions.get() > 0 {
|
||||
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
|
||||
}
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
match failure.take() {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! `voelin-gpui`: the GPUI front end of the desktop app (docs/ui.md, "The
|
||||
//! GPUI front end").
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
voelin_gpui::run()
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! What the app costs, once a second, in the log: the CPU of the process and
|
||||
//! of each group of threads, the resident memory, and the app's own counters
|
||||
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
|
||||
//! it costs). It is `spike_common::meter` of the GPUI spikes
|
||||
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
|
||||
//! measuring run's summary and exit, writing log lines instead of JSON.
|
||||
//!
|
||||
//! CPU is in percent of one core (200 means two cores busy). Threads are
|
||||
//! grouped by name without a trailing number (`llvmpipe-12` becomes
|
||||
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
|
||||
//! threads, work a GPU would take over) from GPUI's thread, the engine's
|
||||
//! runtime and the codecs. The numbers come from `/proc/self`: on other
|
||||
//! systems the meter says it cannot read them and stops.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A number the app counts up (events handled, frames drawn) or sets (open
|
||||
/// connections); the meter reports counters per second and gauges as they
|
||||
/// are.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counter(Arc<AtomicU64>);
|
||||
|
||||
impl Counter {
|
||||
/// Add one.
|
||||
pub fn incr(&self) {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Set (gauges).
|
||||
pub fn set(&self, value: u64) {
|
||||
self.0.store(value, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The current value.
|
||||
pub fn get(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's own numbers the meter reports besides the process's.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counters {
|
||||
/// Engine events handled by the root state (per second).
|
||||
pub engine_events: Counter,
|
||||
/// One-second ticks of the root state (per second: 1).
|
||||
pub ticks: Counter,
|
||||
/// Windows drawn (frames, per second).
|
||||
pub renders: Counter,
|
||||
/// Jobs other threads handed to the foreground through
|
||||
/// [`crate::app::Later`] (per second).
|
||||
pub later_jobs: Counter,
|
||||
/// Voice connections that are up (a gauge).
|
||||
pub connections: Counter,
|
||||
}
|
||||
|
||||
/// CPU ticks of the process and of each thread group, and the resident
|
||||
/// memory, at one moment.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Snapshot {
|
||||
at: Instant,
|
||||
process: u64,
|
||||
threads: BTreeMap<String, u64>,
|
||||
rss_bytes: u64,
|
||||
}
|
||||
|
||||
/// The size of a page of memory, for `statm`'s page counts.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn page_size() -> u64 {
|
||||
rustix::param::page_size() as u64
|
||||
}
|
||||
|
||||
/// The size of a page of memory (Linux only matters: `/proc`).
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn page_size() -> u64 {
|
||||
4096
|
||||
}
|
||||
|
||||
/// The unit of the CPU times in `stat`.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn clock_ticks_per_second() -> u64 {
|
||||
rustix::param::clock_ticks_per_second()
|
||||
}
|
||||
|
||||
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn clock_ticks_per_second() -> u64 {
|
||||
100
|
||||
}
|
||||
|
||||
/// `utime + stime` and the name of a `/proc/.../stat` line.
|
||||
fn ticks_of(stat: &str) -> Option<(String, u64)> {
|
||||
let open = stat.find('(')?;
|
||||
let close = stat.rfind(')')?;
|
||||
let name = stat.get(open + 1..close)?.to_owned();
|
||||
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
|
||||
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
|
||||
let utime: u64 = fields.get(11)?.parse().ok()?;
|
||||
let stime: u64 = fields.get(12)?.parse().ok()?;
|
||||
Some((name, utime + stime))
|
||||
}
|
||||
|
||||
/// A thread's group: its name without a trailing number or separator.
|
||||
pub fn group_of(name: &str) -> String {
|
||||
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
|
||||
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
|
||||
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Read `/proc/self` now; `None` where there is none.
|
||||
pub fn now() -> Option<Self> {
|
||||
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
|
||||
let mut threads = BTreeMap::new();
|
||||
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
|
||||
for entry in dir.flatten() {
|
||||
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
|
||||
if let Some((name, ticks)) = ticks_of(&stat) {
|
||||
*threads.entry(group_of(&name)).or_insert(0) += ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
|
||||
.ok()
|
||||
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
|
||||
.map_or(0, |pages| pages * page_size());
|
||||
Some(Self { at: Instant::now(), process, threads, rss_bytes })
|
||||
}
|
||||
|
||||
/// Resident memory in MiB.
|
||||
pub fn rss_mib(&self) -> f64 {
|
||||
self.rss_bytes as f64 / (1024.0 * 1024.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU in percent of one core between two snapshots: the process's and each
|
||||
/// thread group's that used any (groups that exited in between count from
|
||||
/// zero).
|
||||
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
|
||||
let hz = clock_ticks_per_second() as f64;
|
||||
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
|
||||
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
|
||||
let process = pct(b.process.saturating_sub(a.process));
|
||||
let threads = b
|
||||
.threads
|
||||
.iter()
|
||||
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
|
||||
.filter(|(_, p)| *p > 0.0)
|
||||
.collect();
|
||||
(process, threads)
|
||||
}
|
||||
|
||||
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
|
||||
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
|
||||
pub fn line(
|
||||
cpu: f64,
|
||||
rss_mib: f64,
|
||||
threads: &BTreeMap<String, f64>,
|
||||
rates: &[(&str, f64)],
|
||||
gauges: &[(&str, u64)],
|
||||
) -> String {
|
||||
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
|
||||
// The busiest groups first; a thread group under 0.5 % is noise.
|
||||
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
|
||||
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
|
||||
if !busy.is_empty() {
|
||||
text.push_str(" | threads");
|
||||
for (name, pct) in busy {
|
||||
let _ = write!(text, " {name} {pct:.1}");
|
||||
}
|
||||
}
|
||||
text.push_str(" |");
|
||||
for (name, rate) in rates {
|
||||
let _ = write!(text, " {name} {rate:.1}/s");
|
||||
}
|
||||
if !gauges.is_empty() {
|
||||
text.push_str(" |");
|
||||
for (name, value) in gauges {
|
||||
let _ = write!(text, " {name} {value}");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Start the meter on a thread of its own: once a second, a log line (target
|
||||
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
|
||||
/// `counters`' rates. It ends with the process.
|
||||
pub fn start(counters: Counters) {
|
||||
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
|
||||
let Some(mut last) = Snapshot::now() else {
|
||||
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
|
||||
return;
|
||||
};
|
||||
let rated = [
|
||||
("engine_events", counters.engine_events.clone()),
|
||||
("ticks", counters.ticks.clone()),
|
||||
("renders", counters.renders.clone()),
|
||||
("later_jobs", counters.later_jobs.clone()),
|
||||
];
|
||||
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let Some(now) = Snapshot::now() else { return };
|
||||
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
|
||||
let (cpu, threads) = cpu_between(&last, &now);
|
||||
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
let rates: Vec<(&str, f64)> = rated
|
||||
.iter()
|
||||
.zip(counts.iter().zip(&last_counts))
|
||||
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
|
||||
.collect();
|
||||
let gauges = [("connections", counters.connections.get())];
|
||||
tracing::info!(
|
||||
target: "voelin_gpui::meter",
|
||||
"{}",
|
||||
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
|
||||
);
|
||||
last = now;
|
||||
last_counts = counts;
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawned {
|
||||
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn groups_drop_trailing_numbers() {
|
||||
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
|
||||
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
|
||||
assert_eq!(group_of("voelin-meter"), "voelin-meter");
|
||||
assert_eq!(group_of("1234"), "1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stat_lines_parse_with_spaces_in_names() {
|
||||
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
|
||||
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
|
||||
let threads = BTreeMap::from([
|
||||
("main".to_owned(), 5.04),
|
||||
("llvmpipe".to_owned(), 310.0),
|
||||
("idle".to_owned(), 0.2),
|
||||
]);
|
||||
let text = line(
|
||||
317.0,
|
||||
210.44,
|
||||
&threads,
|
||||
&[("engine_events", 0.0), ("renders", 59.96)],
|
||||
&[("connections", 1)],
|
||||
);
|
||||
assert_eq!(
|
||||
text,
|
||||
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_can_be_read_on_linux() {
|
||||
if !cfg!(target_os = "linux") {
|
||||
return;
|
||||
}
|
||||
let a = Snapshot::now().expect("/proc/self");
|
||||
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
|
||||
// machine this thread gets a tick's worth of CPU only after a long wall
|
||||
// time: burn CPU until a second reading shows the process's ticks above
|
||||
// the first, and in a thread group (the process's total and a thread's
|
||||
// own are rounded separately). The deadline only ends a hang
|
||||
// (docs/testing/load.md); it never decides the result.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let (b, cpu) = loop {
|
||||
let burn = Instant::now();
|
||||
let mut x = 0u64;
|
||||
while burn.elapsed() < Duration::from_millis(2) {
|
||||
x = x.wrapping_mul(31).wrapping_add(7);
|
||||
}
|
||||
std::hint::black_box(x);
|
||||
let b = Snapshot::now().expect("/proc/self");
|
||||
let (cpu, threads) = cpu_between(&a, &b);
|
||||
if b.process > a.process && !threads.is_empty() {
|
||||
break (b, cpu);
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"no CPU tick showed in 30 s: {} -> {}",
|
||||
a.process,
|
||||
b.process
|
||||
);
|
||||
};
|
||||
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
//! The swatch page: every colour token of the theme with its name and value,
|
||||
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
|
||||
//! from the second layer of the theme) and the client's icons, in the mode
|
||||
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
|
||||
//! of a theme change, and what the screenshots in docs/ui/ show.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::checkbox::Checkbox;
|
||||
use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::{
|
||||
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
|
||||
StatefulInteractiveElement as _, Styled as _, div, px, svg,
|
||||
};
|
||||
|
||||
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
|
||||
|
||||
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
|
||||
pub const GROUPS: [(&str, &[&str]); 6] = [
|
||||
(
|
||||
"Backgrounds",
|
||||
&[
|
||||
"bg-app",
|
||||
"bg-rail",
|
||||
"surface",
|
||||
"surface-2",
|
||||
"surface-3",
|
||||
"surface-4",
|
||||
"scrim",
|
||||
"scrim-light",
|
||||
"overlay",
|
||||
],
|
||||
),
|
||||
("Lines", &["border", "border-strong", "border-popup", "glow"]),
|
||||
(
|
||||
"Accent",
|
||||
&[
|
||||
"accent",
|
||||
"accent-hover",
|
||||
"accent-pressed",
|
||||
"accent-soft",
|
||||
"accent-soft-hover",
|
||||
"accent-text",
|
||||
"name-text",
|
||||
"on-accent",
|
||||
],
|
||||
),
|
||||
(
|
||||
"States",
|
||||
&[
|
||||
"live",
|
||||
"live-soft",
|
||||
"danger",
|
||||
"danger-soft",
|
||||
"success",
|
||||
"success-soft",
|
||||
"warning",
|
||||
"warning-soft",
|
||||
"idle",
|
||||
"dnd",
|
||||
"offline",
|
||||
"gold",
|
||||
"info",
|
||||
],
|
||||
),
|
||||
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
|
||||
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
|
||||
];
|
||||
|
||||
/// Icons shown, by the name of the client's file.
|
||||
const ICONS: [&str; 16] = [
|
||||
"mic.svg",
|
||||
"mic-off.svg",
|
||||
"headphones.svg",
|
||||
"volume-2.svg",
|
||||
"settings.svg",
|
||||
"search.svg",
|
||||
"bell.svg",
|
||||
"users.svg",
|
||||
"message-square.svg",
|
||||
"monitor-up.svg",
|
||||
"hash.svg",
|
||||
"lock.svg",
|
||||
"crown.svg",
|
||||
"plus.svg",
|
||||
"x.svg",
|
||||
"check.svg",
|
||||
];
|
||||
|
||||
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(theme.colors.text))
|
||||
.child(text.to_owned())
|
||||
}
|
||||
|
||||
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.w(px(100.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.child(
|
||||
div()
|
||||
.h(px(24.0))
|
||||
.rounded(px(m.radius_xs))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_strong))
|
||||
.bg(hsla(color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(name.to_owned()),
|
||||
)
|
||||
.child(
|
||||
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn colours(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
|
||||
let mut column = div().flex().flex_col().gap(px(m.space_4));
|
||||
for (group, names) in GROUPS {
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
|
||||
for name in names {
|
||||
row = row.child(chip(theme, name, by_name[name]));
|
||||
}
|
||||
column = column.child(
|
||||
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
|
||||
);
|
||||
}
|
||||
column
|
||||
}
|
||||
|
||||
fn radii(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().gap(px(m.space_4));
|
||||
for (name, radius) in [
|
||||
("xs", m.radius_xs),
|
||||
("sm", m.radius_sm),
|
||||
("md", m.radius_md),
|
||||
("lg", m.radius_lg),
|
||||
("xl", m.radius_xl),
|
||||
("pill", m.radius_pill),
|
||||
] {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.size(px(40.0))
|
||||
.rounded(px(radius))
|
||||
.bg(hsla(c.surface_4))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup)),
|
||||
)
|
||||
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
|
||||
}
|
||||
|
||||
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col().gap(px(m.space_1));
|
||||
for (name, space) in [
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.w(px(56.0))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(name),
|
||||
)
|
||||
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{space} px")),
|
||||
),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
|
||||
}
|
||||
|
||||
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col();
|
||||
for (name, size, weight) in [
|
||||
("font-3xl", m.font_3xl, FontWeight::BOLD),
|
||||
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
|
||||
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
|
||||
("font-lg", m.font_lg, FontWeight::MEDIUM),
|
||||
("font-md", m.font_md, FontWeight::MEDIUM),
|
||||
("font-body", m.font_body, FontWeight::NORMAL),
|
||||
("font-sm", m.font_sm, FontWeight::NORMAL),
|
||||
("font-xs", m.font_xs, FontWeight::NORMAL),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.text_size(px(size))
|
||||
.font_weight(weight)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("{name} {size}: Raid tonight at 21:00")),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
|
||||
}
|
||||
|
||||
fn components(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.gap(px(m.space_3))
|
||||
.child(Button::new("primary").primary().label("Primary"))
|
||||
.child(Button::new("secondary").label("Secondary"))
|
||||
.child(Button::new("danger").danger().label("Danger"))
|
||||
.child(Button::new("success").success().label("Success"))
|
||||
.child(Button::new("warning").warning().label("Warning"))
|
||||
.child(Button::new("info").info().label("Info")),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_5))
|
||||
.child(Switch::new("on").checked(true))
|
||||
.child(Switch::new("off").checked(false))
|
||||
.child(Checkbox::new("checked").checked(true).label("Checked"))
|
||||
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
|
||||
)
|
||||
}
|
||||
|
||||
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
|
||||
let [first, _, last] = b.stops;
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
|
||||
div()
|
||||
.h(px(36.0))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(b.to_gpui())
|
||||
.px(px(m.space_3))
|
||||
.py(px(m.space_2))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(format!(
|
||||
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
|
||||
b.angle,
|
||||
first.0,
|
||||
last.0,
|
||||
b.stops[1].0,
|
||||
(b.stops[1].1 * 100.0).round()
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn icons(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
|
||||
for name in ICONS {
|
||||
row = row.child(
|
||||
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
|
||||
);
|
||||
}
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
|
||||
.child(row)
|
||||
}
|
||||
|
||||
/// The page: the colours on the left, the rest on the right; it scrolls when
|
||||
/// the window is smaller than it.
|
||||
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.id("swatch")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_6))
|
||||
.bg(hsla(c.bg_app))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_baseline()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_2xl))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child("Voelin theme"),
|
||||
)
|
||||
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
|
||||
format!(
|
||||
"{} (setting {}), text size {}",
|
||||
if theme.is_dark() { "dark" } else { "light" },
|
||||
theme.choice().name(),
|
||||
m.font_scale
|
||||
),
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_8))
|
||||
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
|
||||
.child(
|
||||
div()
|
||||
.w(px(600.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.child(backdrop(theme))
|
||||
.child(radii(theme))
|
||||
.child(spacing(theme))
|
||||
.child(type_scale(theme))
|
||||
.child(components(theme))
|
||||
.child(icons(theme)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
use crate::assets::client_icon;
|
||||
use crate::theme::Palette;
|
||||
|
||||
#[test]
|
||||
fn every_colour_token_is_in_exactly_one_group() {
|
||||
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
|
||||
let unique: BTreeSet<&str> = shown.iter().copied().collect();
|
||||
assert_eq!(shown.len(), unique.len(), "a token in two groups");
|
||||
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(unique, tokens);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_icons_shown_are_the_clients() {
|
||||
for name in ICONS {
|
||||
assert!(client_icon(name).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! The second layer of the theme: the colours gpui-component's widgets read,
|
||||
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
|
||||
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
|
||||
//! for the list, one for the table, one for each kind of button); the
|
||||
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
|
||||
//! What has no counterpart stays as the registered theme of the mode has it
|
||||
//! (charts' bullish and bearish colours, the cyan and magenta of the base
|
||||
//! palette).
|
||||
//!
|
||||
//! gpui-component's "accent" is a hover background, not a brand colour: the
|
||||
//! client's `accent` is its `primary`.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use gpui_kit::component::ThemeColor;
|
||||
|
||||
use super::tokens::{Palette, Rgba};
|
||||
|
||||
/// A palette colour as GPUI's.
|
||||
pub fn hsla(color: Rgba) -> Hsla {
|
||||
gpui_kit::rgba(color.0).into()
|
||||
}
|
||||
|
||||
/// Of `base`, the colours a status button needs: hover, active, and a text
|
||||
/// that reads on it (white or the window's ink, whichever contrasts more).
|
||||
struct Status {
|
||||
base: Hsla,
|
||||
hover: Hsla,
|
||||
active: Hsla,
|
||||
foreground: Hsla,
|
||||
}
|
||||
|
||||
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
|
||||
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
|
||||
Status {
|
||||
base: hsla(base),
|
||||
hover: hsla(base.mix(toward_hover, 0.14)),
|
||||
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
|
||||
foreground: hsla(base.readable(ink)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the palette's colours into `colors`, over what the registered theme
|
||||
/// of the mode left there. Every field that gpui-component's themes derive
|
||||
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
|
||||
/// too, so that none keeps the default theme's blue.
|
||||
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
|
||||
let c = colors;
|
||||
let h = hsla;
|
||||
let clear = Hsla::transparent_black();
|
||||
|
||||
// The window and its text.
|
||||
c.background = h(p.bg_app);
|
||||
c.foreground = h(p.text);
|
||||
c.border = h(p.border);
|
||||
c.input = h(p.border_strong);
|
||||
c.ring = h(p.glow);
|
||||
c.overlay = h(p.scrim);
|
||||
c.window_border = h(p.border);
|
||||
c.caret = h(p.text);
|
||||
c.selection = h(p.accent_soft);
|
||||
c.drag_border = h(p.accent);
|
||||
c.drop_target = h(p.accent_soft);
|
||||
|
||||
// Links: one colour for all three states, as the client has one.
|
||||
c.link = h(p.accent_text);
|
||||
c.link_hover = h(p.accent_text);
|
||||
c.link_active = h(p.accent_text);
|
||||
|
||||
// The brand colour, and gpui-component's hover "accent".
|
||||
c.primary = h(p.accent);
|
||||
c.primary_hover = h(p.accent_hover);
|
||||
c.primary_active = h(p.accent_pressed);
|
||||
c.primary_foreground = h(p.on_accent);
|
||||
c.accent = h(p.surface_3);
|
||||
c.accent_foreground = h(p.text);
|
||||
|
||||
// Cards, inputs, menus, popovers.
|
||||
c.secondary = h(p.surface_2);
|
||||
c.secondary_hover = h(p.surface_3);
|
||||
c.secondary_active = h(p.surface_4);
|
||||
c.secondary_foreground = h(p.text);
|
||||
c.muted = h(p.surface_2);
|
||||
c.muted_foreground = h(p.text_muted);
|
||||
c.popover = h(p.surface_3);
|
||||
c.popover_foreground = h(p.text);
|
||||
c.group_box = h(p.surface_2);
|
||||
c.group_box_foreground = h(p.text);
|
||||
c.accordion = h(p.surface_2);
|
||||
c.description_list_label = h(p.surface_2);
|
||||
c.description_list_label_foreground = h(p.text_secondary);
|
||||
|
||||
// The status colours, with the text that reads on each.
|
||||
let [danger, success, warning, info] =
|
||||
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
|
||||
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
|
||||
(danger.base, danger.hover, danger.active, danger.foreground);
|
||||
(c.success, c.success_hover, c.success_active, c.success_foreground) =
|
||||
(success.base, success.hover, success.active, success.foreground);
|
||||
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
|
||||
(warning.base, warning.hover, warning.active, warning.foreground);
|
||||
(c.info, c.info_hover, c.info_active, c.info_foreground) =
|
||||
(info.base, info.hover, info.active, info.foreground);
|
||||
|
||||
// Lists and tables: rows on the panel, hovered rows raised, the selected
|
||||
// row the soft accent with the accent's edge.
|
||||
c.list = h(p.surface);
|
||||
c.list_hover = h(p.surface_3);
|
||||
c.list_active = h(p.accent_soft);
|
||||
c.list_active_border = h(p.accent);
|
||||
c.list_even = h(p.surface);
|
||||
c.list_head = h(p.surface_2);
|
||||
c.table = h(p.surface);
|
||||
c.table_hover = h(p.surface_3);
|
||||
c.table_active = h(p.accent_soft);
|
||||
c.table_active_border = h(p.accent);
|
||||
c.table_even = h(p.surface);
|
||||
c.table_head = h(p.surface_2);
|
||||
c.table_head_foreground = h(p.text_secondary);
|
||||
c.table_foot = h(p.surface_2);
|
||||
c.table_foot_foreground = h(p.text_secondary);
|
||||
c.table_row_border = h(p.border);
|
||||
|
||||
// The panels around the content: the sidebar, the title and status bars.
|
||||
c.sidebar = h(p.surface);
|
||||
c.sidebar_foreground = h(p.text);
|
||||
c.sidebar_border = h(p.border);
|
||||
c.sidebar_accent = h(p.surface_3);
|
||||
c.sidebar_accent_foreground = h(p.text);
|
||||
c.sidebar_primary = h(p.accent);
|
||||
c.sidebar_primary_foreground = h(p.on_accent);
|
||||
c.title_bar = h(p.surface);
|
||||
c.title_bar_border = h(p.border);
|
||||
c.status_bar = h(p.surface);
|
||||
c.status_bar_border = h(p.border);
|
||||
|
||||
// Small widgets.
|
||||
c.scrollbar = clear;
|
||||
c.scrollbar_thumb = h(p.border_strong);
|
||||
c.scrollbar_thumb_hover = h(p.text_muted);
|
||||
c.slider_bar = h(p.accent);
|
||||
c.slider_thumb = h(p.on_accent);
|
||||
c.switch = h(p.surface_4);
|
||||
c.switch_thumb = h(p.on_accent);
|
||||
c.progress_bar = h(p.accent);
|
||||
c.skeleton = h(p.surface_3);
|
||||
c.tab = clear;
|
||||
c.tab_active = h(p.surface_2);
|
||||
c.tab_active_foreground = h(p.text);
|
||||
c.tab_bar = h(p.surface);
|
||||
c.tab_bar_segmented = h(p.surface_2);
|
||||
c.tab_foreground = h(p.text_secondary);
|
||||
|
||||
// The base palette and the charts: the client's state colours.
|
||||
c.red = h(p.danger);
|
||||
c.red_light = h(p.danger_soft);
|
||||
c.green = h(p.success);
|
||||
c.green_light = h(p.success_soft);
|
||||
c.yellow = h(p.warning);
|
||||
c.yellow_light = h(p.warning_soft);
|
||||
c.blue = h(p.info);
|
||||
c.blue_light = h(p.accent_soft);
|
||||
c.chart_1 = h(p.accent);
|
||||
c.chart_2 = h(p.success);
|
||||
c.chart_3 = h(p.warning);
|
||||
c.chart_4 = h(p.danger);
|
||||
c.chart_5 = h(p.info);
|
||||
|
||||
// The buttons: what a theme file leaves out they take from the colours
|
||||
// above, so they are written from them here.
|
||||
c.button = c.secondary;
|
||||
c.button_hover = c.secondary_hover;
|
||||
c.button_active = c.secondary_active;
|
||||
c.button_foreground = c.secondary_foreground;
|
||||
c.button_primary = c.primary;
|
||||
c.button_primary_hover = c.primary_hover;
|
||||
c.button_primary_active = c.primary_active;
|
||||
c.button_primary_foreground = c.primary_foreground;
|
||||
c.button_secondary = c.secondary;
|
||||
c.button_secondary_hover = c.secondary_hover;
|
||||
c.button_secondary_active = c.secondary_active;
|
||||
c.button_secondary_foreground = c.secondary_foreground;
|
||||
c.button_danger = c.danger;
|
||||
c.button_danger_hover = c.danger_hover;
|
||||
c.button_danger_active = c.danger_active;
|
||||
c.button_danger_foreground = c.danger_foreground;
|
||||
c.button_success = c.success;
|
||||
c.button_success_hover = c.success_hover;
|
||||
c.button_success_active = c.success_active;
|
||||
c.button_success_foreground = c.success_foreground;
|
||||
c.button_warning = c.warning;
|
||||
c.button_warning_hover = c.warning_hover;
|
||||
c.button_warning_active = c.warning_active;
|
||||
c.button_warning_foreground = c.warning_foreground;
|
||||
c.button_info = c.info;
|
||||
c.button_info_hover = c.info_hover;
|
||||
c.button_info_active = c.info_active;
|
||||
c.button_info_foreground = c.info_foreground;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn written(dark: bool) -> (Palette, ThemeColor) {
|
||||
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
|
||||
let mut colors = ThemeColor::default();
|
||||
write(&palette, dark, &mut colors);
|
||||
(palette, colors)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_tokens_land_where_the_table_says() {
|
||||
for dark in [true, false] {
|
||||
let (p, c) = written(dark);
|
||||
assert_eq!(c.background, hsla(p.bg_app));
|
||||
assert_eq!(c.foreground, hsla(p.text));
|
||||
assert_eq!(c.primary, hsla(p.accent));
|
||||
assert_eq!(c.primary_hover, hsla(p.accent_hover));
|
||||
assert_eq!(c.primary_active, hsla(p.accent_pressed));
|
||||
assert_eq!(c.primary_foreground, hsla(p.on_accent));
|
||||
assert_eq!(
|
||||
c.accent,
|
||||
hsla(p.surface_3),
|
||||
"gpui-component's accent is a hover background"
|
||||
);
|
||||
assert_eq!(c.secondary, hsla(p.surface_2));
|
||||
assert_eq!(c.secondary_active, hsla(p.surface_4));
|
||||
assert_eq!(c.border, hsla(p.border));
|
||||
assert_eq!(c.input, hsla(p.border_strong));
|
||||
assert_eq!(c.ring, hsla(p.glow));
|
||||
assert_eq!(c.overlay, hsla(p.scrim));
|
||||
assert_eq!(c.list_active, hsla(p.accent_soft));
|
||||
assert_eq!(c.link, hsla(p.accent_text));
|
||||
assert_eq!(c.muted_foreground, hsla(p.text_muted));
|
||||
assert_eq!(c.sidebar, hsla(p.surface));
|
||||
assert_eq!(c.danger, hsla(p.danger));
|
||||
assert_eq!(c.success, hsla(p.success));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_buttons_follow_the_colours_they_fall_back_to() {
|
||||
let (_, c) = written(true);
|
||||
assert_eq!(c.button_primary, c.primary);
|
||||
assert_eq!(c.button_primary_hover, c.primary_hover);
|
||||
assert_eq!(c.button_danger_foreground, c.danger_foreground);
|
||||
assert_eq!(c.button, c.secondary);
|
||||
assert_eq!(c.button_info_active, c.info_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
|
||||
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
|
||||
for base in [p.danger, p.success, p.warning, p.info] {
|
||||
let s = status(base, p.bg_app, dark);
|
||||
let chosen = base.readable(p.bg_app);
|
||||
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
|
||||
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
|
||||
assert_eq!(s.foreground, hsla(chosen));
|
||||
assert_ne!(s.hover, s.base);
|
||||
assert_ne!(s.active, s.base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixing_and_contrast_do_what_they_say() {
|
||||
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
|
||||
assert_eq!(black.mix(white, 0.0), black);
|
||||
assert_eq!(black.mix(white, 1.0), white);
|
||||
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
|
||||
assert!((black.contrast(white) - 21.0).abs() < 0.01);
|
||||
assert_eq!(black.readable(black), white);
|
||||
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
|
||||
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
|
||||
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
|
||||
//!
|
||||
//! 1. [`VoelinTheme`], a GPUI global with every token of
|
||||
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
|
||||
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
|
||||
//! elements (the server rail, presence dots, meters, the backdrop) read it.
|
||||
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
|
||||
//! menus, dialogs) read, written from the first on every change
|
||||
//! ([`components`]), so that they look like ours.
|
||||
//!
|
||||
//! The mode is the client's `ui.theme`: `system` follows the window's
|
||||
//! appearance (and its changes), `light` and `dark` do not.
|
||||
|
||||
mod components;
|
||||
#[cfg(test)]
|
||||
mod slint_parity;
|
||||
pub mod tokens;
|
||||
|
||||
pub use components::hsla;
|
||||
use gpui_kit::component::{Theme, ThemeMode};
|
||||
use gpui_kit::{App, Background, Global, WindowAppearance, linear_color_stop, linear_gradient, px};
|
||||
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
impl Backdrop {
|
||||
/// What GPUI draws: its gradient has two colour stops, so the first and the
|
||||
/// last of the three; the middle one is not drawn.
|
||||
pub fn to_gpui(&self) -> Background {
|
||||
let [first, _, last] = self.stops;
|
||||
linear_gradient(
|
||||
self.angle,
|
||||
linear_color_stop(hsla(first.0), first.1),
|
||||
linear_color_stop(hsla(last.0), last.1),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode setting (`ui.theme` of the Slint front end).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Choice {
|
||||
/// Follow the window's appearance.
|
||||
System,
|
||||
/// Always light.
|
||||
Light,
|
||||
/// Always dark.
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
/// `system`, `light` or `dark`.
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text {
|
||||
"system" => Some(Self::System),
|
||||
"light" => Some(Self::Light),
|
||||
"dark" => Some(Self::Dark),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The setting's value.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the theme is dark, given whether the window's appearance is.
|
||||
pub fn resolve(self, system_dark: bool) -> bool {
|
||||
match self {
|
||||
Self::System => system_dark,
|
||||
Self::Light => false,
|
||||
Self::Dark => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a window's appearance is a dark one.
|
||||
pub fn is_dark(appearance: WindowAppearance) -> bool {
|
||||
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
|
||||
}
|
||||
|
||||
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
|
||||
/// global.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoelinTheme {
|
||||
choice: Choice,
|
||||
dark: bool,
|
||||
/// The colours of the resolved mode.
|
||||
pub colors: Palette,
|
||||
/// The window's backdrop gradient of the resolved mode.
|
||||
pub backdrop: Backdrop,
|
||||
/// The sizes, radii, type and durations at the text size factor.
|
||||
pub metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Global for VoelinTheme {}
|
||||
|
||||
impl VoelinTheme {
|
||||
/// The tokens for a mode (resolved against `system_dark`) and a text size
|
||||
/// factor.
|
||||
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
|
||||
let dark = choice.resolve(system_dark);
|
||||
Self {
|
||||
choice,
|
||||
dark,
|
||||
colors: if dark { Palette::DARK } else { Palette::LIGHT },
|
||||
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
|
||||
metrics: Metrics::new(font_scale),
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode that was set.
|
||||
pub fn choice(&self) -> Choice {
|
||||
self.choice
|
||||
}
|
||||
|
||||
/// Whether the colours are the dark ones.
|
||||
pub fn is_dark(&self) -> bool {
|
||||
self.dark
|
||||
}
|
||||
|
||||
/// Install the theme as the global and write it into gpui-component, which
|
||||
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
|
||||
/// the system's before there is a window).
|
||||
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The theme global.
|
||||
pub fn global(cx: &App) -> &Self {
|
||||
cx.global::<Self>()
|
||||
}
|
||||
|
||||
/// Change the mode (a setting changed), given the window's appearance now.
|
||||
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
|
||||
let (scale, current) = {
|
||||
let this = Self::global(cx);
|
||||
(this.metrics.font_scale, this.choice)
|
||||
};
|
||||
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
|
||||
return;
|
||||
}
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The window's appearance changed; it matters only in `system` mode.
|
||||
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
|
||||
let this = Self::global(cx);
|
||||
if this.choice == Choice::System && this.dark != is_dark(appearance) {
|
||||
let (choice, scale) = (this.choice, this.metrics.font_scale);
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text size factor changed (`ui.font_scale`).
|
||||
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
|
||||
let this = Self::global(cx);
|
||||
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
|
||||
return;
|
||||
}
|
||||
// `dark` is what the mode resolved to: for every mode, resolving it again
|
||||
// against it gives the same.
|
||||
let (choice, dark) = (this.choice, this.dark);
|
||||
cx.set_global(Self::new(choice, dark, font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// Write the global into gpui-component's theme: the mode, the colours of
|
||||
/// the second layer, the font, the base size and the radii.
|
||||
fn apply(cx: &mut App) {
|
||||
let this = Self::global(cx).clone();
|
||||
// The registered theme of the mode first (it sets whatever the second
|
||||
// layer leaves alone), then our colours over it in a second update, as
|
||||
// `Theme::update` says a mode change must be.
|
||||
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
|
||||
Theme::update(cx, |theme| {
|
||||
components::write(&this.colors, this.dark, &mut theme.colors);
|
||||
theme.font_family = FONT_FAMILY.into();
|
||||
theme.font_size = px(this.metrics.font_body);
|
||||
theme.radius = px(this.metrics.radius_sm);
|
||||
theme.radius_lg = px(this.metrics.radius_lg);
|
||||
});
|
||||
// Where the platform draws the window's frame itself (macOS), it follows
|
||||
// the mode; elsewhere this does nothing.
|
||||
cx.set_window_appearance(match this.choice {
|
||||
Choice::System => None,
|
||||
Choice::Light => Some(WindowAppearance::Light),
|
||||
Choice::Dark => Some(WindowAppearance::Dark),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::component::ActiveTheme as _;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
|
||||
cx.update(|cx| {
|
||||
gpui_kit::init(cx);
|
||||
VoelinTheme::init(cx, choice, appearance, 1.0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mode_resolves_against_the_window() {
|
||||
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
|
||||
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
|
||||
for choice in [Choice::System, Choice::Light, Choice::Dark] {
|
||||
assert_eq!(Choice::parse(choice.name()), Some(choice));
|
||||
}
|
||||
assert_eq!(Choice::parse("blue"), None);
|
||||
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_draws_the_first_and_the_last_of_its_three_stops() {
|
||||
let b = Backdrop::DARK;
|
||||
let [first, middle, last] = b.stops;
|
||||
assert_eq!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(last.0), 1.0)
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(middle.0), 1.0)
|
||||
),
|
||||
"the middle stop is not the end one"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Light);
|
||||
cx.update(|cx| {
|
||||
let theme = cx.theme();
|
||||
assert!(theme.is_dark());
|
||||
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
|
||||
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.font_family.as_ref(), "Inter");
|
||||
assert_eq!(theme.font_size, px(14.0));
|
||||
assert_eq!(theme.radius, px(6.0));
|
||||
assert_eq!(theme.radius_lg, px(12.0));
|
||||
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
|
||||
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::System, WindowAppearance::Light);
|
||||
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Dark);
|
||||
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
|
||||
cx.update(|cx| {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
assert!(theme.is_dark(), "the mode stays");
|
||||
assert_eq!(theme.metrics.font_body, 17.5);
|
||||
assert_eq!(theme.metrics.control_height, 45.0);
|
||||
assert_eq!(cx.theme().font_size, px(17.5));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
|
||||
//! read and every token in it is compared with the Rust value of the same
|
||||
//! name, light and dark and at four text sizes; a token on one side only, a
|
||||
//! value that differs, or a declaration of a kind this test does not know
|
||||
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
|
||||
//! `font-family`) fails it. While both front ends live, a token changed in
|
||||
//! one place and not the other is caught here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
|
||||
|
||||
/// What `theme.slint` declares: the kind and the expression of each property
|
||||
/// of the `Theme` global, in file order.
|
||||
fn declarations() -> Vec<(String, String, String)> {
|
||||
declarations_of(SLINT)
|
||||
}
|
||||
|
||||
/// The same for the text of a `.slint` file (the tests below also read
|
||||
/// altered copies of `theme.slint`).
|
||||
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
|
||||
let without_comments: String = source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
|
||||
let mut found = Vec::new();
|
||||
for statement in body.split(';') {
|
||||
let statement = statement.trim();
|
||||
let Some(rest) = ["in-out property", "out property", "in property"]
|
||||
.iter()
|
||||
.find_map(|prefix| statement.strip_prefix(prefix))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (kind, rest) =
|
||||
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
|
||||
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
|
||||
// One line, single spaces: `backdrop` is written over several.
|
||||
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `#rgb`-style literal as `Rgba`.
|
||||
fn colour(text: &str) -> Rgba {
|
||||
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
|
||||
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
|
||||
match hex.len() {
|
||||
6 => Rgba(value << 8 | 0xff),
|
||||
8 => Rgba(value),
|
||||
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
|
||||
fn by_mode(expr: &str) -> (String, String) {
|
||||
let Some(rest) = expr.strip_prefix("dark ?") else {
|
||||
return (expr.to_owned(), expr.to_owned());
|
||||
};
|
||||
let mut depth = 0;
|
||||
for (i, c) in rest.char_indices() {
|
||||
match c {
|
||||
'(' => depth += 1,
|
||||
')' => depth -= 1,
|
||||
':' if depth == 0 => {
|
||||
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("no `:` in {expr:?}");
|
||||
}
|
||||
|
||||
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
|
||||
/// `*`, `+`, `max(a, b)` and parentheses.
|
||||
struct Eval<'a> {
|
||||
tokens: Vec<String>,
|
||||
at: usize,
|
||||
env: &'a BTreeMap<String, String>,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl<'a> Eval<'a> {
|
||||
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
|
||||
let mut tokens = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in expr.chars() {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
|
||||
word.push(c);
|
||||
} else {
|
||||
if !word.is_empty() {
|
||||
tokens.push(std::mem::take(&mut word));
|
||||
}
|
||||
if !c.is_whitespace() {
|
||||
tokens.push(c.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
tokens.push(word);
|
||||
}
|
||||
let mut eval = Eval { tokens, at: 0, env, scale };
|
||||
let value = eval.sum();
|
||||
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
|
||||
value
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<&str> {
|
||||
self.tokens.get(self.at).map(String::as_str)
|
||||
}
|
||||
|
||||
fn take(&mut self) -> String {
|
||||
self.at += 1;
|
||||
self.tokens[self.at - 1].clone()
|
||||
}
|
||||
|
||||
fn sum(&mut self) -> f64 {
|
||||
let mut value = self.product();
|
||||
while self.peek() == Some("+") {
|
||||
self.take();
|
||||
value += self.product();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn product(&mut self) -> f64 {
|
||||
let mut value = self.factor();
|
||||
while self.peek() == Some("*") {
|
||||
self.take();
|
||||
value *= self.factor();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn factor(&mut self) -> f64 {
|
||||
let token = self.take();
|
||||
if token == "(" {
|
||||
let value = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return value;
|
||||
}
|
||||
if token == "max" {
|
||||
assert_eq!(self.take(), "(");
|
||||
let a = self.sum();
|
||||
assert_eq!(self.take(), ",");
|
||||
let b = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return a.max(b);
|
||||
}
|
||||
if token == "font-scale" {
|
||||
return self.scale;
|
||||
}
|
||||
if token.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
let number: String =
|
||||
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
|
||||
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
|
||||
}
|
||||
let expr =
|
||||
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
|
||||
Eval::run(&expr, self.env, self.scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names `theme.slint` declares that are state, not tokens: the mode and
|
||||
/// what it resolves to, and the text size factor (the factor is a parameter
|
||||
/// of [`Metrics`]).
|
||||
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
|
||||
|
||||
#[test]
|
||||
fn every_colour_is_the_same_in_both_files() {
|
||||
let slint: Vec<(String, String, String)> =
|
||||
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
|
||||
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
|
||||
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
|
||||
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &slint {
|
||||
let (d, l) = by_mode(expr);
|
||||
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
|
||||
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let ours: BTreeSet<&str> = dark.keys().copied().collect();
|
||||
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_length_weight_and_duration_is_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let env: BTreeMap<String, String> =
|
||||
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
|
||||
let numeric: Vec<&(String, String, String)> = all
|
||||
.iter()
|
||||
.filter(|(name, kind, _)| {
|
||||
matches!(kind.as_str(), "length" | "int" | "duration")
|
||||
&& !STATE.contains(&name.as_str())
|
||||
})
|
||||
.collect();
|
||||
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
|
||||
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
|
||||
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &numeric {
|
||||
let slint = Eval::run(expr, &env, f64::from(scale));
|
||||
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
|
||||
assert!(
|
||||
(slint - ours).abs() < 1e-3,
|
||||
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
|
||||
);
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let rust: BTreeSet<&str> = ours.keys().copied().collect();
|
||||
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let get = |name: &str| {
|
||||
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
|
||||
};
|
||||
let gradient = |text: &str| -> Backdrop {
|
||||
let inner = text
|
||||
.trim()
|
||||
.strip_prefix("@linear-gradient(")
|
||||
.and_then(|t| t.strip_suffix(')'))
|
||||
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
|
||||
let mut parts = inner.split(',').map(str::trim);
|
||||
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
|
||||
let stops: Vec<(Rgba, f32)> = parts
|
||||
.map(|stop| {
|
||||
let (colour_text, position) = stop.split_once(' ').unwrap();
|
||||
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
|
||||
(colour(colour_text), percent / 100.0)
|
||||
})
|
||||
.collect();
|
||||
Backdrop { angle, stops: stops.try_into().expect("three stops") }
|
||||
};
|
||||
let (dark, light) = by_mode(&get("backdrop"));
|
||||
assert_eq!(gradient(&dark), Backdrop::DARK);
|
||||
assert_eq!(gradient(&light), Backdrop::LIGHT);
|
||||
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
|
||||
}
|
||||
|
||||
/// What the declarations hold that no comparison above covers, one sentence
|
||||
/// each; empty when there is none: a kind of declaration this test does not
|
||||
/// know, a brush other than `backdrop` or a string other than `mode` and
|
||||
/// `font-family` (the two comparisons of those go by name, so a second one
|
||||
/// would pass unseen), a state name that is no longer declared.
|
||||
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
let kinds: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
|
||||
.map(|(_, kind, _)| kind.as_str())
|
||||
.collect();
|
||||
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
|
||||
if kinds != known {
|
||||
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
|
||||
}
|
||||
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
|
||||
let found: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(_, declared_kind, _)| declared_kind == kind)
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.collect();
|
||||
let expected: BTreeSet<&str> = expected.iter().copied().collect();
|
||||
for name in found.symmetric_difference(&expected) {
|
||||
problems.push(format!(
|
||||
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
for name in STATE {
|
||||
if !declared.iter().any(|(declared, _, _)| declared == name) {
|
||||
problems.push(format!("{name} is not declared"));
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_declares_nothing_this_test_does_not_know() {
|
||||
let problems = unknown_to_this_test(&declarations());
|
||||
assert!(problems.is_empty(), "{problems:#?}");
|
||||
}
|
||||
|
||||
/// `theme.slint` with one more declaration in its `Theme` global.
|
||||
fn with_declaration(declaration: &str) -> String {
|
||||
let opening = "export global Theme {";
|
||||
assert!(SLINT.contains(opening));
|
||||
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_brush_or_string_is_not_passed_unseen() {
|
||||
// Mutants of the Slint file: a token on one side only.
|
||||
for (declaration, name) in [
|
||||
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
|
||||
("out property <string> font-mono: \"Mono\";", "font-mono"),
|
||||
] {
|
||||
let mutant = declarations_of(&with_declaration(declaration));
|
||||
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
|
||||
let problems = unknown_to_this_test(&mutant);
|
||||
assert!(
|
||||
problems.iter().any(|problem| problem.contains(name)),
|
||||
"{name} goes unnoticed: {problems:#?}"
|
||||
);
|
||||
}
|
||||
// And the file as it is has neither.
|
||||
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
|
||||
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
|
||||
//! the original while the Slint front end lives; the test in
|
||||
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
|
||||
//! formula here differs from it, so the two cannot drift apart.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
|
||||
/// is opaque).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Rgba(pub u32);
|
||||
|
||||
impl fmt::Debug for Rgba {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Rgba {
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.alpha() == 255 {
|
||||
write!(f, "#{:06x}", self.0 >> 8)
|
||||
} else {
|
||||
write!(f, "#{:08x}", self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
/// Transparent black, for the widgets that draw nothing.
|
||||
pub const TRANSPARENT: Self = Self(0);
|
||||
|
||||
/// The opacity, 0 to 255.
|
||||
pub fn alpha(self) -> u8 {
|
||||
(self.0 & 0xff) as u8
|
||||
}
|
||||
|
||||
/// The same colour with another opacity.
|
||||
pub fn with_alpha(self, alpha: u8) -> Self {
|
||||
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
|
||||
}
|
||||
|
||||
/// The channels, 0 to 1.
|
||||
pub fn channels(self) -> [f32; 3] {
|
||||
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
|
||||
/// from `self`.
|
||||
pub fn mix(self, other: Self, amount: f32) -> Self {
|
||||
let (a, b) = (self.channels(), other.channels());
|
||||
let channel =
|
||||
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
|
||||
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
|
||||
}
|
||||
|
||||
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
|
||||
pub fn luminance(self) -> f32 {
|
||||
let [r, g, b] = self
|
||||
.channels()
|
||||
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
|
||||
pub fn contrast(self, other: Self) -> f32 {
|
||||
let (a, b) = (self.luminance(), other.luminance());
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05)
|
||||
}
|
||||
|
||||
/// Of white and `ink`, the one that reads better on `self`.
|
||||
pub fn readable(self, ink: Self) -> Self {
|
||||
let white = Self(0xffff_ffff);
|
||||
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! palette {
|
||||
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
|
||||
/// Every colour token of `theme.slint` for one mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Palette {
|
||||
$(
|
||||
#[doc = concat!("`", $name, "` of `theme.slint`.")]
|
||||
pub $field: Rgba,
|
||||
)*
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The dark palette.
|
||||
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
|
||||
/// The light palette.
|
||||
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
|
||||
|
||||
/// Every colour by the name it has in `theme.slint`, in its order.
|
||||
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
|
||||
vec![$(($name, self.$field),)*]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
palette! {
|
||||
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
|
||||
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
|
||||
surface "surface": 0x0b1330ff, 0xf7f9feff;
|
||||
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
|
||||
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
|
||||
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
|
||||
scrim "scrim": 0x02050fc0, 0x0b132b80;
|
||||
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
|
||||
overlay "overlay": 0x060a18c8, 0x0b1330b0;
|
||||
border "border": 0x1b2750ff, 0xd3dceeff;
|
||||
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
|
||||
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
|
||||
accent "accent": 0x2d6bffff, 0x2458e6ff;
|
||||
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
|
||||
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
|
||||
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
|
||||
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
|
||||
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
|
||||
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
|
||||
on_accent "on-accent": 0xffffffff, 0xffffffff;
|
||||
glow "glow": 0x3f7bff90, 0x2458e660;
|
||||
live "live": 0xff2d55ff, 0xe0203fff;
|
||||
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
|
||||
danger "danger": 0xff4d5eff, 0xd92c3cff;
|
||||
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
|
||||
success "success": 0x22d36bff, 0x16a557ff;
|
||||
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
|
||||
warning "warning": 0xf5b301ff, 0xb77f00ff;
|
||||
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
|
||||
idle "idle": 0xf5b301ff, 0xc98b00ff;
|
||||
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
|
||||
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
|
||||
gold "gold": 0xffc233ff, 0xd99a00ff;
|
||||
info "info": 0x3fb3ffff, 0x1180d6ff;
|
||||
text "text": 0xeef2ffff, 0x0e1733ff;
|
||||
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
|
||||
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
|
||||
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
|
||||
icon "icon": 0xb9c4e2ff, 0x43506fff;
|
||||
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
|
||||
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
|
||||
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
|
||||
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
|
||||
}
|
||||
|
||||
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
|
||||
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
|
||||
/// (`Backdrop::to_gpui`, in the theme module) is the first and the last; the
|
||||
/// middle one stays here for a front end that can use it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
|
||||
pub angle: f32,
|
||||
/// Three stops: colour and position (0 to 1).
|
||||
pub stops: [(Rgba, f32); 3],
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// The dark backdrop.
|
||||
pub const DARK: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
|
||||
};
|
||||
/// The light backdrop.
|
||||
pub const LIGHT: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
|
||||
};
|
||||
}
|
||||
|
||||
/// The family of the UI font (`font-family` of `theme.slint`).
|
||||
pub const FONT_FAMILY: &str = "Inter";
|
||||
|
||||
/// Every size, radius, weight and duration token of `theme.slint` for one
|
||||
/// text size factor: lengths in logical pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Metrics {
|
||||
/// `font-scale`: multiplies every type size and the sizes that follow text.
|
||||
pub font_scale: f32,
|
||||
/// `radius-xs`.
|
||||
pub radius_xs: f32,
|
||||
/// `radius-sm`.
|
||||
pub radius_sm: f32,
|
||||
/// `radius-md`.
|
||||
pub radius_md: f32,
|
||||
/// `radius-lg`.
|
||||
pub radius_lg: f32,
|
||||
/// `radius-xl`.
|
||||
pub radius_xl: f32,
|
||||
/// `radius-pill`.
|
||||
pub radius_pill: f32,
|
||||
/// `space-1`.
|
||||
pub space_1: f32,
|
||||
/// `space-2`.
|
||||
pub space_2: f32,
|
||||
/// `space-3`.
|
||||
pub space_3: f32,
|
||||
/// `space-4`.
|
||||
pub space_4: f32,
|
||||
/// `space-5`.
|
||||
pub space_5: f32,
|
||||
/// `space-6`.
|
||||
pub space_6: f32,
|
||||
/// `space-7`.
|
||||
pub space_7: f32,
|
||||
/// `space-8`.
|
||||
pub space_8: f32,
|
||||
/// `font-xs` (scaled).
|
||||
pub font_xs: f32,
|
||||
/// `font-sm` (scaled).
|
||||
pub font_sm: f32,
|
||||
/// `font-body` (scaled).
|
||||
pub font_body: f32,
|
||||
/// `font-md` (scaled).
|
||||
pub font_md: f32,
|
||||
/// `font-lg` (scaled).
|
||||
pub font_lg: f32,
|
||||
/// `font-xl` (scaled).
|
||||
pub font_xl: f32,
|
||||
/// `font-2xl` (scaled).
|
||||
pub font_2xl: f32,
|
||||
/// `font-3xl` (scaled).
|
||||
pub font_3xl: f32,
|
||||
/// `weight-regular`.
|
||||
pub weight_regular: u16,
|
||||
/// `weight-medium`.
|
||||
pub weight_medium: u16,
|
||||
/// `weight-semibold`.
|
||||
pub weight_semibold: u16,
|
||||
/// `weight-bold`.
|
||||
pub weight_bold: u16,
|
||||
/// `row-height` (scaled).
|
||||
pub row_height: f32,
|
||||
/// `control-height` (scaled).
|
||||
pub control_height: f32,
|
||||
/// `control-height-sm` (scaled).
|
||||
pub control_height_sm: f32,
|
||||
/// `icon-sm`.
|
||||
pub icon_sm: f32,
|
||||
/// `icon-md`.
|
||||
pub icon_md: f32,
|
||||
/// `icon-lg`.
|
||||
pub icon_lg: f32,
|
||||
/// `glow-width`: the ring around focused and selected items.
|
||||
pub glow_width: f32,
|
||||
/// `rail-width`.
|
||||
pub rail_width: f32,
|
||||
/// `sidebar-width`: 264 and more with large text.
|
||||
pub sidebar_width: f32,
|
||||
/// `topbar-height`: 44, taller when large text makes the controls taller.
|
||||
pub topbar_height: f32,
|
||||
/// `right-panel-min`.
|
||||
pub right_panel_min: f32,
|
||||
/// `fast`, in milliseconds.
|
||||
pub fast_ms: u32,
|
||||
/// `normal`, in milliseconds.
|
||||
pub normal_ms: u32,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
/// The tokens at a text size factor (1 is the default).
|
||||
pub fn new(font_scale: f32) -> Self {
|
||||
let s = font_scale;
|
||||
let control_height = 36.0 * s;
|
||||
let space_3 = 8.0;
|
||||
Self {
|
||||
font_scale,
|
||||
radius_xs: 4.0,
|
||||
radius_sm: 6.0,
|
||||
radius_md: 8.0,
|
||||
radius_lg: 12.0,
|
||||
radius_xl: 16.0,
|
||||
radius_pill: 999.0,
|
||||
space_1: 2.0,
|
||||
space_2: 4.0,
|
||||
space_3,
|
||||
space_4: 12.0,
|
||||
space_5: 16.0,
|
||||
space_6: 20.0,
|
||||
space_7: 24.0,
|
||||
space_8: 32.0,
|
||||
font_xs: 11.0 * s,
|
||||
font_sm: 12.0 * s,
|
||||
font_body: 14.0 * s,
|
||||
font_md: 15.0 * s,
|
||||
font_lg: 17.0 * s,
|
||||
font_xl: 20.0 * s,
|
||||
font_2xl: 24.0 * s,
|
||||
font_3xl: 30.0 * s,
|
||||
weight_regular: 400,
|
||||
weight_medium: 500,
|
||||
weight_semibold: 600,
|
||||
weight_bold: 700,
|
||||
row_height: 32.0 * s,
|
||||
control_height,
|
||||
control_height_sm: 28.0 * s,
|
||||
icon_sm: 16.0,
|
||||
icon_md: 20.0,
|
||||
icon_lg: 24.0,
|
||||
glow_width: 2.0,
|
||||
rail_width: 72.0,
|
||||
sidebar_width: 264.0 * s.max(1.0),
|
||||
topbar_height: 44.0_f32.max(control_height + space_3),
|
||||
right_panel_min: 220.0,
|
||||
fast_ms: 120,
|
||||
normal_ms: 200,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every number token by the name it has in `theme.slint`, in its order:
|
||||
/// lengths in pixels, weights as they are, durations in milliseconds.
|
||||
pub fn entries(&self) -> Vec<(&'static str, f64)> {
|
||||
let m = self;
|
||||
[
|
||||
("radius-xs", m.radius_xs),
|
||||
("radius-sm", m.radius_sm),
|
||||
("radius-md", m.radius_md),
|
||||
("radius-lg", m.radius_lg),
|
||||
("radius-xl", m.radius_xl),
|
||||
("radius-pill", m.radius_pill),
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
("font-xs", m.font_xs),
|
||||
("font-sm", m.font_sm),
|
||||
("font-body", m.font_body),
|
||||
("font-md", m.font_md),
|
||||
("font-lg", m.font_lg),
|
||||
("font-xl", m.font_xl),
|
||||
("font-2xl", m.font_2xl),
|
||||
("font-3xl", m.font_3xl),
|
||||
("row-height", m.row_height),
|
||||
("control-height", m.control_height),
|
||||
("control-height-sm", m.control_height_sm),
|
||||
("icon-sm", m.icon_sm),
|
||||
("icon-md", m.icon_md),
|
||||
("icon-lg", m.icon_lg),
|
||||
("glow-width", m.glow_width),
|
||||
("rail-width", m.rail_width),
|
||||
("sidebar-width", m.sidebar_width),
|
||||
("topbar-height", m.topbar_height),
|
||||
("right-panel-min", m.right_panel_min),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, f64::from(value)))
|
||||
.chain([
|
||||
("weight-regular", f64::from(m.weight_regular)),
|
||||
("weight-medium", f64::from(m.weight_medium)),
|
||||
("weight-semibold", f64::from(m.weight_semibold)),
|
||||
("weight-bold", f64::from(m.weight_bold)),
|
||||
("fast", f64::from(m.fast_ms)),
|
||||
("normal", f64::from(m.normal_ms)),
|
||||
])
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self::new(1.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The window's content. The shell is not built yet (slice 1 of the
|
||||
//! migration): the window is the theme's page with the one line of the root
|
||||
//! state that proves the loops run in a status bar, or, with
|
||||
//! `VOELIN_OPEN=swatch`, the swatch page above that bar.
|
||||
|
||||
use gpui_kit::{
|
||||
Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px,
|
||||
};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::dev::Page;
|
||||
use crate::meter::Counters;
|
||||
use crate::swatch::swatch;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the main window draws, from the root state and the theme.
|
||||
pub struct MainView {
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
counters: Counters,
|
||||
}
|
||||
|
||||
impl MainView {
|
||||
/// A view of `app` that draws again whenever it changes, and that keeps
|
||||
/// the theme in `system` mode in step with the window's appearance.
|
||||
pub fn new(
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
counters: Counters,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
cx.observe(&app, |_, _, cx| cx.notify()).detach();
|
||||
cx.observe_window_appearance(window, |_, window, cx| {
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
})
|
||||
.detach();
|
||||
Self { app, page, counters }
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for MainView {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.renders.incr();
|
||||
let line = self.app.read(cx).state_line();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let page = match self.page {
|
||||
Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)),
|
||||
Page::Shell => div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_3xl))
|
||||
.text_color(hsla(c.text))
|
||||
.child(voelin_platform::APP_NAME),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("The desktop shell is the next slice."),
|
||||
),
|
||||
};
|
||||
div()
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.bg(hsla(c.bg_app))
|
||||
.text_color(hsla(c.text))
|
||||
.font_family(crate::theme::FONT_FAMILY)
|
||||
.child(page)
|
||||
.child(
|
||||
div()
|
||||
.h(px(m.control_height_sm))
|
||||
.px(px(m.space_5))
|
||||
.flex()
|
||||
.items_center()
|
||||
.bg(hsla(c.surface))
|
||||
.border_t_1()
|
||||
.border_color(hsla(c.border))
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(line),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! The binary's failure path, end to end: when the main window cannot be
|
||||
//! opened (no display server, no Vulkan or GL driver), `voelin-gpui` prints
|
||||
//! why and exits with status 1 instead of staying alive with no window and no
|
||||
//! message.
|
||||
//!
|
||||
//! It has to start the real binary. GPUI's Linux platform runs the launch
|
||||
//! callback before it starts its event loop, and the loop forgets a quit asked
|
||||
//! for before it started, so a failure handled by quitting inside the
|
||||
//! callback hung the process; the test platform of the unit tests has no such
|
||||
//! loop and cannot show it.
|
||||
//!
|
||||
//! The no-driver test needs a test X server in `VOELIN_X11_TEST_DISPLAY` (an
|
||||
//! Xvfb, as CI has; never the desktop's display) and is skipped without one.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Where the drivers are not: the Vulkan loader, EGL's vendor library
|
||||
/// directory and Mesa's driver directory all point here.
|
||||
const NOWHERE: &str = "/nonexistent-voelin-gpui-test";
|
||||
|
||||
/// Loaded machines are slow, so the wait is generous; a run that works takes a
|
||||
/// second or two.
|
||||
const WAIT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The scratch directory of one run, removed at the end.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// How a run of the binary went.
|
||||
enum Outcome {
|
||||
/// It ended, with this status and this much of the log.
|
||||
Ended(ExitStatus, String),
|
||||
/// It picked a GPU: the window can open, so nothing failed.
|
||||
Opened,
|
||||
/// It was still running after [`WAIT`] with no GPU picked.
|
||||
Hung(String),
|
||||
}
|
||||
|
||||
/// Run the binary with the drivers hidden (`hide_drivers`) on `display`
|
||||
/// (none: no display server at all) and wait for it to end, to pick a GPU or
|
||||
/// to run out of time. Nothing of the user's state, display or session bus is
|
||||
/// in its environment.
|
||||
fn run_binary(name: &str, display: Option<&str>, hide_drivers: bool) -> Outcome {
|
||||
let scratch = Scratch(
|
||||
Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())),
|
||||
);
|
||||
let home = scratch.0.join("home");
|
||||
let runtime = scratch.0.join("runtime");
|
||||
fs::create_dir_all(&runtime).unwrap();
|
||||
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let log = scratch.0.join("stderr.log");
|
||||
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_voelin-gpui"));
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("XDG_SESSION_TYPE")
|
||||
.env_remove("DBUS_SESSION_BUS_ADDRESS")
|
||||
.env_remove("RUST_LOG")
|
||||
.env("HOME", &home)
|
||||
.env("XDG_RUNTIME_DIR", &runtime)
|
||||
.env("XDG_CONFIG_HOME", home.join("config"))
|
||||
.env("XDG_DATA_HOME", home.join("data"))
|
||||
.env("XDG_STATE_HOME", home.join("state"))
|
||||
.env("XDG_CACHE_HOME", home.join("cache"))
|
||||
.env("VOELIN_DATA_DIR", home.join("voelin"))
|
||||
// The log line that tells a GPU was picked.
|
||||
.env("VOELIN_LOG", "warn,voelin_gpui=info,gpui_wgpu=info")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(fs::File::create(&log).unwrap());
|
||||
if let Some(display) = display {
|
||||
command.env("DISPLAY", display);
|
||||
}
|
||||
if hide_drivers {
|
||||
command
|
||||
.env("VK_DRIVER_FILES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("VK_ICD_FILENAMES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("__EGL_VENDOR_LIBRARY_DIRS", NOWHERE)
|
||||
.env("__EGL_VENDOR_LIBRARY_FILENAMES", format!("{NOWHERE}/egl.json"))
|
||||
.env("LIBGL_DRIVERS_PATH", NOWHERE);
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
|
||||
let deadline = Instant::now() + WAIT;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
return Outcome::Ended(status, fs::read_to_string(&log).unwrap_or_default());
|
||||
}
|
||||
let seen = fs::read_to_string(&log).unwrap_or_default();
|
||||
let outcome = if seen.contains("Selected GPU adapter") {
|
||||
Outcome::Opened
|
||||
} else if Instant::now() > deadline {
|
||||
Outcome::Hung(seen)
|
||||
} else {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
};
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_cannot_open_for_want_of_a_driver_ends_the_binary_with_an_error() {
|
||||
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
|
||||
else {
|
||||
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
|
||||
return;
|
||||
};
|
||||
match run_binary("no-driver", Some(&display), true) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => eprintln!(
|
||||
"skipped: this machine's driver was found in spite of the environment, \
|
||||
so the window can open"
|
||||
),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window and no GPU: a quit asked for in the \
|
||||
launch callback is lost\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_display_server_the_binary_ends_with_an_error() {
|
||||
match run_binary("no-display", None, false) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
assert!(seen.contains("no display"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => panic!("a GPU was picked without a display server"),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window: GPUI's headless platform keeps \
|
||||
the app alive\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,13 @@ tracing = "0.1.44"
|
||||
yuv = "0.8.19"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
|
||||
# `async-io`, not `tokio`: GPUI's Linux backend enables ashpd's `async-io`, ashpd
|
||||
# refuses both at once, and a front end holds the portals and GPUI in one binary.
|
||||
# zbus then runs every connection on an I/O thread of its own, whichever thread
|
||||
# builds it: no crate of the workspace turns zbus's `tokio` feature on (with it
|
||||
# zbus would pick tokio for a connection made inside a tokio runtime, and ashpd
|
||||
# shares one connection per process with every later caller).
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "async-io"], optional = true }
|
||||
memmap2 = { version = "0.9.11", optional = true }
|
||||
pipewire = { version = "0.10.1", optional = true }
|
||||
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
|
||||
|
||||
@@ -279,14 +279,14 @@ impl FrameSink for QueueSink {
|
||||
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
|
||||
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
|
||||
loop {
|
||||
match frames.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(frame) => {
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
let Some(frame) = frames.recv_timeout(Duration::from_millis(100)) else {
|
||||
if frames.is_closed() {
|
||||
break;
|
||||
}
|
||||
None if frames.is_closed() => break,
|
||||
None => {}
|
||||
continue;
|
||||
};
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
@@ -181,7 +181,9 @@ impl ScreenCapture for PortalCapture {
|
||||
}
|
||||
|
||||
/// Asks the user through the portal dialog (unless a restore token
|
||||
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
|
||||
/// applies). Any executor will do: ashpd runs on zbus's `async-io` in every
|
||||
/// binary of the workspace (no crate turns zbus's `tokio` feature on), whose
|
||||
/// connection has an I/O thread of its own, whichever thread builds it.
|
||||
fn start(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
|
||||
@@ -446,7 +446,7 @@ fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
|
||||
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
@@ -466,7 +466,7 @@ fn ldconfig(base: &str) -> Vec<PathBuf> {
|
||||
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -603,8 +603,8 @@ mod v4l2 {
|
||||
// Seconds per frame; a stepwise range starts with its smallest
|
||||
// interval, which is the highest rate.
|
||||
let (num, den) = (entry.interval[0], entry.interval[1]);
|
||||
if num > 0 {
|
||||
best = best.max(den / num);
|
||||
if let Some(rate) = den.checked_div(num) {
|
||||
best = best.max(rate);
|
||||
}
|
||||
if entry.type_ != FRMIVAL_DISCRETE {
|
||||
break;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,11 @@ tokio = { version = "1", features = ["rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
|
||||
# `async-io`, not `tokio`, as in voelin-media: GPUI enables ashpd's `async-io` and
|
||||
# ashpd refuses both features at once.
|
||||
ashpd = { version = "0.13", default-features = false, features = ["async-io", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
|
||||
futures-util = { version = "0.3", optional = true }
|
||||
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
|
||||
notify-rust = { version = "4.18", default-features = false, features = ["z"] }
|
||||
x11rb = { version = "0.13", features = ["xinput"], optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
@@ -46,8 +48,11 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
|
||||
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
|
||||
# A stand-in desktop portal on a private session bus (tests/proxy.rs); the
|
||||
# zbus ashpd uses.
|
||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||
# zbus ashpd uses, on `async-io` like every other zbus in the workspace: a
|
||||
# `tokio` here would put the executor choice of ashpd's connection (zbus picks
|
||||
# tokio when a tokio runtime is current where it builds the connection) into
|
||||
# the tests alone, and tests/proxy.rs checks that the choice does not matter.
|
||||
zbus = { version = "5", default-features = false, features = ["async-io"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,8 +1,15 @@
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
|
||||
//! session bus. Run it on a private bus:
|
||||
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
|
||||
//! without a session bus it checks nothing. Its own test binary: answers
|
||||
//! are kept process-wide.
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
|
||||
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
|
||||
//! own that starts no services: on a desktop's bus the real portal is running
|
||||
//! or startable, and when the stand-in leaves the bus (as the test has it do)
|
||||
//! the real one is started and answers instead. Without `dbus-run-session`,
|
||||
//! or a bus daemon for it, the test says so and checks nothing. Its own test
|
||||
//! binary: answers are kept process-wide.
|
||||
//!
|
||||
//! The second and third tests call ashpd from a thread with no tokio runtime,
|
||||
//! as GPUI's executor would: ashpd runs on zbus's `async-io`, whichever thread
|
||||
//! built its connection (the third lets a tokio caller build it first;
|
||||
//! docs/design/gpui-spikes.md, "Dependencies").
|
||||
|
||||
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
|
||||
@@ -11,6 +18,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use voelin_platform::proxy::proxy_for;
|
||||
|
||||
/// Set for the run on the bus of its own.
|
||||
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
|
||||
|
||||
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
|
||||
/// others.
|
||||
struct Resolver {
|
||||
@@ -34,10 +44,72 @@ impl Resolver {
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration of the bus of its own: a session bus without the service
|
||||
/// directories, so that nothing on it can be started by name. Its socket is
|
||||
/// made in `dir`.
|
||||
fn bus_config(dir: &std::path::Path) -> String {
|
||||
format!(
|
||||
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>session</type>
|
||||
<listen>unix:tmpdir={}</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow send_destination="*" eavesdrop="true"/>
|
||||
<allow eavesdrop="true"/>
|
||||
<allow own="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
"#,
|
||||
dir.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Run the test `name` again under `dbus-run-session` on a bus of its own, and
|
||||
/// say nothing was checked when that bus cannot be had.
|
||||
fn on_a_bus_of_its_own(name: &str) {
|
||||
let dir = std::env::temp_dir();
|
||||
let config = dir.join(format!("voelin-proxy-test-bus-{}-{name}.conf", std::process::id()));
|
||||
std::fs::write(&config, bus_config(&dir)).unwrap();
|
||||
let run = std::process::Command::new("dbus-run-session")
|
||||
.arg(format!("--config-file={}", config.display()))
|
||||
.arg("--")
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--exact", name, "--nocapture", "--test-threads=1"])
|
||||
.env(ON_ITS_OWN_BUS, "1")
|
||||
.output();
|
||||
let _ = std::fs::remove_file(&config);
|
||||
let run = match run {
|
||||
Ok(run) => run,
|
||||
Err(e) => {
|
||||
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let text =
|
||||
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
if run.status.success() {
|
||||
// A child that ran no test (its filter matched nothing) exits 0 as well.
|
||||
assert!(
|
||||
text.contains("test result: ok. 1 passed;"),
|
||||
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
// The test ran and failed, or the bus never came up.
|
||||
assert!(
|
||||
!text.contains("running 1 test"),
|
||||
"the test failed on its own bus ({}):\n{text}",
|
||||
run.status
|
||||
);
|
||||
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_portal_names_the_proxy() {
|
||||
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
|
||||
eprintln!("no session bus: run under dbus-run-session");
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own("the_portal_names_the_proxy");
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
@@ -66,3 +138,96 @@ async fn the_portal_names_the_proxy() {
|
||||
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// Run `future` on the calling thread, which parks while it waits: an executor
|
||||
/// of no runtime at all, as a GPUI foreground task is to ashpd.
|
||||
fn block_on<F: std::future::Future>(future: F) -> F::Output {
|
||||
struct Unpark(std::thread::Thread);
|
||||
impl std::task::Wake for Unpark {
|
||||
fn wake(self: Arc<Self>) {
|
||||
self.0.unpark();
|
||||
}
|
||||
}
|
||||
let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current())));
|
||||
let mut cx = std::task::Context::from_waker(&waker);
|
||||
let mut future = std::pin::pin!(future);
|
||||
loop {
|
||||
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
|
||||
return output;
|
||||
}
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stand-in portal on the bus of its own, served from the calling task.
|
||||
async fn stand_in_portal(lookups: &Arc<AtomicU32>) -> zbus::Connection {
|
||||
zbus::connection::Builder::session()
|
||||
.unwrap()
|
||||
.name("org.freedesktop.portal.Desktop")
|
||||
.unwrap()
|
||||
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
|
||||
.unwrap()
|
||||
.build()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A lookup through ashpd, from the calling task.
|
||||
async fn lookup() -> Vec<ashpd::Uri> {
|
||||
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
|
||||
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
|
||||
resolver.lookup(&uri).await.unwrap()
|
||||
}
|
||||
|
||||
/// A lookup through ashpd from a thread of its own with no runtime, blocking
|
||||
/// the caller's task for it (the pool's threads, `spawn_blocking`, have the
|
||||
/// runtime in reach). The stand-in portal runs on the test's runtime: keep it
|
||||
/// free while waiting.
|
||||
async fn lookup_without_a_runtime() -> Vec<String> {
|
||||
let caller = std::thread::spawn(|| {
|
||||
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
|
||||
block_on(lookup()).iter().map(|uri| uri.as_str().to_owned()).collect::<Vec<_>>()
|
||||
});
|
||||
tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap()
|
||||
}
|
||||
|
||||
/// ashpd with `async-io`: a caller outside any tokio runtime gets its answer,
|
||||
/// the connection's I/O running on zbus's own thread.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_portal_answers_a_caller_without_a_runtime() {
|
||||
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime";
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own(TEST);
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
let _portal = stand_in_portal(&lookups).await;
|
||||
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// ashpd keeps one session connection for the process, and zbus picks the
|
||||
/// executor of a connection once, when it builds it: tokio if a tokio runtime
|
||||
/// is current on that thread and zbus has its `tokio` feature on, its own
|
||||
/// `async-io` thread otherwise. If the engine's runtime made the connection
|
||||
/// first, a later caller with no runtime (a GPUI foreground task) would find a
|
||||
/// tokio connection with no reactor to run on and panic ("there is no reactor
|
||||
/// running" in zbus's property cache). With zbus on `async-io` alone in every
|
||||
/// binary (notify-rust without `z-with-tokio`, no zbus `tokio` here either)
|
||||
/// the order does not matter.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller() {
|
||||
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller";
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own(TEST);
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
let _portal = stand_in_portal(&lookups).await;
|
||||
// The tokio caller first: it builds the process's session connection.
|
||||
let answer: Vec<_> = lookup().await.iter().map(|uri| uri.as_str().to_owned()).collect();
|
||||
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
|
||||
// Then the caller with no runtime, on the same connection.
|
||||
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
@@ -35,44 +35,119 @@
|
||||
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
|
||||
//! record and the device key with [`KeyStore::get`]: one damaged row, the
|
||||
//! record's own included, would otherwise keep a sign-out from ever finishing,
|
||||
//! and with it the deletion of the key the user asked to forget. Unbound is the
|
||||
//! reading that never deletes on a guess: a sign-out neither deletes such a row
|
||||
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
|
||||
//! four good binding columns. A `data` column that is not text (a BLOB, or text
|
||||
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
|
||||
//! that a record that cannot be read is deleted by the sign-out, as the trait
|
||||
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! and with it the deletion of the synced copies and of the record, and the
|
||||
//! forgetting of the key the user asked to forget. Unbound is the reading that
|
||||
//! never deletes on a guess: a sign-out neither deletes such a row as a synced
|
||||
//! copy nor writes it, it stays as it is until a `put` of it writes four good
|
||||
//! binding columns. A `data` column that is not text (a BLOB, or text of bytes
|
||||
//! that are no UTF-8) is read as text with the odd bytes replaced, so that a
|
||||
//! record that cannot be read is deleted by the sign-out, as the trait says,
|
||||
//! instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! [`KeyStore::get`] returned for such a row is taken for the data that is
|
||||
//! there: it changes the binding and keeps the stored bytes, where any other
|
||||
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
|
||||
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
|
||||
//! out with a warning.
|
||||
//!
|
||||
//! # Signing out keeps every key
|
||||
//!
|
||||
//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since
|
||||
//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts
|
||||
//! design, answered by the owner on 2026-10-24) it keeps every key of the
|
||||
//! device. The device key stays, unbound and byte for byte, whether it was in
|
||||
//! use before the account existed or the client made it for the account:
|
||||
//! `AccountRecord::bound_existing_key` only records which, for the client's
|
||||
//! wording, and no rule reads it. At every host without accounts that the user
|
||||
//! reached with it, either key is the user's identity, and deleting it would
|
||||
//! lose their servers, roles and memberships there. The identities that only
|
||||
//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user
|
||||
//! kept local) are unbound and kept as well.
|
||||
//!
|
||||
//! What a sign-out deletes is not a key of the device: the synced copies of
|
||||
//! integration secrets, which the account service holds and every device can
|
||||
//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted
|
||||
//! like one, see below), and the account record, which holds no secret. A
|
||||
//! sign-out does not release the device key at the account service either: the
|
||||
//! key stays registered with the account there. The release is its own
|
||||
//! operation, see below.
|
||||
//!
|
||||
//! # Releasing a device key
|
||||
//!
|
||||
//! The release of the device key from its account (part 2 of open question 10)
|
||||
//! is the account service's operation followed by a local unbind, and the unbind
|
||||
//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls
|
||||
//! `POST /v1/devices/<own>/release` after a password check, and then runs
|
||||
//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key,
|
||||
//! unbound. So the store needs nothing of its own for it: no call that unbinds
|
||||
//! one key (a [`KeyStore::put`] of the blob without its binding does that, and
|
||||
//! keeps the data, as the sign-out does), and no record that the key was
|
||||
//! released. The accounts design asks the client to remember nothing of the
|
||||
//! kind: the service holds the registration of the key (after a release it is
|
||||
//! registered with no account, after a sign-out with the account that was
|
||||
//! signed out of), and the client learns which at the next sign-in or sign-up,
|
||||
//! from the service's answer (`CONFLICT`, field `device`), not from a note kept
|
||||
//! here. The deletion of the account (`AccountClient::delete_account`) is the
|
||||
//! same: the service writes a DEVICE and a RELEASED entry for every device key
|
||||
//! of the account, and the local half is this sign-out, which keeps this
|
||||
//! device's key.
|
||||
//!
|
||||
//! # Forgetting the device's identity
|
||||
//!
|
||||
//! "Forget this device's identity" is the user's explicit choice and the only
|
||||
//! deletion of a key of the device; the UI offers to export the key first and
|
||||
//! asks before it deletes.
|
||||
//!
|
||||
//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of
|
||||
//! the device key. The caller names the key, because the key goes before the
|
||||
//! record is read: a record that cannot be read does not keep it.
|
||||
//! - Signed out, or with a key that no account ever bound, it is
|
||||
//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is
|
||||
//! [`Store::delete_identity`]. Neither looks at an account record, so a UI
|
||||
//! that forgets the device key of the account it is signed in to does it
|
||||
//! through the sign-out, not through `remove`.
|
||||
//!
|
||||
//! The store has no call that exports, because it would only wrap what the
|
||||
//! caller can read before it deletes: a Voelin key is
|
||||
//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that
|
||||
//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is
|
||||
//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by
|
||||
//! `voelin_core::ts::identity::export` or `write_export`. The same two calls,
|
||||
//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes
|
||||
//! the account: it offers an export of the device keys before the service is
|
||||
//! asked.
|
||||
//!
|
||||
//! # Deleted keys leave no trace
|
||||
//!
|
||||
//! The rows are private keys, so a removed row is not left behind in the file:
|
||||
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
|
||||
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
|
||||
//! [`Store::delete_identity`] does, so that the frame of the log that held the
|
||||
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
|
||||
//! `remove`, truncates the log once, after its last step, not after each
|
||||
//! removal. The checkpoint waits for another connection for a moment at most
|
||||
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
|
||||
//! and then the removal still succeeds and a warning says that the deleted
|
||||
//! bytes may stay in the log file, until a later checkpoint truncates the log,
|
||||
//! later writes overwrite those frames, or the last connection to the database
|
||||
//! closes and the log is deleted.
|
||||
//! page with the key is gone too. A forgotten key needs exactly that. So does
|
||||
//! the one deletion a sign-out still makes of a key: a synced copy of a
|
||||
//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out
|
||||
//! deletes with `remove` on a `SignOutPass` and truncates the log once, after
|
||||
//! its last step, not after each removal; one that deletes nothing (the record
|
||||
//! was gone, no copies) truncates nothing. The checkpoint waits for another
|
||||
//! connection for a moment at most (`Store::truncate_wal`): one that keeps
|
||||
//! reading an old snapshot blocks it, and then the removal still succeeds and a
|
||||
//! warning says that the deleted bytes may stay in the log file, until a later
|
||||
//! checkpoint truncates the log, later writes overwrite those frames, or the
|
||||
//! last connection to the database closes and the log is deleted.
|
||||
//!
|
||||
//! The device key is never a synced copy. The account record names the Voelin key
|
||||
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
|
||||
//! every identity bound with `synced = true` in its first step, before it reads
|
||||
//! the record, so a key stored that way would be deleted whatever the record
|
||||
//! says (a key that predates the account is to be kept). The store therefore
|
||||
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
|
||||
//! with `synced = true` while an account record names its uid as the device, or
|
||||
//! while a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! # The device key is never a synced copy
|
||||
//!
|
||||
//! A sign-out keeps the device key, but its first step deletes every identity
|
||||
//! bound with `synced = true`, before it reads the account record that names
|
||||
//! the device key. A device key stored that way would be deleted by that step,
|
||||
//! whether it predates the account or not, which is what the rule that a
|
||||
//! sign-out keeps every device key forbids. The store therefore refuses, with an
|
||||
//! error that says why, a [`KeyStore::put`] of a `voelin` blob with
|
||||
//! `synced = true` while an account record names its uid as the device, or while
|
||||
//! a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! account record that names a key which is stored as a synced copy. A binding
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
|
||||
//! follows the record. The check and the write are done under the store's lock;
|
||||
//! a second process writing the same file at the same moment is not covered.
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps
|
||||
//! it. The check and the write are done under the store's lock; a second
|
||||
//! process writing the same file at the same moment is not covered.
|
||||
//!
|
||||
//! A TeamSpeak blob that is refused says why in words that carry none of its
|
||||
//! input: its `data` is the identity's private key, and an error reaches log
|
||||
@@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities
|
||||
/// access to the TeamSpeak methods of the same connection.
|
||||
///
|
||||
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
|
||||
/// `voelin-identity` defines them, on top of the five methods here; the
|
||||
/// sign-out only truncates the write-ahead log once, at its end.
|
||||
/// `voelin-identity` defines them, on top of the five methods here: a sign-out
|
||||
/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the
|
||||
/// device key), and only truncates the write-ahead log once, at its end, when
|
||||
/// it deleted something.
|
||||
pub struct SqliteKeyStore {
|
||||
store: Mutex<Store>,
|
||||
}
|
||||
@@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore {
|
||||
|
||||
/// The trait's sign-out, with the log truncated once after its last step
|
||||
/// instead of after each of its removals: it removes up to a handful of
|
||||
/// rows, and a checkpoint that another connection blocks costs a moment
|
||||
/// rows (the synced copies, the account record and, with
|
||||
/// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and
|
||||
/// a checkpoint that another connection blocks costs a moment
|
||||
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
|
||||
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
|
||||
/// the checkpoint to this method.
|
||||
/// the checkpoint to this method. A sign-out that deleted nothing does not
|
||||
/// checkpoint.
|
||||
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
|
||||
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
|
||||
let outcome = KeyStore::sign_out(&pass, account, device_key);
|
||||
@@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
|
||||
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
|
||||
/// rows, but `remove` only notes that it deleted something, so that the sign-out
|
||||
/// truncates the log once at its end.
|
||||
/// truncates the log once at its end. What a sign-out removes is the synced
|
||||
/// copies of integration secrets, the account record and, when the user chose
|
||||
/// to forget it, the device key; unbinding goes through `put`, which deletes
|
||||
/// nothing.
|
||||
struct SignOutPass<'a> {
|
||||
store: &'a SqliteKeyStore,
|
||||
/// Whether a row was deleted.
|
||||
@@ -470,26 +553,28 @@ enum Refused {
|
||||
/// `uid` is unique across kinds in this table.
|
||||
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
|
||||
UidHeld { uid: String, kind: String },
|
||||
/// The Voelin key is the device key of an account record. A sign-out
|
||||
/// deletes a synced copy without reading the record, so the key the record
|
||||
/// says to keep would be deleted.
|
||||
/// The Voelin key is the device key of an account record. A sign-out keeps
|
||||
/// the device key, but it deletes a synced copy without reading the record,
|
||||
/// so a device key stored as one would be deleted all the same.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
|
||||
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
||||
reads the record, so it would delete the device key that it keeps"
|
||||
)]
|
||||
SyncedDeviceKey { uid: String, record: String },
|
||||
/// An account record cannot be read, so the store cannot tell whether the
|
||||
/// Voelin key is its device key.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
|
||||
record {record:?} cannot be read, so it may name this key as the device key"
|
||||
record {record:?} cannot be read, so it may name this key as the device key, which a \
|
||||
sign-out keeps but would delete as a synced copy"
|
||||
)]
|
||||
UnreadableRecord { uid: String, record: String },
|
||||
/// The device key of the record is stored as a synced copy already.
|
||||
#[error(
|
||||
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
|
||||
says"
|
||||
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
||||
reads the record, so it would delete the device key that it keeps"
|
||||
)]
|
||||
RecordNamesSyncedKey { record: String, device: String },
|
||||
}
|
||||
|
||||
@@ -33,12 +33,48 @@ pub use store::{
|
||||
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
|
||||
};
|
||||
|
||||
/// How the JSON of a stored TeamSpeak identity is wrong: the category of the
|
||||
/// reader's complaint and nothing of the text, which holds a private key.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum IdentityDamage {
|
||||
/// The text is not JSON.
|
||||
Malformed,
|
||||
/// The text ends before the JSON does.
|
||||
CutShort,
|
||||
/// The JSON is not that of an identity: a field is missing or of another
|
||||
/// type, or the key does not import.
|
||||
NotAnIdentity,
|
||||
/// The text could not be read.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IdentityDamage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Malformed => "malformed",
|
||||
Self::CutShort => "cut short",
|
||||
Self::NotAnIdentity => "not an identity",
|
||||
Self::Unreadable => "unreadable",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("database: {0}")]
|
||||
Db(#[from] rusqlite::Error),
|
||||
#[error("serialization: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
/// The JSON of a stored TeamSpeak identity cannot be read, which only damage
|
||||
/// outside the client can cause. It says how the text is wrong and where, and
|
||||
/// never what it holds: the text is a private key, and the message of the
|
||||
/// JSON reader quotes the value it refuses (`tsproto` reports a key that does
|
||||
/// not import as an invalid value, the key string and all), so that message is
|
||||
/// not kept, not here and not in a log line.
|
||||
#[error(
|
||||
"the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}"
|
||||
)]
|
||||
Identity { damage: IdentityDamage, line: usize, column: usize },
|
||||
#[error("{0} {1} not found")]
|
||||
NotFound(&'static str, i64),
|
||||
#[error("secret store: {0}")]
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsclientlib::Identity;
|
||||
|
||||
use crate::{Error, Result};
|
||||
use crate::{Error, IdentityDamage, Result};
|
||||
|
||||
/// A schema migration: SQL, or code for what SQL alone cannot do.
|
||||
enum Migration {
|
||||
@@ -244,6 +244,28 @@ impl Bookmark {
|
||||
/// waits.
|
||||
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
|
||||
|
||||
/// The TeamSpeak identity in the JSON of a stored row.
|
||||
///
|
||||
/// A text that does not read (it could only have been damaged outside the
|
||||
/// client: [`Store::add_identity`] writes what `serde_json` makes of an
|
||||
/// identity) is refused with [`Error::Identity`], which says how it is wrong and
|
||||
/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json`
|
||||
/// does for the text it is handed. The reader's own message is dropped: it
|
||||
/// quotes a value it refuses, and `tsproto` reports a key that does not import
|
||||
/// as an invalid value, the key string and all, which would reach a status line
|
||||
/// or a log.
|
||||
fn identity_from_json(json: &str) -> Result<Identity> {
|
||||
serde_json::from_str(json).map_err(|error| {
|
||||
let damage = match error.classify() {
|
||||
serde_json::error::Category::Syntax => IdentityDamage::Malformed,
|
||||
serde_json::error::Category::Eof => IdentityDamage::CutShort,
|
||||
serde_json::error::Category::Data => IdentityDamage::NotAnIdentity,
|
||||
serde_json::error::Category::Io => IdentityDamage::Unreadable,
|
||||
};
|
||||
Error::Identity { damage, line: error.line(), column: error.column() }
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
pub(crate) db: Connection,
|
||||
}
|
||||
@@ -348,7 +370,7 @@ impl Store {
|
||||
})?;
|
||||
rows.map(|row| {
|
||||
let (id, name, uid, data, origin, is_default) = row?;
|
||||
let identity: Identity = serde_json::from_str(&data)?;
|
||||
let identity = identity_from_json(&data)?;
|
||||
let origin = IdentityOrigin::parse(&origin);
|
||||
Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default })
|
||||
})
|
||||
@@ -395,7 +417,7 @@ impl Store {
|
||||
)
|
||||
.optional()?;
|
||||
let data = data.ok_or(Error::NotFound("identity", id))?;
|
||||
Ok(serde_json::from_str(&data)?)
|
||||
identity_from_json(&data)
|
||||
}
|
||||
|
||||
/// Store an identity again, e.g. after its security level was improved.
|
||||
@@ -630,23 +652,43 @@ mod tests {
|
||||
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
|
||||
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A value that is not the default, so that restoring a constant would show.
|
||||
// A value that is not the default, so that restoring a constant would
|
||||
// show, and one so long that a checkpoint that waited as long as the
|
||||
// connection allows would not come back by itself.
|
||||
const HOUR_MS: i64 = 3_600_000;
|
||||
let timeout = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
|
||||
};
|
||||
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
store.truncate_wal();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
|
||||
store.db.busy_timeout(Duration::from_secs(3600)).unwrap();
|
||||
|
||||
// "Briefly" is not a time: a checkpoint ends in two fsyncs, which take
|
||||
// seconds under disk pressure (it took 6 s here beside `dd conv=fsync`
|
||||
// loops), and only a checkpoint that comes back while the reader still
|
||||
// holds its snapshot has not waited for it. So the reader lets go from
|
||||
// another thread after 30 s, which ends a checkpoint that does not give
|
||||
// up with a failure here and not with an hour's wait.
|
||||
let (back, hear) = std::sync::mpsc::channel::<()>();
|
||||
let watchdog = std::thread::spawn(move || {
|
||||
let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok();
|
||||
if !in_time {
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
}
|
||||
(reader, in_time)
|
||||
});
|
||||
// One attempt, which the reader blocks (`1`).
|
||||
let blocked = store.checkpoint_truncate();
|
||||
back.send(()).ok();
|
||||
let (reader, in_time) = watchdog.join().unwrap();
|
||||
assert!(in_time, "the checkpoint waited for the reader instead of giving up");
|
||||
assert_eq!(blocked.unwrap(), 1, "the reader should block the reset");
|
||||
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
assert_eq!(timeout(&store), HOUR_MS);
|
||||
|
||||
// Without the reader the same call resets the log.
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
store.truncate_wal();
|
||||
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
assert_eq!(timeout(&store), HOUR_MS);
|
||||
drop(reader);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! A damaged identity row: what the store returns and logs about it says how
|
||||
//! the row is wrong and never what it holds.
|
||||
//!
|
||||
//! The `data` of a TeamSpeak row is the JSON of a private key. Only something
|
||||
//! outside the client can damage it, but when that happens the error of the
|
||||
//! JSON reader quotes the value it refuses (`tsproto` reports a key that does
|
||||
//! not import as an invalid value, the key string and all), and an error
|
||||
//! reaches a status line, an event or a log. `Store::identity` and
|
||||
//! `Store::identities` used to return that error as it was.
|
||||
//!
|
||||
//! Every case here damages a row of a database file through a second
|
||||
//! connection, calls everything of the store that reads or writes the row, and
|
||||
//! looks through the errors (their text, their `Debug` text and their sources)
|
||||
//! and the logs at TRACE for any 8 characters in a row of what the row held.
|
||||
|
||||
use rusqlite::types::Value;
|
||||
use rusqlite::{Connection, params};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_identity::{
|
||||
AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK,
|
||||
KeyStore, Uid, account_uid,
|
||||
};
|
||||
use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store};
|
||||
|
||||
mod support;
|
||||
|
||||
/// A directory of its own that is removed again.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("voelin-identity-text-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn db(&self) -> std::path::PathBuf {
|
||||
self.0.join("client.db")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Letters and digits that no message of this crate, of `serde_json` or of
|
||||
/// SQLite is made of in a run of eight.
|
||||
const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga";
|
||||
const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za";
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that
|
||||
/// string: the reader quotes it in its message.
|
||||
fn json_with_a_counter_of_the_wrong_type() -> String {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
json["counter"] = SECRET.into();
|
||||
json.to_string()
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity cut in the middle of its key, and the key.
|
||||
fn json_cut_inside_its_key() -> (String, String) {
|
||||
let json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let text = json.to_string();
|
||||
let cut = text.find(&key).unwrap() + key.len() / 2;
|
||||
(text[..cut].to_owned(), key)
|
||||
}
|
||||
|
||||
/// How a row's `data` is damaged: what is stored, as which storage class, and
|
||||
/// the text of it that must never be repeated.
|
||||
struct Damage {
|
||||
label: &'static str,
|
||||
value: Value,
|
||||
/// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB.
|
||||
as_text: bool,
|
||||
secret: String,
|
||||
/// What the store says of it, when it reads it as JSON.
|
||||
damage: Option<IdentityDamage>,
|
||||
}
|
||||
|
||||
fn damages() -> Vec<Damage> {
|
||||
let (cut, cut_key) = json_with_a_cut_key();
|
||||
let (cut_short, whole_key) = json_cut_inside_its_key();
|
||||
let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes();
|
||||
not_utf8.push(0xff);
|
||||
vec![
|
||||
Damage {
|
||||
label: "a key that does not import",
|
||||
value: Value::Text(cut),
|
||||
as_text: false,
|
||||
secret: cut_key,
|
||||
damage: Some(IdentityDamage::NotAnIdentity),
|
||||
},
|
||||
Damage {
|
||||
label: "a field of the wrong type",
|
||||
value: Value::Text(json_with_a_counter_of_the_wrong_type()),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: Some(IdentityDamage::NotAnIdentity),
|
||||
},
|
||||
Damage {
|
||||
label: "syntax",
|
||||
value: Value::Text(format!("not json: {SECRET}")),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: Some(IdentityDamage::Malformed),
|
||||
},
|
||||
Damage {
|
||||
label: "cut short",
|
||||
value: Value::Text(cut_short),
|
||||
as_text: false,
|
||||
secret: whole_key,
|
||||
damage: Some(IdentityDamage::CutShort),
|
||||
},
|
||||
Damage {
|
||||
label: "bytes that are no UTF-8, stored as a BLOB",
|
||||
value: Value::Blob(not_utf8.clone()),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: None,
|
||||
},
|
||||
Damage {
|
||||
label: "bytes that are no UTF-8, stored as TEXT",
|
||||
value: Value::Blob(not_utf8),
|
||||
as_text: true,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data");
|
||||
}
|
||||
}
|
||||
|
||||
/// The texts an error shows to a caller: how it reads, its `Debug` text and
|
||||
/// those of everything it was caused by.
|
||||
fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec<String> {
|
||||
let mut texts = vec![error.to_string(), format!("{error:?}")];
|
||||
let mut source = error.source();
|
||||
while let Some(cause) = source {
|
||||
texts.push(cause.to_string());
|
||||
texts.push(format!("{cause:?}"));
|
||||
source = cause.source();
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
fn binding() -> AccountBinding {
|
||||
let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16]));
|
||||
AccountBinding {
|
||||
account,
|
||||
integration: Some(IntegrationId::from_bytes([7; 16])),
|
||||
rev: 3,
|
||||
synced: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A database file with one TeamSpeak identity, its `data` replaced by `damage`
|
||||
/// through a second connection. Returns the id and uid of the row.
|
||||
fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) {
|
||||
let store = Store::open(&scratch.db()).unwrap();
|
||||
let identity = Identity::create();
|
||||
let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap();
|
||||
let uid = identity.key().to_pub().get_uid();
|
||||
drop(store);
|
||||
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
let sql = if damage.as_text {
|
||||
"UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2"
|
||||
} else {
|
||||
"UPDATE identities SET data = ?1 WHERE id = ?2"
|
||||
};
|
||||
assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1);
|
||||
(id, uid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_json_readers_own_message_quotes_what_it_refuses() {
|
||||
// Without this the cases below could not fail: serde's message for a key
|
||||
// that does not import and for a field of the wrong type repeats the value.
|
||||
let (json, cut_key) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}");
|
||||
let typed = json_with_a_counter_of_the_wrong_type();
|
||||
let raw = serde_json::from_str::<Identity>(&typed).unwrap_err().to_string();
|
||||
assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() {
|
||||
for damage in damages() {
|
||||
let scratch = Scratch::new("store");
|
||||
let (id, _) = damaged_database(&scratch, &damage);
|
||||
let label = damage.label;
|
||||
let store = Store::open(&scratch.db()).unwrap();
|
||||
|
||||
let ((one, all, default), lines) = support::at_trace(|| {
|
||||
(
|
||||
store.identity(id).unwrap_err(),
|
||||
store.identities().unwrap_err(),
|
||||
store.default_identity().unwrap_err(),
|
||||
)
|
||||
});
|
||||
for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] {
|
||||
for text in texts_of(error) {
|
||||
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}"));
|
||||
}
|
||||
if let Some(expected) = damage.damage {
|
||||
// The kind of damage and where, in the store's own words.
|
||||
match error {
|
||||
Error::Identity { damage, line, column } => {
|
||||
assert_eq!(*damage, expected, "{label}: {call}");
|
||||
assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}");
|
||||
let shown = error.to_string();
|
||||
assert!(
|
||||
shown.starts_with(&format!(
|
||||
"the stored TeamSpeak identity cannot be read: {expected} at line 1, column "
|
||||
)),
|
||||
"{label}: {call}: {shown}"
|
||||
);
|
||||
}
|
||||
other => panic!("{label}: {call}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() {
|
||||
for damage in damages() {
|
||||
let scratch = Scratch::new("keystore");
|
||||
let (_id, uid) = damaged_database(&scratch, &damage);
|
||||
let label = damage.label;
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
|
||||
// Everything that reads or writes the row, in the order a sign-out would,
|
||||
// with the errors and the logs of all of it kept.
|
||||
let (results, lines) = support::at_trace(|| {
|
||||
let mut errors: Vec<Box<dyn std::error::Error + Send + Sync>> = Vec::new();
|
||||
let mut note = |result: Result<(), voelin_identity::KeyStoreError>| {
|
||||
if let Err(error) = result {
|
||||
errors.push(Box::new(error));
|
||||
}
|
||||
};
|
||||
let listed = store.list().unwrap();
|
||||
let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed");
|
||||
assert_eq!(entry.level, 0, "{label}: damage reads as level 0");
|
||||
|
||||
// What `get` hands out is the data itself; a `put` of it rebinds the row.
|
||||
let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read");
|
||||
note(store.put(&blob.clone().with_binding(binding())));
|
||||
// Other data over the row is checked and refused, and the refusal does
|
||||
// not repeat it.
|
||||
let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#);
|
||||
note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other)));
|
||||
note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET)));
|
||||
// The sign-out that unbinds it, and the delete that removes it.
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
store.remove(KIND_TEAMSPEAK, &uid).unwrap();
|
||||
errors
|
||||
});
|
||||
assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}");
|
||||
for error in &results {
|
||||
for text in texts_of(error.as_ref()) {
|
||||
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal"));
|
||||
assert_holds_no_piece_of(
|
||||
&text,
|
||||
SECRET,
|
||||
&format!("{label}: a refusal of other data"),
|
||||
);
|
||||
assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data"));
|
||||
}
|
||||
}
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
|
||||
assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_capture_sees_what_the_store_logs() {
|
||||
// A control for the cases above: a row whose binding columns are damaged is
|
||||
// listed with a warning that names it, and the capture takes it in at TRACE.
|
||||
let scratch = Scratch::new("control");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#));
|
||||
store.put(&blob).unwrap();
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
assert_eq!(
|
||||
db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
let (listed, lines) = support::at_trace(|| store.list().unwrap());
|
||||
assert_eq!(listed.len(), 1);
|
||||
let warning = lines
|
||||
.iter()
|
||||
.find(|line| line.contains("the binding columns of an identity cannot be read"))
|
||||
.unwrap_or_else(|| panic!("no warning in {lines:?}"));
|
||||
assert!(warning.starts_with("WARN "), "{warning}");
|
||||
assert!(warning.contains("future:one"), "{warning}");
|
||||
// And it does not carry the row's data either.
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, SECRET, "a log line");
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ use voelin_identity::{
|
||||
};
|
||||
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
|
||||
|
||||
mod support;
|
||||
|
||||
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
|
||||
/// identity of tsproto's own `identity_tests`.
|
||||
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
|
||||
@@ -803,8 +805,9 @@ fn the_record_fixture_is_what_the_protocol_writes() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
// The device key was made for the account: signing out deletes it.
|
||||
fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() {
|
||||
// The device key was made for the account: signing out keeps it all the
|
||||
// same, unbound (open question 10 of the accounts design).
|
||||
let Install { store, synced, device_only, local } = signed_in_install(false);
|
||||
let mine = binding().account;
|
||||
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
|
||||
@@ -815,19 +818,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
store.put_voelin_key(&other_key).unwrap();
|
||||
|
||||
let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap();
|
||||
let mut expected_removed = vec![
|
||||
(KIND_ACCOUNT.to_owned(), record().blob_uid()),
|
||||
pair(&synced),
|
||||
(KIND_VOELIN.to_owned(), key().uid().to_base32()),
|
||||
];
|
||||
let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
|
||||
expected_removed.sort();
|
||||
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
|
||||
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
|
||||
assert_eq!(
|
||||
sorted(done.unbound.clone()),
|
||||
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
|
||||
"{done:?}"
|
||||
);
|
||||
|
||||
// What is left: the device secret unbound and byte for byte as it was, the
|
||||
// local and the other account's identities as they were, the other key.
|
||||
// What is left: the device key, the device secret unbound and byte for
|
||||
// byte as it was, the local and the other account's identities as they
|
||||
// were, the other key.
|
||||
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid());
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
|
||||
assert_eq!(kept, device_only.clone().with_binding(None));
|
||||
@@ -835,11 +839,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local);
|
||||
assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob);
|
||||
assert!(store.voelin_key(&other_key.uid()).unwrap().is_some());
|
||||
assert_eq!(store.list().unwrap().len(), 4);
|
||||
assert_eq!(store.list().unwrap().len(), 5);
|
||||
|
||||
// Signing out again finds nothing to do.
|
||||
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
|
||||
assert_eq!(store.list().unwrap().len(), 4);
|
||||
assert_eq!(store.list().unwrap().len(), 5);
|
||||
// Another account's sign-out acts on that account's identities only.
|
||||
assert_eq!(
|
||||
store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed,
|
||||
@@ -892,17 +896,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_out_deletes_a_device_key_the_client_made_for_the_account() {
|
||||
fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() {
|
||||
// Open question 10 of the accounts design (answered 2026-10-24): a key that
|
||||
// the client made for the account is the user's identity at every host
|
||||
// without accounts that the user reached with it as well, so `Auto` keeps
|
||||
// it like a key that predates the account. Only `Forget` deletes it.
|
||||
let Install { store, device_only, local, .. } = signed_in_install(false);
|
||||
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
|
||||
let signature = key().sign(b"the same key, signed before and after");
|
||||
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert!(!done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
|
||||
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
|
||||
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
|
||||
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
|
||||
assert_eq!(key_after, key_before, "the stored blob is untouched");
|
||||
assert_eq!(key_after.binding, None);
|
||||
let mut left = sorted(store.list().unwrap());
|
||||
left.sort();
|
||||
let mut expected = vec![pair(&device_only), pair(&local)];
|
||||
let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)];
|
||||
expected.sort();
|
||||
assert_eq!(left, expected, "the device secret and the local one");
|
||||
assert_eq!(left, expected, "the key, the device secret and the local one");
|
||||
|
||||
// The flag changes nothing: a key that predates the account gets the same
|
||||
// treatment. (The other identities of the two installs are fresh ones, so
|
||||
// the reports differ in them.)
|
||||
let existing = signed_in_install(true);
|
||||
let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(again.unbound.contains(&device_key_info()), "{again:?}");
|
||||
assert!(!again.removed.contains(&device_key_info()), "{again:?}");
|
||||
assert_eq!(again.removed.len(), done.removed.len());
|
||||
assert_eq!(again.unbound.len(), done.unbound.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1282,16 +1307,10 @@ impl OnFile {
|
||||
/// What a sign-out of `choice` must have done, whatever else was damaged:
|
||||
/// the record and the synced copy are gone, the device-only secret is
|
||||
/// unbound and the local identity is as it was; the device key is deleted
|
||||
/// when the user forgot it or the client made it for the account, and
|
||||
/// reported as kept and unbound otherwise.
|
||||
fn assert_signed_out(
|
||||
&self,
|
||||
done: &SignOut,
|
||||
bound_existing_key: bool,
|
||||
choice: DeviceKeyChoice,
|
||||
label: &str,
|
||||
) {
|
||||
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key;
|
||||
/// when the user forgot it, and reported as kept and unbound otherwise,
|
||||
/// whether it predates the account or not.
|
||||
fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) {
|
||||
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_));
|
||||
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)];
|
||||
let mut unbound = vec![pair(&self.device_only)];
|
||||
let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32());
|
||||
@@ -1335,7 +1354,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [
|
||||
fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
// The record carries no binding, so damage in those columns says nothing
|
||||
// about the record: it is read, and the sign-out does what it always does.
|
||||
// `Forget` deletes the key it names; `Auto` follows the record.
|
||||
// `Forget` deletes the key it names; `Auto` keeps it.
|
||||
for bound_existing_key in [true, false] {
|
||||
for damage in RECORD_ROW_DAMAGE {
|
||||
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
|
||||
@@ -1346,7 +1365,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
.store
|
||||
.sign_out(&binding().account, choice)
|
||||
.unwrap_or_else(|error| panic!("{label}: {error}"));
|
||||
install.assert_signed_out(&done, bound_existing_key, choice, &label);
|
||||
install.assert_signed_out(&done, choice, &label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1354,8 +1373,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
|
||||
#[test]
|
||||
fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
// With `Auto` and a key that predates the account, the trait reads the key
|
||||
// to report it as kept. Damage in its binding columns must not fail that.
|
||||
// With `Auto` the trait reads the key to report it as kept, whether it
|
||||
// predates the account or not. Damage in its binding columns must not fail
|
||||
// that.
|
||||
for bound_existing_key in [true, false] {
|
||||
for damage in [
|
||||
"UPDATE identities SET synced = 2 WHERE kind = 'voelin'",
|
||||
@@ -1369,12 +1389,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
.store
|
||||
.sign_out(&binding().account, DeviceKeyChoice::Auto)
|
||||
.unwrap_or_else(|error| panic!("{label}: {error}"));
|
||||
install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label);
|
||||
if bound_existing_key {
|
||||
// The key was kept, as it was stored.
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label);
|
||||
// The key was kept, as it was stored.
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1423,7 +1441,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record()
|
||||
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}");
|
||||
let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap();
|
||||
assert_eq!(secret.binding, None, "{label}");
|
||||
// `Auto` cannot find the key the record named, and keeps it.
|
||||
// `Auto` keeps the key, as it always does; `Forget` deleted it first.
|
||||
let forgot = matches!(choice, DeviceKeyChoice::Forget(_));
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}");
|
||||
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
|
||||
@@ -1623,14 +1641,13 @@ fn key_text(json: &str, field: &str) -> String {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
|
||||
// The device key the client made for the account goes with `Auto`, and a
|
||||
// key that predates the account goes when the user forgets it. Either way
|
||||
// its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the
|
||||
// free pages of `client.db` or in a frame of `client.db-wal`.
|
||||
for (bound_existing_key, choice) in
|
||||
[(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))]
|
||||
{
|
||||
fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
|
||||
// The device key goes when the user forgets it, whether it predates the
|
||||
// account or the client made it for the account. Its PKCS#8 text, and a
|
||||
// synced TeamSpeak copy's key, must not stay in the free pages of
|
||||
// `client.db` or in a frame of `client.db-wal`.
|
||||
for bound_existing_key in [true, false] {
|
||||
let choice = DeviceKeyChoice::Forget(key().uid());
|
||||
let scratch = Scratch::new("scrub-signout");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device = IdentityBlob::voelin(&key()).unwrap();
|
||||
@@ -1697,13 +1714,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() {
|
||||
fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() {
|
||||
// A connection that keeps a read snapshot (a long query of the UI, a backup)
|
||||
// keeps the checkpoint that truncates the log from finishing. The sign-out
|
||||
// still deletes and warns that the bytes may stay in the log, and it waits
|
||||
// for the checkpoint a moment, not for the busy timeout of five seconds once
|
||||
// per removed row. While the checkpoint waits it holds the writer lock of the
|
||||
// log, so a second connection that writes meanwhile must get through.
|
||||
// still deletes and warns that the bytes may stay in the log, and it makes
|
||||
// one checkpoint for all its removals, not one per removed row. While the
|
||||
// checkpoint waits it holds the writer lock of the log, so a second
|
||||
// connection that writes meanwhile must get through.
|
||||
//
|
||||
// No clock decides anything here. A checkpoint ends in two fsyncs, and under
|
||||
// disk pressure (a build or a copy writing beside the tests) they take
|
||||
// seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O
|
||||
// pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A
|
||||
// bound on the sign-out or a short busy timeout on the writer failed this
|
||||
// test with "database is locked" for a checkpoint that was only slow. That a
|
||||
// checkpoint gives up on a reader after a moment and does not wait out the
|
||||
// connection's busy timeout is pinned where that timeout can be set to an
|
||||
// hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`.
|
||||
let scratch = Scratch::new("blocked-checkpoint");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
@@ -1718,37 +1745,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
|
||||
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 4);
|
||||
|
||||
/// Stops the writer when dropped, so that a failed assertion of the test does
|
||||
/// not leave the scope waiting for it.
|
||||
struct StopsTheWriter<'a>(&'a AtomicBool);
|
||||
impl Drop for StopsTheWriter<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let stop = AtomicBool::new(false);
|
||||
let (done, elapsed, writes, errors) = std::thread::scope(|scope| {
|
||||
let written = AtomicUsize::new(0);
|
||||
let (done, elapsed, errors, lines) = std::thread::scope(|scope| {
|
||||
let _stops = StopsTheWriter(&stop);
|
||||
let writer = scope.spawn(|| {
|
||||
// Its own connection, which gives up on a lock after one second.
|
||||
// Its own connection, set up as the app's are (`Store::open`: the log
|
||||
// and `synchronous = NORMAL`, so that a commit does not wait for the
|
||||
// disk), with a busy timeout that a slow checkpoint does not reach.
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
db.busy_timeout(Duration::from_secs(1)).unwrap();
|
||||
db.pragma_update(None, "synchronous", "NORMAL").unwrap();
|
||||
db.busy_timeout(Duration::from_secs(60)).unwrap();
|
||||
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
|
||||
let (mut writes, mut errors) = (0, Vec::new());
|
||||
let mut errors = Vec::new();
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
match db.execute(sql, [writes.to_string()]) {
|
||||
Ok(_) => writes += 1,
|
||||
let began = Instant::now();
|
||||
match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) {
|
||||
Ok(_) => {
|
||||
written.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(error) => errors.push(error.to_string()),
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
// It pauses ten times as long as the write took, and 5 ms at least.
|
||||
// Under disk pressure a commit takes 100 ms and more, and a writer
|
||||
// that paused 5 ms after each would hold the writer lock nearly all
|
||||
// the time and keep the sign-out, whose busy timeout is the default
|
||||
// five seconds, from getting it (`DatabaseBusy`).
|
||||
let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5));
|
||||
while Instant::now() < wake && !stop.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
(writes, errors)
|
||||
errors
|
||||
});
|
||||
// The sign-out starts when the writer is up and has written, not when
|
||||
// the thread was spawned: a thread of a busy machine can start late.
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while written.load(Ordering::Relaxed) == 0 {
|
||||
assert!(Instant::now() < deadline, "the writer never ran");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
|
||||
let (done, lines) = support::at_trace(|| {
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid()))
|
||||
});
|
||||
let elapsed = started.elapsed();
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let (writes, errors) = writer.join().unwrap();
|
||||
(done.unwrap(), elapsed, writes, errors)
|
||||
let errors = writer.join().unwrap();
|
||||
(done.unwrap(), elapsed, errors, lines)
|
||||
});
|
||||
|
||||
// Four removals: the two copies, the device key the client made, the record.
|
||||
// Four removals: the two copies, the device key the user forgot, the record.
|
||||
assert_eq!(done.removed.len(), 4, "{done:?}");
|
||||
assert!(store.list().unwrap().is_empty());
|
||||
assert!(writes > 0, "the writer never ran");
|
||||
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
|
||||
assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}");
|
||||
// One checkpoint for the four removals: each one that is blocked says so.
|
||||
let blocked = support::blocked_checkpoints(&lines);
|
||||
assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})");
|
||||
|
||||
// Nothing is lost by the wait: once the reader is gone, the next removal
|
||||
// truncates the log.
|
||||
@@ -1758,6 +1819,245 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
|
||||
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
|
||||
}
|
||||
|
||||
// ------------------------- the keys a sign-out keeps, and the one the user forgets
|
||||
//
|
||||
// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps
|
||||
// every device key, and "Forget this device's identity" is the only deletion.
|
||||
|
||||
/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name.
|
||||
fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> {
|
||||
db.query_row(
|
||||
"SELECT * FROM identities WHERE kind = ?1 AND uid = ?2",
|
||||
params![kind, uid],
|
||||
|row| {
|
||||
let names: Vec<String> =
|
||||
row.as_ref().column_names().iter().map(|n| n.to_string()).collect();
|
||||
names
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, name)| Ok((name, row.get(index)?)))
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() {
|
||||
// Whether it predates the account or the client made it for the account, no
|
||||
// column of its row changes: the key never carried a binding, and a sign-out
|
||||
// writes nothing to it.
|
||||
for bound_existing_key in [true, false] {
|
||||
let install = signed_in_install_on_file(bound_existing_key);
|
||||
let uid = key().uid().to_base32();
|
||||
let db = Connection::open(install.scratch.db()).unwrap();
|
||||
let before = named_row(&db, KIND_VOELIN, &uid);
|
||||
assert!(before.len() >= 8, "{before:?}");
|
||||
|
||||
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}");
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() {
|
||||
// The store accepts a binding with `synced = false` on the device key (a
|
||||
// binding with `synced = true` is refused, see the last section). A sign-out
|
||||
// unbinds it and keeps it: the four binding columns are the only ones that
|
||||
// change.
|
||||
const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"];
|
||||
for bound_existing_key in [true, false] {
|
||||
let install = signed_in_install_on_file(bound_existing_key);
|
||||
let uid = key().uid().to_base32();
|
||||
let device_only = AccountBinding { synced: false, ..binding() };
|
||||
install
|
||||
.store
|
||||
.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only))
|
||||
.unwrap();
|
||||
let db = Connection::open(install.scratch.db()).unwrap();
|
||||
let before = named_row(&db, KIND_VOELIN, &uid);
|
||||
let bound = |row: &[(String, rusqlite::types::Value)]| {
|
||||
row.iter().any(|(name, value)| {
|
||||
name == "account" && !matches!(value, rusqlite::types::Value::Null)
|
||||
})
|
||||
};
|
||||
assert!(bound(&before), "the setup binds the key");
|
||||
|
||||
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
|
||||
let after = named_row(&db, KIND_VOELIN, &uid);
|
||||
assert!(!bound(&after), "{bound_existing_key}: unbound");
|
||||
assert_eq!(before.len(), after.len());
|
||||
for ((name, was), (_, is)) in before.iter().zip(&after) {
|
||||
if !BINDING_COLUMNS.contains(&name.as_str()) {
|
||||
assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column");
|
||||
}
|
||||
}
|
||||
let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap());
|
||||
assert!(install.store.bound_to(&binding().account).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() {
|
||||
// What a sign-out still deletes is a synced copy (a private key, which
|
||||
// the service holds again) and the record: those are gone from the file and
|
||||
// its log. The device key and the device-only secret are kept, so their text
|
||||
// is still there.
|
||||
let scratch = Scratch::new("scrub-keeps");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device = IdentityBlob::voelin(&key()).unwrap();
|
||||
let synced = fresh_teamspeak(binding());
|
||||
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
|
||||
let device_text = key_text(&device.json, "pkcs8");
|
||||
let (synced_text, device_only_text) =
|
||||
(key_text(&synced.json, "key"), key_text(&device_only.json, "key"));
|
||||
for blob in [&device, &synced, &device_only] {
|
||||
store.put(blob).unwrap();
|
||||
}
|
||||
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
|
||||
let neighbour = Store::open(&scratch.db()).unwrap();
|
||||
let before = RawFiles::read(&scratch);
|
||||
assert!(before.holds(&device_text) && before.holds(&synced_text));
|
||||
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
let after = RawFiles::read(&scratch);
|
||||
assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy");
|
||||
assert!(after.holds(&device_text), "the device key is kept");
|
||||
assert!(after.holds(&device_only_text), "the device-only secret is kept");
|
||||
assert!(after.wal.is_empty(), "the log is truncated");
|
||||
drop(neighbour);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_out_that_deletes_nothing_does_not_checkpoint() {
|
||||
// With no record and no synced copy a sign-out only unbinds. The checkpoint
|
||||
// belongs to deletions: with a reader that blocks it, a deletion says so, and
|
||||
// the sign-out does not.
|
||||
let scratch = Scratch::new("no-deletion");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
|
||||
store.put(&device_only).unwrap();
|
||||
let reader = Connection::open(scratch.db()).unwrap();
|
||||
reader.execute_batch("BEGIN").unwrap();
|
||||
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
let (done, lines) =
|
||||
support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap());
|
||||
assert!(done.removed.is_empty(), "{done:?}");
|
||||
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
|
||||
assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}");
|
||||
|
||||
// The same reader does block the checkpoint of a deletion, so the count above
|
||||
// would have shown one.
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
let (removed, lines) =
|
||||
support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
|
||||
assert!(removed);
|
||||
assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}");
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() {
|
||||
// The flow of "Forget this device's identity" after a sign-out: the key is
|
||||
// still there, unbound; the UI exports it, then deletes it. The export is
|
||||
// what `voelin_key` and `to_pkcs8` give, and it restores the key.
|
||||
let scratch = Scratch::new("export-forget");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
let uid = key().uid();
|
||||
let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap();
|
||||
let text = key_text(&stored.json, "pkcs8");
|
||||
|
||||
let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap();
|
||||
assert!(RawFiles::read(&scratch).holds(&text));
|
||||
assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap());
|
||||
assert!(store.voelin_key(&uid).unwrap().is_none());
|
||||
let after = RawFiles::read(&scratch);
|
||||
assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left");
|
||||
assert!(after.wal.is_empty(), "the log is truncated");
|
||||
|
||||
// The export brings the same key back.
|
||||
let restored = IdentityKey::from_pkcs8(&exported).unwrap();
|
||||
assert_eq!(restored.uid(), uid);
|
||||
assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key"));
|
||||
store.put_voelin_key(&restored).unwrap();
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored);
|
||||
}
|
||||
|
||||
// ------------------------------------------ releasing the device key from its account
|
||||
//
|
||||
// `AccountClient::release` asks the service to release the key and then runs the
|
||||
// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so
|
||||
// the store's part is the sign-out of the tests above, and the key has to be
|
||||
// usable for another account afterwards.
|
||||
|
||||
#[test]
|
||||
fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() {
|
||||
let Install { store, .. } = signed_in_install(false);
|
||||
let uid = key().uid().to_base32();
|
||||
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
let signature = key().sign(b"the same key, before and after the release");
|
||||
|
||||
// The service released the key; the device finishes with a local sign-out.
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
|
||||
// The key is registered with no account and signs up for another one: its
|
||||
// record names the same key, and a copy of the new account's material is
|
||||
// bound to it.
|
||||
let other_id = AccountId::from_bytes([42; 16]);
|
||||
let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() };
|
||||
store.put_account_record(&other).unwrap();
|
||||
assert_eq!(store.account_record().unwrap(), Some(other.clone()));
|
||||
let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() };
|
||||
let other_copy = fresh_teamspeak(other_binding);
|
||||
store.put(&other_copy).unwrap();
|
||||
|
||||
// Signing out of the new account keeps the key again, and the copy goes.
|
||||
let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}");
|
||||
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
|
||||
assert_eq!(kept.sign(b"the same key, before and after the release"), signature);
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() {
|
||||
// The service released the device and the call was dropped before the local
|
||||
// sign-out took the slot: the record and the copies are still here, and the
|
||||
// key is still the record's device key. A sign-out with `Auto` finishes it
|
||||
// and keeps the key; running it again finds nothing to do.
|
||||
let Install { store, synced, device_only, .. } = signed_in_install(true);
|
||||
let uid = key().uid().to_base32();
|
||||
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.removed.contains(&info_of(&synced)), "{done:?}");
|
||||
assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}");
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before);
|
||||
assert_eq!(
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
|
||||
SignOut::default()
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------- the device key is never a synced copy
|
||||
//
|
||||
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its
|
||||
@@ -1798,15 +2098,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() {
|
||||
assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0);
|
||||
|
||||
// A binding that is not synced is a device-only secret: accepted, and a
|
||||
// sign-out unbinds it and keeps it (or deletes it, as the record says).
|
||||
// sign-out unbinds it and keeps it.
|
||||
let device_only = AccountBinding { synced: false, ..binding() };
|
||||
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
|
||||
store.put(&before).unwrap();
|
||||
|
||||
// So the sign-out still does what the record says with the key.
|
||||
// So the sign-out keeps the key, whether it predates the account or not.
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}");
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key);
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Helpers the integration tests of this crate share.
|
||||
|
||||
// Each integration test crate of this directory uses some of these helpers.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::span::{Attributes, Id, Record};
|
||||
use tracing::{Event, Metadata, Subscriber};
|
||||
|
||||
/// A subscriber that keeps every event and span it sees as one line of text
|
||||
/// each: level, target and every field with its `Debug` text, as a log line
|
||||
/// would show them.
|
||||
struct Capture {
|
||||
lines: Arc<Mutex<Vec<String>>>,
|
||||
spans: AtomicU64,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
fn push(&self, line: String) {
|
||||
self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of an event or a span as ` name=value` text.
|
||||
struct Fields<'a>(&'a mut String);
|
||||
|
||||
impl Visit for Fields<'_> {
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
|
||||
let _ = write!(self.0, " {}={value:?}", field.name());
|
||||
}
|
||||
}
|
||||
|
||||
impl Subscriber for Capture {
|
||||
fn enabled(&self, _: &Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn max_level_hint(&self) -> Option<LevelFilter> {
|
||||
Some(LevelFilter::TRACE)
|
||||
}
|
||||
|
||||
fn new_span(&self, attributes: &Attributes<'_>) -> Id {
|
||||
let mut line = format!("span {}", attributes.metadata().name());
|
||||
attributes.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
|
||||
fn record(&self, _: &Id, values: &Record<'_>) {
|
||||
let mut line = String::from("span record");
|
||||
values.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
}
|
||||
|
||||
fn record_follows_from(&self, _: &Id, _: &Id) {}
|
||||
|
||||
fn event(&self, event: &Event<'_>) {
|
||||
let metadata = event.metadata();
|
||||
let mut line = format!("{} {}:", metadata.level(), metadata.target());
|
||||
event.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
}
|
||||
|
||||
fn enter(&self, _: &Id) {}
|
||||
|
||||
fn exit(&self, _: &Id) {}
|
||||
}
|
||||
|
||||
/// Run `f` on this thread with a subscriber that takes in everything logged at
|
||||
/// TRACE and above, and return what `f` returned with the lines logged.
|
||||
pub fn at_trace<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
|
||||
let lines = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) };
|
||||
let out = tracing::subscriber::with_default(subscriber, f);
|
||||
let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
(out, lines)
|
||||
}
|
||||
|
||||
/// How many of the lines say that a checkpoint was blocked.
|
||||
pub fn blocked_checkpoints(lines: &[String]) -> usize {
|
||||
lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count()
|
||||
}
|
||||
@@ -1075,7 +1075,8 @@ impl Task {
|
||||
}
|
||||
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
|
||||
Event::MediaAdded(m) => {
|
||||
if !self.mids.iter().any(|(mid, _)| *mid == m.mid) {
|
||||
let known = self.mids.iter().any(|(mid, _)| *mid == m.mid);
|
||||
if !known {
|
||||
self.mids.push((m.mid, m.kind));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,7 +801,8 @@ impl StreamerSession {
|
||||
}
|
||||
StreamNotification::JoinRequest { viewer, remove: true, .. }
|
||||
| StreamNotification::ViewerLeft { viewer, .. } => {
|
||||
if self.viewers.remove(&viewer.0).is_some() {
|
||||
let was_viewer = self.viewers.remove(&viewer.0).is_some();
|
||||
if was_viewer {
|
||||
self.emit_viewers(out);
|
||||
self.update_targets(out);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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;
|
||||
@@ -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>,
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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};
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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>,
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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
@@ -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() {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user