Compare commits
323
Commits
No files matched your search
@@ -2,7 +2,7 @@
|
||||
name: mao-designer
|
||||
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
|
||||
model: opus
|
||||
effort: max
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-designer**, the design and escalation role of the Voelin
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: mao-opus-reviewer
|
||||
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
|
||||
model: opus
|
||||
effort: max
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||
"model": "fable",
|
||||
"effortLevel": "xhigh"
|
||||
"effortLevel": "xhigh",
|
||||
"maxEffortLevel": "xhigh"
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
# the sources only. Builds keep target/ in cache mounts, never in the context.
|
||||
.git
|
||||
.claude
|
||||
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
|
||||
# VoelinProtocol checkout): never part of a build. Only the root one; the
|
||||
# committed third_party/dimpl/.cargo stays.
|
||||
.cargo
|
||||
target
|
||||
dist
|
||||
fuzz/target
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
name: Linux checks
|
||||
description: Shared Linux validation for Gitea CI and release packaging.
|
||||
description: >
|
||||
Linux validation for Gitea CI: formatting, Clippy, the build, the tests, the
|
||||
dependency policy, the third-party notices and the release tooling tests. It
|
||||
runs after the job has fetched every dependency (the steps before it in
|
||||
.gitea/workflows/ci.yml: system packages, the Rust toolchain and `cargo fetch`
|
||||
with the read-only deploy key for the private VoelinProtocol repository) and
|
||||
has deleted the key (docs/ci.md, "VoelinProtocol access"). This action has no
|
||||
input and no secret, and every cargo command in it is --offline (or has
|
||||
CARGO_NET_OFFLINE set where a script or a plugin starts cargo): it needs no key
|
||||
and cannot use one, so the build scripts, procedural macros and tests it runs
|
||||
hold none.
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
|
||||
sh -s -- -y --profile minimal --default-toolchain none
|
||||
fi
|
||||
if [[ -f "$CARGO_HOME/env" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "$CARGO_HOME/env"
|
||||
fi
|
||||
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
|
||||
rustup toolchain install
|
||||
shell: bash
|
||||
- name: rustfmt (own crates)
|
||||
env:
|
||||
CARGO_NET_OFFLINE: "true"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
packages=$(scripts/own-crates.sh)
|
||||
@@ -28,33 +23,45 @@ runs:
|
||||
cargo fmt "${packages[@]}" --check
|
||||
shell: bash
|
||||
- name: clippy (own crates, deny warnings)
|
||||
env:
|
||||
CARGO_NET_OFFLINE: "true"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
packages=$(scripts/own-crates.sh)
|
||||
read -r -a packages <<< "$packages"
|
||||
cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings
|
||||
cargo clippy "${packages[@]}" --all-targets --no-deps --locked --offline -- -D warnings
|
||||
shell: bash
|
||||
- name: clippy (workspace, report warnings)
|
||||
run: cargo clippy --workspace --all-targets --locked
|
||||
run: cargo clippy --workspace --all-targets --locked --offline
|
||||
shell: bash
|
||||
- name: Build
|
||||
run: cargo build --workspace --all-targets --locked
|
||||
run: cargo build --workspace --all-targets --locked --offline
|
||||
shell: bash
|
||||
- name: Test (X11 enabled)
|
||||
run: |
|
||||
# DISPLAY is assigned by xvfb-run, then expanded by the inner shell.
|
||||
# shellcheck disable=SC2016
|
||||
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked'
|
||||
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked --offline'
|
||||
shell: bash
|
||||
- name: Install cargo-deny and cargo-about
|
||||
# The only cargo commands here that go online: they download two tools from
|
||||
# crates.io and build them. They read no manifest of this workspace and
|
||||
# nothing in the job gives them a key.
|
||||
run: |
|
||||
cargo install cargo-deny --locked --version 0.20.2
|
||||
cargo install cargo-about --locked --version 0.9.2 --features cli
|
||||
shell: bash
|
||||
- name: Dependency policy
|
||||
# cargo-deny's own --offline would also stop it from fetching the RustSec
|
||||
# advisory database, which the check needs (from github.com, no key).
|
||||
# CARGO_NET_OFFLINE keeps only the `cargo metadata` it runs offline.
|
||||
env:
|
||||
CARGO_NET_OFFLINE: "true"
|
||||
run: cargo deny --locked --workspace check
|
||||
shell: bash
|
||||
- name: Third-party notices
|
||||
env:
|
||||
CARGO_NET_OFFLINE: "true"
|
||||
run: scripts/notices.sh --check
|
||||
shell: bash
|
||||
- name: Release tooling regressions
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# 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 in place by ssh (-o UserKnownHostsFile, in the command line that the fetch
|
||||
# step of .gitea/workflows/ci.yml gives git: nothing is appended to ~/.ssh) and
|
||||
# COPYed by docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to
|
||||
# re-check it and how to rotate it: docs/ci.md, "VoelinProtocol access".
|
||||
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
+246
-1
@@ -1,7 +1,22 @@
|
||||
name: CI
|
||||
|
||||
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
|
||||
# Off for pushes and pull requests: run by hand only.
|
||||
# Runs on pushes to main and on pull requests (not when only docs or Markdown
|
||||
# files change, apart from THIRD_PARTY_NOTICES.md), and by hand.
|
||||
#
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH, so
|
||||
# the job needs the read-only deploy key (the repository secret
|
||||
# VOELIN_PROTOCOL_DEPLOY_KEY). The key exists for one step only: "Fetch the
|
||||
# dependencies" runs `cargo fetch` with it, before any build script, procedural
|
||||
# macro or test of the repository has run, and deletes it again. Everything after
|
||||
# that (the composite action .gitea/actions/checks) runs `--offline` in a job that
|
||||
# holds no key. docs/ci.md, "VoelinProtocol access", has the whole story; the
|
||||
# order of the steps is part of it:
|
||||
#
|
||||
# 1. check that this job may hold the key (the runner, the pull request's head)
|
||||
# 2. system packages and the Rust toolchain (no key yet)
|
||||
# 3. install the key into a directory of its own, 4. fetch with it and delete it
|
||||
# 5. delete it again whatever happened, 6. the checks, offline
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
@@ -20,15 +35,245 @@ on:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
# Cargo fetches the private VoelinProtocol dependency with the system git and
|
||||
# ssh, whose command line the fetch step sets (docs/ci.md, "VoelinProtocol
|
||||
# access"); Cargo's own git client could not use that key file.
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux checks
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
# 'yes' unless this run is a pull request whose head branch lives in
|
||||
# another repository. For a pull request Gitea's event payload has
|
||||
# github.event.pull_request.head.repo.full_name, the repository that holds
|
||||
# the branch to be merged: this repository (equal to github.repository)
|
||||
# for a branch pushed here, the fork's own name for a fork. Any other
|
||||
# event (push, workflow_dispatch) has no pull request and the first
|
||||
# operand is true at once. An absent or unequal name reads 'no', and the
|
||||
# check below treats everything but 'yes' as no. The check asks the same
|
||||
# question again in its script, from the head repository's name itself.
|
||||
VOELIN_PR_HEAD_HERE: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && 'yes' || 'no' }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
# A runner prints the `env:` of a step in the job log when the step starts,
|
||||
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
|
||||
# there in clear (the deploy keys of all four repositories, 2026-10-27; they
|
||||
# were rotated the next day). Both runners carry the same labels, so
|
||||
# `runs-on` cannot keep the job off it. What the workflow can do is not to
|
||||
# start the step that declares the secret on such a runner, and not to give
|
||||
# the secret to a fork's pull request: this step decides, before any step
|
||||
# names the secret, and writes the one positive flag that the key step asks
|
||||
# for. Without the flag the job stops here: the key is not optional (nothing
|
||||
# builds without voelin-identity), and a green job that checked nothing
|
||||
# would be worse than a red one that says why.
|
||||
- name: Check that this job may hold the VoelinProtocol deploy key
|
||||
env:
|
||||
# The oldest runner version known to mask a multi-line secret in the
|
||||
# log. Lower it only after a canary secret has been shown masked on
|
||||
# that runner (docs/ci.md, "VoelinProtocol access"). release.yml has
|
||||
# the same line.
|
||||
MIN_MASKING_RUNNER_VERSION: 3.1.0
|
||||
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
|
||||
name="${RUNNER_NAME:-an unnamed runner}"
|
||||
problems=()
|
||||
masks=no
|
||||
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
|
||||
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
|
||||
masks=yes
|
||||
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
|
||||
fi
|
||||
fi
|
||||
if [[ "$masks" != yes ]]; then
|
||||
problems+=("the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner")
|
||||
fi
|
||||
# The pull request's head. The job-level expression has answered in
|
||||
# VOELIN_PR_HEAD_HERE; the answer is asked for again here, from the
|
||||
# head repository's name and the repository's, so that a mistake in
|
||||
# one of the two places does not hand the key to a fork's code. A pull
|
||||
# request (any event whose name starts with pull_request, or any event
|
||||
# that carries a head repository) passes only with a head repository
|
||||
# that is named and is this repository.
|
||||
head_here=yes
|
||||
[[ "${VOELIN_PR_HEAD_HERE:-}" == yes ]] || head_here=no
|
||||
case "${GITHUB_EVENT_NAME:-}" in
|
||||
pull_request*) pull_request=yes ;;
|
||||
*) pull_request=no ;;
|
||||
esac
|
||||
[[ -z "${PR_HEAD_REPO:-}" ]] || pull_request=yes
|
||||
if [[ "$pull_request" == yes ]]; then
|
||||
if [[ -z "${PR_HEAD_REPO:-}" || "$PR_HEAD_REPO" != "${GITHUB_REPOSITORY:-}" ]]; then
|
||||
head_here=no
|
||||
fi
|
||||
fi
|
||||
if [[ "$head_here" == yes ]]; then
|
||||
if [[ "$pull_request" == yes ]]; then
|
||||
echo "Event ${GITHUB_EVENT_NAME:-unknown}: the pull request's head is in $PR_HEAD_REPO, which is this repository, not a fork."
|
||||
else
|
||||
echo "Event ${GITHUB_EVENT_NAME:-unknown}: no pull request, the code is this repository's own."
|
||||
fi
|
||||
else
|
||||
problems+=("the pull request's head repository is '${PR_HEAD_REPO:-unknown}', and this repository is ${GITHUB_REPOSITORY:-unknown}, so it is a fork's pull request (or the event did not say where the head is), and the key is not given to a fork's code. Push the branch to ${GITHUB_REPOSITORY:-this repository} to have it checked")
|
||||
fi
|
||||
if ((${#problems[@]})); then
|
||||
for problem in "${problems[@]}"; do
|
||||
echo "::error::The VoelinProtocol deploy key is not given to this job: $problem." >&2
|
||||
done
|
||||
echo "::error::The job stops here: the workspace cannot be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
|
||||
# Native libraries and tools (apt), the same action as GitHub CI. The job
|
||||
# image has git and the OpenSSH client; the key step checks for ssh.
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
|
||||
sh -s -- -y --profile minimal --default-toolchain none
|
||||
fi
|
||||
if [[ -f "$CARGO_HOME/env" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "$CARGO_HOME/env"
|
||||
fi
|
||||
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
|
||||
rustup toolchain install
|
||||
# The key, as late as it can be: after the packages and the toolchain have
|
||||
# been installed, right before the one step that uses it.
|
||||
- name: Install the VoelinProtocol deploy key
|
||||
# Both lines below ask for the positive flag of the check above. On a
|
||||
# runner that is not known to mask the secret (or whose expression context
|
||||
# does not hold what an earlier step wrote to GITHUB_ENV) the flag reads
|
||||
# empty: the step is not started, so it prints no header, and the
|
||||
# expression is empty as well, in case a runner prints a header anyway.
|
||||
# The key reaches the step through the environment only: never in the
|
||||
# script text, never echoed, no `set -x`. A pull request from a fork gets
|
||||
# no secrets from Gitea and fails the check above before it gets here.
|
||||
if: env.VOELIN_KEY_ALLOWED == 'yes'
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh ssh-keygen; do
|
||||
command -v "$tool" > /dev/null || {
|
||||
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
[[ -s "$GITHUB_WORKSPACE/.gitea/known_hosts" ]] || {
|
||||
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# A directory of this job's own (mode 0700, a name that nothing else
|
||||
# uses, so a host runner that keeps its temporary directory between
|
||||
# jobs does not share it). On any way out of this step but the last
|
||||
# line, the step removes it itself; the directory is left only for the
|
||||
# fetch step, which removes it in turn. Its name goes to the later
|
||||
# steps first, so that the cleanup step finds it even if this step is
|
||||
# killed.
|
||||
key_dir="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/voelin-protocol-key.XXXXXX")"
|
||||
installed=
|
||||
trap '[[ -n "$installed" ]] || rm -rf "$key_dir"' EXIT
|
||||
echo "VOELIN_PROTOCOL_KEY_DIR=$key_dir" >> "$GITHUB_ENV"
|
||||
key_file="$key_dir/id"
|
||||
|
||||
# Whatever the secret store did to the line ends and the final newline,
|
||||
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
chmod 600 "$key_file"
|
||||
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
|
||||
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
|
||||
exit 1
|
||||
fi
|
||||
# The fingerprint of the public half, to compare with the deploy key in
|
||||
# the VoelinProtocol settings.
|
||||
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
|
||||
echo "VOELIN_PROTOCOL_KEY=installed" >> "$GITHUB_ENV"
|
||||
installed=1
|
||||
# The only step that uses the key, and the only place that sets
|
||||
# GIT_SSH_COMMAND: not in GITHUB_ENV, so no later step has it.
|
||||
- name: Fetch the dependencies with the deploy key
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "${VOELIN_PROTOCOL_KEY:-}" != installed || -z "${VOELIN_PROTOCOL_KEY_DIR:-}" ]]; then
|
||||
echo "::error::The deploy key was not installed by the step before (the check at the start of the job or the key step did not pass its flag on)." >&2
|
||||
exit 1
|
||||
fi
|
||||
key_dir="$VOELIN_PROTOCOL_KEY_DIR"
|
||||
key_file="$key_dir/id"
|
||||
# On every way out of this step, a failed fetch included.
|
||||
trap 'rm -rf "$key_dir"' EXIT
|
||||
[[ -f "$key_file" ]] || { echo "::error::The deploy key file is missing." >&2; exit 1; }
|
||||
|
||||
# The system git runs this ssh command, so the key and the host key are
|
||||
# named outright and nothing in ~/.ssh or /etc/ssh is read: -F /dev/null
|
||||
# leaves out every ssh config file, -i with IdentitiesOnly and no agent
|
||||
# offers this one key, and the only host key accepted is the reviewed
|
||||
# line in .gitea/known_hosts, never one fetched now (a changed or unknown
|
||||
# host key fails rather than asks). The paths are absolute: Cargo runs
|
||||
# git in its own directory under CARGO_HOME, not in the checkout.
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
export GIT_SSH_COMMAND="ssh -F /dev/null -i '$key_file' -o IdentitiesOnly=yes -o IdentityAgent=none -o UserKnownHostsFile='$GITHUB_WORKSPACE/.gitea/known_hosts' -o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes -o BatchMode=yes -o ConnectTimeout=30"
|
||||
|
||||
# The first thing that touches the server with the key, so that a wrong
|
||||
# key or a changed host key fails here with a clear message and not
|
||||
# minutes later inside Cargo.
|
||||
if ! timeout 120 git ls-remote --exit-code \
|
||||
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
|
||||
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Voelin/VoelinProtocol is readable with the deploy key."
|
||||
|
||||
# Cargo reads the manifests and Cargo.lock and downloads every package
|
||||
# of the lock file (all targets: cargo deny and cargo about, later, read
|
||||
# the whole graph). It runs no build script, procedural macro or test
|
||||
# of the repository. Nothing else in the job needs the key: every later
|
||||
# cargo command is --offline.
|
||||
cargo fetch --locked
|
||||
|
||||
unset GIT_SSH_COMMAND
|
||||
rm -rf "$key_dir"
|
||||
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
|
||||
echo "The deploy key is removed from the job."
|
||||
# Whatever happened to the two steps above (a failed fetch, a key that was
|
||||
# installed and never fetched with, a cancelled job), the key is gone before
|
||||
# the checks start. Idempotent: the fetch step has already removed it.
|
||||
- name: Delete the deploy key
|
||||
if: always()
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key_dir="${VOELIN_PROTOCOL_KEY_DIR:-}"
|
||||
if [[ -n "$key_dir" && -e "$key_dir" ]]; then
|
||||
rm -rf "$key_dir"
|
||||
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
|
||||
echo "The deploy key is removed from the job."
|
||||
else
|
||||
echo "No deploy key is left in the job."
|
||||
fi
|
||||
{
|
||||
echo "VOELIN_PROTOCOL_KEY_DIR="
|
||||
echo "VOELIN_PROTOCOL_KEY="
|
||||
} >> "$GITHUB_ENV"
|
||||
# Formatting, Clippy, build, tests, dependency policy, notices: all
|
||||
# offline, in a job that holds no key (docs/ci.md, "VoelinProtocol access").
|
||||
- uses: ./.gitea/actions/checks
|
||||
@@ -32,6 +32,81 @@ 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 an
|
||||
# ssh-agent (`docker build --ssh default`): the key lives in the agent's
|
||||
# memory, never on disk and never in an image layer, and only the
|
||||
# `cargo fetch` of each Dockerfile is given the agent (the build that
|
||||
# follows is --offline and has no ssh mount, so the build scripts and
|
||||
# procedural macros run without the key). The agent is stopped by the step
|
||||
# right after the last build, whatever the builds did; the lifetime below
|
||||
# ends the key anyway if the runner dies first.
|
||||
#
|
||||
# A runner prints the `env:` of a step in the job log when the step starts,
|
||||
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
|
||||
# there in clear (2026-10-27; the keys were rotated the next day). It
|
||||
# carries the same labels as the release runner, so `runs-on` cannot keep
|
||||
# the job off it: this step decides, before any step names the secret, and
|
||||
# writes the one positive flag that the agent step asks for. Without the
|
||||
# flag the job stops here (no package can be built without voelin-identity).
|
||||
# ci.yml has the same step, with the check of a pull request's head repository
|
||||
# that a release (tags and manual runs only) does not need.
|
||||
- name: Check that this runner may hold the VoelinProtocol deploy key
|
||||
env:
|
||||
# The oldest runner version known to mask a multi-line secret in the
|
||||
# log. Lower it only after a canary secret has been shown masked on
|
||||
# that runner (docs/ci.md, "VoelinProtocol access"). ci.yml has the
|
||||
# same line.
|
||||
MIN_MASKING_RUNNER_VERSION: 3.1.0
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
|
||||
name="${RUNNER_NAME:-an unnamed runner}"
|
||||
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
|
||||
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
|
||||
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
|
||||
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo "::error::The VoelinProtocol deploy key is not given to this job: the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner." >&2
|
||||
echo "::error::The job stops here: no package can be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
- name: Start ssh-agent with the VoelinProtocol deploy key
|
||||
# Both lines below ask for the positive flag of the check above: on a
|
||||
# runner that is not known to mask the secret (or whose expression context
|
||||
# does not hold what an earlier step wrote to GITHUB_ENV) the step is not
|
||||
# started and the expression is empty as well, in case a runner prints a
|
||||
# header anyway. The key reaches the step through the environment only:
|
||||
# never in the script text, never echoed, no `set -x`.
|
||||
if: env.VOELIN_KEY_ALLOWED == 'yes'
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
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,9 +152,30 @@ 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
|
||||
# Right after the builds, the only steps that use the agent, and whatever
|
||||
# they did (a failed build, a cancelled job): the steps after this one
|
||||
# (the artifact upload, the release draft with its token) have neither the
|
||||
# key nor the socket.
|
||||
- name: Stop the ssh-agent
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
|
||||
if ssh-agent -k > /dev/null; then
|
||||
echo "The ssh-agent with the deploy key is stopped."
|
||||
else
|
||||
echo "::warning::ssh-agent -k failed; the agent ends by itself when its lifetime (nine hours) is over." >&2
|
||||
fi
|
||||
else
|
||||
echo "No ssh-agent of this job is running."
|
||||
fi
|
||||
{
|
||||
echo "SSH_AUTH_SOCK="
|
||||
echo "SSH_AGENT_PID="
|
||||
echo "VOELIN_AGENT_STARTED="
|
||||
} >> "$GITHUB_ENV"
|
||||
- name: Collect packages and checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
|
||||
/.scratch/
|
||||
+125
@@ -8,6 +8,69 @@ 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 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.
|
||||
- The GPUI front end's desktop shell: the server rail, the top bar, the
|
||||
sidebar and the main area, on the client's own database (the servers saved in
|
||||
the Slint app are there, and the other way round). Add, edit, select and
|
||||
remove a server, connect and disconnect voice, mute the microphone and the
|
||||
sound, hold to talk and copy an invite link, as in the Slint app; the window's
|
||||
title names the server on screen, and its size and whether it was maximized
|
||||
are kept for the next run (setting `ui.window`; on X11 the window is
|
||||
maximized once it is shown, not before the window manager has it, and a
|
||||
resize made before it answers is kept). The chat and the other pages are the
|
||||
next slices; the search and the settings buttons only log that.
|
||||
`VOELIN_DEMO_UI=1` shows the Slint app's sample servers without sending or
|
||||
keeping anything (docs/ui.md, "The desktop shell").
|
||||
- The GPUI front end's channel tree and members panel. The server on screen's
|
||||
channels nest in the sidebar with their spacers, icons, banners (under a veil
|
||||
that keeps the names readable on any picture), locks and counts, and the
|
||||
people in them with their badges and marks; a click selects a channel, a
|
||||
double-click joins it (a locked one asks for its password: Enter joins, and
|
||||
Escape closes the prompt), the chevron folds it, a right-click offers the
|
||||
same, and what is folded and selected is kept for each server (setting
|
||||
`ui.tree`). The panel on the right lists everyone on the server in sections,
|
||||
with a search; a click on a person opens their card. A person who starts or
|
||||
stops talking is marked in the tree (the ring on their avatar and the bars on
|
||||
their row, as in the Slint app) and the members panel, which are redrawn for
|
||||
it and nothing else of the window, and the pictures the engine writes again show
|
||||
at once. `VOELIN_METER=1` counts the renders of each pane;
|
||||
`VOELIN_DEMO_SERVER` and `VOELIN_DEMO_TALK` pick the sample server and make a
|
||||
sample person talk (docs/ui.md, "The channel tree and the members").
|
||||
- The GPUI front end's voice channel page and call bar. A server's Voice channel
|
||||
button (or `VOELIN_OPEN=voice`) shows the channel we are in with its topic,
|
||||
its banner and who is there: large avatars ringed green while they talk and
|
||||
blue while they stream, with the marks of a microphone or sound that is off,
|
||||
and under them the call bar (mute, deafen, share and the voice settings, which
|
||||
only log until their pages come, and Leave). The smaller stage, one row of
|
||||
small avatars centred while it fits and scrolling sideways when crowded, is
|
||||
remembered and a window under 800 pixels tall always has it (the same setting
|
||||
as the Slint app's); toggle icon buttons refresh their tooltips as soon as
|
||||
their state flips. The sidebar's server card shows the server's banner, a
|
||||
person's card has their volume and a mute for us, and the voice card says the
|
||||
transmit mode when it is not push-to-talk. Hold to talk and the global
|
||||
push-to-talk key (`Ctrl+Shift+T` by default, as in the Slint app, working
|
||||
while another window has focus) track button and hotkey holds independently and
|
||||
fail closed across voice drops (including drop and reconnect within one event
|
||||
batch), window focus loss, leaving push-to-talk mode, switching or removing
|
||||
servers, repeated portal activations across servers, desktop shortcut removal,
|
||||
hotkey task exit, and window shutdown. A person's picture is round in its
|
||||
avatar. `voelin-gpui` is still not the app (docs/ui.md, "The voice page and
|
||||
the call bar").
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
|
||||
opens the folder.
|
||||
@@ -69,6 +132,43 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- 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
|
||||
databases migrate on first start and every identity stays what it was (kind
|
||||
TeamSpeak, no account, same key, name, origin and default); nothing changes
|
||||
on screen yet. The build now fetches `voelin-identity` from the private
|
||||
VoelinProtocol repository, so a fresh checkout needs read access to it
|
||||
(see docs/building.md).
|
||||
- Selecting a server observes it through its gateway at once; the Observe
|
||||
button is gone. The server dialog asks only for the address, password,
|
||||
name and nickname: the gateway is found from the address.
|
||||
@@ -168,6 +268,28 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
connections, so tsgw no longer earns a 600 second ban. It starts while
|
||||
the TeamSpeak server is still down and connects once it is up, its
|
||||
`/health` says what is missing, and it stops cleanly on SIGTERM.
|
||||
- The client builds on VoelinProtocol's release `v0.2.0` (the tag, no longer a
|
||||
commit) for `voelin-identity`, `voelin-proto` and `voelin-model`; nothing the
|
||||
apps do changes. Two differences underneath: signing out of an account lists
|
||||
a kept device key once (a key whose row carried a device-only binding was
|
||||
listed twice), and the debug text of the protocol's messages (`Hello`,
|
||||
`Welcome`, `Server`, `Channel`, `Member` and the others whose secrets
|
||||
VoelinProtocol lists) shows `<redacted>` in place of a password or a token, so
|
||||
a log line or a failed test that prints one does not show it.
|
||||
- CI and the package builds give the VoelinProtocol deploy key only to the step
|
||||
that fetches the sources. The CI job writes the key to a directory of its own
|
||||
(no `~/.ssh` configuration), uses it for `cargo fetch` as `ssh -i` with the
|
||||
committed host key, and deletes it right after and again in a step that always
|
||||
runs; the formatting, Clippy, build, test and policy steps, which run the
|
||||
repository's build scripts and tests, are `--offline` and run in a job without
|
||||
the key. The Docker builds (Linux, Windows, Android and the gateway image)
|
||||
fetch in a `RUN` with the ssh mount and build `--offline` without it, and the
|
||||
release workflow stops its ssh-agent right after the last build. A job gives
|
||||
the key only to a runner that reports version 3.1.0 or newer (the old runner
|
||||
gitea-runner-docker v0.6.1 printed a multi-line secret in the job log; the
|
||||
deploy key was replaced, id 7) and, on a pull request, only when its head
|
||||
branch is in this repository; otherwise it stops with the reason. See
|
||||
docs/ci.md, "VoelinProtocol access".
|
||||
|
||||
### Removed
|
||||
|
||||
@@ -180,6 +302,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Fixed
|
||||
|
||||
- A deleted identity key no longer stays in the database file: SQLite overwrites
|
||||
what it deletes, and the log is truncated after a key is deleted (an identity
|
||||
you delete, a key a sign-out deletes).
|
||||
- Hover help in the Stream Studio (a source's error, the status details)
|
||||
shows each time and closes when the pointer leaves; it showed only once,
|
||||
and stayed open until a click.
|
||||
|
||||
@@ -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,
|
||||
@@ -30,10 +36,10 @@ review, help) and does not delegate it again or spawn further orchestration.
|
||||
| Agent | Model / effort | Job |
|
||||
|---|---|---|
|
||||
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
|
||||
| `mao-designer` | opus / max | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
|
||||
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
|
||||
| `mao-opus-reviewer` | opus / max | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
|
||||
|
||||
### Before delegating
|
||||
|
||||
Generated
+3764
-150
File diff suppressed because it is too large.
Load diff
+27
-3
@@ -15,14 +15,15 @@ members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
default-members = [
|
||||
@@ -36,23 +37,46 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
|
||||
[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
|
||||
|
||||
[workspace.dependencies]
|
||||
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
|
||||
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
|
||||
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
|
||||
# VoelinProtocol checkout"). Pinned by the release tag (v0.2.0 is the first with the
|
||||
# protocol crates; its README, "Releases", says how): the three crates below are at
|
||||
# one tag, so the lock has one revision of each, and moving to a newer release means
|
||||
# changing the `tag` of all three together (docs/building.md, "Depending on
|
||||
# VoelinProtocol"). The account-bound KeyStore whose sign-out keeps every device key
|
||||
# and the release of a device key, Phase 2 task 34, and the account types of the
|
||||
# session seam are in it.
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
# The UI-facing domain model and the client's replica of v1 entities.
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
|
||||
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
|
||||
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
|
||||
# "The version to pin").
|
||||
gpui-kit = "=0.8.1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
|
||||
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
|
||||
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
|
||||
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
|
||||
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
|
||||
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
|
||||
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
|
||||
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
|
||||
@@ -45,6 +45,14 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
|
||||
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
|
||||
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
|
||||
- `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
|
||||
@@ -76,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
|
||||
|
||||
+3267
-50
File diff suppressed because it is too large.
Load diff
+9
-1
@@ -3,13 +3,21 @@
|
||||
|
||||
<!-- From about-assets.md, appended by scripts/notices.sh. -->
|
||||
|
||||
The user interface bundles these assets (in crates/voelin-ui):
|
||||
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
|
||||
archive in crates/voelin-ui-vm):
|
||||
|
||||
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
|
||||
the SIL Open Font License 1.1 (OFL-1.1; text below).
|
||||
- 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
|
||||
|
||||
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
|
||||
tracing = "0.1.44"
|
||||
voelin-core = { path = "../voelin-core" }
|
||||
# Channels and people for the voice notification.
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
anyhow = "1.0.104"
|
||||
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-ui = { path = "../voelin-ui" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Client ids of stream viewers in the tests.
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
|
||||
mod tests {
|
||||
use voelin_core::SessionState;
|
||||
use voelin_core::stream::EndReason;
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -244,7 +244,7 @@ mod tests {
|
||||
let info = Event::ServerInfo {
|
||||
session: 1,
|
||||
name: "Home".into(),
|
||||
flavor: ServerFlavor::Unknown(String::new()),
|
||||
backend: voelin_core::BackendInfo::default(),
|
||||
capabilities: Capabilities::default(),
|
||||
};
|
||||
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
|
||||
@@ -316,7 +316,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
|
||||
let viewer = |client, state| ViewerInfo {
|
||||
client: tsclientlib::ClientId(client),
|
||||
client,
|
||||
state,
|
||||
message: String::new(),
|
||||
layer: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "voelin-audio"
|
||||
version = "0.1.0"
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
|
||||
sonora-simd = "0.2"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
@@ -1,45 +1,15 @@
|
||||
//! Opus encoding into TeamSpeak voice packets.
|
||||
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
|
||||
|
||||
use opus2::{Application, Bitrate, Channels, Encoder};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||
|
||||
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use crate::packet::{EncodedVoice, VoiceCodec};
|
||||
use crate::pcm::SAMPLE_RATE;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Largest possible Opus packet.
|
||||
const MAX_PACKET: usize = 1275;
|
||||
|
||||
/// The two Opus codecs TeamSpeak channels use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech (`CodecType::OpusVoice`).
|
||||
Voice,
|
||||
/// Stereo, tuned for music (`CodecType::OpusMusic`).
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
|
||||
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
|
||||
pub struct VoiceEncoder {
|
||||
encoder: Encoder,
|
||||
codec: VoiceCodec,
|
||||
@@ -53,7 +23,7 @@ impl VoiceEncoder {
|
||||
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
||||
// Survive some packet loss: TeamSpeak voice is plain UDP.
|
||||
// Survive some packet loss: voice travels over unreliable datagrams.
|
||||
encoder.set_inband_fec(true)?;
|
||||
encoder.set_packet_loss_perc(5)?;
|
||||
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
||||
@@ -82,26 +52,25 @@ impl VoiceEncoder {
|
||||
Ok(&self.out[..len])
|
||||
}
|
||||
|
||||
/// Encode one frame into a packet ready for `Connection::send_audio`.
|
||||
/// The connection assigns the packet id.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
|
||||
let codec = self.codec.codec_type();
|
||||
let data = self.encode_to_bytes(frame)?;
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
|
||||
/// Encode one frame for the transport to send. The transport assigns the
|
||||
/// packet number.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
|
||||
let codec = self.codec;
|
||||
let payload = self.encode_to_bytes(frame)?.to_vec();
|
||||
Ok(EncodedVoice { codec, payload })
|
||||
}
|
||||
|
||||
/// The empty packet that tells listeners the transmission ended.
|
||||
pub fn end_of_stream(&self) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
|
||||
pub fn end_of_stream(&self) -> EncodedVoice {
|
||||
EncodedVoice { codec: self.codec, payload: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::{self, FRAME_SAMPLES};
|
||||
|
||||
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
||||
/// decoder), and check the tone comes out.
|
||||
@@ -112,15 +81,16 @@ mod tests {
|
||||
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
||||
let mut decoded = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 7,
|
||||
data: &data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
|
||||
let sent = encoder.encode(frame).unwrap();
|
||||
assert_eq!(sent.codec, VoiceCodec::Voice);
|
||||
let packet = VoicePacket {
|
||||
talker: TalkerId(7),
|
||||
seq: i as u16,
|
||||
codec: sent.codec,
|
||||
whisper: false,
|
||||
payload: sent.payload,
|
||||
};
|
||||
mixer.handle_packet(packet).unwrap();
|
||||
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut out);
|
||||
decoded.extend(pcm::to_mono(&out, 2));
|
||||
@@ -131,6 +101,24 @@ mod tests {
|
||||
assert!(ratio > 0.8, "tone ratio {ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_stream_has_no_payload() {
|
||||
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let end = encoder.end_of_stream();
|
||||
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
|
||||
assert!(end.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_frames_carry_codec_and_audio() {
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
|
||||
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
|
||||
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
|
||||
assert!(!a.is_end() && !b.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_size() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -0,0 +1,879 @@
|
||||
//! Handle receiving audio.
|
||||
//!
|
||||
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
|
||||
//! transport: it reads [`VoicePacket`]s, whatever carried them.
|
||||
//!
|
||||
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||
//! talker. It decodes the audio, handles out-of-order packets and missing
|
||||
//! packets. It automatically adjusts the queue length based on the jitter of
|
||||
//! incoming packets.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::convert::TryInto;
|
||||
|
||||
use opus2::{Channels, Decoder, packet};
|
||||
use thiserror::Error;
|
||||
use tracing::{Span, debug, info_span, trace, warn};
|
||||
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: Channels = Channels::Stereo;
|
||||
const CHANNEL_NUM: usize = 2;
|
||||
/// If this amount of packets is lost consecutively, we assume the stream stopped.
|
||||
const MAX_PACKET_LOSSES: usize = 3;
|
||||
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
|
||||
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
|
||||
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
|
||||
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
|
||||
/// Maximum number of packets in the queue.
|
||||
const MAX_BUFFER_PACKETS: usize = 50;
|
||||
/// Buffer for maximal 0.5 s without playing anything.
|
||||
const MAX_BUFFER_TIME: usize = 48_000 / 2;
|
||||
/// Duplicate or remove every `step` sample when speeding-up.
|
||||
const SPEED_CHANGE_STEPS: usize = 100;
|
||||
/// The usual amount of samples in a frame.
|
||||
///
|
||||
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
|
||||
/// This means 1920 samples and 7.5 kiB.
|
||||
const USUAL_FRAME_SIZE: usize = 48000 / 50;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create opus decoder: {0}")]
|
||||
CreateDecoder(#[source] opus2::Error),
|
||||
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||
Decode {
|
||||
#[source]
|
||||
error: opus2::Error,
|
||||
packet: Option<Vec<u8>>,
|
||||
},
|
||||
#[error("Get duplicate packet id {0}")]
|
||||
Duplicate(u16),
|
||||
#[error("Failed to get packet samples: {0}")]
|
||||
GetPacketSample(#[source] opus2::Error),
|
||||
#[error("Audio queue is full, dropping")]
|
||||
QueueFull,
|
||||
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
|
||||
TooLate { wanted: u16, got: u16 },
|
||||
#[error("Packet has too many samples")]
|
||||
TooManySamples,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
|
||||
/// How long a value stays in the sliding window.
|
||||
size: u8,
|
||||
/// This is a sliding window minimum, it contains
|
||||
/// `(insertion time, value)`.
|
||||
///
|
||||
/// When we insert a value, we can remove all bigger sample counts,
|
||||
/// thus the queue always stays sorted with the minimum at the front
|
||||
/// and the maximum at the back (latest entry).
|
||||
///
|
||||
/// Provides amortized O(1) minimum.
|
||||
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
|
||||
queue: VecDeque<(u8, T)>,
|
||||
/// The current insertion time.
|
||||
cur_time: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct QueuePacket {
|
||||
packet: VoicePacket,
|
||||
samples: usize,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
/// A queue for audio packets for one audio stream.
|
||||
pub struct AudioQueue {
|
||||
span: Span,
|
||||
decoder: Decoder,
|
||||
pub volume: f32,
|
||||
/// The id of the next packet that should be decoded.
|
||||
///
|
||||
/// Used to check for packet loss.
|
||||
next_id: u16,
|
||||
/// If the last packet was a whisper packet.
|
||||
whispering: bool,
|
||||
packet_buffer: VecDeque<QueuePacket>,
|
||||
/// Amount of samples in the `packet_buffer`.
|
||||
packet_buffer_samples: usize,
|
||||
/// Temporary buffer that contains the samples of one decoded packet.
|
||||
decoded_buffer: Vec<f32>,
|
||||
/// The number of samples in `decoded_buffer` that have been returned.
|
||||
decoded_pos: usize,
|
||||
/// The number of samples in the last packet.
|
||||
last_packet_samples: usize,
|
||||
/// The last `packet_loss_num` packet decodes were a loss.
|
||||
packet_loss_num: usize,
|
||||
/// The amount of samples to buffer until this queue is ready to play.
|
||||
buffering_samples: usize,
|
||||
/// The amount of packets in the buffer when a packet was decoded.
|
||||
///
|
||||
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
|
||||
/// Used to expand or reduce the buffer.
|
||||
last_buffer_size_min: SlidingWindowMinimum<u8>,
|
||||
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
|
||||
/// Buffered for this duration.
|
||||
buffered_for_samples: usize,
|
||||
}
|
||||
|
||||
/// Handles incoming audio, has one [`AudioQueue`] per talker.
|
||||
#[derive(Default)]
|
||||
pub struct AudioHandler {
|
||||
queues: HashMap<TalkerId, AudioQueue>,
|
||||
/// Buffer this amount of samples for new queues before starting to play.
|
||||
///
|
||||
/// Updated when a new queue gets added.
|
||||
avg_buffer_samples: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
|
||||
fn new(size: u8) -> Self {
|
||||
Self { size, queue: Default::default(), cur_time: 0 }
|
||||
}
|
||||
|
||||
fn push(&mut self, value: T) {
|
||||
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
|
||||
self.queue.pop_back();
|
||||
}
|
||||
let i = self.cur_time;
|
||||
self.queue.push_back((i, value));
|
||||
while self
|
||||
.queue
|
||||
.front()
|
||||
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
self.queue.pop_front();
|
||||
}
|
||||
self.cur_time = self.cur_time.wrapping_add(1);
|
||||
}
|
||||
|
||||
fn get_min(&self) -> T {
|
||||
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioQueue {
|
||||
fn new(packet: VoicePacket) -> Result<Self> {
|
||||
let last_packet_samples =
|
||||
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if last_packet_samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
|
||||
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
|
||||
let whispering = packet.whisper;
|
||||
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||
|
||||
let mut res = Self {
|
||||
span: Span::current(),
|
||||
decoder,
|
||||
volume: 1.0,
|
||||
next_id: packet.seq,
|
||||
whispering,
|
||||
packet_buffer: Default::default(),
|
||||
packet_buffer_samples: 0,
|
||||
decoded_buffer: Default::default(),
|
||||
decoded_pos: 0,
|
||||
last_packet_samples,
|
||||
packet_loss_num: 0,
|
||||
buffering_samples: 0,
|
||||
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
|
||||
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
|
||||
buffered_for_samples: 0,
|
||||
};
|
||||
res.add_buffer_size(0);
|
||||
res.add_packet(packet)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn get_decoder(&self) -> &Decoder {
|
||||
&self.decoder
|
||||
}
|
||||
pub fn is_whispering(&self) -> bool {
|
||||
self.whispering
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
self.last_buffer_size_min.push(size);
|
||||
self.last_buffer_size_max.push(Reverse(size));
|
||||
} else {
|
||||
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
|
||||
}
|
||||
}
|
||||
|
||||
/// The approximate deviation of the buffer size.
|
||||
fn get_deviation(&self) -> u8 {
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let max = self.last_buffer_size_max.get_min();
|
||||
max.0 - min
|
||||
}
|
||||
|
||||
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
|
||||
let _span = self.span.enter();
|
||||
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||
return Err(Error::QueueFull);
|
||||
}
|
||||
let samples;
|
||||
if packet.is_end() {
|
||||
// End of stream
|
||||
samples = 0;
|
||||
} else {
|
||||
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
|
||||
.map_err(Error::GetPacketSample)?;
|
||||
if samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
}
|
||||
|
||||
let id = packet.seq;
|
||||
let packet = QueuePacket { packet, samples, id };
|
||||
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
|
||||
return Err(Error::TooLate { wanted: self.next_id, got: id });
|
||||
}
|
||||
|
||||
// Put into first spot where the id is smaller
|
||||
let i = self.packet_buffer.len()
|
||||
- self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
|
||||
.count();
|
||||
// Check for duplicate packet
|
||||
if let Some(p) = self.packet_buffer.get(i)
|
||||
&& p.id == packet.id
|
||||
{
|
||||
return Err(Error::Duplicate(p.id));
|
||||
}
|
||||
|
||||
trace!("Insert packet {} at {}", id, i);
|
||||
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
|
||||
if last_id <= id {
|
||||
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
|
||||
// Reduce buffering counter by lost packets if there are some
|
||||
self.buffering_samples = self
|
||||
.buffering_samples
|
||||
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
|
||||
}
|
||||
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.insert(i, packet);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
|
||||
let packet_data;
|
||||
let len;
|
||||
if let Some(p) = packet {
|
||||
packet_data = &p.packet.payload[..];
|
||||
len = p.samples;
|
||||
self.whispering = p.packet.whisper;
|
||||
} else {
|
||||
// An empty slice signals packet loss to the decoder
|
||||
packet_data = &[];
|
||||
len = self.last_packet_samples;
|
||||
}
|
||||
self.packet_loss_num += 1;
|
||||
|
||||
let orig_buffer_len = self.decoded_buffer.len();
|
||||
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
|
||||
let len = self
|
||||
.decoder
|
||||
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
|
||||
.map_err(|e| Error::Decode {
|
||||
error: e,
|
||||
packet: packet.map(|p| p.packet.payload.clone()),
|
||||
})?;
|
||||
self.last_packet_samples = len;
|
||||
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
|
||||
|
||||
// Update packet_loss_num
|
||||
if packet.is_some() && !fec {
|
||||
self.packet_loss_num = 0;
|
||||
}
|
||||
|
||||
// Update last_buffer_size
|
||||
let mut count = self.packet_buffer_samples;
|
||||
if let Some(last) = self.packet_buffer.back() {
|
||||
// Lost packets
|
||||
trace!(
|
||||
last.id,
|
||||
next_id = self.next_id,
|
||||
first_id = self.packet_buffer.front().unwrap().id,
|
||||
buffer_len = self.packet_buffer.len(),
|
||||
"Ids"
|
||||
);
|
||||
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
|
||||
- self.packet_buffer.len())
|
||||
* self.last_packet_samples;
|
||||
}
|
||||
self.add_buffer_size(count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode data and return the requested length of buffered data.
|
||||
///
|
||||
/// Returns `true` in the second return value when the stream ended,
|
||||
/// `false` when it continues normally.
|
||||
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
|
||||
let _span = self.span.clone().entered();
|
||||
if self.buffering_samples > 0 {
|
||||
if self.buffered_for_samples >= MAX_BUFFER_TIME {
|
||||
self.buffering_samples = 0;
|
||||
self.buffered_for_samples = 0;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffered for too long"
|
||||
);
|
||||
} else {
|
||||
self.buffered_for_samples += len;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffering"
|
||||
);
|
||||
return Ok((&[], false));
|
||||
}
|
||||
}
|
||||
// Need to refill buffer
|
||||
self.decoded_buffer.drain(..self.decoded_pos);
|
||||
|
||||
while self.decoded_buffer.len() < len {
|
||||
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
|
||||
|
||||
// Decode a packet
|
||||
if let Some(packet) = self.packet_buffer.pop_front() {
|
||||
if packet.packet.is_end() {
|
||||
// End of stream
|
||||
return Ok((&self.decoded_buffer, true));
|
||||
}
|
||||
|
||||
self.packet_buffer_samples -= packet.samples;
|
||||
let cur_id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if packet.id != cur_id {
|
||||
debug_assert!(
|
||||
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
|
||||
"Invalid packet queue state: {} < {}",
|
||||
packet.id,
|
||||
cur_id
|
||||
);
|
||||
// Packet loss
|
||||
debug!(need = cur_id, have = packet.id, "Audio packet loss");
|
||||
if packet.id == self.next_id {
|
||||
// Can use forward-error-correction
|
||||
self.decode_packet(Some(&packet), true)?;
|
||||
} else {
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.push_front(packet);
|
||||
} else {
|
||||
self.decode_packet(Some(&packet), false)?;
|
||||
}
|
||||
} else {
|
||||
debug!("No packets in queue");
|
||||
// Packet loss or end of stream
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
|
||||
if self.last_packet_samples == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should speed-up playback
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let dev = self.get_deviation();
|
||||
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
|
||||
debug!(min, "Truncating buffer");
|
||||
// Throw out all but min samples
|
||||
let mut keep_samples = 0;
|
||||
let keep = self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|p| {
|
||||
keep_samples += p.samples;
|
||||
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
|
||||
})
|
||||
.count();
|
||||
let len = self.packet_buffer.len() - keep;
|
||||
self.packet_buffer.drain(..len);
|
||||
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
|
||||
if let Some(p) = self.packet_buffer.front() {
|
||||
self.next_id = p.id;
|
||||
}
|
||||
} else if min > dev {
|
||||
// Speed-up
|
||||
debug!(
|
||||
min,
|
||||
cur_packet_count = self.packet_buffer.len(),
|
||||
last_packet_samples = self.last_packet_samples,
|
||||
dev,
|
||||
"Speed-up buffer"
|
||||
);
|
||||
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
|
||||
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
|
||||
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
|
||||
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.decoded_pos = len;
|
||||
Ok((&self.decoded_buffer[..len], false))
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Delete all queues
|
||||
pub fn reset(&mut self) {
|
||||
self.queues.clear();
|
||||
}
|
||||
|
||||
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
|
||||
&self.queues
|
||||
}
|
||||
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
|
||||
&mut self.queues
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
|
||||
/// function is called. The queue volume is applied after calling the preprocessor.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
|
||||
&mut self,
|
||||
buf: &mut [f32],
|
||||
mut handle: F,
|
||||
) -> Vec<TalkerId> {
|
||||
trace!(len = buf.len(), "Filling audio buffer");
|
||||
let mut to_remove = Vec::new();
|
||||
for (id, queue) in self.queues.iter_mut() {
|
||||
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
|
||||
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
|
||||
to_remove.push(*id);
|
||||
continue;
|
||||
}
|
||||
|
||||
let vol = queue.volume;
|
||||
match queue.get_next_data(buf.len()) {
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to decode audio packet");
|
||||
}
|
||||
Ok((r, is_end)) => {
|
||||
handle(id, r);
|
||||
for i in 0..r.len() {
|
||||
buf[i] += r[i] * vol;
|
||||
}
|
||||
if is_end {
|
||||
to_remove.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for id in &to_remove {
|
||||
self.queues.remove(id);
|
||||
}
|
||||
to_remove
|
||||
}
|
||||
|
||||
/// Add a packet to the queue of its talker.
|
||||
///
|
||||
/// If a new talker started talking, returns its id.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
|
||||
let id = packet.talker;
|
||||
let empty = packet.is_end();
|
||||
|
||||
if let Some(queue) = self.queues.get_mut(&id) {
|
||||
queue.add_packet(packet)?;
|
||||
Ok(None)
|
||||
} else {
|
||||
if empty {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let _span = info_span!("audio queue", client = ?id);
|
||||
trace!("Adding talker");
|
||||
let mut queue = AudioQueue::new(packet)?;
|
||||
if !self.queues.is_empty() {
|
||||
// Update avg_buffer_samples
|
||||
let total: usize = self
|
||||
.queues
|
||||
.values()
|
||||
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||
.sum();
|
||||
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
|
||||
}
|
||||
queue.buffering_samples = self.avg_buffer_samples;
|
||||
self.queues.insert(id, queue);
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use opus2::Encoder;
|
||||
|
||||
use super::*;
|
||||
use crate::packet::VoiceCodec;
|
||||
|
||||
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
const ID: TalkerId = TalkerId(0);
|
||||
|
||||
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
enum SimulateAction {
|
||||
CreateEncoder,
|
||||
/// Create packet with id.
|
||||
///
|
||||
/// The `bool` is `false` if packet handling should fail.
|
||||
ReceivePacket(u16, bool),
|
||||
ReceiveRaw(u16, Vec<u8>),
|
||||
/// Fetch audio of this sample count and expect a certain packet id.
|
||||
FillBuffer(usize, Option<u16>),
|
||||
/// Custom check
|
||||
Check(Box<dyn FnOnce(&AudioHandler)>),
|
||||
}
|
||||
|
||||
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
|
||||
let mut encoder = None;
|
||||
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||
let mut handler = AudioHandler::new();
|
||||
|
||||
for a in actions {
|
||||
println!("\nCurrent state");
|
||||
for q in &handler.queues {
|
||||
print!("Queue {:?}:", q.0);
|
||||
for p in &q.1.packet_buffer {
|
||||
print!(" {:?},", p);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
match a {
|
||||
SimulateAction::CreateEncoder => {
|
||||
encoder = Some(Encoder::new(
|
||||
48_000,
|
||||
opus2::Channels::Mono,
|
||||
opus2::Application::Voip,
|
||||
)?);
|
||||
}
|
||||
SimulateAction::ReceivePacket(i, success) => {
|
||||
let e = encoder.as_mut().unwrap();
|
||||
let data = vec![i as f32; USUAL_FRAME_SIZE];
|
||||
let len = e.encode_float(&data, &mut opus_output[..])?;
|
||||
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
|
||||
return Err(format!(
|
||||
"handle_packet returned {:?} but expected {:?}",
|
||||
!success, success
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
SimulateAction::ReceiveRaw(i, data) => {
|
||||
let _ = handler.handle_packet(packet(i, &data));
|
||||
}
|
||||
SimulateAction::FillBuffer(size, expect) => {
|
||||
let mut buf = vec![0.0; size * 2]; // Stereo
|
||||
let cur_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
handler.fill_buffer(&mut buf);
|
||||
let next_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
|
||||
if expect.is_some() {
|
||||
assert_eq!(expect, cur_packet_id);
|
||||
assert_ne!(cur_packet_id, next_packet_id);
|
||||
}
|
||||
}
|
||||
SimulateAction::Check(f) => {
|
||||
f(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum() {
|
||||
let data = &[
|
||||
(5, 5),
|
||||
(6, 5),
|
||||
(3, 3),
|
||||
(4, 3),
|
||||
(6, 3),
|
||||
(5, 3),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 5),
|
||||
(6, 5),
|
||||
(6, 6),
|
||||
(7, 6),
|
||||
(5, 5),
|
||||
];
|
||||
let mut window = SlidingWindowMinimum::new(5);
|
||||
assert_eq!(window.get_min(), 0);
|
||||
for (i, (val, min)) in data.iter().enumerate() {
|
||||
println!("{:?}", window);
|
||||
window.push(*val);
|
||||
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum_full() {
|
||||
let mut window = SlidingWindowMinimum::new(255);
|
||||
window.push(1);
|
||||
assert_eq!(window.get_min(), 1);
|
||||
for _ in 0..254 {
|
||||
window.push(2);
|
||||
}
|
||||
assert_eq!(window.get_min(), 1);
|
||||
window.push(2);
|
||||
assert_eq!(window.get_min(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for i in 0..100 {
|
||||
let seq = 65_500u16.wrapping_add(i);
|
||||
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
|
||||
|
||||
if i > 5 {
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short and malformed packets of any content are errors, never panics.
|
||||
#[test]
|
||||
fn short_packet_fuzz() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
let mut state = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
|
||||
for _ in 0..3_000 {
|
||||
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
|
||||
let len = (next() % 101) as usize;
|
||||
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
let _ = handler.handle_packet(packet(30, &payload));
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping2() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..100 {
|
||||
let i = 65_500u16.wrapping_add(i);
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for _ in 0..100 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..5 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceivePacket(4, false));
|
||||
a.push(SimulateAction::ReceivePacket(3, false));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, false));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_whole() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 27120..27124 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
|
||||
for _ in 0..10 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
for i in 27339..27349 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_packet() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..10 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(10, vec![]));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(50, true));
|
||||
a.push(SimulateAction::ReceivePacket(53, true));
|
||||
for _ in 0..8 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_wrapping_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(65534, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
for _ in 0..7 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
/// The talker is the key of the queues, and a new one is reported once.
|
||||
#[test]
|
||||
fn talkers_have_their_own_queues() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let from = |talker: u16, seq: u16| VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
|
||||
assert_eq!(handler.handle_packet(from(7, 101))?, None);
|
||||
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
|
||||
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
|
||||
talkers.sort_unstable();
|
||||
assert_eq!(talkers, [7, 9]);
|
||||
// A talker that only says goodbye never gets a queue.
|
||||
let end = VoicePacket { payload: vec![], ..from(11, 0) };
|
||||
assert_eq!(handler.handle_packet(end)?, None);
|
||||
assert_eq!(handler.get_queues().len(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A queue knows whether the last packet it played was a whisper.
|
||||
#[test]
|
||||
fn whisper_flag_follows_the_packets() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let packet = |seq: u16, whisper: bool| VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
handler.handle_packet(packet(0, true))?;
|
||||
assert!(handler.get_queues()[&ID].is_whispering());
|
||||
handler.handle_packet(packet(1, false))?;
|
||||
// One packet is played per call.
|
||||
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
assert!(!handler.get_queues()[&ID].is_whispering());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
//! Voice pipeline building blocks.
|
||||
//!
|
||||
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
|
||||
//! - [`packet`]: the voice packet types the pipeline takes and produces
|
||||
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
|
||||
//! - [`framer`]: slice an arbitrary sample stream into codec frames
|
||||
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
|
||||
//! - [`wav`]: WAV file input/output
|
||||
//! - [`process`]: echo cancellation, noise suppression and gain control
|
||||
//! - [`vad`]: voice activity detection
|
||||
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
|
||||
//! vendored `tsclientlib::audio::AudioHandler`)
|
||||
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
|
||||
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
|
||||
//! buffer, mixing to stereo
|
||||
//! - [`settings`]: all user audio settings in one serde struct
|
||||
//! - [`tap`]: the processed microphone for other consumers (the stream
|
||||
//! mixer), free while nobody listens
|
||||
@@ -17,7 +20,9 @@
|
||||
|
||||
pub mod encode;
|
||||
pub mod framer;
|
||||
pub mod jitter;
|
||||
pub mod mixer;
|
||||
pub mod packet;
|
||||
pub mod pcm;
|
||||
pub mod process;
|
||||
pub mod resample;
|
||||
@@ -29,12 +34,13 @@ pub mod wav;
|
||||
#[cfg(feature = "device")]
|
||||
pub mod device;
|
||||
|
||||
pub use encode::{VoiceCodec, VoiceEncoder};
|
||||
pub use encode::VoiceEncoder;
|
||||
pub use framer::Framer;
|
||||
pub use jitter::AudioHandler;
|
||||
pub use mixer::Mixer;
|
||||
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
pub use process::{ProcessingSettings, Processor};
|
||||
pub use settings::AudioSettings;
|
||||
pub use tsclientlib::audio::AudioHandler;
|
||||
pub use vad::{Vad, VadSettings};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per client, and everyone else dimmed while a priority
|
||||
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per talker, and everyone else dimmed while a priority
|
||||
//! speaker talks.
|
||||
//!
|
||||
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
|
||||
//! sender it keeps a queue of Opus packets and adapts its length:
|
||||
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
|
||||
//! packets and adapts its length:
|
||||
//!
|
||||
//! - a new talker starts after a pre-buffer derived from the queue lengths of
|
||||
//! the other talkers (none for the first one);
|
||||
@@ -21,13 +21,11 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsclientlib::audio::{AudioHandler, Error as QueueError};
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
|
||||
use crate::jitter::{AudioHandler, Error as QueueError};
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Loudest per-client volume: +12 dB.
|
||||
/// Loudest per-talker volume: +12 dB.
|
||||
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
|
||||
/// Most a priority speaker dims the others (dB).
|
||||
const MAX_DIMM_DB: f32 = -60.0;
|
||||
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
|
||||
/// samples (5 frames, 100 ms) instead of jumping.
|
||||
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
|
||||
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
|
||||
/// Output is interleaved stereo at 48 kHz.
|
||||
pub struct Mixer {
|
||||
handler: AudioHandler<ClientId>,
|
||||
volumes: HashMap<ClientId, f32>,
|
||||
muted: HashSet<ClientId>,
|
||||
handler: AudioHandler,
|
||||
volumes: HashMap<TalkerId, f32>,
|
||||
muted: HashSet<TalkerId>,
|
||||
/// While one of them talks, everyone else is dimmed.
|
||||
priority: HashSet<ClientId>,
|
||||
priority: HashSet<TalkerId>,
|
||||
/// Linear gain of the others while a priority speaker talks (1: none).
|
||||
dimm: f32,
|
||||
/// How far the dimming has faded in (0..=1).
|
||||
@@ -70,21 +68,17 @@ impl Mixer {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
|
||||
/// just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on UDP they are expected and can be ignored.
|
||||
pub fn handle_packet(
|
||||
&mut self,
|
||||
id: ClientId,
|
||||
packet: InAudioBuf,
|
||||
) -> Result<Option<ClientId>, QueueError> {
|
||||
self.handler.handle_packet(id, packet)
|
||||
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
|
||||
/// talker just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on datagrams they are expected and can be ignored.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
|
||||
self.handler.handle_packet(packet)
|
||||
}
|
||||
|
||||
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
|
||||
/// (not cleared first), each scaled by its volume, and dimmed while a
|
||||
/// priority speaker talks. Returns the clients that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
|
||||
/// priority speaker talks. Returns the talkers that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
let queues = self.handler.get_mut_queues();
|
||||
// A priority speaker with a queue (talking or buffering) dims all
|
||||
// other queues, streams too, unless we muted it.
|
||||
@@ -141,9 +135,9 @@ impl Mixer {
|
||||
stopped
|
||||
}
|
||||
|
||||
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the client stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
|
||||
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the talker stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
|
||||
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
|
||||
if volume == 1.0 {
|
||||
self.volumes.remove(&id);
|
||||
@@ -153,15 +147,15 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
|
||||
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
|
||||
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
|
||||
self.set_volume(id, 10f32.powf(db / 20.0));
|
||||
}
|
||||
|
||||
pub fn volume(&self, id: ClientId) -> f32 {
|
||||
pub fn volume(&self, id: TalkerId) -> f32 {
|
||||
self.volumes.get(&id).copied().unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
|
||||
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
|
||||
if muted {
|
||||
self.muted.insert(id);
|
||||
} else {
|
||||
@@ -169,30 +163,30 @@ impl Mixer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_muted(&self, id: ClientId) -> bool {
|
||||
pub fn is_muted(&self, id: TalkerId) -> bool {
|
||||
self.muted.contains(&id)
|
||||
}
|
||||
|
||||
/// The priority speakers, and how much everyone else is dimmed while
|
||||
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
|
||||
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
|
||||
/// the caller sends a new set when the clients change.
|
||||
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
|
||||
self.priority = clients.into_iter().collect();
|
||||
/// the caller sends a new set when the talkers change.
|
||||
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
|
||||
self.priority = talkers.into_iter().collect();
|
||||
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
|
||||
self.dimm = 10f32.powf(db / 20.0);
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a client (e.g. it left the server; client
|
||||
/// ids are reused).
|
||||
pub fn forget(&mut self, id: ClientId) {
|
||||
/// Forget volume and mute of a talker (e.g. it left the server; ids may
|
||||
/// be reused).
|
||||
pub fn forget(&mut self, id: TalkerId) {
|
||||
self.volumes.remove(&id);
|
||||
self.muted.remove(&id);
|
||||
self.handler.get_mut_queues().remove(&id);
|
||||
}
|
||||
|
||||
/// Clients with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
|
||||
/// Talkers with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
|
||||
self.handler.get_queues().keys().copied()
|
||||
}
|
||||
|
||||
@@ -202,7 +196,7 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// The underlying jitter buffer.
|
||||
pub fn handler(&self) -> &AudioHandler<ClientId> {
|
||||
pub fn handler(&self) -> &AudioHandler {
|
||||
&self.handler
|
||||
}
|
||||
}
|
||||
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
|
||||
|
||||
use super::*;
|
||||
use crate::VoiceEncoder;
|
||||
use crate::encode::VoiceCodec;
|
||||
use crate::packet::VoiceCodec;
|
||||
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
|
||||
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
|
||||
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two clients send tones at the same level; after setting volumes the
|
||||
/// mix carries each at its own gain, and a muted one not at all.
|
||||
#[test]
|
||||
fn volume_per_client() {
|
||||
let (a, b) = (ClientId(3), ClientId(4));
|
||||
let (a, b) = (TalkerId(3), TalkerId(4));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -251,11 +248,11 @@ mod tests {
|
||||
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
|
||||
for (i, (fa, fb)) in frames.enumerate() {
|
||||
let id = i as u16;
|
||||
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
if i == 0 {
|
||||
assert_eq!(started.unwrap(), Some(a));
|
||||
}
|
||||
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -274,8 +271,8 @@ mod tests {
|
||||
let id = 100 + i;
|
||||
let fa = &tone_a[..FRAME_SAMPLES];
|
||||
let fb = &tone_b[..FRAME_SAMPLES];
|
||||
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -289,7 +286,7 @@ mod tests {
|
||||
/// in and out, but not itself, and not while we muted it.
|
||||
#[test]
|
||||
fn priority_speaker_dims_others() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
let (a, p) = (TalkerId(3), TalkerId(5));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 4.0, 0.2);
|
||||
@@ -308,14 +305,12 @@ mod tests {
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let fa = frame(&tone_a, id_a);
|
||||
mixer
|
||||
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
|
||||
.unwrap();
|
||||
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
|
||||
id_a += 1;
|
||||
if with_p {
|
||||
let fp = frame(&tone_p, id_p);
|
||||
let data = enc_p.encode_to_bytes(&fp).unwrap();
|
||||
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
|
||||
mixer.handle_packet(packet(5, id_p, data)).unwrap();
|
||||
id_p += 1;
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
@@ -359,7 +354,7 @@ mod tests {
|
||||
/// frame: the other talker's level (per period of its tone) never jumps.
|
||||
#[test]
|
||||
fn priority_dimming_ramps_per_sample() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
let p = TalkerId(5);
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -371,10 +366,10 @@ mod tests {
|
||||
// p talks from frame 30 to 59.
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let id = i as u16;
|
||||
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
|
||||
let data = enc_p.encode_to_bytes(frame).unwrap();
|
||||
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
|
||||
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
@@ -400,17 +395,17 @@ mod tests {
|
||||
fn priority_dimm_bounds() {
|
||||
let mut mixer = Mixer::new();
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], -18.0);
|
||||
mixer.set_priority([TalkerId(1)], -18.0);
|
||||
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
|
||||
mixer.set_priority([ClientId(1)], 6.0);
|
||||
mixer.set_priority([TalkerId(1)], 6.0);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
|
||||
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
|
||||
assert!((mixer.dimm - 0.001).abs() < 1e-6);
|
||||
mixer.set_priority([ClientId(1)], f32::NAN);
|
||||
mixer.set_priority([TalkerId(1)], f32::NAN);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
// Forgetting a client keeps the set: the caller replaces it.
|
||||
mixer.forget(ClientId(1));
|
||||
assert!(mixer.priority.contains(&ClientId(1)));
|
||||
mixer.forget(TalkerId(1));
|
||||
assert!(mixer.priority.contains(&TalkerId(1)));
|
||||
mixer.set_priority([], -18.0);
|
||||
assert!(mixer.priority.is_empty());
|
||||
}
|
||||
@@ -418,7 +413,7 @@ mod tests {
|
||||
#[test]
|
||||
fn volume_bounds_and_forget() {
|
||||
let mut mixer = Mixer::new();
|
||||
let id = ClientId(9);
|
||||
let id = TalkerId(9);
|
||||
mixer.set_volume(id, 100.0);
|
||||
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
|
||||
mixer.set_volume(id, -1.0);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Voice packets as the audio pipeline sees them, whatever transport carries
|
||||
//! them (the TeamSpeak connection today, a Voelin server later).
|
||||
//!
|
||||
//! The transport adapter turns what it receives into a [`VoicePacket`] and
|
||||
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
|
||||
//! into its own wire format; nothing in this crate knows either format.
|
||||
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Who is talking: a sender id, unique among the talkers of one voice
|
||||
/// connection. A transport maps its own client ids onto it (TeamSpeak's
|
||||
/// 16-bit client id is used as is).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct TalkerId(pub u16);
|
||||
|
||||
/// The two Opus flavours voice is sent in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech.
|
||||
Voice,
|
||||
/// Stereo, tuned for music.
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet received from a talker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VoicePacket {
|
||||
pub talker: TalkerId,
|
||||
/// Packet number of this talker, counting up by one per 20 ms frame and
|
||||
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
|
||||
pub seq: u16,
|
||||
pub codec: VoiceCodec,
|
||||
/// Sent to us as a whisper instead of to the whole channel.
|
||||
pub whisper: bool,
|
||||
/// One Opus packet. An empty one ends the talk (a single byte counts as
|
||||
/// empty too: some servers send one).
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl VoicePacket {
|
||||
/// Whether this packet only ends the talk and carries no audio.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.len() <= 1
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded frame to send. The transport assigns the packet number.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedVoice {
|
||||
pub codec: VoiceCodec,
|
||||
/// One Opus packet; empty: the transmission ended.
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EncodedVoice {
|
||||
/// Whether this only tells listeners the transmission ended.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codec_frames() {
|
||||
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
|
||||
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_talk() {
|
||||
let voice = |payload: &[u8]| VoicePacket {
|
||||
talker: TalkerId(1),
|
||||
seq: 0,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
};
|
||||
assert!(voice(&[]).is_end());
|
||||
assert!(voice(&[2]).is_end());
|
||||
assert!(!voice(&[2, 3]).is_end());
|
||||
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
|
||||
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,8 @@
|
||||
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
|
||||
//! the latency is the time from generating a marker to it leaving the mixer.
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
|
||||
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
|
||||
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
|
||||
|
||||
/// The receiver pulls 10 ms at a time, like a playback loop.
|
||||
const PULL: usize = SAMPLE_RATE as usize / 100;
|
||||
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
|
||||
let mut rng = Rng(ppm.to_bits());
|
||||
let mut mixer = Mixer::new();
|
||||
let client = ClientId(5);
|
||||
let talker = TalkerId(5);
|
||||
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
|
||||
// Sender frame n is made at n * 20 ms of the sender's clock.
|
||||
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
|
||||
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
|
||||
for (_, n) in in_flight.drain(..arrived) {
|
||||
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: n as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 5,
|
||||
data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let packet = VoicePacket {
|
||||
talker,
|
||||
seq: n as u16,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.clone(),
|
||||
};
|
||||
// Late packets are dropped by the jitter buffer, as on a real network.
|
||||
let _ = mixer.handle_packet(client, packet);
|
||||
let _ = mixer.handle_packet(packet);
|
||||
}
|
||||
|
||||
out.fill(0.0);
|
||||
|
||||
@@ -14,8 +14,9 @@ default = ["audio-device"]
|
||||
audio-device = ["voelin-audio/device"]
|
||||
# The `media` module: capture and video codecs for streams, with whatever
|
||||
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
|
||||
# source on Android).
|
||||
media = ["dep:voelin-media"]
|
||||
# source on Android), and the studio's WHIP output. The crate itself is always
|
||||
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
|
||||
media = ["voelin-media/whip"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
|
||||
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
|
||||
# (libvpx does not cross-compile there).
|
||||
@@ -24,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
|
||||
bytes = "1"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
@@ -49,11 +52,17 @@ toml = "1.1.6"
|
||||
tracing = "0.1"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
|
||||
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
|
||||
# keeps it, or a Voelin key).
|
||||
voelin-identity = { workspace = true }
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
|
||||
# and the v1 messages it speaks.
|
||||
voelin-proto = { workspace = true }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
@@ -64,13 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
# An HTTP/2 connection in a test (both already in the tree through h2).
|
||||
bytes = "1"
|
||||
# An HTTP/2 connection in a test (already in the tree through h2).
|
||||
http = "1"
|
||||
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
|
||||
rustls = { version = "0.23", default-features = false }
|
||||
# `process`: the browser interop test drives Chromium through Node.js.
|
||||
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
|
||||
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
|
||||
# suite).
|
||||
voelin-proto = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES};
|
||||
use voelin_audio::settings::TransmitMode;
|
||||
use voelin_audio::tap;
|
||||
use voelin_audio::vad::SILENCE_DB;
|
||||
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{
|
||||
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
|
||||
VoicePacket,
|
||||
};
|
||||
|
||||
pub(crate) enum AudioIn {
|
||||
Packet(InAudioBuf),
|
||||
/// Voice of a talker, from the voice connection.
|
||||
Packet(VoicePacket),
|
||||
Transmit(bool),
|
||||
InputMuted(bool),
|
||||
OutputMuted(bool),
|
||||
@@ -33,19 +35,19 @@ pub(crate) enum AudioIn {
|
||||
Settings(Box<AudioSettings>),
|
||||
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||
ClientVolume {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
volume: f32,
|
||||
},
|
||||
ClientMuted {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
muted: bool,
|
||||
},
|
||||
/// The client left; client ids are reused, so forget its volume.
|
||||
ClientLeft(ClientId),
|
||||
ClientLeft(TalkerId),
|
||||
/// The priority speakers: while one talks, everyone else (streams too)
|
||||
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
|
||||
PrioritySpeakers {
|
||||
clients: Vec<ClientId>,
|
||||
clients: Vec<TalkerId>,
|
||||
dimm_db: f32,
|
||||
},
|
||||
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||
@@ -111,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
|
||||
const OPUS_FRAME: u64 = 960;
|
||||
|
||||
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
|
||||
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
|
||||
/// no device) and the microphone level are reported through `events`.
|
||||
pub(crate) fn spawn(
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) -> AudioHandle {
|
||||
@@ -126,9 +128,9 @@ pub(crate) fn spawn(
|
||||
AudioHandle { tx }
|
||||
}
|
||||
|
||||
/// Audio of a watched stream in the mixer, under a made-up client id.
|
||||
/// Audio of a watched stream in the mixer, under a made-up talker id.
|
||||
struct StreamAudio {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
/// RTP time and packet id of the last packet.
|
||||
last: Option<(u64, u64)>,
|
||||
}
|
||||
@@ -190,11 +192,7 @@ impl Pipeline {
|
||||
fn handle(&mut self, msg: AudioIn) {
|
||||
match msg {
|
||||
AudioIn::Packet(packet) => {
|
||||
let from = match packet.data().data() {
|
||||
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
||||
_ => return,
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped voice packet");
|
||||
}
|
||||
}
|
||||
@@ -241,8 +239,8 @@ impl Pipeline {
|
||||
let client = match self.streams.get(&stream) {
|
||||
Some(s) => s.client,
|
||||
None => {
|
||||
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
|
||||
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -263,19 +261,15 @@ impl Pipeline {
|
||||
}
|
||||
};
|
||||
entry.last = Some((time, id));
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: id as u16,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: client.0,
|
||||
data,
|
||||
});
|
||||
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
|
||||
Ok(packet) => {
|
||||
if let Err(error) = self.mixer.handle_packet(client, packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
Err(error) => debug!(?error, "stream audio packet"),
|
||||
let packet = VoicePacket {
|
||||
talker: client,
|
||||
seq: id as u16,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +280,7 @@ impl Pipeline {
|
||||
|
||||
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
|
||||
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
|
||||
self.processor.set_delay_ms(delay_ms);
|
||||
self.processed.clear();
|
||||
self.processor.capture(samples, &mut self.processed);
|
||||
@@ -308,7 +302,7 @@ impl Pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
|
||||
// Always analysed, so the detector's state is current when needed.
|
||||
let voice = self.vad.process(&frame);
|
||||
let level = self.vad.level_db().max(SILENCE_DB);
|
||||
@@ -369,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
|
||||
|
||||
fn run(
|
||||
rx: std_mpsc::Receiver<AudioIn>,
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) {
|
||||
@@ -445,11 +439,10 @@ fn run(
|
||||
#[cfg(feature = "audio-device")]
|
||||
mod devices {
|
||||
use tracing::debug;
|
||||
use tsproto_packets::packets::OutPacket;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use voelin_audio::resample::Linear;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice};
|
||||
|
||||
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
|
||||
|
||||
@@ -509,7 +502,7 @@ mod devices {
|
||||
pub fn step(
|
||||
&mut self,
|
||||
pipeline: &mut Pipeline,
|
||||
send: &mut impl FnMut(OutPacket),
|
||||
send: &mut impl FnMut(EncodedVoice),
|
||||
error: &impl Fn(String),
|
||||
) -> bool {
|
||||
if let Some(event) = self.playback.poll() {
|
||||
@@ -575,16 +568,20 @@ mod tests {
|
||||
/// end-of-stream packets).
|
||||
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
|
||||
let (mut voice, mut end) = (0, 0);
|
||||
p.capture(samples, 0, &mut |packet: OutPacket| {
|
||||
// Header of 3 bytes (id + codec) for C2S audio.
|
||||
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
|
||||
p.capture(samples, 0, &mut |packet: EncodedVoice| {
|
||||
if packet.is_end() { end += 1 } else { voice += 1 }
|
||||
});
|
||||
(voice, end)
|
||||
}
|
||||
|
||||
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
|
||||
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
|
||||
AudioIn::Packet(VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -667,14 +664,14 @@ mod tests {
|
||||
energy(&out[out.len() / 2..])
|
||||
};
|
||||
let full = play(&mut p, 1);
|
||||
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
|
||||
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
|
||||
let half = play(&mut p, 2);
|
||||
let ratio_db = 10.0 * (half / full).log10();
|
||||
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
|
||||
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
|
||||
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
|
||||
assert!(play(&mut p, 3) < 1e-8);
|
||||
p.handle(AudioIn::ClientLeft(ClientId(3)));
|
||||
assert!(!p.mixer.is_muted(ClientId(3)));
|
||||
p.handle(AudioIn::ClientLeft(TalkerId(3)));
|
||||
assert!(!p.mixer.is_muted(TalkerId(3)));
|
||||
}
|
||||
|
||||
/// While a priority speaker talks, another talker and a watched stream
|
||||
@@ -682,7 +679,7 @@ mod tests {
|
||||
#[test]
|
||||
fn priority_speaker() {
|
||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
|
||||
//! map access, and the same image seen on several servers or under
|
||||
//! several clients is one file. Pictures from the web (banners,
|
||||
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
|
||||
//! `web`) are named by the MD5 hash of their address. Keys are
|
||||
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
|
||||
//!
|
||||
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
|
||||
//! limit): the least recently used files go first. Use times survive
|
||||
//! restarts as the files' modification times.
|
||||
//!
|
||||
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
|
||||
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
|
||||
//! download (into a temporary path), later askers wait for the same
|
||||
//! download ([`Cache::finish`] answers them all).
|
||||
//! download (`Cache::finish` answers them all).
|
||||
//!
|
||||
//! A picture from the web keeps its host's validators (`ETag`,
|
||||
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
|
||||
//! again, it is downloaded only if it changed ([`Cache::validators`],
|
||||
//! [`Arrived::Unchanged`]).
|
||||
//! again, it is downloaded only if it changed (`Cache::validators`,
|
||||
//! `Arrived::Unchanged`).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
@@ -489,6 +500,15 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
let secs = std::time::Duration::from_secs;
|
||||
assert_eq!(image_download_time(0), secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"voelin-cache-{tag}-{}-{:?}",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Picked by the caller; the answer carries it back.
|
||||
pub type RequestId = u64;
|
||||
@@ -106,11 +106,11 @@ impl TransferState {
|
||||
}
|
||||
|
||||
/// Reports a transfer's states.
|
||||
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
|
||||
/// Where a running download writes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Sink {
|
||||
pub enum Sink {
|
||||
/// Write `part` (appending with `append`), then rename it to `dest`.
|
||||
File {
|
||||
part: PathBuf,
|
||||
@@ -168,9 +168,10 @@ impl Progress<'_> {
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Receive a file: `size` bytes in total, `offset` of them already in the
|
||||
/// sink. Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn download(
|
||||
mut stream: TcpStream,
|
||||
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
|
||||
/// final state.
|
||||
pub(crate) async fn download<R: AsyncRead + Unpin>(
|
||||
mut stream: R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
@@ -185,8 +186,8 @@ pub(crate) async fn download(
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
stream: &mut TcpStream,
|
||||
async fn receive<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: &Sink,
|
||||
@@ -198,19 +199,22 @@ async fn receive(
|
||||
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())?;
|
||||
@@ -253,26 +257,34 @@ async fn receive(
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload(
|
||||
mut stream: TcpStream,
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn upload_to<W, F>(
|
||||
mut writer: W,
|
||||
stored: F,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
) where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Future<Output = Result<(), String>>,
|
||||
{
|
||||
report(TransferState::Started { size, offset });
|
||||
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
|
||||
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
|
||||
Ok(()) => stored.await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
report(match result {
|
||||
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
|
||||
Err(e) => TransferState::Failed(e),
|
||||
});
|
||||
}
|
||||
|
||||
async fn send(
|
||||
stream: &mut TcpStream,
|
||||
async fn send<W: AsyncWrite + Unpin>(
|
||||
stream: &mut W,
|
||||
path: &Path,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
@@ -300,8 +312,6 @@ async fn send(
|
||||
}
|
||||
stream.flush().await.map_err(|e| e.to_string())?;
|
||||
stream.shutdown().await.map_err(|e| e.to_string())?;
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -421,7 +431,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -562,7 +572,8 @@ mod tests {
|
||||
});
|
||||
let (report, states) = recorder();
|
||||
let stream = TcpStream::connect(addr).await.unwrap();
|
||||
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
let (_, write) = tokio::io::split(stream);
|
||||
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
assert_eq!(server.await.unwrap(), b"456789");
|
||||
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
|
||||
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
|
||||
|
||||
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
|
||||
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
|
||||
StreamSpec, TopicInfo, UserRef,
|
||||
};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{ChannelId, ChatTarget, Presence};
|
||||
use voelin_store::WriteOutcome;
|
||||
|
||||
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
|
||||
/// with it.
|
||||
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
|
||||
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
|
||||
/// TeamSpeak identity.
|
||||
/// TeamSpeak identity (a blob of kind `teamspeak`, see
|
||||
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
|
||||
/// [`ErrorCode::AuthFailed`], the way the gateway would).
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
identity: &IdentityBlob,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
connect_watched(url, identity, &Progress::default()).await
|
||||
let identity = login_identity(identity)
|
||||
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
|
||||
connect_watched(url, &identity, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step (for the log).
|
||||
@@ -114,10 +125,19 @@ async fn connect_watched(
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
mut urls: Vec<String>,
|
||||
identity: tsclientlib::Identity,
|
||||
identity: IdentityBlob,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
// An identity that cannot be read will not be tomorrow: like a refused login.
|
||||
let identity = match login_identity(&identity) {
|
||||
Ok(identity) => identity,
|
||||
Err(reason) => {
|
||||
debug!(%reason, "gateway: the identity cannot be read");
|
||||
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// A gateway that is away (down, restarting, a network change, a proxy
|
||||
// in front of it that fails) or cannot log us in yet (it does not know
|
||||
// the identity before voice connected once, its server is restarting)
|
||||
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
|
||||
}
|
||||
|
||||
impl Observed {
|
||||
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
|
||||
Self {
|
||||
urls: urls.to_vec(),
|
||||
key: identity.key().to_pub().to_ts(),
|
||||
counter: identity.counter(),
|
||||
nudged: None,
|
||||
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
|
||||
let (key, counter) = Self::of(identity);
|
||||
Self { urls: urls.to_vec(), key, counter, nudged: None }
|
||||
}
|
||||
|
||||
/// The public key and the counter of an identity: an identity that cannot be
|
||||
/// read has neither (and so is the same as any other that cannot).
|
||||
fn of(identity: &IdentityBlob) -> (String, u64) {
|
||||
match login_identity(identity) {
|
||||
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
|
||||
Err(_) => (String::new(), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is what is observed with.
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
|
||||
self.urls == urls
|
||||
&& self.counter == identity.counter()
|
||||
&& self.key == identity.key().to_pub().to_ts()
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
|
||||
let (key, counter) = Self::of(identity);
|
||||
self.urls == urls && self.counter == counter && self.key == key
|
||||
}
|
||||
|
||||
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
|
||||
@@ -1182,15 +1206,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_same_observation_is_nudged_at_most_every_5_s() {
|
||||
let blob = crate::ts::identity::to_blob;
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
|
||||
let mut observed = Observed::new(&urls, &identity);
|
||||
assert!(observed.same(&urls, &identity));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
|
||||
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
|
||||
let mut observed = Observed::new(&urls, &blob(&identity));
|
||||
assert!(observed.same(&urls, &blob(&identity)));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
|
||||
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
|
||||
// Its security level raised: logged in with the new counter.
|
||||
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
|
||||
assert!(!observed.same(&urls, &raised));
|
||||
assert!(!observed.same(&urls, &blob(&raised)));
|
||||
let now = Instant::now();
|
||||
assert!(observed.nudge_at(now));
|
||||
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
|
||||
//! Each server the user works with is a session with up to three sources:
|
||||
//!
|
||||
//! - **voice**: a normal client connection (visible, can talk)
|
||||
//! - **voice**: a normal client connection (visible, can talk): a
|
||||
//! `voelin_proto::link::Session` that the connector of the server's address
|
||||
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
|
||||
//! [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -16,9 +19,9 @@
|
||||
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
|
||||
//! of watched streams plays through the session's speakers by itself
|
||||
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
|
||||
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
|
||||
//! are in `media` (feature `media`), and the Stream Studio (scenes of
|
||||
//! sources composited into one stream, recording, a replay buffer, WHIP) in
|
||||
//! [`studio`].
|
||||
//! `studio`.
|
||||
//!
|
||||
//! Settings are a [`settings::Settings`] service: typed keys, runtime
|
||||
//! values stored in the client database ahead of command line, config file
|
||||
@@ -45,14 +48,13 @@
|
||||
//! volume) are engine-wide ([`contacts`]).
|
||||
|
||||
mod audio;
|
||||
mod book;
|
||||
pub mod cache;
|
||||
pub mod contacts;
|
||||
pub mod discover;
|
||||
pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod history;
|
||||
pub mod identity;
|
||||
pub mod link;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod media;
|
||||
pub mod offline;
|
||||
@@ -61,22 +63,21 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
pub mod ts;
|
||||
mod web;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
pub use voelin_audio::settings::TransmitMode;
|
||||
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
|
||||
ServerFlavor,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
|
||||
@@ -88,14 +89,14 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
|
||||
pub use gateway::{GatewayRequest, GatewayUpdate};
|
||||
use history::SharedHistory;
|
||||
pub use history::{History, HistoryMessage, HistorySource};
|
||||
pub use link::{Backends, VoiceOptions};
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
pub use query::{QueryLogin, QueryTransport};
|
||||
pub use route::{ChatRoute, Dedup, route_chat};
|
||||
use settings::{SettingChange, Settings, SharedSettings};
|
||||
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
|
||||
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
|
||||
};
|
||||
pub use voice::VoiceOptions;
|
||||
pub use voelin_identity::IdentityBlob;
|
||||
/// Banners are downloaded and shown by the same rule.
|
||||
pub use web::is_svg;
|
||||
/// Pictures from the web go through the desktop's proxy (set at startup).
|
||||
@@ -110,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100;
|
||||
/// What the UI asks for.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Command {
|
||||
/// Main account proof for every current and future voice connection.
|
||||
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
|
||||
/// What voice servers are shown of the main account (its avatar and
|
||||
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
|
||||
/// every connection that presents the account's myTS ID, once connected
|
||||
/// and when it changes; cleared on a sign-out.
|
||||
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
|
||||
ConnectVoice {
|
||||
session: SessionId,
|
||||
options: Box<VoiceOptions>,
|
||||
@@ -132,12 +126,15 @@ pub enum Command {
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
urls: Vec<String>,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
|
||||
/// One that is none, or cannot be read, ends the observation with
|
||||
/// its reason.
|
||||
identity: Box<IdentityBlob>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
ObserveQuery {
|
||||
session: SessionId,
|
||||
connect: Box<voelin_query::Connect>,
|
||||
connect: Box<QueryLogin>,
|
||||
},
|
||||
StopObserving {
|
||||
session: SessionId,
|
||||
@@ -248,11 +245,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
layers: Vec<LayerSpec>,
|
||||
},
|
||||
/// SRTP protection profiles for stream connections, in order of
|
||||
/// preference (a user setting; empty: the default,
|
||||
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
|
||||
/// on, in all sessions and those started later.
|
||||
SetSrtpProfiles(Vec<SrtpProfile>),
|
||||
/// SRTP protection profiles for stream connections by name (RFC 5764 and
|
||||
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
|
||||
/// transport does not know are left out), in order of preference (the
|
||||
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
|
||||
/// Applies to connections made from now on, in all sessions and those
|
||||
/// started later.
|
||||
SetSrtpProfiles(Vec<String>),
|
||||
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
|
||||
/// [`Engine::subscribe_frames`].
|
||||
WatchStream {
|
||||
@@ -270,7 +269,7 @@ pub enum Command {
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
/// connection without this one). `media::Viewer` sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
@@ -507,6 +506,30 @@ pub enum JoinFailure {
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The software on the other end of a session, as its link names it. It is
|
||||
/// for people to read; nothing branches on it (what the server can do is
|
||||
/// [`Capabilities`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BackendInfo {
|
||||
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
|
||||
pub product: String,
|
||||
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
|
||||
/// server said, as it is, when `product` is empty.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl BackendInfo {
|
||||
/// For a sentence: the product and the version, whichever there are
|
||||
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
|
||||
pub fn label(&self) -> String {
|
||||
match (self.product.is_empty(), self.version.is_empty()) {
|
||||
(false, false) => format!("{} {}", self.product, self.version),
|
||||
(false, true) => self.product.clone(),
|
||||
(true, _) => self.version.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine reports.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
@@ -514,10 +537,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
state: SessionState,
|
||||
},
|
||||
/// The server answered: its name, the software it runs and what that
|
||||
/// software can do (the UI hides what it cannot).
|
||||
ServerInfo {
|
||||
session: SessionId,
|
||||
name: String,
|
||||
flavor: ServerFlavor,
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
},
|
||||
/// Full presence of the session (the UI rebuilds its view from it).
|
||||
@@ -760,8 +785,18 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with the engine's own connectors
|
||||
/// ([`Backends::default`]: TeamSpeak 3 and 6).
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_backends(settings, history, Backends::default())
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with the connectors in `backends`:
|
||||
/// the one for the scheme of a session's address makes its
|
||||
/// `voelin_proto::link::Session`.
|
||||
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
|
||||
let link = Arc::new(link::SessionLink::new(backends));
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -773,7 +808,7 @@ impl Engine {
|
||||
history,
|
||||
cache: SharedCache::new(Cache::new(Cache::default_dir())),
|
||||
};
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
|
||||
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
|
||||
}
|
||||
|
||||
@@ -857,19 +892,18 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<link::SessionLink>,
|
||||
) {
|
||||
let Shared { settings: shared, history, cache, contacts } = engine.clone();
|
||||
// Before any command: a contact set meanwhile would be lost.
|
||||
contacts.load().await;
|
||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||
let (myts_identity, _) = watch::channel(None);
|
||||
let (myts_data, _) = watch::channel(None);
|
||||
let mut current = shared.current();
|
||||
// Pruning: at start, then hourly (and when the setting changes).
|
||||
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
let mut changes = current.subscribe();
|
||||
let mut settings = AudioSettings::default();
|
||||
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
|
||||
let mut srtp_profiles: Option<Vec<String>> = None;
|
||||
let mut mic_test: Option<AudioHandle> = None;
|
||||
loop {
|
||||
let input = tokio::select! {
|
||||
@@ -908,29 +942,6 @@ async fn run(
|
||||
},
|
||||
};
|
||||
let id = match command {
|
||||
Command::SetMytsIdentity(identity) => {
|
||||
// Still no account is no change: every notification restarts
|
||||
// handshakes and sends `updatemytsid` on every connection. Any
|
||||
// account is (each connection's proof is signed anew).
|
||||
myts_identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetMytsData(data) => {
|
||||
myts_data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetAudioSettings(new) => {
|
||||
settings = (*new).clone();
|
||||
for s in sessions.values() {
|
||||
@@ -1006,8 +1017,7 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
link.clone(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1086,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::DeleteOfflineMessage { session, .. }
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
@@ -1111,3 +1119,21 @@ fn command_session(command: &Command) -> SessionId {
|
||||
fn one_rustls_crypto_provider() {
|
||||
let _ = rustls::ClientConfig::builder();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackendInfo;
|
||||
|
||||
#[test]
|
||||
fn a_backend_reads_as_its_product_and_version() {
|
||||
let backend = |product: &str, version: &str| BackendInfo {
|
||||
product: product.into(),
|
||||
version: version.into(),
|
||||
};
|
||||
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
|
||||
// Not recognised: the version string alone, or nothing.
|
||||
assert_eq!(backend("", "custom 9").label(), "custom 9");
|
||||
assert_eq!(BackendInfo::default().label(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! The registry of the engine's connectors, by address scheme.
|
||||
//!
|
||||
//! A session's voice source is a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
|
||||
//! scheme of the address: [`Backends`] holds the plain connectors of
|
||||
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
|
||||
//! later, `FakeConnector` in tests) and the in-process connectors, which
|
||||
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
|
||||
//! stream task, [`StreamPort`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{
|
||||
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
|
||||
HostTrust, SessionError,
|
||||
};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::LinkCtx;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd};
|
||||
use crate::ts::TsConnector;
|
||||
|
||||
/// The scheme of the TeamSpeak servers a bookmark names without one.
|
||||
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
|
||||
|
||||
/// What comes back from the stream task of a connection that has one.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StreamEvent {
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame of a watched stream, for the audio thread.
|
||||
Audio { stream: String, time: u64, data: Arc<[u8]> },
|
||||
/// A watched stream ended.
|
||||
AudioEnded(String),
|
||||
}
|
||||
|
||||
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
|
||||
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
|
||||
/// and not v1 entities yet, so the commands go to the connection's stream
|
||||
/// task and its events come back here.
|
||||
pub(crate) struct StreamPort {
|
||||
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
|
||||
/// What the stream task reports.
|
||||
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
}
|
||||
|
||||
impl StreamPort {
|
||||
/// A port whose commands go to `send`.
|
||||
pub(crate) fn new(
|
||||
send: impl Fn(StreamCmd) + Send + Sync + 'static,
|
||||
events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
) -> Self {
|
||||
Self { send: Box::new(send), events }
|
||||
}
|
||||
|
||||
/// Give the stream task a command.
|
||||
pub(crate) fn send(&self, cmd: StreamCmd) {
|
||||
(self.send)(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// What an in-process backend needs besides the connect parameters.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LocalCtx {
|
||||
/// The session's side of the engine: its id, event bus, frames and
|
||||
/// settings.
|
||||
pub(crate) link: LinkCtx,
|
||||
/// Open the audio devices (the stream task plays what streams carry).
|
||||
pub(crate) audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub(crate) stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl LocalCtx {
|
||||
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
|
||||
Self { link, audio, stream_peer }
|
||||
}
|
||||
|
||||
/// A context for a connection made outside an engine (a test or a tool
|
||||
/// that calls a connector itself): a session of its own that nobody
|
||||
/// listens to.
|
||||
pub(crate) fn standalone() -> Self {
|
||||
let (events, _) = tokio::sync::broadcast::channel(16);
|
||||
let (frames, _) = tokio::sync::broadcast::channel(16);
|
||||
let link = LinkCtx {
|
||||
session: 0,
|
||||
events,
|
||||
frames,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
|
||||
};
|
||||
Self { link, audio: false, stream_peer: PeerConfig::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection an in-process connector made.
|
||||
pub(crate) struct LocalConnected {
|
||||
pub(crate) connected: Connected,
|
||||
/// The stream task's port, for a backend that runs one.
|
||||
pub(crate) streams: Option<StreamPort>,
|
||||
}
|
||||
|
||||
/// A connector that runs in this process and can use the engine's context
|
||||
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
|
||||
pub(crate) trait LocalConnector: Connector {
|
||||
/// Whether this connector serves addresses of `scheme`. By default, the
|
||||
/// schemes it names.
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.schemes().contains(&scheme)
|
||||
}
|
||||
|
||||
/// Connect with the engine's context.
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>>;
|
||||
}
|
||||
|
||||
/// The connectors of an engine, found by the scheme of an address.
|
||||
///
|
||||
/// A scheme served by an in-process connector goes to it, one served by a
|
||||
/// plain connector ([`Backends::register`]) to that. An address without a
|
||||
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
|
||||
#[derive(Clone)]
|
||||
pub struct Backends {
|
||||
connectors: Connectors,
|
||||
locals: Vec<Arc<dyn LocalConnector>>,
|
||||
account: Option<Arc<dyn AccountAgent>>,
|
||||
/// The connections' trust in hosts that are neither valid nor pinned.
|
||||
trust: Option<Arc<dyn HostTrust>>,
|
||||
}
|
||||
|
||||
impl Default for Backends {
|
||||
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
|
||||
/// `teamspeak://`, and an address without a scheme).
|
||||
fn default() -> Self {
|
||||
let mut backends = Self::empty();
|
||||
backends.register_teamspeak(TsConnector::new());
|
||||
backends
|
||||
}
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
|
||||
pub fn empty() -> Self {
|
||||
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
|
||||
}
|
||||
|
||||
/// Register a connector for the schemes it names.
|
||||
pub fn register(&mut self, connector: Arc<dyn Connector>) {
|
||||
self.connectors.register(connector);
|
||||
}
|
||||
|
||||
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
|
||||
self.locals.push(connector);
|
||||
}
|
||||
|
||||
/// Register the TeamSpeak connector for the schemes it names
|
||||
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
|
||||
/// [`Backends::default`] registers one of its own; register yours to keep a
|
||||
/// clone of it, whose [`TsConnector::set_myts_identity`] and
|
||||
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
|
||||
/// connection it makes.
|
||||
pub fn register_teamspeak(&mut self, connector: TsConnector) {
|
||||
self.register_local(Arc::new(connector));
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
|
||||
/// The account agent, if one was set ([`Backends::set_account`]).
|
||||
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
|
||||
self.account.clone()
|
||||
}
|
||||
|
||||
/// Decide about hosts that are neither valid nor pinned. The default
|
||||
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
|
||||
/// key.
|
||||
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
|
||||
self.trust = trust;
|
||||
}
|
||||
|
||||
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
|
||||
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
|
||||
}
|
||||
|
||||
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
|
||||
/// is none.
|
||||
pub(crate) fn scheme(address: &str) -> String {
|
||||
match address.split_once("://") {
|
||||
Some((scheme, _)) => scheme.to_ascii_lowercase(),
|
||||
None => TEAMSPEAK_SCHEME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a session to `params.address` with the connector of its scheme.
|
||||
pub(crate) fn connect(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
let scheme = Self::scheme(¶ms.address);
|
||||
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
|
||||
return local.connect_local(params, ctx);
|
||||
}
|
||||
// Not `Connectors::connect`, which names the whole address when none serves it:
|
||||
// the text is shown, and a TeamSpeak link carries a channel password.
|
||||
let Some(connector) = self.connectors.for_address(¶ms.address) else {
|
||||
let shown = without_query(¶ms.address).to_owned();
|
||||
return Box::pin(async move {
|
||||
Err(SessionError::Protocol(format!("no connector for {shown}")))
|
||||
});
|
||||
};
|
||||
let connect = connector.connect(params);
|
||||
Box::pin(async move {
|
||||
let connected = connect.await?;
|
||||
Ok(LocalConnected { connected, streams: None })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An address as it may be shown or logged: without its query and fragment,
|
||||
/// where a link keeps a channel password or a host pin.
|
||||
pub(crate) fn without_query(address: &str) -> &str {
|
||||
address.split(['?', '#']).next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Refuses every host that asks to be trusted.
|
||||
struct RefuseUnknownHosts;
|
||||
|
||||
impl HostTrust for RefuseUnknownHosts {
|
||||
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
|
||||
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
|
||||
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
|
||||
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_shown_without_its_secrets() {
|
||||
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
|
||||
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
|
||||
assert_eq!(without_query("host:9987"), "host:9987");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! What a session hands the connector of an address: the `ConnectParams` of
|
||||
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
|
||||
//!
|
||||
//! The options are the engine's own, and a connector reads them back: the
|
||||
//! address is the link of the bookmark (a `ts3server://` link for a
|
||||
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
|
||||
//! the server password and the privilege key are in the hello, the identity
|
||||
//! is the credential. What v1 has no field for yet (the channel to join and
|
||||
//! its password, the client version a TeamSpeak server is shown) rides in
|
||||
//! the address, as parameters of the link.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
|
||||
use voelin_model::Link;
|
||||
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
|
||||
use voelin_proto::v1;
|
||||
|
||||
use super::{Backends, VoiceOptions, without_query};
|
||||
|
||||
/// The link parameter that carries the client version to impersonate: the
|
||||
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
|
||||
/// The connector for TeamSpeak resolves it; other connectors never read it.
|
||||
pub(crate) const VERSION_PARAM: &str = "client_version";
|
||||
|
||||
/// The connect parameters of a connection, from the options the session was
|
||||
/// asked to connect with.
|
||||
///
|
||||
/// The address is the link of the bookmark (the channel and its password
|
||||
/// ride in it, and so does the client version to claim, until v1 has fields
|
||||
/// for them), the server password is `Hello.password` and the privilege key
|
||||
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
|
||||
/// account is used yet.
|
||||
///
|
||||
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
|
||||
/// an identity that is of no kind a connector can use.
|
||||
pub(crate) fn connect_params(
|
||||
options: &VoiceOptions,
|
||||
media: Arc<dyn MediaSink>,
|
||||
backends: &Backends,
|
||||
) -> Result<ConnectParams, SessionError> {
|
||||
let hello = v1::Hello {
|
||||
version: 1,
|
||||
client: Some(v1::ClientInfo {
|
||||
name: "Voelin".into(),
|
||||
version: voelin_platform::crash::app_version().to_owned(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
kind: v1::ClientKind::User as i32,
|
||||
}),
|
||||
nickname: options.nickname.clone(),
|
||||
password: options.server_password.clone().unwrap_or_default(),
|
||||
invite_code: options.token.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ConnectParams {
|
||||
address: address_link(options)?,
|
||||
credential: credential(options.identity.as_ref())?,
|
||||
linked: Vec::new(),
|
||||
account: backends.account(),
|
||||
issuer_trust: IssuerTrust::Unknown,
|
||||
hello,
|
||||
host_pin: None,
|
||||
trust: backends.trust(),
|
||||
media,
|
||||
push_capacity: 1024,
|
||||
timeout: Duration::from_secs(35),
|
||||
})
|
||||
}
|
||||
|
||||
/// The credential of an identity (`docs/session-seam.md` section 7). A
|
||||
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
|
||||
/// an empty one, for which the TeamSpeak connector makes an identity up (the
|
||||
/// protocol's convention for "generate one", follow-up P11); a Voelin key
|
||||
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
|
||||
/// it would be that same empty blob and be taken for the request to make one
|
||||
/// up, which only the absence of an identity may be.
|
||||
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
|
||||
let Some(blob) = identity else {
|
||||
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
|
||||
};
|
||||
if blob.is_teamspeak() {
|
||||
if blob.json.trim().is_empty() {
|
||||
return Err(SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is empty".into(),
|
||||
));
|
||||
}
|
||||
let json = Bytes::copy_from_slice(blob.json.as_bytes());
|
||||
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
|
||||
} else if blob.is_voelin() {
|
||||
let key = blob.voelin_key().map_err(|e| {
|
||||
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
|
||||
})?;
|
||||
Ok(Credential::Voelin(Arc::new(key)))
|
||||
} else {
|
||||
Err(SessionError::Protocol(format!(
|
||||
"an identity of kind {:?} cannot be used to connect",
|
||||
blob.kind
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ts3server://` link of the options' address, with the channel to join
|
||||
/// and the client version to claim.
|
||||
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
|
||||
let mut link = match Link::parse(&options.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
|
||||
_ if !options.address.contains("://") => bookmark(&options.address)?,
|
||||
// Some other scheme: as given, for the connector of that scheme.
|
||||
_ => return Ok(options.address.clone()),
|
||||
};
|
||||
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
|
||||
link.channel_password =
|
||||
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
|
||||
let mut url = link.to_url();
|
||||
if let Some(spec) = &options.client_version {
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(VERSION_PARAM);
|
||||
url.push('=');
|
||||
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// The link to a bookmark's `host[:port]`.
|
||||
///
|
||||
/// A link cannot say everything an address can: it drops a port that is no
|
||||
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
|
||||
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
|
||||
/// `%` (so that a `?` in the host would hide the channel behind the next
|
||||
/// one). The TeamSpeak library refuses such an address when it resolves it;
|
||||
/// so does this, in words, instead of connecting to something else.
|
||||
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
|
||||
let address = address.trim();
|
||||
// Without the query: a link keeps secrets in it.
|
||||
let shown = without_query(address);
|
||||
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
|
||||
if address.is_empty()
|
||||
|| address
|
||||
.chars()
|
||||
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
|
||||
{
|
||||
return Err(not_an_address());
|
||||
}
|
||||
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
|
||||
// colon (more colons are an IPv6 address without a port).
|
||||
let port = if let Some(rest) = address.strip_prefix('[') {
|
||||
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
|
||||
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
|
||||
} else {
|
||||
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
|
||||
};
|
||||
if let Some(port) = port
|
||||
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
|
||||
{
|
||||
return Err(SessionError::Protocol(format!(
|
||||
"the port in {shown} is not a number from 1 to 65535"
|
||||
)));
|
||||
}
|
||||
Ok(voelin_model::ServerLink::new(address))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use voelin_identity::IdentityKey;
|
||||
|
||||
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty())
|
||||
}
|
||||
|
||||
/// The identity of the options is the credential of its kind: a TeamSpeak
|
||||
/// identity as the JSON the key store keeps, none as the empty blob a
|
||||
/// connector makes an identity up for, a Voelin key as its signer.
|
||||
#[test]
|
||||
fn an_identity_is_the_credential_of_its_kind() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
let none = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&none.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
|
||||
let sent = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&sent.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
|
||||
));
|
||||
|
||||
let key = IdentityKey::generate().unwrap();
|
||||
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
|
||||
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
|
||||
panic!("a Voelin credential")
|
||||
};
|
||||
assert_eq!(signer.public_key(), key.public_key());
|
||||
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
|
||||
|
||||
// A Voelin blob whose key cannot be read, and a kind that connects to
|
||||
// nothing: refused in words, without the JSON.
|
||||
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert!(
|
||||
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
|
||||
);
|
||||
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
|
||||
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
|
||||
/// it is refused here instead of being sent as that request.
|
||||
#[test]
|
||||
fn a_teamspeak_identity_without_json_is_refused() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
for json in ["", " \n\t"] {
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else {
|
||||
panic!("a refusal for {json:?}")
|
||||
};
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
|
||||
}
|
||||
// No identity at all is the request to make one up, as before.
|
||||
options.identity = None;
|
||||
assert!(matches!(
|
||||
params(&options).unwrap().credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
}
|
||||
|
||||
/// The client version spec rides the link as it was typed, whatever it
|
||||
/// holds, and only for an address that is a TeamSpeak bookmark or link.
|
||||
#[test]
|
||||
fn the_client_version_spec_rides_the_link_unchanged() {
|
||||
let spec = |address: &str, spec: &str| {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.client_version = Some(spec.into());
|
||||
params(&options).unwrap().address
|
||||
};
|
||||
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
|
||||
let (_, query) = address.split_once('?').unwrap();
|
||||
let text = query
|
||||
.split('&')
|
||||
.find_map(|pair| pair.strip_prefix("client_version="))
|
||||
.expect("the parameter");
|
||||
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
|
||||
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
|
||||
// Another scheme is left as it is: its connector has no use for a TeamSpeak
|
||||
// client's version.
|
||||
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
|
||||
// No spec, no parameter.
|
||||
let options = VoiceOptions::new("ts.example.com", "nick");
|
||||
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
|
||||
//! connection the test asks for to the test, which plays the server by
|
||||
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
|
||||
//! gives. These are the tests that need the inner link itself:
|
||||
//!
|
||||
//! - the stream commands, which travel on the in-process port of the link
|
||||
//! and which a `voelin_proto::link::Session` has no part in until the
|
||||
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
|
||||
//! - the order in which a reconnect shuts the streams and the old connection
|
||||
//! down, which is the order of the one queue `LinkSession` keeps;
|
||||
//! - a link that keeps talking after the engine replaced its connection,
|
||||
//! which a closed `FakeSession` cannot do on purpose.
|
||||
//!
|
||||
//! (They were integration tests while the inner link was public; it is the
|
||||
//! TeamSpeak module's now, and so are these.)
|
||||
//!
|
||||
//! Presence, chat, the dedup of a message that comes twice, history, transfers
|
||||
//! and the rest of what the engine does with a session are tested on the
|
||||
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
|
||||
//! needs a TeamSpeak server or a TeamSpeak type.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
|
||||
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
|
||||
use crate::settings::Settings;
|
||||
use crate::stream::{StreamCmd, StreamSetup};
|
||||
use crate::ts::ts_session::LinkConnector;
|
||||
use crate::ts::{ConnectOptions, ServerLink};
|
||||
use crate::{
|
||||
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
ServerDetails,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
/// Play `script`, the server's side, in order.
|
||||
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
|
||||
for event in script {
|
||||
self.events.send(event).expect("the session listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// The next command the session gave.
|
||||
async fn cmd(&mut self) -> LinkCmd {
|
||||
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
|
||||
.await
|
||||
.expect("a command in time")
|
||||
.expect("the session keeps the connection")
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands every connection to the test.
|
||||
struct FakeLink {
|
||||
conns: mpsc::UnboundedSender<Conn>,
|
||||
}
|
||||
|
||||
impl FakeLink {
|
||||
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
|
||||
let (conns, rx) = mpsc::unbounded_channel();
|
||||
(Self { conns }, rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for FakeLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
_options: ConnectOptions,
|
||||
_ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
let _ = self.conns.send(Conn { cmds, events });
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION: SessionId = 1;
|
||||
const SERVER_UID: &str = "fake-server=";
|
||||
const ME: u16 = 7;
|
||||
const ME_UID: &str = "me=";
|
||||
const LOBBY: ChannelId = 1;
|
||||
const GAMES: ChannelId = 2;
|
||||
|
||||
struct Harness {
|
||||
engine: Engine,
|
||||
events: broadcast::Receiver<Event>,
|
||||
conns: mpsc::UnboundedReceiver<Conn>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn start() -> Self {
|
||||
let (link, conns) = FakeLink::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let events = engine.subscribe();
|
||||
Self { engine, events, conns }
|
||||
}
|
||||
|
||||
/// Ask for a voice connection and take it from the link.
|
||||
async fn connect(&mut self) -> Conn {
|
||||
let options = VoiceOptions::new("fake.test:9987", "tester");
|
||||
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
||||
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
|
||||
.await
|
||||
.expect("the session spawns the link")
|
||||
.expect("the link lives")
|
||||
}
|
||||
|
||||
/// The next event `f` picks, skipping the others.
|
||||
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// The next state of the session that `ok` accepts.
|
||||
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
|
||||
self.next(|e| match e {
|
||||
Event::State { state, .. } if ok(&state) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The next live chat message.
|
||||
async fn chat(&mut self) -> ChatMessage {
|
||||
self.next(|e| match e {
|
||||
Event::Chat { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
|
||||
}
|
||||
|
||||
fn capabilities(streams: bool) -> Capabilities {
|
||||
Capabilities { streams, file_transfer: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn backend() -> BackendInfo {
|
||||
BackendInfo { product: "Fake".into(), version: "1.2".into() }
|
||||
}
|
||||
|
||||
fn connected(streams: bool) -> LinkEvent {
|
||||
LinkEvent::Connected {
|
||||
name: "Fake Server".into(),
|
||||
backend: backend(),
|
||||
capabilities: capabilities(streams),
|
||||
own_client: ME,
|
||||
server_uid: SERVER_UID.into(),
|
||||
own_uid: Some(ME_UID.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client as a TeamSpeak link reports one: with its database id, and not
|
||||
/// talking (who talks comes from the media, which the session derives).
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
talking: Some(false),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel. The shape is
|
||||
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
||||
/// server is named and has its unique id.
|
||||
fn presence() -> Presence {
|
||||
let channel =
|
||||
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.server = ServerDetails {
|
||||
name: "Fake Server".into(),
|
||||
uid: Some(SERVER_UID.into()),
|
||||
version: backend().version,
|
||||
..Default::default()
|
||||
};
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
||||
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
||||
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
presence
|
||||
}
|
||||
|
||||
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
author_name: author.into(),
|
||||
author_uid: Some(format!("{author}=")),
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream commands reach a link that has streams in its capabilities, and
|
||||
/// end with the connection; a link without them is spared. (The rest of what
|
||||
/// the user asks for is checked on the fake host in `session_fake.rs`.)
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stream_commands_reach_a_link_with_streams() {
|
||||
let mut h = Harness::start();
|
||||
let mut conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let engine = h.engine.clone();
|
||||
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(error.contains("streams"), "{error}");
|
||||
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
|
||||
|
||||
// A link with streams: stream commands go to it, and end with the connection.
|
||||
let mut with_streams = {
|
||||
let link_engine = h.engine.clone();
|
||||
link_engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
|
||||
});
|
||||
h.conns.recv().await.expect("the second connection")
|
||||
};
|
||||
// The replaced connection is told to go.
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
|
||||
with_streams.play([connected(true)]);
|
||||
h.next(|e| match e {
|
||||
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// A connection with streams is given the (empty) stream directory first.
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
|
||||
panic!("a stream start")
|
||||
};
|
||||
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
|
||||
engine.send(Command::StopStream { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// A reconnect ends the streams of the connection it replaces through that
|
||||
/// connection, before the connection itself: the old link is given
|
||||
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
|
||||
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
|
||||
/// there) relies on this order for the streams to hear of their end.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(true),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
|
||||
// Connecting again replaces the connection.
|
||||
let _new = h.connect().await;
|
||||
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
|
||||
panic!("the streams end first")
|
||||
};
|
||||
assert_eq!(reason, "voice reconnecting");
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// Events of a connection the session replaced do not reach it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_replaced_connection_is_ignored() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let new = h.connect().await;
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
// The old connection winds down, and says more than it should.
|
||||
let mut stale = presence();
|
||||
stale.clients.insert(10, client(10, "ghost", LOBBY));
|
||||
old.play([
|
||||
LinkEvent::Presence(Box::new(stale)),
|
||||
LinkEvent::Chat(message("ghost", "boo", now_ms())),
|
||||
LinkEvent::Disconnected(None),
|
||||
]);
|
||||
let mut fresh = presence();
|
||||
fresh.clients.remove(&9);
|
||||
// A link that says we are in the lobby shows us in the lobby.
|
||||
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
||||
new.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(fresh.clone())),
|
||||
LinkEvent::OwnChannel(LOBBY),
|
||||
]);
|
||||
// Only the new connection's presence is shown (nobody else has 2 clients).
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
|
||||
Some(presence)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, fresh);
|
||||
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
||||
// Channel chat reaches the channel we are in (the lobby, now).
|
||||
new.play([LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Channel(LOBBY),
|
||||
..message("alice", "hello", now_ms())
|
||||
})]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! The engine's side of the seam against the protocol repository's fake host
|
||||
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
|
||||
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
|
||||
//! suite run against the session the engine's registry hands over.
|
||||
//!
|
||||
//! The tests that need only the engine's public API are in
|
||||
//! `tests/session_fake.rs`; these need what is private to the crate: the
|
||||
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
|
||||
//! the registry's `connect` and the context of a connector called outside an
|
||||
//! engine.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{
|
||||
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
|
||||
};
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
|
||||
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
|
||||
const ALICE: u32 = 50;
|
||||
const ALICE_SLOT: u32 = 90;
|
||||
const BOB: u32 = 51;
|
||||
const BOB_SLOT: u32 = 91;
|
||||
|
||||
fn put(connector: &FakeConnector, kind: Kind) {
|
||||
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
|
||||
}
|
||||
|
||||
/// A host with one server, a lobby, and alice and bob talking in it.
|
||||
fn host() -> FakeConnector {
|
||||
let connector = FakeConnector::new();
|
||||
put(
|
||||
&connector,
|
||||
Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: 10,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: "Lobby".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
for (user, participant, slot, name) in
|
||||
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
|
||||
{
|
||||
put(
|
||||
&connector,
|
||||
Kind::User(v1::User {
|
||||
id: user,
|
||||
uid: vec![user as u8; 32].into(),
|
||||
uid_kind: v1::IdKind::Voelin as i32,
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: 1,
|
||||
participant_id: participant,
|
||||
user_id: user,
|
||||
channel_id: 10,
|
||||
slot,
|
||||
nick: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
connector
|
||||
}
|
||||
|
||||
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
|
||||
struct HostRig {
|
||||
handle: FakeHandle,
|
||||
cmds: mpsc::UnboundedSender<LinkCmd>,
|
||||
events: mpsc::UnboundedReceiver<LinkEvent>,
|
||||
/// Our participant and voice slot, as the host gave them.
|
||||
own_client: u16,
|
||||
own_slot: u32,
|
||||
/// The clients the link told started talking, in order.
|
||||
talking: Vec<u16>,
|
||||
}
|
||||
|
||||
/// The next event `f` picks from `events`, skipping the others.
|
||||
async fn event_of<T>(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
mut f: impl FnMut(LinkEvent) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(WAIT, async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("the link lives")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
impl HostRig {
|
||||
async fn connect() -> Self {
|
||||
let connector = host();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let link = SessionLink::new(backends);
|
||||
let (cmds, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, mut events) = mpsc::unbounded_channel();
|
||||
let ctx = LocalCtx::standalone().link;
|
||||
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
|
||||
let own_client = event_of(&mut events, |e| match e {
|
||||
LinkEvent::Connected { own_client, .. } => Some(own_client),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
|
||||
let own_slot = connector
|
||||
.host()
|
||||
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind? {
|
||||
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host seated us in voice");
|
||||
let handle = connector.last_session().expect("the connector made a session");
|
||||
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
|
||||
}
|
||||
|
||||
/// The next voice packet the audio thread would get; who started to talk on
|
||||
/// the way is kept in `talking`.
|
||||
async fn audio(&mut self) -> VoicePacket {
|
||||
let talking = &mut self.talking;
|
||||
event_of(&mut self.events, |e| match e {
|
||||
LinkEvent::Talking { client, talking: true } => {
|
||||
talking.push(client);
|
||||
None
|
||||
}
|
||||
LinkEvent::Audio(packet) => Some(packet),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn give(&self, cmd: LinkCmd) {
|
||||
self.cmds.send(cmd).expect("the link listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
|
||||
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
|
||||
let flow = FlowId::new(slot, sub);
|
||||
let mut out = bytes::BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
|
||||
.write(flow, &mut out)
|
||||
.expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
|
||||
/// every packet, the timestamp advances by the duration of the previous one,
|
||||
/// the marker is on the first packet of a spurt, the end of a spurt is an
|
||||
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
|
||||
let rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back; this test looks at what left.
|
||||
rig.handle.set_loopback(false);
|
||||
for n in 1..=3 {
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
|
||||
}
|
||||
rig.give(LinkCmd::Audio(voice(&[])));
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
|
||||
|
||||
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
|
||||
let sent = rig.handle.sent_media();
|
||||
let seen: Vec<_> = sent
|
||||
.iter()
|
||||
.map(|(class, packet)| {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
assert_eq!(*class, MediaClass::Voice);
|
||||
assert_eq!(packet.flow, flow);
|
||||
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
|
||||
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
|
||||
})
|
||||
.collect();
|
||||
let ticks = OPUS_20_MS_TICKS;
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
|
||||
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
|
||||
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
|
||||
// The end of the spurt: no payload, no marker, once.
|
||||
(3, false, 3 * ticks, vec![]),
|
||||
// The next spurt marks its first packet again.
|
||||
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The RTP of other slots becomes the packets of the audio thread: the talker
|
||||
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
|
||||
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
|
||||
/// slot the host told about is dropped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
let handle = rig.handle.clone();
|
||||
|
||||
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
|
||||
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
|
||||
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
|
||||
handle.inject_media(MediaPacket {
|
||||
flow: FlowId::FEEDBACK,
|
||||
rtp: bytes::Bytes::from_static(&[1, 2]),
|
||||
});
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
|
||||
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
|
||||
);
|
||||
|
||||
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
|
||||
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
|
||||
(BOB as u16, 6, VoiceCodec::Music, true)
|
||||
);
|
||||
|
||||
// Alice stops: an empty payload.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
|
||||
|
||||
// Who talks comes from the same packets: alice started, then bob, once each
|
||||
// (the slot nobody has started nobody).
|
||||
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
|
||||
}
|
||||
|
||||
/// A host whose session loops our own voice back (the fake one does, so that
|
||||
/// the conformance suite can see media move) does not make the engine play us
|
||||
/// our own voice or show us as talking: the engine never plays itself.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_own_voice_coming_back_is_not_played_back() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back into the sink (the default).
|
||||
rig.give(LinkCmd::Audio(voice(&MONO)));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
|
||||
// A packet of alice behind it: when this one is out, ours has been through.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
|
||||
let own = rig.own_client;
|
||||
let mut heard = Vec::new();
|
||||
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
|
||||
heard.push(rig.audio().await.talker.0);
|
||||
}
|
||||
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
|
||||
}
|
||||
|
||||
/// The link conformance suite of the protocol repository against the session
|
||||
/// the engine's registry hands over: the registry adds nothing to a plain
|
||||
/// connector's session (`Backends::connect` returns it untouched), so the 17
|
||||
/// cases pass as they do in the protocol repository, none skipped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
async fn through_the_registry() -> Fixture {
|
||||
let connector = FakeConnector::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let (params, media) = connect_params("fake://conformance");
|
||||
let local = backends
|
||||
.connect(params, LocalCtx::standalone())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
|
||||
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
|
||||
assert!(local.streams.is_none(), "a plain connector has no stream port");
|
||||
let backend = connector.last_session().expect("the connector made a session");
|
||||
// The session is the connector's own, so a request id means the same to both.
|
||||
Fixture {
|
||||
shared_request_ids: true,
|
||||
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
|
||||
}
|
||||
}
|
||||
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 v0.2.0 has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
report.cases
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
||||
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
||||
//! the audio thread's packets, and who is talking from the media.
|
||||
//!
|
||||
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
||||
//! thread speaks; this is the framing in the v1 media codec
|
||||
//! (`voelin_proto::media`, protocol section 6).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
/// A talker is silent after this long without a packet.
|
||||
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
||||
/// timestamp starts at 0 and advances by the duration of the previous
|
||||
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
||||
/// spurt is a packet with an empty payload, sent once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Uplink {
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
/// The ticks the last voice packet spans.
|
||||
ticks: u32,
|
||||
in_spurt: bool,
|
||||
}
|
||||
|
||||
impl Uplink {
|
||||
/// `voice` as the RTP packet of our voice slot.
|
||||
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
||||
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
||||
// The previous packet's duration has passed.
|
||||
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
||||
let end = voice.is_end();
|
||||
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
||||
header.marker = !end && !self.in_spurt;
|
||||
self.ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.in_spurt = !end;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(&voice.payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of some slot, taken from its RTP.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Incoming {
|
||||
pub(crate) slot: u32,
|
||||
/// Sent on a whisper sub-flow (1 to 6).
|
||||
pub(crate) whisper: bool,
|
||||
pub(crate) sequence: u16,
|
||||
pub(crate) codec: VoiceCodec,
|
||||
/// Empty: the spurt ends.
|
||||
pub(crate) payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Parse a media packet. `None` for what is not the voice of a slot:
|
||||
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
||||
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
||||
if !packet.flow.is_media() {
|
||||
return None;
|
||||
}
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(Incoming {
|
||||
slot: packet.flow.slot(),
|
||||
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
||||
.contains(&packet.flow.sub()),
|
||||
sequence: view.sequence(),
|
||||
codec,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The packet for the audio thread, from `talker`.
|
||||
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: self.sequence,
|
||||
codec: self.codec,
|
||||
whisper: self.whisper,
|
||||
payload: self.payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is talking: derived from the media (protocol section 6.4). A talker
|
||||
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
|
||||
///
|
||||
/// A host can also say that someone talks whose voice it does not carry as
|
||||
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
|
||||
/// that is a hint, which holds until the host says it is over.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TalkTracker {
|
||||
last: HashMap<u16, Instant>,
|
||||
hinted: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl TalkTracker {
|
||||
/// A packet of `client` arrived; whether this starts its talking.
|
||||
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
self.last.insert(client, now);
|
||||
!was
|
||||
}
|
||||
|
||||
/// The host says `client` talks or has stopped; whether this changes
|
||||
/// whether it is talking.
|
||||
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
if talking {
|
||||
self.hinted.insert(client);
|
||||
} else {
|
||||
self.hinted.remove(&client);
|
||||
}
|
||||
was != self.is_talking(client)
|
||||
}
|
||||
|
||||
/// Forget the hints about clients `present` does not hold any more: a
|
||||
/// client that left cannot say it stopped.
|
||||
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
|
||||
self.hinted.retain(|client| present(*client));
|
||||
}
|
||||
|
||||
/// The talkers that have been silent long enough, no longer talking.
|
||||
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
||||
let mut silent: Vec<u16> = self
|
||||
.last
|
||||
.iter()
|
||||
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
||||
.map(|(client, _)| *client)
|
||||
.collect();
|
||||
silent.sort_unstable();
|
||||
for client in &silent {
|
||||
self.last.remove(client);
|
||||
}
|
||||
silent.retain(|client| !self.hinted.contains(client));
|
||||
silent
|
||||
}
|
||||
|
||||
pub(crate) fn is_talking(&self, client: u16) -> bool {
|
||||
self.last.contains_key(&client) || self.hinted.contains(&client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 20 ms of CELT, mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_is_sequenced_stamped_and_marked() {
|
||||
let mut up = Uplink::default();
|
||||
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
||||
let (a, b) = (view(&first), view(&second));
|
||||
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
||||
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
||||
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
||||
assert_eq!(a.payload(), OPUS_20_MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
||||
let mut up = Uplink::default();
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let end = up.frame(8, &voice(&[])).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
assert_eq!(view(&end).sequence(), 1);
|
||||
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
assert_eq!(view(&next).sequence(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sequence_wraps() {
|
||||
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!(view(&wrapped).sequence(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
||||
let flow = FlowId::new(9, 0);
|
||||
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
||||
header.marker = true;
|
||||
let mut rtp = BytesMut::new();
|
||||
header.write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(&OPUS_20_MS);
|
||||
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
||||
let got = Incoming::parse(&packet).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
Incoming {
|
||||
slot: 9,
|
||||
whisper: false,
|
||||
sequence: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
payload: OPUS_20_MS.to_vec()
|
||||
}
|
||||
);
|
||||
let voice = got.voice(8);
|
||||
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_stereo_ends_and_what_is_no_voice() {
|
||||
let packet = |flow: FlowId, payload: &[u8]| {
|
||||
let mut rtp = BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: rtp.freeze() }
|
||||
};
|
||||
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
||||
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
||||
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
assert_eq!(
|
||||
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
||||
VoiceCodec::Music
|
||||
);
|
||||
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
||||
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
||||
// Feedback and probes are no voice.
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(talk.heard(8, t0));
|
||||
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
||||
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
||||
assert!(talk.is_talking(8));
|
||||
// 399 ms after 8's last packet: still talking.
|
||||
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
||||
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
||||
// A packet after the silence starts it again.
|
||||
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
// A talker whose voice is no media: on, and no silence ends it.
|
||||
assert!(talk.hint(8, true));
|
||||
assert!(!talk.hint(8, true), "already talking");
|
||||
assert!(talk.is_talking(8));
|
||||
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
|
||||
assert!(talk.hint(8, false));
|
||||
assert!(!talk.is_talking(8));
|
||||
// A talker with media that the host also names: the media ends it, when
|
||||
// the host has said it is over (in either order).
|
||||
assert!(talk.heard(9, t0));
|
||||
assert!(!talk.hint(9, true), "heard already");
|
||||
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
|
||||
assert!(talk.is_talking(9));
|
||||
assert!(talk.hint(9, false));
|
||||
assert!(!talk.is_talking(9));
|
||||
assert!(talk.heard(10, t0));
|
||||
assert!(!talk.hint(10, false), "the media goes on");
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
|
||||
// A hint about somebody who is gone is forgotten.
|
||||
assert!(talk.hint(11, true));
|
||||
talk.retain_hints(|client| client != 11);
|
||||
assert!(!talk.is_talking(11));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The engine's seam to the server its voice source talks to.
|
||||
//!
|
||||
//! A session merges up to three sources (voice, gateway, query). The *voice*
|
||||
//! source is the connection that is visible on the server, can talk and
|
||||
//! carries chat, files, pokes, offline messages and streams. The engine holds
|
||||
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
|
||||
//! protocol repository, and knows nothing else of the server software behind
|
||||
//! it: which backend makes the `Session` is the scheme of the address, and
|
||||
//! [`Backends`] is the registry of connectors by scheme
|
||||
//! ([`Backends::default`] has the TeamSpeak one,
|
||||
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
|
||||
//! another). [`VoiceOptions`] says what to connect to and as whom.
|
||||
//!
|
||||
//! Inside the crate `session.rs` merges and routes, and an adapter below it
|
||||
//! turns what it asks into `Session` calls and what the `Session` pushes into
|
||||
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
|
||||
//! `docs/session-seam.md` describes the mapping row by row.
|
||||
|
||||
mod backends;
|
||||
mod connect;
|
||||
#[cfg(test)]
|
||||
mod fake_link_tests;
|
||||
#[cfg(test)]
|
||||
mod fake_tests;
|
||||
pub(crate) mod media;
|
||||
pub(crate) mod project;
|
||||
mod session_link;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use backends::Backends;
|
||||
pub(crate) use backends::{
|
||||
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
|
||||
};
|
||||
pub(crate) use connect::{VERSION_PARAM, connect_params};
|
||||
pub(crate) use session_link::SessionLink;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::{broadcast, oneshot};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use crate::files::{Report, RequestId, Sink, TransferId};
|
||||
use crate::settings::SharedSettings;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
|
||||
use crate::{BackendInfo, Event, SessionId};
|
||||
|
||||
/// What a voice connection needs to know: the server, who to be, where to
|
||||
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
|
||||
///
|
||||
/// Nothing in it belongs to one kind of server: what a connector needs of it
|
||||
/// that is its own (a TeamSpeak identity, the client version to claim) is in
|
||||
/// the `identity` blob and the `client_version` spec, which the connector of
|
||||
/// the address reads.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoiceOptions {
|
||||
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
|
||||
/// 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
|
||||
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
|
||||
/// connection generates an identity, which a server then knows as a new
|
||||
/// client).
|
||||
pub identity: Option<IdentityBlob>,
|
||||
/// The client version a TeamSpeak server is shown, as a spec for
|
||||
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
|
||||
/// `<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>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl VoiceOptions {
|
||||
/// Options for `address` and `nickname`; everything else is left to the
|
||||
/// connector.
|
||||
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine gives a link besides the options: where the connection
|
||||
/// answers the requests the session need not see, and what it shares with
|
||||
/// the session's other parts.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkCtx {
|
||||
pub(crate) session: SessionId,
|
||||
pub(crate) events: broadcast::Sender<Event>,
|
||||
/// The frames of watched streams (kept off the event bus).
|
||||
pub(crate) frames: broadcast::Sender<StreamFrame>,
|
||||
pub(crate) settings: SharedSettings,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub(crate) fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub(crate) fn emit(&self, event: Event) {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
|
||||
self.emit(Event::RequestDone { session: self.session, request, result });
|
||||
}
|
||||
}
|
||||
|
||||
/// A file on the server: channel, its password, path.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A boxed stream of bytes to read: the body of a file the server sends.
|
||||
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
|
||||
|
||||
/// A connection that can be read and written: a file transfer connection.
|
||||
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
|
||||
|
||||
/// A boxed [`Duplex`].
|
||||
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub(crate) enum LinkCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
Move(ChannelId, Option<String>),
|
||||
SetInputMuted(bool),
|
||||
SetOutputMuted(bool),
|
||||
/// An encoded voice frame from the audio thread.
|
||||
Audio(EncodedVoice),
|
||||
/// A stream command; the link answers on the event bus. Only sent while
|
||||
/// the connection's capabilities include streams.
|
||||
Stream(StreamCmd),
|
||||
Poke {
|
||||
client: u16,
|
||||
message: String,
|
||||
},
|
||||
ListFiles {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Download `file`; `transfer` if the user can cancel it.
|
||||
Download {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
sink: Sink,
|
||||
report: Report,
|
||||
},
|
||||
Upload {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
from: PathBuf,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
report: Report,
|
||||
},
|
||||
CancelTransfer(TransferId),
|
||||
/// Open a file of the server for reading, from `offset`: the transfer
|
||||
/// connection itself, and the file's size in all, once the server has
|
||||
/// agreed (the text of the failure otherwise). The engine copies the
|
||||
/// bytes, reports the progress and cancels by dropping the connection, so
|
||||
/// this does not use [`LinkCmd::Download`]'s sink and report.
|
||||
OpenRead {
|
||||
file: Remote,
|
||||
offset: u64,
|
||||
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
|
||||
},
|
||||
/// Open a file of the server for writing: the transfer connection and the
|
||||
/// position the server wants the bytes from (the size it already has, if
|
||||
/// `resume`). The engine writes the bytes and ends the connection.
|
||||
OpenWrite {
|
||||
file: Remote,
|
||||
/// The file's size in all.
|
||||
size: u64,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
|
||||
},
|
||||
DeleteFiles {
|
||||
/// `None`: best effort, nobody waits for the answer.
|
||||
request: Option<RequestId>,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
paths: Vec<String>,
|
||||
},
|
||||
RenameFile {
|
||||
request: RequestId,
|
||||
from: Remote,
|
||||
to: Remote,
|
||||
},
|
||||
CreateDirectory {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Announce our avatar's hash (empty: no avatar).
|
||||
SetAvatarHash {
|
||||
request: Option<RequestId>,
|
||||
hash: String,
|
||||
},
|
||||
OfflineList {
|
||||
request: RequestId,
|
||||
},
|
||||
OfflineGet {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineAdd {
|
||||
request: RequestId,
|
||||
to_uid: String,
|
||||
subject: String,
|
||||
text: String,
|
||||
},
|
||||
OfflineDelete {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineFlag {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
read: bool,
|
||||
},
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
/// What a connection tells the session.
|
||||
pub(crate) enum LinkEvent {
|
||||
Connected {
|
||||
name: String,
|
||||
/// The server software, and what it can do (the connection knows
|
||||
/// both from the server's version).
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
/// Our client id when the link connected. TeamSpeak's own reconnect gives
|
||||
/// a new one, which is not announced; the engine follows it in the
|
||||
/// snapshots by our unique id.
|
||||
own_client: u16,
|
||||
/// The server's unique id.
|
||||
server_uid: String,
|
||||
/// Our unique id as the server knows it.
|
||||
own_uid: Option<String>,
|
||||
},
|
||||
/// The server's channels and clients as they are now.
|
||||
Presence(Box<Presence>),
|
||||
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
|
||||
/// derives it itself, from our own voice state in the snapshots of the
|
||||
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
|
||||
/// us another client. What an in-process link such as `TsLink` says here only
|
||||
/// tells the TeamSpeak `Session` made of it that a move has arrived.
|
||||
OwnChannel(ChannelId),
|
||||
Chat(ChatMessage),
|
||||
Poke {
|
||||
from: u16,
|
||||
from_uid: Option<String>,
|
||||
from_name: String,
|
||||
message: String,
|
||||
},
|
||||
/// Incoming voice for the audio thread.
|
||||
Audio(VoicePacket),
|
||||
/// Who is talking (on, and off again when it stopped). The engine derives
|
||||
/// it from the media of its `Session` (protocol section 6.4). What an
|
||||
/// in-process link such as `TsLink` says here reaches the engine as a
|
||||
/// speaking hint next to the media: that is what shows the talkers whose
|
||||
/// packets the link does not forward as Opus (Speex, CELT).
|
||||
Talking {
|
||||
client: u16,
|
||||
talking: bool,
|
||||
},
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
|
||||
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
|
||||
/// clock.
|
||||
StreamAudio {
|
||||
stream: String,
|
||||
time: u64,
|
||||
data: Arc<[u8]>,
|
||||
},
|
||||
/// A watched stream ended: its audio leaves the mixer.
|
||||
StreamAudioEnded(String),
|
||||
/// A command failed (the connection stays).
|
||||
Error(String),
|
||||
/// The connection ended; the reason if it was not asked for. Sent once;
|
||||
/// the stream task's closing reports may still follow (see the module
|
||||
/// documentation).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The engine's view of a session's replica, in the client's older model
|
||||
//! (`docs/session-seam.md` section 5.3).
|
||||
//!
|
||||
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
|
||||
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
|
||||
//! [`chat_message`] project the replica into them with
|
||||
//! `voelin_model::replica::convert`, and fix up where that says less than the
|
||||
//! older model does (F1 to F10 of the design). The fix-ups apply the
|
||||
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
|
||||
//! ids it has; they go when the UI reads the replica.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use voelin_model::replica::{Replica, convert};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
|
||||
|
||||
use super::media::TalkTracker;
|
||||
use crate::ts::ts_session::entities::user_uid;
|
||||
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
|
||||
|
||||
/// What the projection needs to know besides the replica.
|
||||
pub(crate) struct View<'a> {
|
||||
pub(crate) replica: &'a Replica,
|
||||
/// The server of the session.
|
||||
pub(crate) server: u64,
|
||||
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
|
||||
/// (channel groups) are undone.
|
||||
pub(crate) teamspeak: bool,
|
||||
/// The version the host said (`Welcome.host.backend.version`).
|
||||
pub(crate) version: &'a str,
|
||||
pub(crate) features: &'a Features,
|
||||
/// Whether the connection has streams (a port, not just the feature).
|
||||
pub(crate) streams: bool,
|
||||
pub(crate) talking: &'a TalkTracker,
|
||||
}
|
||||
|
||||
/// What a `Foreign` of TeamSpeak holds under `key`.
|
||||
fn foreign_value(
|
||||
foreign: Option<&v1::Foreign>,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
|
||||
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
|
||||
}
|
||||
|
||||
/// The server's unique id as the client keys its history and aliases by it:
|
||||
/// the host's without the `ts:` of protocol section 11.2 (F3).
|
||||
pub(crate) fn server_key(uid: &str) -> String {
|
||||
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
|
||||
}
|
||||
|
||||
/// The client's older model of the server (what `LinkEvent::Presence` holds).
|
||||
pub(crate) fn presence(view: &View<'_>) -> Presence {
|
||||
let replica = view.replica;
|
||||
let server = view.server;
|
||||
// F1: only what the older model calls channels.
|
||||
let channels: Vec<&v1::Channel> = replica
|
||||
.channels(server)
|
||||
.filter(|channel| {
|
||||
!matches!(
|
||||
ChannelKind::try_from(channel.kind),
|
||||
Ok(ChannelKind::ServerChat
|
||||
| ChannelKind::Dm
|
||||
| ChannelKind::GroupDm
|
||||
| ChannelKind::Thread)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
|
||||
let channel_infos = convert::channel_infos(&channels)
|
||||
.into_iter()
|
||||
.map(|mut info| {
|
||||
// F7: a limit of 0 is a limit, not "unlimited".
|
||||
let zero = by_id
|
||||
.get(&info.id)
|
||||
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
|
||||
if zero.and_then(|v| v.as_i64()) == Some(0) {
|
||||
info.max_clients = Some(0);
|
||||
}
|
||||
(info.id, info)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients = replica
|
||||
.voice_states(server)
|
||||
.filter_map(|voice| {
|
||||
let user = replica.user(voice.user_id);
|
||||
let member = replica.member(server, voice.user_id);
|
||||
let mut client =
|
||||
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
|
||||
// F10: a unique id that is no base64 rides in `Foreign`.
|
||||
client.uid = user.and_then(user_uid);
|
||||
// F2: the client's channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
client.channel_group = client.channel_group.map(ids::channel_group);
|
||||
}
|
||||
// F6: the client's icon.
|
||||
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.unwrap_or(0);
|
||||
// F8: who is talking comes from the media.
|
||||
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
|
||||
// F9: the stream flag only where there are streams.
|
||||
if !view.streams {
|
||||
client.streaming = None;
|
||||
}
|
||||
Some((client.id, client))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
for role in replica.roles(server) {
|
||||
let mut info = convert::group_info(role);
|
||||
if role.scope == RoleScope::Channel as i32 {
|
||||
if view.teamspeak {
|
||||
info.id = ids::channel_group(info.id);
|
||||
}
|
||||
channel_groups.insert(info.id, info);
|
||||
} else {
|
||||
server_groups.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
|
||||
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
|
||||
Presence {
|
||||
server_name: details.name.clone(),
|
||||
channels: channel_infos,
|
||||
clients,
|
||||
server: details,
|
||||
server_groups,
|
||||
channel_groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// `convert::server_details` with F2 to F5.
|
||||
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
|
||||
let mut details = convert::server_details(server);
|
||||
// F3: the unique id as the client keys it.
|
||||
details.uid = details.uid.as_deref().map(server_key);
|
||||
let foreign = server.foreign.as_ref();
|
||||
// F4: the version the server sent, else the one the host reports.
|
||||
details.version = foreign_value(foreign, "server", "version")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| view.version.to_owned());
|
||||
// F5: the server's platform.
|
||||
details.platform = foreign_value(foreign, "server", "platform")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
// F2: the default channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
|
||||
}
|
||||
details
|
||||
}
|
||||
|
||||
/// Where the older model files the messages of a channel (the replica's
|
||||
/// `chat_target`, with the unique id of F10).
|
||||
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
|
||||
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
|
||||
match ChannelKind::try_from(info.kind) {
|
||||
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
|
||||
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
|
||||
let own = replica.own_user();
|
||||
info.recipients
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|id| *id != own)
|
||||
.and_then(|id| replica.user(id))
|
||||
.and_then(user_uid)
|
||||
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
|
||||
}
|
||||
_ => ChatTarget::Channel(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the replica as the older model has it.
|
||||
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
|
||||
let message = replica.message(channel, id)?;
|
||||
let author = replica.user(message.author_id);
|
||||
let name = Some(message.author_name.as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
|
||||
.unwrap_or_default();
|
||||
Some(ChatMessage {
|
||||
target: chat_target(replica, channel),
|
||||
author_name: name.to_owned(),
|
||||
author_uid: author.and_then(user_uid),
|
||||
author_id: (message.author_participant != 0)
|
||||
.then(|| u16::try_from(message.author_participant).ok())
|
||||
.flatten(),
|
||||
text: message.text.clone(),
|
||||
ts_ms: message.ts_ms,
|
||||
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
|
||||
blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ts_prefix_of_a_server_uid_goes() {
|
||||
assert_eq!(server_key("ts:abc="), "abc=");
|
||||
assert_eq!(server_key("abc="), "abc=");
|
||||
assert_eq!(server_key(""), "");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+141
-54
@@ -56,16 +56,16 @@ use voelin_media::mix::{
|
||||
};
|
||||
pub use voelin_media::mix::{Level, SourceState};
|
||||
use voelin_media::scale::Pyramid;
|
||||
use voelin_media::stream::EncodedFrame;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
|
||||
|
||||
/// The `voelin_media` codec of a negotiated video codec.
|
||||
pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
match codec {
|
||||
VideoCodec::Vp8 => Codec::Vp8,
|
||||
VideoCodec::Vp9 => Codec::Vp9,
|
||||
VideoCodec::H264 => Codec::H264,
|
||||
VideoCodec::Av1 => Codec::Av1,
|
||||
VideoCodec::H265 => Codec::H265,
|
||||
}
|
||||
crate::stream::media_codec(codec)
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
|
||||
pub bytes: u64,
|
||||
/// Pictures decoded per second and video received in bit/s, over the
|
||||
/// time since the previous [`VideoPipeline::stats`] (at least
|
||||
/// [`RATE_WINDOW`]; the watch screen asks once a second).
|
||||
/// `RATE_WINDOW`; the watch screen asks once a second).
|
||||
pub fps: u32,
|
||||
pub bitrate: u64,
|
||||
}
|
||||
@@ -3263,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};
|
||||
@@ -3276,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)
|
||||
}
|
||||
@@ -3416,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
|
||||
@@ -3429,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
|
||||
@@ -3522,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;
|
||||
@@ -3697,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
|
||||
@@ -4129,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) {
|
||||
@@ -4139,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
|
||||
@@ -4163,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);
|
||||
@@ -4207,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);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,94 @@
|
||||
//! The query source: own ServerQuery credentials, in-process observer and relays.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||
use voelin_observer::{
|
||||
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
||||
};
|
||||
|
||||
/// How a ServerQuery connection talks to the server.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QueryTransport {
|
||||
/// The raw text protocol (TeamSpeak 3; port 10011).
|
||||
Raw,
|
||||
/// SSH.
|
||||
Ssh,
|
||||
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
|
||||
Http,
|
||||
}
|
||||
|
||||
/// The user's own ServerQuery credentials for a server
|
||||
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
|
||||
/// engine logs in with to observe a server invisibly and to relay its
|
||||
/// channels' chat. The connection's own tuning (flood protection, timeouts)
|
||||
/// is the engine's.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct QueryLogin {
|
||||
/// The protocol of the query interface at `address`.
|
||||
pub transport: QueryTransport,
|
||||
/// `host:port` of the query interface.
|
||||
pub address: String,
|
||||
/// The login name (raw and SSH; ignored for HTTP).
|
||||
pub user: String,
|
||||
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port...
|
||||
pub server_port: Option<u16>,
|
||||
/// ...or by id (the first server when neither is given).
|
||||
pub server_id: Option<u32>,
|
||||
/// This machine's address is on the server's query allowlist, which the
|
||||
/// server's flood protection skips: the engine then sends its commands
|
||||
/// without the limit it keeps for a server that has not said so (a command
|
||||
/// the server refuses as a flood slows the connection down all the same).
|
||||
/// The application usually cannot know, and says `false`; the development
|
||||
/// servers of the tests allowlist their clients.
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for QueryLogin {
|
||||
// The secret is kept out of logs.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("QueryLogin")
|
||||
.field("transport", &self.transport)
|
||||
.field("address", &self.address)
|
||||
.field("user", &self.user)
|
||||
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
|
||||
.field("server_port", &self.server_port)
|
||||
.field("server_id", &self.server_id)
|
||||
.field("allowlisted", &self.allowlisted)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl QueryLogin {
|
||||
/// The connection the observer and the relays open.
|
||||
fn connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: match self.transport {
|
||||
QueryTransport::Raw => voelin_query::Transport::Raw,
|
||||
QueryTransport::Ssh => voelin_query::Transport::Ssh,
|
||||
QueryTransport::Http => voelin_query::Transport::Http,
|
||||
},
|
||||
addr: self.address.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: self.server_id,
|
||||
line: voelin_query::LineOptions {
|
||||
// Off the client-side limit only where the server skips it.
|
||||
rate_limit: if self.allowlisted {
|
||||
None
|
||||
} else {
|
||||
voelin_query::LineOptions::default().rate_limit
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum QueryCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
connect: voelin_query::Connect,
|
||||
login: QueryLogin,
|
||||
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
|
||||
events: mpsc::UnboundedSender<QueryEvent>,
|
||||
) {
|
||||
let connect = login.connect();
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = RelayPool::new(RelayConfig::new(connect));
|
||||
let mut observed = observer.subscribe();
|
||||
@@ -88,3 +172,59 @@ pub(crate) async fn run(
|
||||
relays.close_all().await;
|
||||
let _ = events.send(QueryEvent::Disconnected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_login_is_the_connection_the_query_crate_opens() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Ssh,
|
||||
address: "ts.example.com:10022".into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: Some(3),
|
||||
allowlisted: false,
|
||||
};
|
||||
let connect = login.connect();
|
||||
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
|
||||
assert_eq!(
|
||||
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
|
||||
("ts.example.com:10022", "serveradmin", Some("hunter2"))
|
||||
);
|
||||
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
|
||||
for (ours, theirs) in [
|
||||
(QueryTransport::Raw, voelin_query::Transport::Raw),
|
||||
(QueryTransport::Http, voelin_query::Transport::Http),
|
||||
] {
|
||||
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
|
||||
assert_eq!(connect.transport, theirs);
|
||||
}
|
||||
// The line options are the query crate's defaults, as the UI always
|
||||
// gave them, unless the server allowlists the client.
|
||||
let line = voelin_query::LineOptions::default();
|
||||
assert!(line.rate_limit.is_some());
|
||||
assert_eq!(connect.line.rate_limit, line.rate_limit);
|
||||
assert_eq!(connect.line.timeout, line.timeout);
|
||||
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
|
||||
assert_eq!(allowlisted.line.rate_limit, None);
|
||||
assert_eq!(allowlisted.line.timeout, line.timeout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_secret_stays_out_of_the_debug_text() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Raw,
|
||||
address: "h:1".into(),
|
||||
user: "u".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
let text = format!("{login:?}");
|
||||
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
|
||||
}
|
||||
}
|
||||
+146
-185
@@ -16,11 +16,9 @@ use tokio::time::Instant;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tracing::{debug, info, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
|
||||
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
|
||||
use voelin_stream::ClientState;
|
||||
|
||||
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
|
||||
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
|
||||
@@ -31,6 +29,7 @@ use crate::gateway::{
|
||||
Push, ReactionPush,
|
||||
};
|
||||
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
|
||||
use crate::query::{self, QueryCmd, QueryEvent};
|
||||
use crate::route::{ChatRoute, Dedup, route_chat};
|
||||
use crate::settings::{
|
||||
@@ -38,10 +37,9 @@ use crate::settings::{
|
||||
PRIVACY_PRIVATE_MESSAGES, SharedSettings,
|
||||
};
|
||||
use crate::stream::{
|
||||
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
|
||||
StreamInput, StreamKind, kind_name, parse_kind,
|
||||
LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name,
|
||||
parse_kind, parse_srtp_profiles,
|
||||
};
|
||||
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
|
||||
use crate::web;
|
||||
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
|
||||
|
||||
@@ -86,14 +84,10 @@ impl SessionHandle {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
|
||||
.run(rx),
|
||||
);
|
||||
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
|
||||
Self { tx }
|
||||
}
|
||||
|
||||
@@ -105,13 +99,11 @@ impl SessionHandle {
|
||||
/// Events from sources, tagged with the generation of the source so events
|
||||
/// of a replaced source are ignored.
|
||||
enum SourceEvent {
|
||||
Voice(u64, VoiceEvent),
|
||||
Voice(u64, LinkEvent),
|
||||
Gateway(u64, GatewayEvent),
|
||||
Query(u64, QueryEvent),
|
||||
AudioOut(u64, tsproto_packets::packets::OutPacket),
|
||||
AudioOut(u64, EncodedVoice),
|
||||
Audio(u64, AudioEvent),
|
||||
/// Our own stream (from the stream task of that voice connection).
|
||||
OwnStream(u64, OwnStreamEvent),
|
||||
/// The gateway's stream directory after subscribing.
|
||||
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
|
||||
/// The server's unique id the database remembers for an address.
|
||||
@@ -290,13 +282,13 @@ struct OwnStream {
|
||||
}
|
||||
|
||||
struct Session {
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
/// Starts the voice connections.
|
||||
link: Arc<SessionLink>,
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
state: SessionState,
|
||||
generation: u64,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<LinkCmd>)>,
|
||||
voice_address: String,
|
||||
voice_presence: Option<Presence>,
|
||||
nickname: String,
|
||||
@@ -318,18 +310,15 @@ struct Session {
|
||||
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
|
||||
/// remembered with its unique id once a source tells it.
|
||||
aliases: Vec<String>,
|
||||
/// Streams of the voice connection (TeamSpeak 6 only).
|
||||
streams: Option<StreamHandle>,
|
||||
stream_peer: PeerConfig,
|
||||
/// The voice connection carries streams (its capabilities say so; the
|
||||
/// connection runs their task, `LinkCmd::Stream` reaches it).
|
||||
streams: bool,
|
||||
/// Simulcast layers of our stream, for the stream task.
|
||||
stream_layers: Vec<LayerSpec>,
|
||||
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
|
||||
/// options' `stream_peer`.
|
||||
srtp_profiles: Option<Vec<SrtpProfile>>,
|
||||
srtp_profiles: Option<Vec<String>>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
/// Channel and `client_is_streaming` of the voice presence, as last told
|
||||
/// to the streams.
|
||||
streaming_clients: BTreeMap<u16, ClientState>,
|
||||
/// The gateway's stream directory, by id.
|
||||
directory: BTreeMap<String, StreamEntry>,
|
||||
own_stream: Option<OwnStream>,
|
||||
@@ -386,15 +375,13 @@ impl Session {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
||||
let Shared { settings, history, cache, contacts } = shared;
|
||||
let contacts_rx = Some(contacts.watch());
|
||||
Self {
|
||||
myts_identity,
|
||||
myts_data,
|
||||
link,
|
||||
cache,
|
||||
contacts,
|
||||
contacts_rx,
|
||||
@@ -434,12 +421,10 @@ impl Session {
|
||||
history,
|
||||
own_uid: None,
|
||||
aliases: Vec::new(),
|
||||
streams: None,
|
||||
stream_peer: PeerConfig::default(),
|
||||
streams: false,
|
||||
stream_layers: Vec::new(),
|
||||
srtp_profiles: None,
|
||||
frames,
|
||||
streaming_clients: BTreeMap::new(),
|
||||
directory: BTreeMap::new(),
|
||||
own_stream: None,
|
||||
open_chats: HashSet::new(),
|
||||
@@ -509,17 +494,19 @@ impl Session {
|
||||
fn command(&mut self, cmd: Command) {
|
||||
match cmd {
|
||||
Command::ConnectVoice { options, .. } => {
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
}
|
||||
// The streams end first: their shutdown goes through the
|
||||
// connection that is replaced.
|
||||
self.stop_streams("voice reconnecting");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
let mut options = *options;
|
||||
let generation = self.next_generation();
|
||||
self.voice_address = options.address.clone();
|
||||
self.details = None;
|
||||
self.nickname = options.nickname.clone();
|
||||
self.stream_peer = options.stream_peer.clone();
|
||||
if let Some(profiles) = &self.srtp_profiles {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles);
|
||||
}
|
||||
self.known_server(format!("voice:{}", options.address));
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -532,14 +519,13 @@ impl Session {
|
||||
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
|
||||
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
|
||||
}
|
||||
let link = VoiceLink {
|
||||
myts_identity: self.myts_identity.clone(),
|
||||
myts_data: self.myts_data.clone(),
|
||||
let ctx = LinkCtx {
|
||||
session: self.id,
|
||||
events: self.events.clone(),
|
||||
frames: self.frames.clone(),
|
||||
settings: self.settings.clone(),
|
||||
};
|
||||
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
|
||||
self.link.spawn(options, ctx, cmd_rx, ev_tx);
|
||||
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
|
||||
self.forget_images();
|
||||
self.voice = Some((generation, cmd_tx));
|
||||
@@ -548,7 +534,7 @@ impl Session {
|
||||
}
|
||||
Command::DisconnectVoice { .. } => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
}
|
||||
Command::ObserveGateway { urls, identity, .. } => {
|
||||
@@ -590,7 +576,10 @@ impl Session {
|
||||
// source, the history is kept under the query address.
|
||||
if self.state.server_uid.is_none() {
|
||||
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
|
||||
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
|
||||
self.learn_server_uid(
|
||||
format!("query:{}{port}", connect.address),
|
||||
Source::Query,
|
||||
);
|
||||
self.open_histories();
|
||||
}
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -626,7 +615,7 @@ impl Session {
|
||||
self.store_own(&target, &text, &route);
|
||||
}
|
||||
match route {
|
||||
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
|
||||
ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)),
|
||||
ChatRoute::Gateway => {
|
||||
if let Some((_, tx)) = &self.gateway {
|
||||
let _ = tx.send(GatewayCmd::SendChat(target, text));
|
||||
@@ -657,11 +646,11 @@ impl Session {
|
||||
},
|
||||
Command::Gateway { request, .. } => self.gateway_request(request),
|
||||
Command::MoveToChannel { channel, password, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Move(channel, password));
|
||||
self.voice_cmd(LinkCmd::Move(channel, password));
|
||||
}
|
||||
Command::SetInputMuted { muted, .. } => {
|
||||
self.state.input_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetInputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetInputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::InputMuted(muted));
|
||||
}
|
||||
@@ -669,7 +658,7 @@ impl Session {
|
||||
}
|
||||
Command::SetOutputMuted { muted, .. } => {
|
||||
self.state.output_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetOutputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetOutputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::OutputMuted(muted));
|
||||
}
|
||||
@@ -692,12 +681,12 @@ impl Session {
|
||||
// again after connecting.
|
||||
Command::SetClientVolume { client, volume, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
|
||||
}
|
||||
}
|
||||
Command::SetClientMuted { client, muted, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
|
||||
}
|
||||
}
|
||||
Command::SetStreamVolume { stream_id, volume, .. } => {
|
||||
@@ -706,50 +695,43 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Command::StartStream { setup, auto_accept, .. } => {
|
||||
self.stream_input(StreamInput::Start { setup, auto_accept });
|
||||
self.stream_input(StreamCmd::Start { setup, auto_accept });
|
||||
}
|
||||
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
|
||||
Command::StopStream { .. } => self.stream_input(StreamCmd::Stop),
|
||||
Command::AcceptViewer { viewer, accept, .. } => {
|
||||
self.stream_input(StreamInput::Respond { viewer, accept });
|
||||
self.stream_input(StreamCmd::Respond { viewer, accept });
|
||||
}
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }),
|
||||
Command::SendStreamFrame { frame, .. } => {
|
||||
// Frames without a stream are dropped silently.
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Frame(frame));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Frame(frame));
|
||||
}
|
||||
Command::WatchStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Watch { stream_id });
|
||||
self.stream_input(StreamCmd::Watch { stream_id });
|
||||
}
|
||||
Command::LeaveStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Leave { stream_id });
|
||||
self.stream_input(StreamCmd::Leave { stream_id });
|
||||
}
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
self.stream_input(StreamCmd::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::StreamUndecodable { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Undecodable { stream_id });
|
||||
self.stream_input(StreamCmd::Undecodable { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
self.stream_input(StreamCmd::WatchLayer { stream_id, layer });
|
||||
}
|
||||
// Kept for streams started later, also without a connection.
|
||||
Command::SetStreamLayers { layers, .. } => {
|
||||
self.stream_layers = layers.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Layers(layers));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Layers(layers));
|
||||
}
|
||||
Command::SetSrtpProfiles(profiles) => {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
self.srtp_profiles = Some(profiles.clone());
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::SrtpProfiles(profiles));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
Command::Poke { client, message, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Poke { client, message });
|
||||
self.voice_cmd(LinkCmd::Poke { client, message });
|
||||
}
|
||||
Command::ListFiles { request, channel, password, path, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -759,7 +741,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
|
||||
self.voice_cmd(LinkCmd::ListFiles { request, dir });
|
||||
}
|
||||
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
|
||||
self.download(transfer, Remote { channel, password, path }, &to);
|
||||
@@ -797,34 +779,27 @@ impl Session {
|
||||
let report = self.transfer_report(transfer);
|
||||
let file = Remote { channel, password, path };
|
||||
let transfer = Some(transfer);
|
||||
self.voice_cmd(VoiceCmd::Upload {
|
||||
transfer,
|
||||
file,
|
||||
from,
|
||||
overwrite,
|
||||
resume,
|
||||
report,
|
||||
});
|
||||
self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report });
|
||||
}
|
||||
Command::CancelTransfer { transfer, .. } => {
|
||||
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
|
||||
self.voice_cmd(LinkCmd::CancelTransfer(transfer));
|
||||
}
|
||||
Command::DeleteFiles { request, channel, password, paths, .. } => {
|
||||
let request = Some(request);
|
||||
self.voice_request(
|
||||
request,
|
||||
VoiceCmd::DeleteFiles { request, channel, password, paths },
|
||||
LinkCmd::DeleteFiles { request, channel, password, paths },
|
||||
);
|
||||
}
|
||||
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
|
||||
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
|
||||
let from = Remote { channel, password, path: from };
|
||||
let to = Remote { channel: to_channel, password: to_password, path: to };
|
||||
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
|
||||
self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to });
|
||||
}
|
||||
Command::CreateDirectory { request, channel, password, path, .. } => {
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
|
||||
self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir });
|
||||
}
|
||||
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
|
||||
Command::FetchAvatar { client_uid, .. } => {
|
||||
@@ -856,7 +831,7 @@ impl Session {
|
||||
self.emit(Event::OfflineMessages { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineList { request });
|
||||
self.voice_cmd(LinkCmd::OfflineList { request });
|
||||
}
|
||||
Command::GetOfflineMessage { request, id, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -864,22 +839,20 @@ impl Session {
|
||||
self.emit(Event::OfflineMessage { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
|
||||
self.voice_cmd(LinkCmd::OfflineGet { request, id });
|
||||
}
|
||||
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
|
||||
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
self.voice_request(Some(request), cmd);
|
||||
}
|
||||
Command::DeleteOfflineMessage { request, id, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id });
|
||||
}
|
||||
Command::SetOfflineMessageRead { request, id, read, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
|
||||
}
|
||||
// Engine-wide.
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::CloseSession { .. }
|
||||
Command::CloseSession { .. }
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
| Command::ResetSetting { .. }
|
||||
@@ -894,7 +867,7 @@ impl Session {
|
||||
// Files, avatars, icons
|
||||
|
||||
/// A request to the voice connection; without one it fails at once.
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: LinkCmd) {
|
||||
match (&self.voice, request) {
|
||||
(Some(_), _) => self.voice_cmd(cmd),
|
||||
(None, Some(request)) => self.emit(Event::RequestDone {
|
||||
@@ -925,7 +898,7 @@ impl Session {
|
||||
}
|
||||
let report = self.transfer_report(transfer);
|
||||
let sink = Sink::from_target(to);
|
||||
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
}
|
||||
|
||||
/// Upload our avatar and announce its hash, or remove it.
|
||||
@@ -938,7 +911,7 @@ impl Session {
|
||||
let Some(image) = image else {
|
||||
// The file too (best effort), then no hash.
|
||||
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
|
||||
let cmd = VoiceCmd::DeleteFiles {
|
||||
let cmd = LinkCmd::DeleteFiles {
|
||||
request: None,
|
||||
channel: 0,
|
||||
password: None,
|
||||
@@ -947,7 +920,7 @@ impl Session {
|
||||
self.voice_cmd(cmd);
|
||||
}
|
||||
let hash = String::new();
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
return;
|
||||
};
|
||||
let (sources, cache, settings) =
|
||||
@@ -983,7 +956,7 @@ impl Session {
|
||||
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
|
||||
});
|
||||
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
|
||||
let upload = VoiceCmd::Upload {
|
||||
let upload = LinkCmd::Upload {
|
||||
transfer: None,
|
||||
file,
|
||||
from: image,
|
||||
@@ -1403,7 +1376,7 @@ impl Session {
|
||||
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
|
||||
let file = Remote { channel, password: None, path };
|
||||
let failed = report.clone();
|
||||
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
failed(TransferState::Failed(NO_VOICE.into()));
|
||||
}
|
||||
}
|
||||
@@ -1436,24 +1409,22 @@ impl Session {
|
||||
if let Some(a) = &self.audio {
|
||||
for (client, (volume, muted)) in &wanted {
|
||||
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
|
||||
}
|
||||
}
|
||||
// No contact setting any more: back to normal.
|
||||
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
|
||||
if p.clients.contains_key(client) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
|
||||
}
|
||||
}
|
||||
self.contact_audio = wanted;
|
||||
}
|
||||
if friends != self.stream_friends {
|
||||
self.stream_friends = friends.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Friends(friends));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Friends(friends));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1464,7 +1435,7 @@ impl Session {
|
||||
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
|
||||
let wanted = (clients, p.server.priority_speaker_dimm_db);
|
||||
if wanted != self.priority_audio {
|
||||
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
|
||||
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
|
||||
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
|
||||
self.priority_audio = wanted;
|
||||
}
|
||||
@@ -1502,26 +1473,36 @@ impl Session {
|
||||
allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u)))
|
||||
}
|
||||
|
||||
fn stream_input(&self, input: StreamInput) {
|
||||
match &self.streams {
|
||||
Some(s) => s.send(input),
|
||||
None if self.state.voice == VoiceState::Connected => {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
}
|
||||
None => self.error("not connected with voice"),
|
||||
/// A stream command of the user: an error where the connection has no
|
||||
/// streams.
|
||||
fn stream_input(&self, cmd: StreamCmd) {
|
||||
if self.streams {
|
||||
self.stream_cmd(cmd);
|
||||
} else if self.state.voice == VoiceState::Connected {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
} else {
|
||||
self.error("not connected with voice");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command for the streams of the voice connection; dropped where it
|
||||
/// has none.
|
||||
fn stream_cmd(&self, cmd: StreamCmd) {
|
||||
if let (true, Some((_, tx))) = (self.streams, &self.voice) {
|
||||
let _ = tx.send(LinkCmd::Stream(cmd));
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_streams(&mut self, reason: &str) {
|
||||
if let Some(s) = self.streams.take() {
|
||||
s.send(StreamInput::Shutdown(reason.into()));
|
||||
if self.streams {
|
||||
self.stream_cmd(StreamCmd::Shutdown(reason.into()));
|
||||
self.streams = false;
|
||||
}
|
||||
self.streaming_clients.clear();
|
||||
// The stream task's report comes from a replaced source.
|
||||
self.own_stream_ended();
|
||||
}
|
||||
|
||||
fn voice_cmd(&self, cmd: VoiceCmd) {
|
||||
fn voice_cmd(&self, cmd: LinkCmd) {
|
||||
match &self.voice {
|
||||
Some((_, tx)) => {
|
||||
let _ = tx.send(cmd);
|
||||
@@ -1710,14 +1691,16 @@ impl Session {
|
||||
|
||||
/// The registered streams of the directory, for the stream task.
|
||||
fn feed_directory(&self) {
|
||||
let Some(streams) = &self.streams else { return };
|
||||
if !self.streams {
|
||||
return;
|
||||
}
|
||||
let entries = self
|
||||
.directory
|
||||
.values()
|
||||
.filter_map(|e| {
|
||||
Some(StreamInfo {
|
||||
id: e.stream_id.clone()?,
|
||||
streamer: ClientId(e.client_id?),
|
||||
streamer: e.client_id?,
|
||||
name: e.title.clone(),
|
||||
kind: parse_kind(&e.kind),
|
||||
// Not in the directory; the stream's offer tells.
|
||||
@@ -1729,7 +1712,7 @@ impl Session {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
streams.send(StreamInput::Directory(entries));
|
||||
self.stream_cmd(StreamCmd::Directory(entries));
|
||||
}
|
||||
|
||||
fn register_own_stream(&mut self) {
|
||||
@@ -1834,7 +1817,7 @@ impl Session {
|
||||
}
|
||||
self.stop_streams("session closed");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
self.audio = None;
|
||||
self.stop_observing();
|
||||
@@ -1858,7 +1841,7 @@ impl Session {
|
||||
SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e),
|
||||
SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Audio(packet));
|
||||
let _ = tx.send(LinkCmd::Audio(packet));
|
||||
}
|
||||
}
|
||||
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
|
||||
@@ -1867,9 +1850,6 @@ impl Session {
|
||||
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
|
||||
}
|
||||
},
|
||||
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
|
||||
self.own_stream_event(e)
|
||||
}
|
||||
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
|
||||
match result {
|
||||
Ok(streams) => {
|
||||
@@ -1895,7 +1875,7 @@ impl Session {
|
||||
}
|
||||
SourceEvent::AvatarUploaded(g, request, result) => match result {
|
||||
Ok(hash) if self.is_current(Source::Voice, g) => {
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
}
|
||||
Ok(_) => self.emit(Event::RequestDone {
|
||||
session: self.id,
|
||||
@@ -1923,9 +1903,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn voice_event(&mut self, e: VoiceEvent) {
|
||||
fn voice_event(&mut self, e: LinkEvent) {
|
||||
match e {
|
||||
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
|
||||
LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
} => {
|
||||
self.state.voice = VoiceState::Connected;
|
||||
self.state.own_client = Some(own_client);
|
||||
if own_uid.is_some() {
|
||||
@@ -1940,50 +1927,26 @@ impl Session {
|
||||
{
|
||||
let _ = tx.send(GatewayCmd::RetryNow);
|
||||
}
|
||||
let capabilities = flavor.capabilities();
|
||||
if capabilities.streams
|
||||
&& let Some((generation, voice)) = &self.voice
|
||||
{
|
||||
let generation = *generation;
|
||||
let (own_tx, own_rx) = mpsc::unbounded_channel();
|
||||
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
|
||||
let streams = StreamHandle::spawn(
|
||||
self.id,
|
||||
own_client,
|
||||
self.stream_peer.clone(),
|
||||
voice.clone(),
|
||||
self.events.clone(),
|
||||
self.frames.clone(),
|
||||
self.audio.clone(),
|
||||
self.settings.clone(),
|
||||
own_tx,
|
||||
);
|
||||
if capabilities.streams {
|
||||
self.streams = true;
|
||||
if !self.stream_layers.is_empty() {
|
||||
streams.send(StreamInput::Layers(self.stream_layers.clone()));
|
||||
self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone()));
|
||||
}
|
||||
// The setting may have changed since the connection was asked for.
|
||||
if let Some(profiles) = self.srtp_profiles.clone() {
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
self.streams = Some(streams);
|
||||
self.feed_directory();
|
||||
}
|
||||
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
||||
self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities });
|
||||
self.reopen_relayed_chats();
|
||||
self.open_histories();
|
||||
}
|
||||
VoiceEvent::Presence(p) => {
|
||||
LinkEvent::Presence(p) => {
|
||||
// Client ids are reused: forget the volumes of those who left.
|
||||
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
|
||||
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
|
||||
a.send(AudioIn::ClientLeft(ClientId(*id)));
|
||||
}
|
||||
}
|
||||
if let Some(s) = &self.streams {
|
||||
let clients: BTreeMap<_, _> = p
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
|
||||
.collect();
|
||||
if clients != self.streaming_clients {
|
||||
self.streaming_clients = clients.clone();
|
||||
s.send(StreamInput::Clients(clients));
|
||||
a.send(AudioIn::ClientLeft(TalkerId(*id)));
|
||||
}
|
||||
}
|
||||
self.report_details(&p);
|
||||
@@ -1993,7 +1956,7 @@ impl Session {
|
||||
self.voice_presence = Some(*p);
|
||||
self.publish_presence();
|
||||
}
|
||||
VoiceEvent::Poke { from, from_uid, from_name, message } => {
|
||||
LinkEvent::Poke { from, from_uid, from_name, message } => {
|
||||
let blocked = self.contacts.is_blocked(from_uid.as_deref());
|
||||
if blocked && self.block_mode() == BlockMode::Hide {
|
||||
debug!(?from_uid, "poke of a blocked contact hidden");
|
||||
@@ -2006,35 +1969,37 @@ impl Session {
|
||||
let session = self.id;
|
||||
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
|
||||
}
|
||||
VoiceEvent::Error(message) => self.error(message),
|
||||
VoiceEvent::Stream(n) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Notification(n));
|
||||
LinkEvent::Error(message) => self.error(message),
|
||||
LinkEvent::OwnStream(e) => self.own_stream_event(e),
|
||||
LinkEvent::StreamAudio { stream, time, data } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamAudio { stream, time, data });
|
||||
}
|
||||
}
|
||||
VoiceEvent::StreamRequestFailed(request, error) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::RequestFailed(request, error));
|
||||
LinkEvent::StreamAudioEnded(stream) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamEnded(stream));
|
||||
}
|
||||
}
|
||||
VoiceEvent::OwnChannel(cid) => {
|
||||
LinkEvent::OwnChannel(cid) => {
|
||||
if self.state.own_channel != Some(cid) {
|
||||
self.state.own_channel = Some(cid);
|
||||
self.emit_state();
|
||||
}
|
||||
}
|
||||
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
VoiceEvent::Audio(packet) => {
|
||||
LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
LinkEvent::Audio(packet) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::Packet(packet));
|
||||
}
|
||||
}
|
||||
VoiceEvent::Talking { client, talking } => {
|
||||
LinkEvent::Talking { client, talking } => {
|
||||
self.emit(Event::Talking { session: self.id, client, talking });
|
||||
}
|
||||
VoiceEvent::Disconnected(reason) => {
|
||||
self.stop_streams("voice disconnected");
|
||||
LinkEvent::Disconnected(reason) => {
|
||||
// The connection ended its streams itself.
|
||||
self.voice = None;
|
||||
self.stop_streams("voice disconnected");
|
||||
self.voice_presence = None;
|
||||
self.audio = None;
|
||||
self.forget_images();
|
||||
@@ -2288,18 +2253,13 @@ mod banner_tests {
|
||||
cache: SharedCache::new(Cache::new(dir)),
|
||||
contacts: Contacts::new(events.clone(), history),
|
||||
};
|
||||
// No myTeamSpeak account; its source stays open, as the engine's does
|
||||
// (a closed one ends voice connections).
|
||||
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let session = Session::new(
|
||||
1,
|
||||
events,
|
||||
frames,
|
||||
AudioSettings::default(),
|
||||
shared,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
Arc::new(SessionLink::new(crate::Backends::empty())),
|
||||
);
|
||||
(session, receiver)
|
||||
}
|
||||
@@ -2386,7 +2346,7 @@ mod banner_tests {
|
||||
Err("temporarily unavailable".into()),
|
||||
);
|
||||
session.retry_images(session.image_retries[&request].due.unwrap());
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected an image download");
|
||||
@@ -2433,7 +2393,7 @@ mod banner_tests {
|
||||
session.state.server_uid = Some("server-a".into());
|
||||
session.fetch_pictures(&presence);
|
||||
assert!(session.pictures.contains(url));
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected a file download");
|
||||
@@ -2975,9 +2935,10 @@ mod banner_tests {
|
||||
let (mut session, _events) = session("gateway-wake");
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
session.gateway = Some((session.next_generation(), tx));
|
||||
let connected = || VoiceEvent::Connected {
|
||||
let connected = || LinkEvent::Connected {
|
||||
name: "test".into(),
|
||||
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
|
||||
backend: crate::BackendInfo::default(),
|
||||
capabilities: voelin_model::Capabilities::default(),
|
||||
own_client: 1,
|
||||
server_uid: "server=".into(),
|
||||
own_uid: None,
|
||||
|
||||
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::{debug, warn};
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_media::{LayerId, LayerSpec};
|
||||
use voelin_store::Store;
|
||||
use voelin_stream::{LayerId, LayerSpec};
|
||||
|
||||
/// A value of any key, typed (`Arc<T>` of the key's `T`).
|
||||
type Stored = Arc<dyn Any + Send + Sync>;
|
||||
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
);
|
||||
|
||||
/// Import identities from the official TeamSpeak clients when the app
|
||||
/// starts ([`crate::identity::import_new`]; their files are only read).
|
||||
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
|
||||
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
|
||||
"identity.import_from_teamspeak",
|
||||
Kind::Bool,
|
||||
|
||||
+539
-161
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
//! The stream types of the engine's API, owned by the core: what the UI is
|
||||
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
|
||||
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
|
||||
//!
|
||||
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
|
||||
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
|
||||
//! TeamSpeak 6 stream crate today) is converted to and from them at the
|
||||
//! boundary in [`crate::stream`], so the UI does not depend on the link's
|
||||
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
|
||||
//! `LayerId`) are `voelin-media`'s.
|
||||
|
||||
use voelin_media::{Codec, LayerId};
|
||||
|
||||
/// What a stream shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamKind {
|
||||
Camera,
|
||||
Screen,
|
||||
Window,
|
||||
/// A kind this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl StreamKind {
|
||||
/// From the number servers use: 2 camera, 3 screen, 4 window.
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
2 => Self::Camera,
|
||||
3 => Self::Screen,
|
||||
4 => Self::Window,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`from_u8`](Self::from_u8) back.
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Camera => 2,
|
||||
Self::Screen => 3,
|
||||
Self::Window => 4,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// The stream's video bitrate in kbit/s (the single layer's without
|
||||
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
|
||||
/// announced as at most 65535; the stream sends its real rate whatever
|
||||
/// the announcement says.
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client sends 1.
|
||||
pub accessibility: u8,
|
||||
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
|
||||
pub mode: u8,
|
||||
/// 0 = unlimited.
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for StreamSetup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 4608,
|
||||
accessibility: 1,
|
||||
mode: 1,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream on the server ([`crate::Event::StreamsChanged`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamInfo {
|
||||
pub id: String,
|
||||
/// The client id of the streamer.
|
||||
pub streamer: u16,
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
pub bitrate: u32,
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
/// How many watch it; `None` where nothing told (e.g. a gateway's
|
||||
/// directory entry).
|
||||
pub viewers: Option<u32>,
|
||||
}
|
||||
|
||||
/// A viewer of our stream, as we see it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ViewerState {
|
||||
/// Asked to watch, waiting for our decision.
|
||||
Requested,
|
||||
/// Offer sent; waiting for the answer and the connection.
|
||||
Connecting,
|
||||
Connected,
|
||||
}
|
||||
|
||||
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ViewerInfo {
|
||||
/// The client id of the viewer.
|
||||
pub client: u16,
|
||||
pub state: ViewerState,
|
||||
/// The message of the join request.
|
||||
pub message: String,
|
||||
/// The simulcast layer the viewer receives (it moves at a keyframe of the
|
||||
/// new layer); `None` before we offered, and with RID simulcast (all
|
||||
/// layers).
|
||||
pub layer: Option<LayerId>,
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
pub estimate: Option<u64>,
|
||||
/// The SRTP profile of the connection by its name (as in RFC 5764 and
|
||||
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
|
||||
/// done.
|
||||
pub srtp_profile: Option<String>,
|
||||
/// The video codec the viewer's answer chose (it gets video in that
|
||||
/// codec).
|
||||
pub codec: Option<Codec>,
|
||||
}
|
||||
|
||||
/// Why a viewer left a stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LeaveReason {
|
||||
None,
|
||||
Left,
|
||||
Denied,
|
||||
Failed,
|
||||
Kicked,
|
||||
Banned,
|
||||
/// A reason this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// Why a stream ended for us ([`crate::StreamState::Ended`],
|
||||
/// [`crate::WatchState::Ended`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum EndReason {
|
||||
/// We stopped streaming or watching.
|
||||
Local,
|
||||
/// The streamer denied our join request.
|
||||
Denied,
|
||||
/// The stream was stopped (or its streamer disconnected).
|
||||
Stopped,
|
||||
/// The streamer or the server ended our viewing session.
|
||||
Removed(Option<LeaveReason>),
|
||||
/// A command failed or no connection could be established.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -331,4 +331,301 @@ mod tests {
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
|
||||
// ---- across the session seam ---------------------------------------------
|
||||
|
||||
/// A presence made into the entities the TeamSpeak session writes
|
||||
/// (`ts_session::entities`), pushed the way a host syncs them, and
|
||||
/// projected back by the engine (`link::project`): what the UI is shown
|
||||
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
|
||||
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, push::Body};
|
||||
|
||||
use crate::link::media::TalkTracker;
|
||||
use crate::link::project::{View, presence as project};
|
||||
use crate::ts::ts_session::entities::build;
|
||||
|
||||
let built = build(presence, ts6, own);
|
||||
let mut replica = Replica::new(SCHEMA_GENERATION);
|
||||
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
|
||||
{
|
||||
replica.subscribe(scope);
|
||||
let pushes = [
|
||||
Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(scope.to_proto()),
|
||||
mode: v1::SyncMode::Full as i32,
|
||||
epoch: 1,
|
||||
}),
|
||||
Body::Change(v1::Change {
|
||||
scope: Some(scope.to_proto()),
|
||||
rev: 1,
|
||||
put: layer.values().cloned().collect(),
|
||||
del: Vec::new(),
|
||||
}),
|
||||
Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(scope.to_proto()),
|
||||
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
|
||||
gap: false,
|
||||
}),
|
||||
];
|
||||
for body in pushes {
|
||||
replica.apply_push(&v1::Push { body: Some(body) });
|
||||
}
|
||||
}
|
||||
let features = Features::new(["voice"]);
|
||||
let talking = TalkTracker::default();
|
||||
project(&View {
|
||||
replica: &replica,
|
||||
server: 1,
|
||||
teamspeak: true,
|
||||
version: "",
|
||||
features: &features,
|
||||
streams: ts6,
|
||||
talking: &talking,
|
||||
})
|
||||
}
|
||||
|
||||
/// A TeamSpeak 6 server and some clients with what the book holds of them.
|
||||
fn ts6_presence() -> Presence {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
);
|
||||
book.handle_command(&message(&list)).unwrap();
|
||||
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
|
||||
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
|
||||
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
|
||||
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=1 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups={groups} client_away={} client_away_message={away} \
|
||||
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
|
||||
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
|
||||
client_nickname_phonetic client_needed_serverquery_view_power=75 \
|
||||
client_is_channel_commander=1 client_country=RU client_badges \
|
||||
client_myteamspeak_id=m{clid} client_integrations{avatar}",
|
||||
100 + u64::from(clid),
|
||||
u8::from(!away.is_empty()),
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
|
||||
enter(6, 12, "8,9", "gone\\sfishing", ""),
|
||||
enter(7, 12, "", "", " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
|
||||
let p = ts6_presence();
|
||||
assert_eq!(p.clients.len(), 3, "the fixture has clients");
|
||||
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
|
||||
// A TeamSpeak 6 client the book has no streaming flag of (it was not
|
||||
// sent) is not streaming: v1 has no "unknown" for it.
|
||||
let mut expected = p.clone();
|
||||
for client in expected.clients.values_mut() {
|
||||
client.streaming = Some(client.streaming.unwrap_or(false));
|
||||
}
|
||||
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
|
||||
// The same server as a TeamSpeak 3 one has no streams to tell of.
|
||||
let mut ts3 = p.clone();
|
||||
for client in ts3.clients.values_mut() {
|
||||
client.streaming = None;
|
||||
}
|
||||
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
|
||||
}
|
||||
|
||||
/// A deterministic stream of numbers for the generated presences.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> bool {
|
||||
self.below(2) == 0
|
||||
}
|
||||
|
||||
fn text(&mut self, prefix: &str) -> String {
|
||||
format!("{prefix}{}", self.below(1000))
|
||||
}
|
||||
}
|
||||
|
||||
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
|
||||
/// order chain, every client with a database id, unique ids that are base64
|
||||
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
|
||||
fn generated(seed: u64, ts6: bool) -> Presence {
|
||||
use base64::Engine as _;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode,
|
||||
};
|
||||
let mut n = Numbers(seed | 1);
|
||||
let mut p = Presence::default();
|
||||
let name = n.text("Server ");
|
||||
p.server_name = name.clone();
|
||||
p.server = voelin_model::ServerDetails {
|
||||
name,
|
||||
uid: Some(n.text("uid")),
|
||||
welcome_message: n.text("welcome "),
|
||||
host_message: n.text("host "),
|
||||
host_message_mode: [
|
||||
HostMessageMode::None,
|
||||
HostMessageMode::Log,
|
||||
HostMessageMode::Modal,
|
||||
][n.below(3) as usize],
|
||||
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
|
||||
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
|
||||
banner_gfx_interval_s: n.below(100),
|
||||
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
|
||||
[n.below(3) as usize],
|
||||
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
|
||||
host_button_url: String::new(),
|
||||
host_button_gfx_url: String::new(),
|
||||
icon: n.below(5) as u32 * 1000,
|
||||
platform: "Linux".into(),
|
||||
version: n.text("6.0."),
|
||||
max_clients: n.below(500) as u16,
|
||||
priority_speaker_dimm_db: -(n.below(30) as i32),
|
||||
default_server_group: Some(1 + n.below(9)),
|
||||
default_channel_group: Some(1 + n.below(9)),
|
||||
};
|
||||
// Groups.
|
||||
for id in 1..=(2 + n.below(4)) {
|
||||
let group = |id: u64, n: &mut Numbers| GroupInfo {
|
||||
id,
|
||||
name: n.text("group "),
|
||||
icon: n.below(3) as u32 * 100,
|
||||
sort_id: n.below(1000) as i32 - 500,
|
||||
naming_mode: [
|
||||
GroupNamingMode::None,
|
||||
GroupNamingMode::Before,
|
||||
GroupNamingMode::After,
|
||||
][n.below(3) as usize],
|
||||
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
|
||||
[n.below(3) as usize],
|
||||
};
|
||||
p.server_groups.insert(id, group(id, &mut n));
|
||||
p.channel_groups.insert(id, group(id, &mut n));
|
||||
}
|
||||
// Channels: a tree whose siblings follow each other.
|
||||
let mut parents = vec![0u64];
|
||||
for id in 1..=(3 + n.below(8)) {
|
||||
let parent = parents[n.below(parents.len() as u64) as usize];
|
||||
let order = p
|
||||
.channels
|
||||
.values()
|
||||
.filter(|c| c.parent == parent)
|
||||
.map(|c| c.id)
|
||||
.next_back()
|
||||
.unwrap_or(0);
|
||||
parents.push(id);
|
||||
p.channels.insert(
|
||||
id,
|
||||
ChannelInfo {
|
||||
id,
|
||||
parent,
|
||||
order,
|
||||
name: n.text("channel "),
|
||||
topic: n.flag().then(|| n.text("topic ")),
|
||||
has_password: n.flag(),
|
||||
max_clients: match n.below(3) {
|
||||
0 => None,
|
||||
1 => Some(0),
|
||||
_ => Some(1 + n.below(50) as i32),
|
||||
},
|
||||
needed_subscribe_power: n.below(3) as i32 * 10,
|
||||
needed_talk_power: n.below(3) as i32 * 25,
|
||||
is_default: id == 1,
|
||||
icon: n.below(3) as u32 * 500,
|
||||
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
|
||||
banner_mode: [
|
||||
BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect,
|
||||
][n.below(3) as usize],
|
||||
},
|
||||
);
|
||||
}
|
||||
// Clients.
|
||||
let channels: Vec<u64> = p.channels.keys().copied().collect();
|
||||
for id in 1..=(1 + n.below(12)) {
|
||||
let id = id as u16;
|
||||
let uid = match n.below(4) {
|
||||
0 => None,
|
||||
1 => Some(n.text("login")),
|
||||
_ => {
|
||||
let bytes: Vec<u8> =
|
||||
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
};
|
||||
let channel = channels[n.below(channels.len() as u64) as usize];
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
uid,
|
||||
nickname: n.text("nick "),
|
||||
channel,
|
||||
is_query: n.below(5) == 0,
|
||||
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
|
||||
input_muted: n.flag(),
|
||||
output_muted: n.flag(),
|
||||
talking: Some(false),
|
||||
streaming: ts6.then(|| n.flag()),
|
||||
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
|
||||
country: n.flag().then(|| "DE".into()),
|
||||
avatar: n.flag().then(|| n.text("hash")),
|
||||
myts_avatar: n.flag().then(|| n.text("https://a/")),
|
||||
description: n.flag().then(|| n.text("about ")),
|
||||
talk_power: n.below(100) as i32,
|
||||
talker: n.flag(),
|
||||
channel_group: n.flag().then(|| 1 + n.below(9)),
|
||||
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
|
||||
icon: n.below(3) as u32 * 111,
|
||||
recording: n.flag(),
|
||||
priority_speaker: n.flag(),
|
||||
channel_commander: n.flag(),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
},
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_presences_survive_the_seam() {
|
||||
for seed in 1..=200u64 {
|
||||
for ts6 in [false, true] {
|
||||
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
|
||||
let own = p.clients.keys().next().copied();
|
||||
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ use std::{fs, str};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_gateway_proto::UniqueIds;
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_store::{IdentityOrigin, Store};
|
||||
|
||||
/// Name given to an identity whose source kept none.
|
||||
@@ -55,6 +56,9 @@ pub enum IdentityError {
|
||||
NoIdentity { path: String },
|
||||
#[error("client database: {0}")]
|
||||
Store(String),
|
||||
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
|
||||
#[error("{0}")]
|
||||
Blob(String),
|
||||
}
|
||||
|
||||
impl IdentityError {
|
||||
@@ -230,6 +234,77 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity as the API takes it
|
||||
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
|
||||
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
|
||||
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
|
||||
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
|
||||
/// the store writes.
|
||||
pub fn to_blob(identity: &Identity) -> IdentityBlob {
|
||||
// An identity is a key and two counters: writing it cannot fail. (A blob with
|
||||
// no JSON is refused when it is used, in words.)
|
||||
let json = serde_json::to_string(identity).unwrap_or_default();
|
||||
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
|
||||
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
if !blob.is_teamspeak() {
|
||||
return Err(IdentityError::Blob(format!(
|
||||
"the identity is of kind {:?}, not a TeamSpeak one",
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
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",
|
||||
serde_json::error::Category::Data => "not an identity",
|
||||
serde_json::error::Category::Io => "unreadable",
|
||||
};
|
||||
IdentityError::Blob(format!(
|
||||
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
|
||||
e.line(),
|
||||
e.column()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -548,18 +623,69 @@ mod tests {
|
||||
Identity::create()
|
||||
}
|
||||
|
||||
/// The blob of an identity is how the key store keeps it, and reads back as
|
||||
/// the same identity; what is no TeamSpeak identity is refused without
|
||||
/// quoting its JSON.
|
||||
#[test]
|
||||
fn an_identity_goes_through_its_blob() {
|
||||
let identity = synthetic();
|
||||
let blob = to_blob(&identity);
|
||||
assert!(blob.is_teamspeak());
|
||||
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
|
||||
assert_eq!(blob.level, identity.level());
|
||||
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
|
||||
let back = from_blob(&blob).unwrap();
|
||||
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
|
||||
|
||||
// Another kind.
|
||||
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
|
||||
let error = from_blob(&other).unwrap_err().to_string();
|
||||
assert!(error.contains("\"voelin\""), "{error}");
|
||||
// Not an identity: the text says where, and nothing of what it holds.
|
||||
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
|
||||
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
|
||||
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
|
||||
assert!(!error.contains("hunter2"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The TeamSpeak implementation of the session seam.
|
||||
//!
|
||||
//! Everything of the engine that is TeamSpeak's lives here, so that it can
|
||||
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
|
||||
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
|
||||
//!
|
||||
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
|
||||
//! (chat, voice, files, pokes, offline messages, the stream task's
|
||||
//! requests) with `book.rs`, its presence from the library's book;
|
||||
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
|
||||
//! ([`TsConnector`] is the `Connector` the engine registers for
|
||||
//! `ts3server://` and `teamspeak://`);
|
||||
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
|
||||
//! about itself: the signed compatibility versions it can claim, and the
|
||||
//! identities (reading, importing from the official clients, the security
|
||||
//! level).
|
||||
//!
|
||||
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
|
||||
//! named in the public items of this module and nowhere else of the crate's
|
||||
//! API.
|
||||
|
||||
mod book;
|
||||
pub mod identity;
|
||||
mod ts_link;
|
||||
pub(crate) mod ts_session;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
|
||||
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
|
||||
pub use ts_session::TsConnector;
|
||||
@@ -0,0 +1,256 @@
|
||||
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
|
||||
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
|
||||
//!
|
||||
//! The engine does not know this vocabulary: it talks to a
|
||||
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
|
||||
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
|
||||
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
|
||||
//! or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`super::voice`]) with everything that rides on it:
|
||||
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
|
||||
//! stream task. Which product the server is (and what it can do) is decided
|
||||
//! there, from the version it sends, and reported in
|
||||
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
|
||||
//!
|
||||
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
|
||||
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
|
||||
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
|
||||
//! of VoelinGateWay.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::voice;
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
|
||||
|
||||
/// Starts the connection of a link: the contract of `crate::link` for the
|
||||
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
|
||||
/// with them, and the module documentation of `link/session_link.rs` states
|
||||
/// it.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub(crate) trait ServerLink: Send + Sync + 'static {
|
||||
/// Connect to the server `options` names and run the connection on its
|
||||
/// own task: take commands from `cmds`, report through `events`, and end
|
||||
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
);
|
||||
}
|
||||
|
||||
/// What a TeamSpeak connection needs to know: the server, who to be, where
|
||||
/// to join. The reverse of what the engine's `ConnectParams` carry
|
||||
/// (`ts_session::inner_options`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with; none generates one.
|
||||
pub identity: Option<tsclientlib::Identity>,
|
||||
/// Signed compatibility version; `None` selects the native platform's tuple.
|
||||
pub client_version: Option<tsclientlib::Version>,
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
/// Options for `address` and `nickname`, the rest as a test leaves it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main myTeamSpeak account of an application, as its connections show
|
||||
/// it to the servers: the proof of the myTS ID, and what servers are shown
|
||||
/// of it (its avatar and badges with their certificates, its User Tag).
|
||||
///
|
||||
/// The senders live here, one pair for every connection of a [`TsLink`]; each
|
||||
/// connection watches the pair through [`Watches`], presents the account it
|
||||
/// finds when it connects, and follows the changes.
|
||||
pub(crate) struct Account {
|
||||
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl Default for Account {
|
||||
/// No account is signed in.
|
||||
fn default() -> Self {
|
||||
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The account proof for every current and future connection. Still no
|
||||
/// account is no change: every notification restarts the handshakes and
|
||||
/// sends `updatemytsid` on every connection. Any account is (each
|
||||
/// connection's proof is signed anew).
|
||||
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What the servers are shown of the account: sent to every connection
|
||||
/// that presents the account's myTS ID, once connected and when it
|
||||
/// changes; cleared on a sign-out. The same data is no change.
|
||||
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What one connection watches. It keeps the senders alive for as long as
|
||||
/// it runs: a connection ends with "account source closed" when its
|
||||
/// watches have lost them, so the account outlives the connector that
|
||||
/// made the connection.
|
||||
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
|
||||
Watches {
|
||||
identity: self.identity.subscribe(),
|
||||
data: self.data.subscribe(),
|
||||
_keep: Some(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The account a connection presents and follows ([`Account::watches`]).
|
||||
pub(crate) struct Watches {
|
||||
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
_keep: Option<Arc<Account>>,
|
||||
}
|
||||
|
||||
impl Watches {
|
||||
/// Watches of senders that someone else keeps (a test's).
|
||||
#[cfg(test)]
|
||||
pub(super) fn of(
|
||||
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
Self { identity, data, _keep: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct TsLink {
|
||||
account: Arc<Account>,
|
||||
}
|
||||
|
||||
impl TsLink {
|
||||
/// A link that presents no account until it is given one.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The account the link's connections present.
|
||||
pub(crate) fn account(&self) -> &Arc<Account> {
|
||||
&self.account
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for TsLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
|
||||
fn identity() -> Arc<tsproto::myts::Identity> {
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
let mut public = [0x66; 32];
|
||||
public[0] = 0x58;
|
||||
Arc::new(
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// An account sets what it holds only when it changes: every notification
|
||||
/// of a watch restarts the handshake of a connection.
|
||||
#[test]
|
||||
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
|
||||
let account = Arc::new(Account::default());
|
||||
let mut watches = account.watches();
|
||||
// No account, still none: nothing.
|
||||
account.set_identity(None);
|
||||
account.set_data(None);
|
||||
assert!(!watches.identity.has_changed().unwrap());
|
||||
assert!(!watches.data.has_changed().unwrap());
|
||||
|
||||
let proof = identity();
|
||||
account.set_identity(Some(proof.clone()));
|
||||
assert!(watches.identity.borrow_and_update().is_some());
|
||||
// An account again is a change (each connection signs its proof anew), the
|
||||
// same data is none.
|
||||
account.set_identity(Some(proof));
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
watches.identity.borrow_and_update();
|
||||
let data = Arc::new(tsclientlib::MytsData::default());
|
||||
account.set_data(Some(data.clone()));
|
||||
assert!(watches.data.has_changed().unwrap());
|
||||
watches.data.borrow_and_update();
|
||||
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
|
||||
// A sign-out is a change.
|
||||
account.set_identity(None);
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
assert!(watches.identity.borrow_and_update().is_none());
|
||||
}
|
||||
|
||||
/// A connection outlives the connector that made it (a session handed out
|
||||
/// by a connector that was dropped): its watches keep their senders.
|
||||
#[test]
|
||||
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
|
||||
let link = TsLink::new();
|
||||
let watches = link.account().watches();
|
||||
drop(link);
|
||||
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
|
||||
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
//! The TeamSpeak connection's presence as v1 entities (protocol section
|
||||
//! 11.1, "Ids and entities"): the client's older model on one side, the
|
||||
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
|
||||
//! `VoiceState` on the other.
|
||||
//!
|
||||
//! [`build`] is the translation the TeamSpeak `Session` makes of every
|
||||
//! snapshot its link reports; the engine's projection (`link/project.rs`)
|
||||
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
|
||||
//! both keep: projecting what was built gives back the snapshot (up to the
|
||||
//! normalisations of section 5.4). What v1 has no field for rides in
|
||||
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use voelin_model::replica::Key;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_proto::v1::{self, Entity, entity::Kind};
|
||||
|
||||
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
|
||||
|
||||
/// Entities by key, as a scope holds them.
|
||||
pub(crate) type Layer = BTreeMap<Key, Entity>;
|
||||
|
||||
/// The entities one snapshot stands for, by scope.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Built {
|
||||
/// SERVER (1): the server, its channels and its roles.
|
||||
pub server: Layer,
|
||||
/// LIVE (1): who is online and where.
|
||||
pub live: Layer,
|
||||
/// The own user, for HOME, when the snapshot holds our client.
|
||||
pub own_user: Option<v1::User>,
|
||||
/// Clients by unique id: their user id and participant id.
|
||||
pub by_uid: HashMap<String, (u64, u32)>,
|
||||
}
|
||||
|
||||
/// The `Foreign` of something v1 has no field for.
|
||||
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
|
||||
v1::Foreign {
|
||||
system: FOREIGN_SYSTEM.into(),
|
||||
kind: kind.into(),
|
||||
json: serde_json::to_vec(json).unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(kind: Kind) -> Entity {
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// A picture known by its id (an icon CRC).
|
||||
fn icon(id: u32) -> Option<v1::Image> {
|
||||
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
|
||||
match mode {
|
||||
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
|
||||
}
|
||||
}
|
||||
|
||||
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
|
||||
match mode {
|
||||
HostMessageMode::None => v1::HostMessageMode::None,
|
||||
HostMessageMode::Log => v1::HostMessageMode::Log,
|
||||
HostMessageMode::Modal => v1::HostMessageMode::Modal,
|
||||
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Server` entity of a connection.
|
||||
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
|
||||
let gfx =
|
||||
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
|
||||
let banner = (!details.banner_url.is_empty()
|
||||
|| !details.banner_gfx_url.is_empty()
|
||||
|| details.banner_gfx_interval_s != 0
|
||||
|| details.banner_mode != BannerMode::NoAdjust)
|
||||
.then(|| v1::Banner {
|
||||
image: gfx(&details.banner_gfx_url),
|
||||
link: details.banner_url.clone(),
|
||||
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
|
||||
mode: banner_mode(details.banner_mode) as i32,
|
||||
});
|
||||
let host_button = (!details.host_button_tooltip.is_empty()
|
||||
|| !details.host_button_url.is_empty()
|
||||
|| !details.host_button_gfx_url.is_empty())
|
||||
.then(|| v1::HostButton {
|
||||
tooltip: details.host_button_tooltip.clone(),
|
||||
url: details.host_button_url.clone(),
|
||||
icon: gfx(&details.host_button_gfx_url),
|
||||
});
|
||||
v1::Server {
|
||||
id: SERVER_ID,
|
||||
name: name.to_owned(),
|
||||
icon: icon(details.icon),
|
||||
banner,
|
||||
host_button,
|
||||
welcome: details.welcome_message.clone(),
|
||||
host_message: details.host_message.clone(),
|
||||
host_message_mode: host_message_mode(details.host_message_mode) as i32,
|
||||
default_channel_id: default_channel,
|
||||
default_role_id: details.default_server_group.unwrap_or(0),
|
||||
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
|
||||
priority_dim_db: details.priority_speaker_dimm_db,
|
||||
max_members: u32::from(details.max_clients),
|
||||
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
|
||||
foreign: Some(foreign(
|
||||
"server",
|
||||
&json!({ "platform": details.platform, "version": details.version }),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The server group or channel group `info` as a role.
|
||||
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
|
||||
v1::Role {
|
||||
id: if channel { ids::channel_role(info.id) } else { info.id },
|
||||
server_id: SERVER_ID,
|
||||
name: info.name.clone(),
|
||||
icon: icon(info.icon),
|
||||
position: info.sort_id.saturating_neg(),
|
||||
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
|
||||
name_mode: match info.naming_mode {
|
||||
GroupNamingMode::None => v1::NameMode::None,
|
||||
GroupNamingMode::Before => v1::NameMode::Before,
|
||||
GroupNamingMode::After => v1::NameMode::After,
|
||||
} as i32,
|
||||
kind: match info.group_type {
|
||||
GroupType::Template => v1::RoleKind::Template,
|
||||
GroupType::Regular => v1::RoleKind::Regular,
|
||||
GroupType::Query => v1::RoleKind::Query,
|
||||
} as i32,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sibling chain of each parent as positions: `order` names the sibling
|
||||
/// above, so the chain is followed from 0; siblings that no chain reaches
|
||||
/// (a snapshot with broken orders) follow by id.
|
||||
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
|
||||
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
|
||||
for channel in channels.values() {
|
||||
by_parent.entry(channel.parent).or_default().push(channel);
|
||||
}
|
||||
let mut positions = HashMap::new();
|
||||
for siblings in by_parent.values() {
|
||||
let mut placed: HashSet<ChannelId> = HashSet::new();
|
||||
let mut next = 0;
|
||||
let mut above = 0;
|
||||
// The sibling whose `order` is the one placed last (lowest id first, so
|
||||
// that two claiming the same place do not depend on map order).
|
||||
while let Some(channel) = siblings
|
||||
.iter()
|
||||
.filter(|c| c.order == above && !placed.contains(&c.id))
|
||||
.min_by_key(|c| c.id)
|
||||
{
|
||||
positions.insert(channel.id, next * 1024);
|
||||
placed.insert(channel.id);
|
||||
above = channel.id;
|
||||
next += 1;
|
||||
}
|
||||
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
|
||||
positions.insert(channel.id, next * 1024);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
|
||||
let mut needed = HashMap::new();
|
||||
if info.needed_talk_power != 0 {
|
||||
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
|
||||
}
|
||||
if info.needed_subscribe_power != 0 {
|
||||
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
|
||||
}
|
||||
let banner =
|
||||
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
|
||||
v1::Banner {
|
||||
image: info
|
||||
.banner_gfx_url
|
||||
.as_ref()
|
||||
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
|
||||
mode: banner_mode(info.banner_mode) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
v1::Channel {
|
||||
id: info.id,
|
||||
server_id: SERVER_ID,
|
||||
parent_id: info.parent,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: info.name.clone(),
|
||||
topic: info.topic.clone().unwrap_or_default(),
|
||||
position,
|
||||
has_password: info.has_password,
|
||||
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
|
||||
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
|
||||
needed,
|
||||
icon: icon(info.icon),
|
||||
banner,
|
||||
is_default: info.is_default,
|
||||
foreign: (info.max_clients == Some(0))
|
||||
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a client is. `Foreign` carries a unique id that is no base64.
|
||||
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let bytes = uid.and_then(ids::uid_bytes);
|
||||
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
|
||||
hash: client.avatar.clone().unwrap_or_default(),
|
||||
url: client.myts_avatar.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
});
|
||||
v1::User {
|
||||
id,
|
||||
uid: bytes.clone().unwrap_or_default().into(),
|
||||
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
|
||||
name: client.nickname.clone(),
|
||||
avatar,
|
||||
badges: client.badges.clone(),
|
||||
country: client.country.clone().unwrap_or_default(),
|
||||
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot (the sender of a message or a poke): its
|
||||
/// unique id and name only. `None` for a unique id with no content.
|
||||
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
|
||||
user(
|
||||
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
|
||||
ids::synthetic_user(uid),
|
||||
ts6,
|
||||
)
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot and has no unique id (the sender of a poke
|
||||
/// or a message that the link names by its client id only): `id` and name.
|
||||
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
|
||||
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
|
||||
}
|
||||
|
||||
/// Everything the snapshot `presence` says, as entities of the scopes of
|
||||
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
|
||||
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
|
||||
let mut built = Built::default();
|
||||
let name =
|
||||
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
|
||||
let default_channel =
|
||||
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
|
||||
let put = |layer: &mut Layer, kind: Kind| {
|
||||
let entity = entity(kind);
|
||||
if let Some(key) = Key::of(&entity) {
|
||||
layer.insert(key, entity);
|
||||
}
|
||||
};
|
||||
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
|
||||
put(
|
||||
&mut built.server,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: SERVER_CHAT,
|
||||
server_id: SERVER_ID,
|
||||
kind: v1::ChannelKind::ServerChat as i32,
|
||||
name: "Server chat".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let positions = positions(&presence.channels);
|
||||
for info in presence.channels.values() {
|
||||
let position = positions.get(&info.id).copied().unwrap_or_default();
|
||||
put(&mut built.server, Kind::Channel(channel(info, position)));
|
||||
}
|
||||
for info in presence.server_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, false)));
|
||||
}
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
// The own client first, then by client id.
|
||||
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
|
||||
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in clients {
|
||||
// The same identity twice on a server has one database id: the own
|
||||
// client keeps it (it must stay the user we are, also while a ghost of
|
||||
// our old connection lingers), else the lower client id; the other is a
|
||||
// user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
});
|
||||
if !used.insert(id) {
|
||||
id = ids::synthetic_user(&format!("client:{}", client.id));
|
||||
used.insert(id);
|
||||
}
|
||||
let participant = u32::from(client.id);
|
||||
if let Some(uid) = uid {
|
||||
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
|
||||
}
|
||||
let user = user(client, id, ts6);
|
||||
if Some(client.id) == own_client {
|
||||
built.own_user = Some(user.clone());
|
||||
}
|
||||
put(&mut built.live, Kind::User(user));
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Member(v1::Member {
|
||||
server_id: SERVER_ID,
|
||||
user_id: id,
|
||||
roles: client.server_groups.clone(),
|
||||
channel_roles: client
|
||||
.channel_group
|
||||
.map(|group| (client.channel, ids::channel_role(group)))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
description: client.description.clone().unwrap_or_default(),
|
||||
foreign: (client.icon != 0)
|
||||
.then(|| foreign("client", &json!({ "icon": client.icon }))),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Presence(v1::Presence {
|
||||
user_id: id,
|
||||
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
|
||||
as i32,
|
||||
text: client.away.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: participant,
|
||||
user_id: id,
|
||||
channel_id: client.channel,
|
||||
slot: slot(client.id),
|
||||
nick: client.nickname.clone(),
|
||||
kind: if client.is_query {
|
||||
v1::ParticipantKind::Query
|
||||
} else {
|
||||
v1::ParticipantKind::User
|
||||
} as i32,
|
||||
self_mute: client.input_muted,
|
||||
self_deaf: client.output_muted,
|
||||
priority_speaker: client.priority_speaker,
|
||||
channel_commander: client.channel_commander,
|
||||
talker: client.talker,
|
||||
talk_power: client.talk_power,
|
||||
recording: client.recording,
|
||||
streaming: client.streaming.unwrap_or(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// The unique id of a user as the client's older model writes it: base64 for
|
||||
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
|
||||
/// ServerQuery client's login name). `None` for a user without one.
|
||||
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
|
||||
let kept = user
|
||||
.foreign
|
||||
.as_ref()
|
||||
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
|
||||
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
|
||||
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
|
||||
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
|
||||
}
|
||||
|
||||
/// The media slot of a client: its id plus one (slot 0 is not a media source).
|
||||
pub(crate) fn slot(client: u16) -> u32 {
|
||||
u32::from(client) + 1
|
||||
}
|
||||
|
||||
/// The key of an entity, as a `Change` deletes it: the key fields only.
|
||||
pub(crate) fn key_only(entity: &Entity) -> Entity {
|
||||
let kind = match entity.kind.as_ref() {
|
||||
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
|
||||
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
|
||||
Some(Kind::Role(r)) => {
|
||||
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Member(m)) => Kind::Member(v1::Member {
|
||||
server_id: m.server_id,
|
||||
user_id: m.user_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
|
||||
Some(Kind::Presence(p)) => {
|
||||
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
|
||||
server_id: v.server_id,
|
||||
participant_id: v.participant_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::Message(m)) => {
|
||||
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
|
||||
_ => return entity.clone(),
|
||||
};
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// What changed from `old` to `new`: the entities to put (new or different)
|
||||
/// and the keys to delete.
|
||||
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
|
||||
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
|
||||
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
|
||||
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_order_chain_becomes_positions() {
|
||||
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
|
||||
let channels: BTreeMap<_, _> = [
|
||||
channel_info(1, 0, 3),
|
||||
channel_info(2, 0, 1),
|
||||
channel_info(3, 0, 0),
|
||||
channel_info(5, 3, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
|
||||
assert_eq!(positions[&5], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siblings_a_chain_does_not_reach_follow_by_id() {
|
||||
// Both claim the first place, and 4 follows nobody.
|
||||
let channels: BTreeMap<_, _> =
|
||||
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_twice_keeps_both_clients() {
|
||||
let client = |id, db| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(db),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3, 77), client(4, 77)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let built = build(&presence, false, None);
|
||||
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
|
||||
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
/// The own client is the user whose database id the identity has, also when a
|
||||
/// ghost of the old connection (the lower client id) lingers.
|
||||
#[test]
|
||||
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
|
||||
let client = |id| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(77),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3), client(4)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let user_of = |built: &Built, client: u32| {
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
|
||||
panic!("no voice state")
|
||||
};
|
||||
voice.user_id
|
||||
};
|
||||
// Nobody is us: the lower client id keeps it.
|
||||
let built = build(&presence, false, None);
|
||||
assert_eq!(user_of(&built, 3), 77);
|
||||
assert_ne!(user_of(&built, 4), 77);
|
||||
// The later client is us: it keeps it, and the ghost has the made-up id.
|
||||
let built = build(&presence, false, Some(4));
|
||||
assert_eq!(user_of(&built, 4), 77);
|
||||
assert_ne!(user_of(&built, 3), 77);
|
||||
assert_eq!(built.own_user.map(|u| u.id), Some(77));
|
||||
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
presence.channels.insert(1, channel_info(1, 0, 0));
|
||||
let before = build(&presence, false, None);
|
||||
presence.channels.insert(2, channel_info(2, 0, 1));
|
||||
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
|
||||
let after = build(&presence, false, None);
|
||||
let (put, del) = diff(&before.server, &after.server);
|
||||
assert_eq!(put.len(), 2, "the renamed channel and the new one");
|
||||
assert!(del.is_empty());
|
||||
let (put, del) = diff(&after.server, &before.server);
|
||||
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
|
||||
assert_eq!(del.len(), 1);
|
||||
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
|
||||
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
|
||||
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
|
||||
//! synthetic ones with bit 63 set.
|
||||
//!
|
||||
//! Both sides of the seam use these rules: the TeamSpeak `Session`
|
||||
//! ([`super::LinkSession`]) writes entities with them, and the engine's
|
||||
//! projection (`link/project.rs`) undoes the few that the client's older
|
||||
//! model has no room for.
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The only server of a TeamSpeak connection (its virtual server).
|
||||
pub(crate) const SERVER_ID: u64 = 1;
|
||||
|
||||
/// Marks the ids the gateway makes up: the server chat, direct-message
|
||||
/// channels and users it knows by their unique id only.
|
||||
pub(crate) const SYNTHETIC: u64 = 1 << 63;
|
||||
|
||||
/// The channel of the server chat, in the SERVER scope.
|
||||
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
|
||||
|
||||
/// Set on the id of a channel group, so that a role id does not mean a server
|
||||
/// group and a channel group at once.
|
||||
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
|
||||
|
||||
/// The `Foreign.system` of what the protocol has no field for.
|
||||
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
|
||||
|
||||
/// The role id of a channel group.
|
||||
pub(crate) fn channel_role(group: u64) -> u64 {
|
||||
group | CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// The channel group a role id stands for (the reverse of [`channel_role`]).
|
||||
pub(crate) fn channel_group(role: u64) -> u64 {
|
||||
role & !CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A synthetic id for something known by a name only: bit 63 set and the
|
||||
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
|
||||
/// [`SERVER_CHAT`]).
|
||||
fn synthetic(name: &str) -> u64 {
|
||||
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
|
||||
SYNTHETIC | low.max(1)
|
||||
}
|
||||
|
||||
/// The direct-message channel with the client of this unique id.
|
||||
pub(crate) fn dm_channel(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The user id of a client that has no database id (or that the snapshot
|
||||
/// does not hold): by unique id, else by whatever names it.
|
||||
pub(crate) fn synthetic_user(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
|
||||
/// writes): decoding and encoding again gives the same text. A ServerQuery
|
||||
/// client's login name, or anything else, is not, and goes into
|
||||
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
|
||||
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
|
||||
let bytes = STANDARD.decode(uid).ok()?;
|
||||
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_groups_keep_their_number_below_the_flag() {
|
||||
assert_eq!(channel_role(8), 8 | (1 << 62));
|
||||
assert_eq!(channel_group(channel_role(8)), 8);
|
||||
assert_eq!(channel_group(channel_role(0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
|
||||
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
|
||||
let id = dm_channel(name);
|
||||
assert_ne!(id & SYNTHETIC, 0, "{name}");
|
||||
assert_ne!(id, SERVER_CHAT, "{name}");
|
||||
}
|
||||
assert_eq!(dm_channel("alice="), dm_channel("alice="));
|
||||
assert_ne!(dm_channel("alice="), dm_channel("bob="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_canonical_base64_is_a_unique_id() {
|
||||
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
|
||||
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
|
||||
assert_eq!(
|
||||
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
|
||||
Some(32)
|
||||
);
|
||||
// A ServerQuery login name, a fixture's name, the empty string.
|
||||
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
|
||||
assert_eq!(uid_bytes(not), None, "{not:?}");
|
||||
}
|
||||
// Non-canonical trailing bits decode but do not round trip.
|
||||
assert_eq!(uid_bytes("Af5="), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
//! The TeamSpeak `Session` against the development servers
|
||||
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
|
||||
//! Runs only with `VOELIN_LIVE=1`:
|
||||
//!
|
||||
//! ```text
|
||||
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
|
||||
//!
|
||||
//! - the link conformance suite of the protocol repository, the cases that
|
||||
//! apply to a TeamSpeak session, with the verdict of every case asserted
|
||||
//! and the reason of every case that cannot pass or cannot run in
|
||||
//! [`EXPECTED`];
|
||||
//! - what the suite cannot reach, as a session of its own does it: a message
|
||||
//! in the own channel answered, then pushed to the other session and back to
|
||||
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
|
||||
//! one session's slot to the other's media sink, and a channel file written
|
||||
//! and read back from an offset.
|
||||
//!
|
||||
//! The sessions are made by [`TsConnector`] through the plain `Connector`
|
||||
//! interface, as a client of the seam outside an engine would make them.
|
||||
//!
|
||||
//! The servers ban an address that connects as often as these tests do
|
||||
//! (`ConnectFailedBanned` after three or four connections) unless their
|
||||
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
|
||||
//! prepares its admin identity; this module raises them itself, once per server
|
||||
//! and run, through the ServerQuery admin login that `refused_moves` uses
|
||||
//! ([`raise_flood_limits`]), so that the command above works on a freshly
|
||||
//! started stack. It needs that login (the development servers of
|
||||
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::PT_OPUS;
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
|
||||
use voelin_proto::v1::request::Op;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// How long a test waits for the server.
|
||||
const WAIT: Duration = Duration::from_secs(20);
|
||||
|
||||
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
|
||||
match tokio::time::timeout(WAIT, future).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A development server: where to connect, and how to ask it as the admin.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Dev {
|
||||
name: &'static str,
|
||||
voice: &'static str,
|
||||
ssh: bool,
|
||||
query: &'static str,
|
||||
}
|
||||
|
||||
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
|
||||
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
|
||||
|
||||
impl Dev {
|
||||
fn query(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: if self.ssh {
|
||||
voelin_query::Transport::Ssh
|
||||
} else {
|
||||
voelin_query::Transport::Raw
|
||||
},
|
||||
addr: self.query.into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("voelin-dev-admin".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// A nickname no other client of this run has.
|
||||
fn nick(&self, role: &str) -> String {
|
||||
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{role}-{}-{n}", std::process::id() % 10_000)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise the anti-flood limits of a development server, once per run, and
|
||||
/// lift the bans an earlier run left behind. The tests connect many times in
|
||||
/// a few seconds from one address, which a server with its default limits
|
||||
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
|
||||
/// values in `admin_args`. Done through the ServerQuery login of the admin,
|
||||
/// which the tests that create channels and keys use as well.
|
||||
async fn raise_flood_limits(dev: &Dev) {
|
||||
use tokio::sync::OnceCell;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
static TS3_READY: OnceCell<()> = OnceCell::const_new();
|
||||
static TS6_READY: OnceCell<()> = OnceCell::const_new();
|
||||
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
|
||||
ready
|
||||
.get_or_init(|| async {
|
||||
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
|
||||
for key in [
|
||||
"virtualserver_antiflood_points_needed_ip_block",
|
||||
"virtualserver_antiflood_points_needed_command_block",
|
||||
] {
|
||||
let edit = Query::new("serveredit").arg(key, 100_000);
|
||||
within("the anti-flood limits", admin.send(&edit))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
|
||||
}
|
||||
// A ban of an earlier run outlives the change of the limit.
|
||||
within("the ban list", admin.send(&Query::new("bandelall")))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A TeamSpeak session as a client of the seam sees it: made by the
|
||||
/// connector, with its push channel and media sink.
|
||||
async fn session(
|
||||
dev: &Dev,
|
||||
options: &VoiceOptions,
|
||||
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
|
||||
raise_flood_limits(dev).await;
|
||||
let (sink, media) = media_channel();
|
||||
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
|
||||
let connected =
|
||||
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
|
||||
(connected.session, connected.pushes, media)
|
||||
}
|
||||
|
||||
/// A client of the TeamSpeak session that has done what an engine does after
|
||||
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
|
||||
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
|
||||
struct Client {
|
||||
session: Arc<dyn Session>,
|
||||
pushes: mpsc::Receiver<v1::Push>,
|
||||
media: MediaReceiver,
|
||||
server: u64,
|
||||
default_channel: u64,
|
||||
/// Our seat in voice (participant, slot, channel).
|
||||
seat: v1::VoiceState,
|
||||
/// The voice states of the server, as the pushes told them.
|
||||
voices: BTreeMap<u32, v1::VoiceState>,
|
||||
}
|
||||
|
||||
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
|
||||
v1::Scope { kind: kind as i32, id }
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn connect(dev: &Dev, nick: &str) -> Self {
|
||||
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
|
||||
}
|
||||
|
||||
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
|
||||
let (session, pushes, media) = session(dev, &options).await;
|
||||
let mut client = Self {
|
||||
session,
|
||||
pushes,
|
||||
media,
|
||||
server: 0,
|
||||
default_channel: 0,
|
||||
seat: v1::VoiceState::default(),
|
||||
voices: BTreeMap::new(),
|
||||
};
|
||||
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
|
||||
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
|
||||
panic!("the server list is not entities")
|
||||
};
|
||||
let server = servers
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
Some(Kind::Server(server)) => Some(server.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host lists its server");
|
||||
client.server = server.id;
|
||||
client.default_channel = server.default_channel_id;
|
||||
for scope in [
|
||||
scope(v1::ScopeKind::Home, 0),
|
||||
scope(v1::ScopeKind::Server, server.id),
|
||||
scope(v1::ScopeKind::Live, server.id),
|
||||
] {
|
||||
client.subscribe(scope).await;
|
||||
}
|
||||
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
|
||||
client.settle().await;
|
||||
client
|
||||
}
|
||||
|
||||
/// A request, answered within [`WAIT`].
|
||||
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
|
||||
within("an answer", self.session.request(op)).await
|
||||
}
|
||||
|
||||
/// Subscribe `scope` and take its sync off the push channel.
|
||||
async fn subscribe(&mut self, scope: v1::Scope) {
|
||||
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
|
||||
self.ask(op).await.expect("a subscription");
|
||||
self.until("the end of the sync", |push| match &push.body {
|
||||
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `JoinVoice`: our seat, or why not.
|
||||
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
|
||||
let join = v1::JoinVoice {
|
||||
server_id: self.server,
|
||||
channel_id: channel,
|
||||
password: password.into(),
|
||||
..Default::default()
|
||||
};
|
||||
match self.ask(Op::JoinVoice(join)).await? {
|
||||
Answer::Entities(entities) => entities
|
||||
.items
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind {
|
||||
Some(Kind::Voice(voice)) => Some(voice),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
|
||||
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep track of what a push says about the server and its voice states.
|
||||
fn absorb(&mut self, push: &v1::Push) {
|
||||
let Some(v1::push::Body::Change(change)) = &push.body else { return };
|
||||
for entity in &change.put {
|
||||
match &entity.kind {
|
||||
Some(Kind::Voice(voice)) => {
|
||||
self.voices.insert(voice.participant_id, voice.clone());
|
||||
}
|
||||
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
|
||||
self.default_channel = server.default_channel_id;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for entity in &change.del {
|
||||
if let Some(Kind::Voice(voice)) = &entity.kind {
|
||||
self.voices.remove(&voice.participant_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next push `f` picks, skipping (and keeping track of) the others.
|
||||
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
|
||||
within(what, async {
|
||||
loop {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
if let Some(t) = f(&push) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wait until the host shows our seat in LIVE: the first snapshot of the
|
||||
/// TeamSpeak link may come after the session was handed out, so the syncs
|
||||
/// can be empty and the voice states follow as changes. The seat then
|
||||
/// names the channel we are in.
|
||||
async fn settle(&mut self) {
|
||||
let participant = self.seat.participant_id;
|
||||
within("our voice state to appear", async {
|
||||
while !self.voices.contains_key(&participant) {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
self.seat = self.voices[&participant].clone();
|
||||
}
|
||||
|
||||
/// The next message `Change` of the CHAT scope of `channel` with `text`.
|
||||
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
|
||||
let chat = Some(scope(v1::ScopeKind::Chat, channel));
|
||||
self.until(&format!("the message {text:?}"), |push| match &push.body {
|
||||
Some(v1::push::Body::Change(change)) if change.scope == chat => {
|
||||
change.put.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
self.session.close(v1::CloseCode::Normal, "");
|
||||
within("the session to close", self.session.closed()).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the conformance suite ----------------------------------------------------
|
||||
|
||||
/// What a case is expected to do against a TeamSpeak session, and why.
|
||||
enum Expect {
|
||||
/// Every assertion of the case holds.
|
||||
Passes,
|
||||
/// The session lacks the feature the case needs (`Verdict::Skipped`).
|
||||
Skipped(&'static str),
|
||||
/// The case does not apply: it cannot run, or cannot pass, for this reason
|
||||
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
|
||||
NotRun(&'static str),
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `v0.2.0`, in its
|
||||
/// order, with what a TeamSpeak session does with it. A case the suite gains
|
||||
/// fails `the_suite_is_known` until it is listed here.
|
||||
///
|
||||
/// The suite is written for a backend that is a `FakeHost`. A case that needs
|
||||
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
|
||||
/// that hold, kill or read it, or push into it, cannot run against a session of
|
||||
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
|
||||
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
|
||||
/// `Emoji`, attachments). Each reason is what the case did when it was run.
|
||||
const EXPECTED: [(&str, Expect); 17] = [
|
||||
("welcome_matches_features", Passes),
|
||||
(
|
||||
"subscribe_syncs_the_scope",
|
||||
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"subscribe_resumes_from_a_cursor",
|
||||
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
|
||||
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"delete_answers_an_ack_and_pushes_the_removal",
|
||||
NotRun(
|
||||
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
|
||||
where the case needs only `chat`, not `chat.delete` (P8)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"a_key_names_an_entity_without_its_server",
|
||||
NotRun(
|
||||
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
|
||||
which TeamSpeak lacks, though it needs no feature (P8)",
|
||||
),
|
||||
),
|
||||
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
|
||||
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
|
||||
("list_pages_history", Skipped("chat.history")),
|
||||
(
|
||||
"cancel_before_apply_is_cancelled",
|
||||
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
|
||||
),
|
||||
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
|
||||
(
|
||||
"notifications_are_fire_and_forget",
|
||||
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
|
||||
),
|
||||
(
|
||||
"renew_account_follows_the_feature",
|
||||
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
|
||||
),
|
||||
(
|
||||
"media_loops_back",
|
||||
NotRun(
|
||||
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
|
||||
),
|
||||
),
|
||||
(
|
||||
"files_round_trip",
|
||||
NotRun(
|
||||
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
|
||||
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
|
||||
),
|
||||
),
|
||||
("close_ends_the_session", Passes),
|
||||
(
|
||||
"the_backend_can_end_the_session",
|
||||
NotRun(
|
||||
"kills the unrelated fake session, so closed() of this one never resolves; and a \
|
||||
kick is Network(text), not Remote{KICKED}, until H1",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
|
||||
/// backend behind the session; a TeamSpeak server has none, so it gets the one
|
||||
/// of an unrelated fake host, which the cases that are run never touch.
|
||||
async fn fixture(dev: Dev) -> Fixture {
|
||||
let (session, pushes, media) =
|
||||
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
|
||||
let unrelated = FakeConnector::new();
|
||||
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
|
||||
unrelated.connect(params).await.expect("a fake session");
|
||||
let backend = unrelated.last_session().expect("a fake session");
|
||||
Fixture::new(session, pushes, media, backend)
|
||||
}
|
||||
|
||||
fn the_suite_is_known() {
|
||||
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
|
||||
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
|
||||
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
|
||||
}
|
||||
|
||||
/// The cases that apply run and pass, the ones that need a feature the session
|
||||
/// lacks are skipped, and the rest are not run (their reason is in
|
||||
/// [`EXPECTED`]).
|
||||
async fn conformance_subset(dev: Dev) {
|
||||
the_suite_is_known();
|
||||
let harness = move || fixture(dev);
|
||||
let (mut passed, mut skipped) = (0, 0);
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
match expect {
|
||||
Passes => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
|
||||
passed += 1;
|
||||
}
|
||||
Skipped(feature) => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
|
||||
skipped += 1;
|
||||
}
|
||||
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
|
||||
}
|
||||
}
|
||||
assert_eq!((passed, skipped), (2, 4));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what the suite cannot reach ----------------------------------------------
|
||||
|
||||
/// A message in the own channel is answered with the message as written, and
|
||||
/// pushed to the CHAT scope of every session in the channel: to the other one
|
||||
/// as a `Change`, and back to ours (the ids agree only with the native
|
||||
/// session of H1: the answer has a local id, the echo the one of the
|
||||
/// `Change`).
|
||||
async fn chat_in_the_own_channel(dev: Dev) {
|
||||
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
|
||||
let channel = a.seat.channel_id;
|
||||
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
|
||||
let text = format!("live-chat-{}", std::process::id());
|
||||
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
|
||||
let write = v1::Write {
|
||||
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
|
||||
paths: Vec::new(),
|
||||
};
|
||||
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
|
||||
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
|
||||
panic!("a message is answered with entities")
|
||||
};
|
||||
let written = match &answer.items[..] {
|
||||
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
|
||||
other => panic!("one message expected, got {other:?}"),
|
||||
};
|
||||
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
|
||||
|
||||
let heard = b.message(channel, &text).await;
|
||||
assert_ne!(heard.id, 0);
|
||||
assert_eq!(heard.channel_id, channel);
|
||||
// And ours, back from the server: the same words, once.
|
||||
let echo = a.message(channel, &text).await;
|
||||
assert_ne!(echo.id, 0);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move into a channel with a password or without room is refused with the
|
||||
/// code the seam names: `PASSWORD` and `FULL`.
|
||||
async fn refused_moves(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let tag = std::process::id() % 10_000;
|
||||
let create = |name: &str| {
|
||||
Query::new("channelcreate")
|
||||
.arg("channel_name", format!("{name}-{tag}"))
|
||||
.arg("channel_flag_semi_permanent", 1)
|
||||
};
|
||||
let locked =
|
||||
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full = create("seam-full")
|
||||
.arg("channel_maxclients", 0)
|
||||
.arg("channel_flag_maxclients_unlimited", 0);
|
||||
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
|
||||
// A key for the Normal group, which has to keep to passwords and limits.
|
||||
let token = group_token(&admin, "Normal").await;
|
||||
|
||||
let check = {
|
||||
let token = token.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
|
||||
options.token = Some(token);
|
||||
let client = Client::connect_with(&dev, options).await;
|
||||
let code = |result: Result<v1::VoiceState, SessionError>| match result {
|
||||
Err(SessionError::Rejected(error)) => error.code(),
|
||||
other => panic!("expected a refusal, got {other:?}"),
|
||||
};
|
||||
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
|
||||
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
|
||||
let seat = client.join(locked, "secret").await.expect("the right password");
|
||||
assert_eq!(seat.channel_id, locked);
|
||||
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
|
||||
client.close().await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
// Clean up before reporting a failure; the key is gone once used.
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
for cid in [locked, full] {
|
||||
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
|
||||
}
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A poke is a `Signal` to a participant: the other session gets it, with
|
||||
/// the participant and the words of the sender.
|
||||
async fn poke_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
|
||||
let text = format!("live-poke-{}", std::process::id());
|
||||
let target = v1::SignalTarget {
|
||||
server_id: a.server,
|
||||
participant_id: b.seat.participant_id,
|
||||
..Default::default()
|
||||
};
|
||||
let signal = v1::Signal {
|
||||
to: Some(target),
|
||||
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
|
||||
..Default::default()
|
||||
};
|
||||
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
|
||||
let from = b
|
||||
.until("the poke", |push| match &push.body {
|
||||
Some(v1::push::Body::Signal(signal)) => match &signal.body {
|
||||
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
|
||||
Some(signal.from_participant)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(from, a.seat.participant_id);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of Opus (20 ms, mono, fullband).
|
||||
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
|
||||
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
|
||||
header.marker = marker;
|
||||
let mut out = bytes::BytesMut::new();
|
||||
header.write(flow, &mut out).expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
/// Voice sent on our slot arrives on the sender's slot at the other session's
|
||||
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
|
||||
/// it only has to count up), the marker on the first, and an empty payload at
|
||||
/// the end.
|
||||
async fn voice_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id);
|
||||
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
|
||||
for n in 0..5u8 {
|
||||
let frame = [0xf8, 0xff, 0xfe, n];
|
||||
let packet = rtp(flow, u16::from(n), n == 0, &frame);
|
||||
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
|
||||
|
||||
let mut heard = Vec::new();
|
||||
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
|
||||
if view.payload().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(heard.len() >= 2, "{heard:?}");
|
||||
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
|
||||
let (_, _, first_marker, first_payload) = &heard[0];
|
||||
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
|
||||
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
|
||||
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
|
||||
assert!(
|
||||
end_payload.is_empty() && !*end_marker,
|
||||
"the spurt ends with an empty payload: {heard:?}"
|
||||
);
|
||||
assert_eq!(*end_flow, flow);
|
||||
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
|
||||
assert!(
|
||||
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
|
||||
"the sequence counts up by one: {sequences:?}"
|
||||
);
|
||||
// Voice on a slot that is not ours is refused before it reaches the server.
|
||||
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
|
||||
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel file written with `write_file` and read back from an offset with
|
||||
/// `read_file`: the head names the file and its size, the body starts where
|
||||
/// the offset says.
|
||||
async fn channel_file_from_an_offset(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
// Guests may not upload: a key for the Server Admin group.
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let token = group_token(&admin, "Server Admin").await;
|
||||
let check = tokio::spawn({
|
||||
let token = token.clone();
|
||||
async move { channel_file_with_a_key(dev, token).await }
|
||||
});
|
||||
let result = check.await;
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-time key for the server group `name` (a template group, type 1).
|
||||
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
|
||||
use voelin_query::Command as Query;
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let group = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.unwrap_or_else(|| panic!("a {name} server group"));
|
||||
let key =
|
||||
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
|
||||
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
|
||||
}
|
||||
|
||||
async fn channel_file_with_a_key(dev: Dev, token: String) {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
|
||||
options.token = Some(token);
|
||||
let a = Client::connect_with(&dev, options).await;
|
||||
let channel = a.seat.channel_id;
|
||||
let name = format!("seam-{}.bin", std::process::id());
|
||||
let path = format!("/{name}");
|
||||
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
|
||||
|
||||
let write = v1::FileWrite {
|
||||
target: Some(v1::file_write::Target::Path(target.clone())),
|
||||
size: data.len() as u64,
|
||||
offset: 0,
|
||||
overwrite: true,
|
||||
sha256: Default::default(),
|
||||
};
|
||||
let mut upload =
|
||||
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
|
||||
upload.body.write_all(&data).await.expect("the body");
|
||||
upload.body.shutdown().await.expect("the end of the body");
|
||||
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
|
||||
assert!(
|
||||
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
|
||||
"{stored:?}"
|
||||
);
|
||||
|
||||
let read = v1::FileRead {
|
||||
target: Some(v1::file_read::Target::Path(target.clone())),
|
||||
offset: 1_000,
|
||||
length: 0,
|
||||
};
|
||||
let mut download =
|
||||
within("the download to open", a.session.read_file(read)).await.expect("a download");
|
||||
let size = download.head.items.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::File(file)) => Some(file.size),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(size, Some(3_000), "{:?}", download.head);
|
||||
let mut body = Vec::new();
|
||||
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
|
||||
assert_eq!(body, data[1_000..], "the body starts at the offset");
|
||||
|
||||
// Clean up what we put on the server.
|
||||
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
|
||||
let delete = Op::Delete(v1::Delete {
|
||||
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
|
||||
..Default::default()
|
||||
});
|
||||
let _ = a.ask(delete).await;
|
||||
a.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the cases that do not apply ----------------------------------------------
|
||||
|
||||
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
|
||||
/// TeamSpeak server, each with a panic of its own (its first line is printed):
|
||||
/// the reasons of the table are what they did when they were run. A case that
|
||||
/// passes one day (with the native session of H1) is to be moved to `Passes`.
|
||||
///
|
||||
/// Ignored by default: the cases that wait for a backend that is not there
|
||||
/// take their three seconds each.
|
||||
async fn cases_that_do_not_apply_fail(dev: Dev) {
|
||||
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
|
||||
// it out without a word.
|
||||
the_suite_is_known();
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
let NotRun(reason) = expect else { continue };
|
||||
let harness = move || async move {
|
||||
let mut fixture = fixture(dev).await;
|
||||
fixture.step = Duration::from_secs(3);
|
||||
fixture
|
||||
};
|
||||
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
|
||||
Err(error) if error.is_panic() => {
|
||||
let payload = error.into_panic();
|
||||
let message = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
|
||||
.unwrap_or_default();
|
||||
let first = message.lines().next().unwrap_or_default();
|
||||
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
|
||||
}
|
||||
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts3_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts6_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS6).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
|
||||
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
|
||||
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
|
||||
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
use super::entities::slot;
|
||||
|
||||
/// Silence this long between two packets of a talker starts a new talk spurt
|
||||
/// (the marker bit is set on the first packet of it).
|
||||
const SPURT_GAP: Duration = Duration::from_millis(250);
|
||||
|
||||
/// What is kept of the last packet of a talker.
|
||||
struct Talker {
|
||||
timestamp: u32,
|
||||
sequence: u16,
|
||||
at: Instant,
|
||||
/// The 48 kHz ticks the last packet spans.
|
||||
ticks: u32,
|
||||
/// The last packet ended the spurt.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Wraps what a TeamSpeak connection receives into RTP.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Downlink {
|
||||
talkers: HashMap<u16, Talker>,
|
||||
}
|
||||
|
||||
impl Downlink {
|
||||
/// `packet` as the RTP packet of its talker's slot. The sequence number is
|
||||
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
|
||||
/// packet's duration (its Opus table-of-contents byte) on the packet id's
|
||||
/// counter, so it never goes back when the id wraps, and by wall-clock time
|
||||
/// across silences, so a silence is not compressed. The marker is set on
|
||||
/// the first packet after an end or a gap, and an end is an empty payload.
|
||||
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
|
||||
let id = packet.talker.0;
|
||||
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
|
||||
let flow = FlowId::new(slot(id), sub);
|
||||
let end = packet.is_end();
|
||||
let (timestamp, marker) = match self.talkers.get(&id) {
|
||||
None => (0, !end),
|
||||
Some(last) => {
|
||||
let gap = now.saturating_duration_since(last.at);
|
||||
if last.ended || gap > SPURT_GAP {
|
||||
// A new spurt: the time that passed since the last packet.
|
||||
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
|
||||
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
|
||||
} else {
|
||||
let ahead = packet.seq.wrapping_sub(last.sequence);
|
||||
if ahead == 0 || ahead >= 0x8000 {
|
||||
// A duplicate or a late packet: where it belongs, and the
|
||||
// state keeps what the latest packet said.
|
||||
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
|
||||
let at = last.timestamp.wrapping_sub(back * last.ticks);
|
||||
return self.finish(flow, packet, at, false);
|
||||
}
|
||||
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
let ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.talkers
|
||||
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
|
||||
self.finish(flow, packet, timestamp, marker)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
&self,
|
||||
flow: FlowId,
|
||||
packet: &VoicePacket,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
) -> Option<MediaPacket> {
|
||||
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
|
||||
header.marker = marker;
|
||||
// An end is an empty payload, also where the server sent one byte.
|
||||
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
|
||||
/// Forget a talker (it left the server).
|
||||
pub(super) fn forget(&mut self, client: u16) {
|
||||
self.talkers.remove(&client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice a media packet of our own slot carries, for TeamSpeak: its
|
||||
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
|
||||
/// that is no RTP.
|
||||
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(EncodedVoice { codec, payload: payload.to_vec() })
|
||||
}
|
||||
|
||||
/// An RTP packet of voice, for tests of both sides.
|
||||
#[cfg(test)]
|
||||
pub(super) fn rtp_packet(
|
||||
flow: FlowId,
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
payload: &[u8],
|
||||
) -> bytes::Bytes {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
|
||||
header.marker = marker;
|
||||
let mut out = BytesMut::new();
|
||||
header.write(flow, &mut out).unwrap();
|
||||
out.extend_from_slice(payload);
|
||||
out.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use voelin_audio::TalkerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
|
||||
/// is 20 ms), mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
|
||||
let v = view(&first);
|
||||
assert!(v.marker());
|
||||
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
|
||||
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
|
||||
// The id wraps; the timestamp keeps counting.
|
||||
let t1 = t0 + Duration::from_millis(20);
|
||||
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
|
||||
let third =
|
||||
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
|
||||
assert!(!view(&second).marker() && !view(&third).marker());
|
||||
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
|
||||
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
// TeamSpeak's single byte after a talk is an end too.
|
||||
let mut down = Downlink::default();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty());
|
||||
let next =
|
||||
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silence_is_not_compressed() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let again =
|
||||
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
|
||||
assert!(view(&again).marker(), "a gap starts a spurt");
|
||||
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
|
||||
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
|
||||
let mut down = Downlink::default();
|
||||
let now = Instant::now();
|
||||
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
|
||||
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
|
||||
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
|
||||
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
|
||||
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
|
||||
let late =
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
|
||||
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
|
||||
let next =
|
||||
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
|
||||
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_loses_its_header_and_stereo_is_music() {
|
||||
let flow = FlowId::new(8, 0);
|
||||
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
|
||||
let voice = uplink(&mono).unwrap();
|
||||
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
|
||||
// The same TOC with the stereo bit.
|
||||
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
|
||||
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
|
||||
// The end of a spurt: an empty payload.
|
||||
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
|
||||
assert!(uplink(&end).unwrap().is_end());
|
||||
// Not RTP.
|
||||
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,887 @@
|
||||
//! A TeamSpeak connection as a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md`, "the TeamSpeak side").
|
||||
//!
|
||||
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
|
||||
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
|
||||
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
|
||||
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
|
||||
//! inside it is what the link tests of the engine run through. [`TsConnector`]
|
||||
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
|
||||
//! addresses.
|
||||
//!
|
||||
//! This module and the files it is made of are TeamSpeak's: they keep the
|
||||
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
|
||||
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
|
||||
//! and everything else is v1 and the client's own model. In the second half
|
||||
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
|
||||
//! (`voelin-gateway-ts` of VoelinGateWay).
|
||||
|
||||
mod driver;
|
||||
pub(crate) mod entities;
|
||||
pub(crate) mod ids;
|
||||
#[cfg(test)]
|
||||
mod live_tests;
|
||||
mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_model::{Link, ServerDetails};
|
||||
use voelin_proto::link::{
|
||||
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
|
||||
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
|
||||
SessionError, Upload, placement, voice_sub,
|
||||
};
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
|
||||
use crate::BackendInfo;
|
||||
use crate::link::{
|
||||
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
|
||||
VERSION_PARAM,
|
||||
};
|
||||
|
||||
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
|
||||
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
|
||||
/// How long the link may take to report its first snapshot after it said it
|
||||
/// is connected; the snapshot gives the `Welcome` its own user.
|
||||
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
|
||||
|
||||
static SESSIONS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ---- what the engine hands a connector ------------------------------------
|
||||
|
||||
/// The options a TeamSpeak link is connected with: the reverse of
|
||||
/// `link::connect_params`. A client version spec that [`versions::resolve`]
|
||||
/// refuses fails the connect, in words.
|
||||
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
|
||||
let link = match Link::parse(¶ms.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
_ => {
|
||||
// Without the query: a channel password rides in it.
|
||||
let shown = crate::link::without_query(¶ms.address);
|
||||
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
|
||||
}
|
||||
};
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
// 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(
|
||||
"a TeamSpeak server needs a TeamSpeak identity".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let spec = params
|
||||
.address
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| {
|
||||
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
|
||||
})
|
||||
.map(|text| {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(text)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
|
||||
})
|
||||
.transpose()?;
|
||||
let client_version = match spec {
|
||||
None => None,
|
||||
Some(spec) => versions::resolve(&spec).map_err(|e| {
|
||||
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
|
||||
})?,
|
||||
};
|
||||
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
|
||||
Ok(ConnectOptions {
|
||||
address: link.address(),
|
||||
nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
|
||||
identity,
|
||||
client_version,
|
||||
server_password: nonempty(¶ms.hello.password).or(link.password.clone()),
|
||||
channel: link.channel.clone(),
|
||||
channel_password: link.channel_password.clone(),
|
||||
token: nonempty(¶ms.hello.invite_code).or(link.token.clone()),
|
||||
audio: ctx.audio,
|
||||
stream_peer: ctx.stream_peer.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- backend and features ---------------------------------------------------
|
||||
|
||||
/// The server software as v1 names it (table 4.7): `teamspeak` with the
|
||||
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
|
||||
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
|
||||
let (product, flavor) = match backend.product.as_str() {
|
||||
"TeamSpeak 3" => ("teamspeak", "ts3"),
|
||||
"TeamSpeak 6" => ("teamspeak", "ts6"),
|
||||
// A TeamSpeak server the engine does not recognise: the version it
|
||||
// sent, no flavor.
|
||||
"" => ("teamspeak", ""),
|
||||
other => (other, ""),
|
||||
};
|
||||
v1::BackendInfo {
|
||||
product: product.into(),
|
||||
version: backend.version.clone(),
|
||||
flavor: flavor.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The features a TeamSpeak connection offers, from what its link can do
|
||||
/// (`docs/session-seam.md` section 4.7).
|
||||
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
|
||||
let mut features =
|
||||
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
|
||||
if capabilities.file_transfer {
|
||||
features.extend(["files", "files.upload"]);
|
||||
}
|
||||
if capabilities.offline_messages {
|
||||
features.push("mailbox");
|
||||
}
|
||||
if capabilities.streams {
|
||||
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
|
||||
}
|
||||
features
|
||||
}
|
||||
|
||||
// ---- the session ------------------------------------------------------------
|
||||
|
||||
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
|
||||
pub(crate) struct LinkSession {
|
||||
welcome: v1::Welcome,
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
/// The media slot of our client; the driver changes it when we are another
|
||||
/// client after TeamSpeak's own reconnect.
|
||||
own_slot: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
|
||||
}
|
||||
|
||||
impl Session for LinkSession {
|
||||
fn welcome(&self) -> &v1::Welcome {
|
||||
&self.welcome
|
||||
}
|
||||
|
||||
fn features(&self) -> Features {
|
||||
self.features.clone()
|
||||
}
|
||||
|
||||
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
match placement(&op) {
|
||||
Placement::Invalid => {
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("a Hello is part of connecting".into()))
|
||||
});
|
||||
}
|
||||
Placement::OwnStream
|
||||
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
|
||||
{
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("files go through read_file and write_file".into()))
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Queued now, in the order of the calls, not when the future is polled.
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
// Only an op of the control stream can go without an answer: a Hello is
|
||||
// part of connecting, and a List and the file transfers have streams
|
||||
// (and answers) of their own.
|
||||
match placement(&op) {
|
||||
Placement::Control => {}
|
||||
Placement::Invalid => {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
Placement::OwnStream => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a List and the file transfers have a stream and an answer of their own, \
|
||||
they cannot be sent without one"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The task may be on its way out and not have dropped its queue yet.
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(SessionError::Closed(closed_reason(&self.closed)));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
|
||||
}
|
||||
|
||||
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
|
||||
let flow = packet.flow;
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(MediaError::Closed);
|
||||
}
|
||||
if packet.rtp.len() > MAX_RTP {
|
||||
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
|
||||
}
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
}
|
||||
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
|
||||
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
|
||||
Ok(Sent::Queued)
|
||||
}
|
||||
|
||||
fn stats(&self) -> LinkStats {
|
||||
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
|
||||
}
|
||||
|
||||
fn close(&self, code: v1::CloseCode, reason: &str) {
|
||||
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<CloseReason> {
|
||||
let mut closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
|
||||
reason.unwrap_or_else(|| closed_reason(&closed))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The write half of an upload: ending it tells the other half of the
|
||||
/// upload that the file is all there.
|
||||
struct UploadBody {
|
||||
inner: tokio::io::WriteHalf<BoxDuplex>,
|
||||
ended: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for UploadBody {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
|
||||
if matches!(done, Poll::Ready(Ok(())))
|
||||
&& let Some(ended) = self.ended.take()
|
||||
{
|
||||
let _ = ended.send(());
|
||||
}
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload over the transfer connection `stream`: the body writes to it,
|
||||
/// and `done` resolves once the body is shut down and the server has closed
|
||||
/// the connection (or 30 s passed), with the file as `stored`.
|
||||
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let (ended, shut) = oneshot::channel();
|
||||
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
|
||||
if shut.await.is_err() {
|
||||
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
|
||||
}
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
|
||||
Ok(v1::Entities {
|
||||
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
|
||||
}
|
||||
|
||||
// ---- the connector ----------------------------------------------------------
|
||||
|
||||
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkConnector {
|
||||
link: Arc<dyn ServerLink>,
|
||||
schemes: &'static [&'static str],
|
||||
/// Serves every scheme (the engine's tests give a link of their own).
|
||||
any: bool,
|
||||
}
|
||||
|
||||
impl LinkConnector {
|
||||
/// A connector for `schemes`.
|
||||
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
|
||||
Self { link, schemes, any: false }
|
||||
}
|
||||
|
||||
/// A connector for addresses of every scheme.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
|
||||
Self { link, schemes: &[], any: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for LinkConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.schemes
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
|
||||
Box::pin(async move { Ok(connect.await?.connected) })
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for LinkConnector {
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.any || self.schemes.contains(&scheme)
|
||||
}
|
||||
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
Box::pin(connect_link(self.link.clone(), params, ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
|
||||
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
|
||||
///
|
||||
/// Clones share one account: the main myTeamSpeak account that every
|
||||
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
|
||||
/// [`TsConnector::set_myts_data`]), also those made before it was set.
|
||||
/// Register a connector in the engine's registry with
|
||||
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
|
||||
/// keep a clone to set the account.
|
||||
#[derive(Clone)]
|
||||
pub struct TsConnector {
|
||||
connector: LinkConnector,
|
||||
link: Arc<TsLink>,
|
||||
}
|
||||
|
||||
impl Default for TsConnector {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TsConnector {
|
||||
/// A connector that presents no account until it is given one.
|
||||
pub fn new() -> Self {
|
||||
let link = Arc::new(TsLink::new());
|
||||
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
|
||||
}
|
||||
|
||||
/// The main account's proof for every current and future connection of
|
||||
/// this connector (and its clones): a myTS ID signed with the account's
|
||||
/// key. Connections that are up show the server the new proof, and those
|
||||
/// that connect later present it from the start; `None` is a sign-out.
|
||||
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.link.account().set_identity(identity);
|
||||
}
|
||||
|
||||
/// What servers are shown of the main account: its avatar and badges with
|
||||
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
|
||||
/// connection that presents the account's myTS ID, once connected and when
|
||||
/// it changes; cleared on a sign-out (`None`).
|
||||
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.link.account().set_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for TsConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.connector.schemes()
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
self.connector.connect(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for TsConnector {
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
self.connector.connect_local(params, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link told when it connected.
|
||||
struct Joined {
|
||||
name: String,
|
||||
backend: BackendInfo,
|
||||
capabilities: voelin_model::Capabilities,
|
||||
own_client: u16,
|
||||
server_uid: String,
|
||||
own_uid: Option<String>,
|
||||
}
|
||||
|
||||
fn ended_error(reason: Option<String>) -> SessionError {
|
||||
SessionError::Closed(match reason {
|
||||
Some(reason) => CloseReason::Network(reason),
|
||||
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the link to say it is connected (or that it failed).
|
||||
async fn wait_connected(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
) -> Result<Joined, SessionError> {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Some(LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
}) => {
|
||||
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
|
||||
}
|
||||
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
|
||||
Some(_) => {}
|
||||
None => return Err(ended_error(Some("the connection ended".into()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a [`LinkSession`] over `link` to the address in `params`.
|
||||
async fn connect_link(
|
||||
link: Arc<dyn ServerLink>,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> Result<LocalConnected, SessionError> {
|
||||
let options = inner_options(¶ms, &ctx)?;
|
||||
let nickname = options.nickname.clone();
|
||||
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
|
||||
let (events_tx, mut events) = mpsc::unbounded_channel();
|
||||
// The link answers requests on a bus of its own: this session reads the
|
||||
// answers, and passes on the rest to the engine's.
|
||||
let (bus_tx, bus) = broadcast::channel(4096);
|
||||
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
|
||||
link.spawn(options, inner_ctx, inner_rx, events_tx);
|
||||
|
||||
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
|
||||
Ok(joined) => joined?,
|
||||
Err(_) => {
|
||||
let _ = inner_tx.send(LinkCmd::Disconnect);
|
||||
return Err(SessionError::Timeout);
|
||||
}
|
||||
};
|
||||
// The link reports its first snapshot right after it says it is connected;
|
||||
// the session needs it to know the own user.
|
||||
let mut early: Vec<LinkEvent> = Vec::new();
|
||||
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
|
||||
while let Some(event) = events.recv().await {
|
||||
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
|
||||
early.push(event);
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
|
||||
return Err(ended_error(reason.clone()));
|
||||
}
|
||||
let own_database_id = early.iter().find_map(|event| match event {
|
||||
LinkEvent::Presence(presence) => {
|
||||
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let ts6 = joined.backend.product == "TeamSpeak 6";
|
||||
let own_user =
|
||||
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
|
||||
let features = features_of(&joined.capabilities);
|
||||
let welcome = v1::Welcome {
|
||||
user_id: own_user,
|
||||
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
|
||||
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
|
||||
host: Some(v1::HostInfo {
|
||||
host_key: Bytes::new(),
|
||||
name: joined.name.clone(),
|
||||
product: joined.backend.product.clone(),
|
||||
version: joined.backend.version.clone(),
|
||||
backend: Some(backend_to_v1(&joined.backend)),
|
||||
icon: None,
|
||||
}),
|
||||
features: features.iter().map(|f| (*f).to_owned()).collect(),
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
// HOME, SERVER and LIVE, and the chats.
|
||||
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
}),
|
||||
time_ms: now_ms(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
let (events_tx, events_rx) = mpsc::unbounded_channel();
|
||||
let cmds = cmds_tx.clone();
|
||||
let send = move |cmd| {
|
||||
let _ = cmds.send(Cmd::Stream(cmd));
|
||||
};
|
||||
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
|
||||
let driver = Driver::new(Parts {
|
||||
cfg: Config {
|
||||
ts6,
|
||||
own_client: joined.own_client,
|
||||
nickname,
|
||||
own_uid: joined.own_uid.clone(),
|
||||
files: joined.capabilities.file_transfer,
|
||||
mail: joined.capabilities.offline_messages,
|
||||
},
|
||||
inner: inner_tx,
|
||||
events,
|
||||
early,
|
||||
bus,
|
||||
engine_bus: ctx.link.events.clone(),
|
||||
pushes: pushes_tx,
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
own_slot: own_slot.clone(),
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
let session = LinkSession {
|
||||
welcome,
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot,
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
connected: Connected {
|
||||
session: Arc::new(session),
|
||||
pushes: pushes_rx,
|
||||
// A TeamSpeak server has no host key to pin.
|
||||
host_uid: [0; 32],
|
||||
},
|
||||
streams,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
use voelin_proto::link::IssuerTrust;
|
||||
|
||||
fn params(options: &VoiceOptions) -> ConnectParams {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty()).unwrap()
|
||||
}
|
||||
|
||||
fn back(options: &VoiceOptions) -> ConnectOptions {
|
||||
inner_options(¶ms(options), &LocalCtx::standalone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_options_of_a_bookmark_come_back_as_they_went() {
|
||||
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
|
||||
let same = back(&options);
|
||||
assert_eq!(
|
||||
(same.address.as_str(), same.nickname.as_str()),
|
||||
("ts.example.com:9988", "nick")
|
||||
);
|
||||
assert!(same.identity.is_none() && same.client_version.is_none());
|
||||
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
|
||||
|
||||
// Everything a connection can be told: the server password and the
|
||||
// privilege key go in the hello, the channel and its password in the
|
||||
// link, the identity as a credential.
|
||||
options.server_password = Some("s3cret pass&word".into());
|
||||
options.channel = Some("Games/Raid Night".into());
|
||||
options.channel_password = Some("p w+%".into());
|
||||
options.token = Some("tokenvalue".into());
|
||||
let identity = tsclientlib::Identity::create();
|
||||
options.identity = Some(crate::ts::identity::to_blob(&identity));
|
||||
// A spec the user can give; the connector resolves it.
|
||||
options.client_version = Some("generic".into());
|
||||
options.audio = false;
|
||||
let sent = params(&options);
|
||||
assert_eq!(sent.hello.password, "s3cret pass&word");
|
||||
assert_eq!(sent.hello.invite_code, "tokenvalue");
|
||||
assert_eq!(sent.hello.nickname, "nick");
|
||||
assert!(
|
||||
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
|
||||
"{}",
|
||||
sent.address
|
||||
);
|
||||
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "ts.example.com:9988");
|
||||
assert_eq!(got.server_password, options.server_password);
|
||||
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
|
||||
assert_eq!(got.channel_password, options.channel_password);
|
||||
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
|
||||
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
|
||||
assert!(got.client_version.is_some());
|
||||
// The identity is the same key and counters.
|
||||
let b = got.identity.as_ref().unwrap();
|
||||
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
|
||||
let mut options = VoiceOptions::new("[::1]:9987", "nick");
|
||||
options.channel = Some("/12".into());
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "[::1]:9987");
|
||||
assert_eq!(got.channel.as_deref(), Some("/12"));
|
||||
|
||||
// A bookmark that is a link keeps its own parameters.
|
||||
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
|
||||
let got = back(&options);
|
||||
assert_eq!(
|
||||
(got.address.as_str(), got.channel.as_deref()),
|
||||
("ts.example.com:1", Some("Lobby"))
|
||||
);
|
||||
// Another scheme is left as it is for the connector of that scheme.
|
||||
let options = VoiceOptions::new("voelin://host/i/code", "nick");
|
||||
assert_eq!(params(&options).address, "voelin://host/i/code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_teamspeak_identity_is_refused() {
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
assert!(matches!(error, SessionError::Protocol(_)));
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
// A host that wants trust is refused: TeamSpeak has no host key.
|
||||
let backends = Backends::empty();
|
||||
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
|
||||
address: "x".into(),
|
||||
uid: [0; 32],
|
||||
previous: None,
|
||||
});
|
||||
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"));
|
||||
assert!(sent.account.is_none());
|
||||
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
|
||||
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
|
||||
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
|
||||
let client = sent.hello.client.unwrap();
|
||||
assert_eq!(client.name, "Voelin");
|
||||
assert_eq!(sent.hello.version, 1);
|
||||
}
|
||||
|
||||
/// Why `connect_params` refused an address, if it did.
|
||||
fn refused(address: &str) -> Option<String> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
|
||||
Ok(_) => None,
|
||||
Err(SessionError::Protocol(text)) => Some(text),
|
||||
Err(other) => panic!("{address}: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_the_link_would_change_is_refused() {
|
||||
// A port that is no port, in any shape: the link would drop it and the
|
||||
// connection would go to the default port.
|
||||
for address in [
|
||||
"ts.example.com:99999",
|
||||
"ts.example.com:65536",
|
||||
"ts.example.com:0",
|
||||
"ts.example.com:abc",
|
||||
"ts.example.com:",
|
||||
"[::1]:70000",
|
||||
"[::1]:",
|
||||
"[::1]x",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
|
||||
assert!(text.contains("65535") && text.contains(address), "{text}");
|
||||
}
|
||||
// A host the link would cut or decode: a `?` hides the channel behind the
|
||||
// next one, a `/` or `#` ends the host, a `%` is decoded.
|
||||
for address in [
|
||||
"",
|
||||
" ",
|
||||
"ts.example.com?x",
|
||||
"ts.example.com#x",
|
||||
"ts.example.com/x",
|
||||
"a b",
|
||||
"h%41",
|
||||
"[::1",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
|
||||
assert!(text.starts_with("not a server address"), "{text}");
|
||||
}
|
||||
// The text names no query: a link keeps secrets in it.
|
||||
let text = refused("ts.example.com?password=hunter2").unwrap();
|
||||
assert!(!text.contains("hunter2"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
|
||||
for (address, host) in [
|
||||
("ts.example.com", "ts.example.com"),
|
||||
("ts.example.com:9987", "ts.example.com:9987"),
|
||||
(" ts.example.com:1 ", "ts.example.com:1"),
|
||||
("127.0.0.1:65535", "127.0.0.1:65535"),
|
||||
("[::1]:9987", "[::1]:9987"),
|
||||
// The brackets of a v6 address without a port are the link's to drop;
|
||||
// the TeamSpeak library reads both forms.
|
||||
("[::1]", "::1"),
|
||||
("::1", "::1"),
|
||||
("2001:db8::1", "2001:db8::1"),
|
||||
] {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.channel = Some("Games/Raid".into());
|
||||
let got = back(&options);
|
||||
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The normalisations of the round trip, listed in `docs/session-seam.md`
|
||||
/// (13): an empty option is none, and an empty nickname stays empty.
|
||||
#[test]
|
||||
fn empty_options_come_back_as_none() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "");
|
||||
options.server_password = Some(String::new());
|
||||
options.channel = Some(String::new());
|
||||
options.channel_password = Some(String::new());
|
||||
options.token = Some(String::new());
|
||||
let got = back(&options);
|
||||
assert!(got.nickname.is_empty());
|
||||
assert!(
|
||||
got.server_password.is_none()
|
||||
&& got.channel.is_none()
|
||||
&& got.channel_password.is_none()
|
||||
&& got.token.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::*;
|
||||
use tsclientlib::Version;
|
||||
|
||||
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
|
||||
/// The signed generic version of every platform, tsclientlib's default.
|
||||
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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");
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::ts::identity::to_blob;
|
||||
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
|
||||
use voelin_gateway_proto::{
|
||||
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
|
||||
@@ -23,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";
|
||||
|
||||
@@ -448,7 +451,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -528,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.
|
||||
@@ -742,7 +747,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// The first attempts fail (the next ones about 1 s, then 2 s later):
|
||||
// still connecting, and the user is told nothing.
|
||||
@@ -811,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());
|
||||
@@ -819,7 +833,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 4,
|
||||
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// Within one round: sooner than the shortest wait after a failed round
|
||||
// (1 s, less 30 %).
|
||||
@@ -904,7 +918,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// After the first wait: about 1 s.
|
||||
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
|
||||
@@ -932,6 +946,45 @@ async fn a_refused_login_ends_observing() {
|
||||
assert_eq!(gw.logins(), 1);
|
||||
}
|
||||
|
||||
/// An identity that cannot be read will not be better tomorrow: like a refused
|
||||
/// login, observing ends, and the gateway is not even asked.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
|
||||
let gw = FakeGateway::start().await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 10,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(not_an_identity),
|
||||
});
|
||||
wait(&mut rx, "connecting", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert_eq!(gw.logins(), 0);
|
||||
// The public entry refuses it the same way.
|
||||
let error = voelin_core::gateway::connect(
|
||||
&gw.url,
|
||||
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("a refusal");
|
||||
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
|
||||
assert_eq!(gw.logins(), 0);
|
||||
}
|
||||
|
||||
/// Selecting the server again while its gateway is still connecting does
|
||||
/// not start it over, and ends the wait for the next attempt.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -944,7 +997,7 @@ async fn asking_again_while_connecting_tries_at_once() {
|
||||
let ask = || Command::ObserveGateway {
|
||||
session: 9,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity.clone()),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
};
|
||||
engine.send(ask());
|
||||
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
|
||||
|
||||
@@ -1,17 +1,33 @@
|
||||
//! 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::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_core::{
|
||||
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
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>,
|
||||
@@ -45,7 +61,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
.await;
|
||||
|
||||
// Session 2: invisible, through own query credentials.
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
|
||||
let (mut observing, mut sees_voice_client) = (false, false);
|
||||
wait_for(&mut events, "query presence with the voice client", |e| {
|
||||
match e {
|
||||
@@ -93,6 +109,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
/// The credentials of a query connection, as the engine takes them.
|
||||
fn login(connect: &voelin_query::Connect) -> QueryLogin {
|
||||
QueryLogin {
|
||||
transport: match connect.transport {
|
||||
voelin_query::Transport::Raw => QueryTransport::Raw,
|
||||
voelin_query::Transport::Ssh => QueryTransport::Ssh,
|
||||
voelin_query::Transport::Http => QueryTransport::Http,
|
||||
},
|
||||
address: connect.addr.clone(),
|
||||
user: connect.user.clone(),
|
||||
secret: connect.secret.clone(),
|
||||
server_port: connect.server_port,
|
||||
server_id: connect.server_id,
|
||||
// The development servers allowlist their clients.
|
||||
allowlisted: connect.line.rate_limit.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport,
|
||||
@@ -110,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;
|
||||
}
|
||||
@@ -237,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;
|
||||
}
|
||||
|
||||
@@ -308,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 =
|
||||
@@ -491,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()));
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
|
||||
//! made: `Engine::start_with_backends` takes the connector registry, and the
|
||||
//! scheme of a session's address picks the connector. The fake host of the
|
||||
//! protocol repository stands for a Voelin host here (the fuller tests of the
|
||||
//! seam on the fake host come with the next slice of
|
||||
//! `docs/session-seam.md`).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::{
|
||||
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
const SESSION: u64 = 1;
|
||||
|
||||
async fn next<T>(
|
||||
events: &mut broadcast::Receiver<Event>,
|
||||
mut f: impl FnMut(Event) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
fn host_with_two_channels(connector: &FakeConnector) {
|
||||
let host = connector.host();
|
||||
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
|
||||
put(Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}));
|
||||
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
|
||||
put(Kind::Channel(v1::Channel {
|
||||
id,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: name.into(),
|
||||
position,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
|
||||
let connector = FakeConnector::new();
|
||||
host_with_two_channels(&connector);
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let mut events = engine.subscribe();
|
||||
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake://host", "tester")),
|
||||
});
|
||||
let (name, backend) = next(&mut events, |e| match e {
|
||||
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
|
||||
let presence = next(&mut events, |e| match e {
|
||||
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let channels: Vec<_> =
|
||||
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
|
||||
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
|
||||
// The host was asked once, with the nickname and the TeamSpeak-shaped
|
||||
// credential the engine makes of its options for now.
|
||||
let connects = connector.connects();
|
||||
assert_eq!(connects.len(), 1);
|
||||
assert_eq!(connects[0].address, "fake://host");
|
||||
assert_eq!(connects[0].hello.nickname, "tester");
|
||||
|
||||
// A move is a request to the host; the host's voice state is where we are.
|
||||
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
|
||||
let state: SessionState = next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
|
||||
let mut events = engine.subscribe();
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
|
||||
});
|
||||
let error = next(&mut events, |e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: no connector for voelin://host/i/code");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
|
||||
Event::StreamViewers { session: 1, viewers }
|
||||
if viewers
|
||||
.iter()
|
||||
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
|
||||
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
|
||||
# TLS (`wss://`, as gateways run behind a proxy) with the system's
|
||||
# certificates; rustls and its crates are in the tree already (reqwest).
|
||||
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -29,7 +29,7 @@ toml = "1.1.6"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
|
||||
|
||||
@@ -1,14 +1,34 @@
|
||||
# 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
|
||||
# the first cargo command needs this, although this crate does not use
|
||||
# voelin-identity: the `cargo fetch` below, the only step that is given the agent.
|
||||
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
|
||||
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
# Only this step is given the agent, and it only fetches: no build script,
|
||||
# procedural macro or test of the workspace runs in it. The build below has no
|
||||
# ssh mount (so no agent socket and no key in reach of the code it compiles and
|
||||
# runs) and is --offline, so it uses what this step fetched or fails.
|
||||
RUN --mount=type=ssh,required=true \
|
||||
cargo fetch --locked
|
||||
RUN cargo build --release --locked --offline -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot
|
||||
COPY --from=build /tsgw /usr/local/bin/tsgw
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
[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); `macros` for the hotkey task's
|
||||
# `select!`.
|
||||
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "sync", "time"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
# The TeamSpeak identity a connection is made with (the store hands it out).
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
|
||||
# commit that moved voelin-media and voelin-platform to it) lets this binary
|
||||
# hold both the portals and gpui-kit.
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
|
||||
# The app's name and id, the hotkeys and portals of the slices to come.
|
||||
voelin-platform = { path = "../voelin-platform" }
|
||||
# The client's database (bookmarks, identities, settings, chat reads) and the
|
||||
# secrets: the OS keyring, as the Slint front end keeps them.
|
||||
voelin-store = { path = "../voelin-store", features = ["keyring"] }
|
||||
# The view models and the state, shared with the Slint front end.
|
||||
voelin-ui-vm = { path = "../voelin-ui-vm" }
|
||||
|
||||
# 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");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,85 @@
|
||||
//! 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)
|
||||
}
|
||||
|
||||
/// The app's mark, the Slint front end's `logo.svg`.
|
||||
const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg");
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
|
||||
return Ok(Some(Cow::Borrowed(bytes)));
|
||||
}
|
||||
if path == "logo.svg" {
|
||||
return Ok(Some(Cow::Borrowed(LOGO)));
|
||||
}
|
||||
gpui_kit::assets::AllAssets.load(path)
|
||||
}
|
||||
|
||||
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,264 @@
|
||||
//! What the window keeps besides the engine and the state, and opens at start
|
||||
//! as the Slint front end's `run()` does (`crates/voelin-ui/src/app.rs`): the
|
||||
//! client's database (the bookmarks, the identities, the chats' read marks),
|
||||
//! the settings service on the same file, the secrets, and the identity a
|
||||
//! connection is made with. The directory is the platform's data directory
|
||||
//! (`voelin_platform::paths::data_dir`, which `VOELIN_DATA_DIR` overrides, so
|
||||
//! that the two front ends share the store); everything below [`Backend::open`]
|
||||
//! takes the directory, so that no test reaches the user's own.
|
||||
//!
|
||||
//! Left out against the Slint front end: importing the identities of the
|
||||
//! official TeamSpeak clients at start (it reads the user's own files; the
|
||||
//! slice with the identities page brings it), the crash reports and the
|
||||
//! configuration of `--set` on the command line.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use tracing::warn;
|
||||
use tsclientlib::Identity;
|
||||
use voelin_core::settings::{AUDIO, Settings};
|
||||
use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob};
|
||||
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
|
||||
use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
|
||||
use voelin_ui_vm::settings::{
|
||||
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_TREE, UI_WINDOW, UiSettings,
|
||||
};
|
||||
|
||||
/// The client's database, its settings and its secrets.
|
||||
pub struct Backend {
|
||||
/// The bookmarks, the identities and the chats' read marks.
|
||||
pub store: Store,
|
||||
/// The settings service, on the same file as the store (its own
|
||||
/// connection); shared with the engine once [`Backend::attach`] ran.
|
||||
pub prefs: Settings,
|
||||
/// The servers' passwords.
|
||||
pub secrets: Box<dyn Secrets>,
|
||||
/// The identity of a server whose bookmark names none that exists, and
|
||||
/// the store has no default for.
|
||||
identity: Identity,
|
||||
/// The database file, for the engine's chat history.
|
||||
database: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// What the store and the settings hold at start, for the state.
|
||||
#[derive(Debug)]
|
||||
pub struct Loaded {
|
||||
/// The saved servers, in the rail's order.
|
||||
pub bookmarks: Vec<Bookmark>,
|
||||
/// The UI's own settings (the `ui` key).
|
||||
pub settings: UiSettings,
|
||||
/// The audio settings.
|
||||
pub audio: AudioSettings,
|
||||
/// The clients' local volumes.
|
||||
pub playback: ClientPlaybackMap,
|
||||
}
|
||||
|
||||
/// The data directory of this process: `VOELIN_DATA_DIR`, else the platform's.
|
||||
pub fn data_dir() -> PathBuf {
|
||||
voelin_platform::paths::data_dir()
|
||||
}
|
||||
|
||||
/// The settings service on the client database in `dir`
|
||||
/// ([`voelin_ui_vm::settings::open_settings`], which the Slint front end opens
|
||||
/// the same way): the UI's keys and this front end's own, then a config file
|
||||
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists) and
|
||||
/// `VOELIN_SETTING_*` variables below the stored values. Without the database
|
||||
/// the settings live in memory.
|
||||
fn open_settings(dir: &Path) -> Settings {
|
||||
voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
|
||||
}
|
||||
|
||||
/// The keys that only this front end uses: where the window was
|
||||
/// (`ui.window`) and what the channel trees remember (`ui.tree`).
|
||||
fn register_own_keys(prefs: &Settings) {
|
||||
prefs.register(&UI_WINDOW);
|
||||
prefs.register(&UI_TREE);
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
/// Open the database in `dir` (created if need be), its settings and the
|
||||
/// default identity (made, and kept, when the store has none). `secrets`
|
||||
/// are where passwords go.
|
||||
pub fn open(dir: &Path, secrets: Box<dyn Secrets>) -> Result<Self> {
|
||||
let database = dir.join("client.db");
|
||||
let store = Store::open(&database).context("failed to open the client database")?;
|
||||
let prefs = open_settings(dir);
|
||||
let identity = match store.default_identity()? {
|
||||
Some(entry) => store.identity(entry.id)?,
|
||||
None => {
|
||||
let identity = Identity::create();
|
||||
store.add_identity(CREATED_IDENTITY, &identity, IdentityOrigin::Created)?;
|
||||
identity
|
||||
}
|
||||
};
|
||||
Ok(Self { store, prefs, secrets, identity, database: Some(database) })
|
||||
}
|
||||
|
||||
/// A backend that stores nothing and keeps its secrets in memory, with a
|
||||
/// fresh identity: the tests', and the sample data's.
|
||||
pub fn in_memory() -> Result<Self> {
|
||||
let prefs = Settings::in_memory();
|
||||
voelin_ui_vm::settings::register_keys(&prefs);
|
||||
register_own_keys(&prefs);
|
||||
Ok(Self {
|
||||
store: Store::open_in_memory()?,
|
||||
prefs,
|
||||
secrets: Box::new(MemorySecrets::default()),
|
||||
identity: Identity::create(),
|
||||
database: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the store and the settings hold now.
|
||||
pub fn load(&self) -> Loaded {
|
||||
Loaded {
|
||||
bookmarks: self.store.bookmarks().unwrap_or_else(|e| {
|
||||
warn!(%e, "the bookmarks cannot be read");
|
||||
Vec::new()
|
||||
}),
|
||||
settings: (*self.prefs.get_arc(&UI)).clone(),
|
||||
audio: self.prefs.get(&AUDIO),
|
||||
playback: self.prefs.get(&CLIENT_PLAYBACK),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand the engine what it keeps for the window: the chat history in the
|
||||
/// same database (without it the engine keeps chats for this run only),
|
||||
/// the settings service and the audio settings.
|
||||
pub fn attach(&self, engine: &Engine) {
|
||||
if let Some(database) = &self.database {
|
||||
match History::open(database) {
|
||||
Ok(history) => engine.send(Command::AttachHistory(history)),
|
||||
Err(e) => warn!(%e, "chat history is not stored this time"),
|
||||
}
|
||||
}
|
||||
engine.send(Command::AttachSettings(self.prefs.clone()));
|
||||
engine.send(Command::SetAudioSettings(Box::new(self.prefs.get(&AUDIO))));
|
||||
}
|
||||
|
||||
/// The identity a connection to the bookmark `bookmark` uses: its own if
|
||||
/// it names one the store has, else the store's default, else the one made
|
||||
/// at start ([`Store::identity_for`]).
|
||||
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
|
||||
self.store.identity_for(bookmark.and_then(|b| b.identity), &self.identity)
|
||||
}
|
||||
|
||||
/// The identity of [`Backend::identity_for`] as the engine takes it, for a
|
||||
/// bookmark that names the identity `named`.
|
||||
pub fn identity_blob(&self, named: Option<i64>) -> IdentityBlob {
|
||||
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
|
||||
}
|
||||
|
||||
/// Write what the settings service holds to the database.
|
||||
pub fn flush(&self) {
|
||||
if let Err(e) = self.prefs.flush() {
|
||||
warn!(%e, "could not store settings");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The secrets of this run: the OS keyring, and memory for what the keyring
|
||||
/// refuses (no Secret Service on a headless Linux); the sample data's never
|
||||
/// reach the keyring.
|
||||
pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
|
||||
if demo {
|
||||
Box::new(MemorySecrets::default())
|
||||
} else {
|
||||
Box::new(voelin_store::FallbackSecrets::new("voelin"))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the tests of this crate need to open a store of their own.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod testing {
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A directory of its own under the temporary one (`TMPDIR`), removed with
|
||||
/// the guard: no test reaches the user's data directory.
|
||||
pub(crate) struct TempDir(pub PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
/// An empty directory path named `name` and this process.
|
||||
pub(crate) fn new(name: &str) -> Self {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("voelin-gpui-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_ui_vm::settings::WindowState;
|
||||
|
||||
use super::testing::TempDir;
|
||||
use super::*;
|
||||
|
||||
fn bookmark(name: &str, address: &str) -> Bookmark {
|
||||
Bookmark { name: name.into(), address: address.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// What a run leaves in the directory is what the next one starts from: the
|
||||
/// bookmarks, the identity (the same one, not a new one) and the settings.
|
||||
#[test]
|
||||
fn a_second_start_finds_what_the_first_kept() {
|
||||
let dir = TempDir::new("backend");
|
||||
let first = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
|
||||
assert_eq!(first.load().bookmarks, Vec::new(), "a new store has no servers");
|
||||
let id = first.store.add_bookmark(&bookmark("Nightfall", "ts.example")).unwrap();
|
||||
let uid = first.identity_for(None).key().to_pub().get_uid();
|
||||
let window = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false };
|
||||
first.prefs.set(&UI_WINDOW, Some(window)).unwrap();
|
||||
first.flush();
|
||||
drop(first);
|
||||
|
||||
let second = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
|
||||
let loaded = second.load();
|
||||
assert_eq!(
|
||||
loaded.bookmarks.iter().map(|b| (b.id, b.name.as_str())).collect::<Vec<_>>(),
|
||||
[(id, "Nightfall")]
|
||||
);
|
||||
assert_eq!(second.identity_for(None).key().to_pub().get_uid(), uid, "the identity is kept");
|
||||
assert_eq!(second.prefs.get(&UI_WINDOW), Some(window));
|
||||
assert!(dir.0.join("client.db").is_file(), "the database is in the directory given");
|
||||
}
|
||||
|
||||
/// A new server's nickname is the default identity's (one imported from
|
||||
/// TeamSpeak keeps the nickname used there), not the name the app gave the
|
||||
/// identity it made.
|
||||
#[test]
|
||||
fn a_new_servers_nickname_is_the_default_identitys_unless_the_app_named_it() {
|
||||
use voelin_ui_vm::servers::sequence::default_nickname;
|
||||
let backend = Backend::in_memory().unwrap();
|
||||
let made = Identity::create();
|
||||
backend.store.add_identity(CREATED_IDENTITY, &made, IdentityOrigin::Created).unwrap();
|
||||
let nickname = default_nickname(&backend.store);
|
||||
assert!(nickname != CREATED_IDENTITY && !nickname.trim().is_empty(), "{nickname}");
|
||||
let imported =
|
||||
backend.store.add_identity("Nova", &Identity::create(), IdentityOrigin::Imported);
|
||||
backend.store.set_default_identity(imported.unwrap(), false).unwrap();
|
||||
assert_eq!(default_nickname(&backend.store), "Nova");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_names_its_identity_and_the_default_serves_the_rest() {
|
||||
let backend = Backend::in_memory().unwrap();
|
||||
let (default, alt) = (Identity::create(), Identity::create());
|
||||
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
|
||||
backend.store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
|
||||
let alt_id = backend.store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
|
||||
assert_eq!(uid(&backend.identity_for(None)), uid(&default), "the first is the default");
|
||||
let named = Bookmark { identity: Some(alt_id), ..bookmark("a", "a.test") };
|
||||
assert_eq!(uid(&backend.identity_for(Some(&named))), uid(&alt));
|
||||
let gone = Bookmark { identity: Some(alt_id + 100), ..bookmark("b", "b.test") };
|
||||
assert_eq!(uid(&backend.identity_for(Some(&gone))), uid(&default));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! 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_OPEN=voice` (`voice:compact`): the voice channel page on screen
|
||||
//! once voice is connected, in place of the server page; `voice:compact`
|
||||
//! with the smaller stage, which is not stored.
|
||||
//! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through
|
||||
//! the app's own events, with their pictures as files of a folder in the
|
||||
//! temporary directory (removed when the window closes); nothing is sent to
|
||||
//! the engine or kept in the store.
|
||||
//! - `VOELIN_DEMO_SERVER=2`: with `VOELIN_DEMO_UI`, the sample server on
|
||||
//! screen, counting from 0 (the first, which is connected and populated, is
|
||||
//! the default; the second is observed, the third not connected).
|
||||
//! - `VOELIN_DEMO_TALK=10`: with `VOELIN_DEMO_UI`, one of the sample people
|
||||
//! starts and stops talking this many times a second, through the app's own
|
||||
//! events (what the meter measures while someone talks).
|
||||
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
|
||||
//! one the settings give (`ui.theme`).
|
||||
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the
|
||||
//! settings' (`ui.font_scale`).
|
||||
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size, in place of the
|
||||
//! remembered one (`ui.window`), which it then leaves alone.
|
||||
//! - `VOELIN_METER=1`: the cost meter, one log line a second
|
||||
//! ([`crate::meter`]).
|
||||
|
||||
use crate::theme::Choice;
|
||||
|
||||
/// A page the window can be opened on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
/// The desktop shell.
|
||||
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 voice channel page is asked for (`VOELIN_OPEN=voice`): it shows
|
||||
/// once voice is connected.
|
||||
pub voice: bool,
|
||||
/// With the voice page, the smaller stage, as the switch says (it is not
|
||||
/// stored, as the Slint front end's `voice:compact`).
|
||||
pub voice_compact: bool,
|
||||
/// Show the sample servers instead of the stored ones.
|
||||
pub demo_ui: bool,
|
||||
/// Write the sample servers' pictures to a folder of the temporary
|
||||
/// directory and deliver them: what the binary does with the sample
|
||||
/// servers, and what a test asks for by name (a test that does not leaves
|
||||
/// nothing behind).
|
||||
pub demo_pictures: bool,
|
||||
/// The sample server to show, by its place in the list, when the switch
|
||||
/// names one.
|
||||
pub demo_server: Option<usize>,
|
||||
/// How many times a second a sample person starts or stops talking (with
|
||||
/// the sample servers), when the switch names a rate.
|
||||
pub demo_talk: Option<f32>,
|
||||
/// The theme mode, when the switch names one.
|
||||
pub theme: Option<Choice>,
|
||||
/// The text size factor, when the switch names one.
|
||||
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,
|
||||
voice: false,
|
||||
voice_compact: false,
|
||||
demo_ui: false,
|
||||
demo_pictures: false,
|
||||
demo_server: None,
|
||||
demo_talk: None,
|
||||
theme: None,
|
||||
font_scale: None,
|
||||
window: None,
|
||||
meter: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
"voice" => switches.voice = true,
|
||||
"voice:compact" => (switches.voice, switches.voice_compact) = (true, true),
|
||||
other => tracing::warn!(
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
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"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_DEMO_SERVER") {
|
||||
match text.trim().parse::<usize>() {
|
||||
Ok(place) if place < 3 => switches.demo_server = Some(place),
|
||||
_ => tracing::warn!("VOELIN_DEMO_SERVER={text}: 0, 1 or 2 (a sample server)"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_DEMO_TALK") {
|
||||
match text.trim().parse::<f32>() {
|
||||
Ok(rate) if (0.1..=100.0).contains(&rate) => switches.demo_talk = Some(rate),
|
||||
_ => tracing::warn!("VOELIN_DEMO_TALK={text}: a rate from 0.1 to 100 a second"),
|
||||
}
|
||||
}
|
||||
let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0"));
|
||||
switches.demo_ui = flag("VOELIN_DEMO_UI");
|
||||
switches.demo_pictures = switches.demo_ui;
|
||||
switches.meter = flag("VOELIN_METER");
|
||||
switches
|
||||
}
|
||||
}
|
||||
|
||||
/// `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,voice:compact"),
|
||||
("VOELIN_DEMO_UI", "1"),
|
||||
("VOELIN_DEMO_SERVER", "2"),
|
||||
("VOELIN_DEMO_TALK", "10"),
|
||||
("VOELIN_DEV_THEME", "light"),
|
||||
("VOELIN_FONT_SCALE", "1.25"),
|
||||
("VOELIN_WINDOW_SIZE", "1440x960"),
|
||||
("VOELIN_METER", "1"),
|
||||
]);
|
||||
assert_eq!(s.open, Page::Swatch);
|
||||
assert!(s.voice && s.voice_compact, "the voice page, with the smaller stage");
|
||||
assert!(s.demo_ui && s.demo_pictures, "the sample servers come with their pictures");
|
||||
assert_eq!(s.demo_server, Some(2));
|
||||
assert_eq!(s.demo_talk, Some(10.0));
|
||||
assert_eq!(s.theme, Some(Choice::Light));
|
||||
assert_eq!(s.font_scale, Some(1.25));
|
||||
assert_eq!(s.window, Some((1440.0, 960.0)));
|
||||
assert!(s.meter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_voice_page_alone_has_the_larger_stage() {
|
||||
let s = env(&[("VOELIN_OPEN", "voice")]);
|
||||
assert_eq!((s.open, s.voice, s.voice_compact), (Page::Shell, true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_makes_no_sense_is_left_out() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "settings:voice,home"),
|
||||
("VOELIN_DEV_THEME", "blue"),
|
||||
("VOELIN_FONT_SCALE", "9"),
|
||||
("VOELIN_WINDOW_SIZE", "10x10"),
|
||||
("VOELIN_DEMO_UI", "0"),
|
||||
("VOELIN_DEMO_SERVER", "7"),
|
||||
("VOELIN_DEMO_TALK", "fast"),
|
||||
("VOELIN_METER", "0"),
|
||||
]);
|
||||
assert_eq!(s, Switches::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! 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::settings::Settings;
|
||||
use voelin_core::{Backends, Engine, Event, History};
|
||||
|
||||
/// 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 {
|
||||
Self::forward(runtime, runtime.block_on(async { Engine::start() }))
|
||||
}
|
||||
|
||||
/// A new engine on `runtime` that connects with `backends` only, and keeps
|
||||
/// nothing (settings and chat history in memory): the tests' (with
|
||||
/// [`Backends::empty`] a connect ends at once, saying that no connector
|
||||
/// serves the address, and touches neither the network nor the sound
|
||||
/// devices).
|
||||
pub fn start_with_backends(runtime: &Runtime, backends: Backends) -> Self {
|
||||
Self::forward(
|
||||
runtime,
|
||||
runtime.block_on(async {
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Forward the events of `engine` into the channel the window reads.
|
||||
fn forward(runtime: &Runtime, engine: Engine) -> Self {
|
||||
let (tx, events) = mpsc::unbounded_channel();
|
||||
let mut rx = engine.subscribe();
|
||||
runtime.spawn(async move {
|
||||
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,361 @@
|
||||
//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the
|
||||
//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports
|
||||
//! the key's presses and releases, whichever window has the focus.
|
||||
//!
|
||||
//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`),
|
||||
//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the
|
||||
//! engine's runtime and the front end's own way back to its state, and the
|
||||
//! Slint crate cannot be a dependency (it brings Slint in); both go into one
|
||||
//! place when the Slint front end is retired.
|
||||
//!
|
||||
//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on
|
||||
//! it), not from a foreground task of GPUI: the portal's backend calls
|
||||
//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which
|
||||
//! panics where no tokio runtime is current, and GPUI's executor has none.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
|
||||
|
||||
/// The id of the push-to-talk registration (the portal remembers the user's
|
||||
/// choice by it).
|
||||
const PTT_ID: &str = "push-to-talk";
|
||||
|
||||
/// The handle to the hotkey task.
|
||||
pub struct GlobalPtt {
|
||||
tx: mpsc::UnboundedSender<Option<String>>,
|
||||
}
|
||||
|
||||
impl GlobalPtt {
|
||||
/// Start the task on `runtime`. `status` gets a line that says how the key
|
||||
/// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered),
|
||||
/// `transmit` the key's state; both are called on the runtime, so they hand
|
||||
/// over to GPUI's thread ([`crate::app::Later`]).
|
||||
pub fn start(
|
||||
runtime: &Handle,
|
||||
status: impl Fn(String) + Send + 'static,
|
||||
transmit: impl Fn(bool) + Send + 'static,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
runtime.spawn(run(rx, status, transmit));
|
||||
Self { tx }
|
||||
}
|
||||
|
||||
/// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered,
|
||||
/// or nothing.
|
||||
pub fn set(&self, key: Option<String>) {
|
||||
let _ = self.tx.send(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream of press and release events for one registered hotkey (`None` once
|
||||
/// the desktop removes it).
|
||||
trait EventStream: Send {
|
||||
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send;
|
||||
}
|
||||
|
||||
impl EventStream for HotkeyEvents {
|
||||
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send {
|
||||
HotkeyEvents::recv(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers and unregisters the global push-to-talk hotkey with the platform
|
||||
/// (or a test double).
|
||||
trait Registrar: Send {
|
||||
type Events: EventStream;
|
||||
|
||||
fn register(
|
||||
&mut self,
|
||||
key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> impl Future<Output = Result<(Self::Events, String), String>> + Send;
|
||||
|
||||
fn unregister(&mut self) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
|
||||
/// The real platform hotkey manager, opened lazily on the first registration.
|
||||
struct PlatformRegistrar {
|
||||
manager: Option<HotkeyManager>,
|
||||
}
|
||||
|
||||
impl Registrar for PlatformRegistrar {
|
||||
type Events = HotkeyEvents;
|
||||
|
||||
async fn register(
|
||||
&mut self,
|
||||
key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> Result<(Self::Events, String), String> {
|
||||
if self.manager.is_none() {
|
||||
match HotkeyManager::new().await {
|
||||
Ok(m) => self.manager = Some(m),
|
||||
Err(e) => return Err(format!("Global hotkeys are not available: {e}")),
|
||||
}
|
||||
}
|
||||
let Some(m) = &mut self.manager else {
|
||||
return Err("Global hotkeys are not available.".into());
|
||||
};
|
||||
match m.register(PTT_ID, "Push to talk", hotkey).await {
|
||||
Ok(registered) => {
|
||||
let line = match m.backend() {
|
||||
BackendKind::Portal => format!(
|
||||
"Registered with the desktop: {}",
|
||||
m.trigger_description(PTT_ID).unwrap_or(key)
|
||||
),
|
||||
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
|
||||
BackendKind::WindowsHook => format!("Active: {hotkey}"),
|
||||
};
|
||||
Ok((registered, line))
|
||||
}
|
||||
Err(e) => Err(format!("Could not register {key}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn unregister(&mut self) {
|
||||
if let Some(m) = &mut self.manager {
|
||||
let _ = m.unregister(PTT_ID).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next event of the registration, or never while there is none.
|
||||
async fn next_event<E: EventStream>(events: &mut Option<E>) -> Option<HotkeyEvent> {
|
||||
match events {
|
||||
Some(events) => events.recv().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// The task: a key to register (or none) arrives on `rx`, the registered key's
|
||||
/// events are reported through `transmit`, and `status` says what happened.
|
||||
async fn run(
|
||||
rx: mpsc::UnboundedReceiver<Option<String>>,
|
||||
status: impl Fn(String),
|
||||
transmit: impl Fn(bool),
|
||||
) {
|
||||
run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await;
|
||||
}
|
||||
|
||||
/// The event loop of [`run`], parameterised over `registrar` so the
|
||||
/// fail-closed release paths are tested without a portal or display.
|
||||
async fn run_loop<R: Registrar>(
|
||||
mut rx: mpsc::UnboundedReceiver<Option<String>>,
|
||||
mut registrar: R,
|
||||
status: impl Fn(String),
|
||||
transmit: impl Fn(bool),
|
||||
) {
|
||||
let mut events: Option<R::Events> = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
key = rx.recv() => {
|
||||
let Some(key) = key else {
|
||||
// Fail closed on task exit: drop any hold that was still down.
|
||||
transmit(false);
|
||||
break;
|
||||
};
|
||||
events = None;
|
||||
// Whatever was held no longer counts.
|
||||
transmit(false);
|
||||
registrar.unregister().await;
|
||||
let Some(key) = key else {
|
||||
status("Off.".into());
|
||||
continue;
|
||||
};
|
||||
let hotkey: Hotkey = match key.parse() {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
status(format!("{e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match registrar.register(key, hotkey).await {
|
||||
Ok((registered, line)) => {
|
||||
events = Some(registered);
|
||||
status(line);
|
||||
}
|
||||
Err(line) => status(line),
|
||||
}
|
||||
}
|
||||
event = next_event(&mut events) => match event {
|
||||
Some(HotkeyEvent::Pressed) => transmit(true),
|
||||
Some(HotkeyEvent::Released) => transmit(false),
|
||||
None => {
|
||||
events = None;
|
||||
// Fail closed if the desktop removes the shortcut mid-hold.
|
||||
transmit(false);
|
||||
status("The hotkey was removed by the desktop.".into());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A channel-backed event stream for testing [`run_loop`] without a display.
|
||||
struct FakeEvents(mpsc::UnboundedReceiver<HotkeyEvent>);
|
||||
|
||||
impl EventStream for FakeEvents {
|
||||
async fn recv(&mut self) -> Option<HotkeyEvent> {
|
||||
self.0.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
/// A registrar that hands out a prepared [`FakeEvents`] stream once.
|
||||
struct FakeRegistrar {
|
||||
stream: Option<FakeEvents>,
|
||||
}
|
||||
|
||||
impl Registrar for FakeRegistrar {
|
||||
type Events = FakeEvents;
|
||||
|
||||
async fn register(
|
||||
&mut self,
|
||||
_key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> Result<(Self::Events, String), String> {
|
||||
let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?;
|
||||
Ok((events, format!("Active: {hotkey} (test)")))
|
||||
}
|
||||
|
||||
async fn unregister(&mut self) {}
|
||||
}
|
||||
|
||||
/// Next recorded message from the task, bounded only against a hang.
|
||||
async fn recv_log(rx: &mut mpsc::UnboundedReceiver<String>) -> String {
|
||||
tokio::time::timeout(Duration::from_secs(30), rx.recv())
|
||||
.await
|
||||
.expect("hotkey loop timed out")
|
||||
.expect("log channel closed unexpectedly")
|
||||
}
|
||||
|
||||
/// A key that is not one is said so and registers nothing, and the held
|
||||
/// state is let go first; no display or desktop is needed to say it.
|
||||
#[test]
|
||||
fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
|
||||
let log = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let (said, held) = (log.clone(), log.clone());
|
||||
let ptt = GlobalPtt::start(
|
||||
runtime.handle(),
|
||||
move |line| said.lock().unwrap().push(format!("status: {line}")),
|
||||
move |on| held.lock().unwrap().push(format!("transmit: {on}")),
|
||||
);
|
||||
ptt.set(Some("Ctrl+Hyper+Banana".into()));
|
||||
ptt.set(None);
|
||||
// The task answers in order: the last answer says the end of the list.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
while log.lock().unwrap().len() < 4 {
|
||||
assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap());
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let log = log.lock().unwrap().clone();
|
||||
assert_eq!(log[0], "transmit: false", "{log:?}");
|
||||
assert!(log[1].starts_with("status: "), "the parse error: {log:?}");
|
||||
assert_eq!(log[2], "transmit: false", "{log:?}");
|
||||
assert_eq!(log[3], "status: Off.", "{log:?}");
|
||||
drop(ptt);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
|
||||
/// When the desktop removes the registered hotkey while it is pressed, the
|
||||
/// loop releases transmit before reporting the removal.
|
||||
#[test]
|
||||
fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let (tx_key, rx_key) = mpsc::unbounded_channel();
|
||||
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
|
||||
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
|
||||
let (said, held) = (tx_log.clone(), tx_log);
|
||||
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
|
||||
let task = tokio::spawn(run_loop(
|
||||
rx_key,
|
||||
registrar,
|
||||
move |line| {
|
||||
let _ = said.send(format!("status: {line}"));
|
||||
},
|
||||
move |on| {
|
||||
let _ = held.send(format!("transmit: {on}"));
|
||||
},
|
||||
));
|
||||
|
||||
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
|
||||
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
|
||||
|
||||
tx_evt.send(HotkeyEvent::Pressed).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
|
||||
|
||||
// Desktop removes the shortcut while held.
|
||||
drop(tx_evt);
|
||||
assert_eq!(
|
||||
recv_log(&mut rx_log).await,
|
||||
"transmit: false",
|
||||
"transmit must fail closed before reporting removal"
|
||||
);
|
||||
assert_eq!(
|
||||
recv_log(&mut rx_log).await,
|
||||
"status: The hotkey was removed by the desktop."
|
||||
);
|
||||
|
||||
drop(tx_key);
|
||||
tokio::time::timeout(Duration::from_secs(30), task)
|
||||
.await
|
||||
.expect("task exit timed out")
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
/// When the command channel closes (task exit) while the hotkey is pressed,
|
||||
/// the loop releases transmit before exiting.
|
||||
#[test]
|
||||
fn closing_command_channel_mid_hold_releases_transmit_before_exiting() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let (tx_key, rx_key) = mpsc::unbounded_channel();
|
||||
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
|
||||
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
|
||||
let (said, held) = (tx_log.clone(), tx_log);
|
||||
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
|
||||
let task = tokio::spawn(run_loop(
|
||||
rx_key,
|
||||
registrar,
|
||||
move |line| {
|
||||
let _ = said.send(format!("status: {line}"));
|
||||
},
|
||||
move |on| {
|
||||
let _ = held.send(format!("transmit: {on}"));
|
||||
},
|
||||
));
|
||||
|
||||
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
|
||||
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
|
||||
|
||||
tx_evt.send(HotkeyEvent::Pressed).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
|
||||
|
||||
// Keep the event stream open while the handle drops (task exit).
|
||||
drop(tx_key);
|
||||
tokio::time::timeout(Duration::from_secs(30), task)
|
||||
.await
|
||||
.expect("task exit timed out")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
rx_log.try_recv().ok().as_deref(),
|
||||
Some("transmit: false"),
|
||||
"closing rx mid-hold must release transmit before breaking"
|
||||
);
|
||||
drop(tx_evt);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! 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 backend;
|
||||
pub mod dev;
|
||||
pub mod engine;
|
||||
pub mod fonts;
|
||||
pub mod hotkey;
|
||||
pub mod meter;
|
||||
pub mod pictures;
|
||||
pub mod shell;
|
||||
pub mod signals;
|
||||
pub mod swatch;
|
||||
pub mod theme;
|
||||
pub mod view;
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui_kit::{
|
||||
App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, point, px, size,
|
||||
};
|
||||
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
|
||||
use voelin_ui_vm::settings::WindowState;
|
||||
|
||||
use crate::app::{AppState, Setup, appearance};
|
||||
use crate::assets::Assets;
|
||||
use crate::backend::Backend;
|
||||
use crate::dev::Switches;
|
||||
use crate::engine::HostedEngine;
|
||||
use crate::meter::Counters;
|
||||
use crate::theme::VoelinTheme;
|
||||
use crate::view::MainView;
|
||||
|
||||
/// The smallest size the window can be given.
|
||||
const MIN_SIZE: (f32, f32) = (640.0, 480.0);
|
||||
|
||||
/// The size of a window that has no remembered one.
|
||||
const DEFAULT_SIZE: (f32, f32) = (1280.0, 800.0);
|
||||
|
||||
/// How long the engine gets, after the window closed, to act on the
|
||||
/// `CloseSession` commands the close sent (the Slint front end waits as long):
|
||||
/// its tasks run on the runtime, and shutting the runtime down drops them.
|
||||
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();
|
||||
}
|
||||
|
||||
/// Where the window opens: the size a development switch names, else the
|
||||
/// remembered place if a screen still shows its corner (a monitor can have
|
||||
/// gone since), else the middle of the screen at the default size. A place
|
||||
/// that has no position (Wayland does not tell one) is the remembered size
|
||||
/// in the middle. A window left maximized is asked for as maximized here, and
|
||||
/// again by [`MainView`] once it is shown (an X11 window manager loses this
|
||||
/// request: it manages a window only from its map).
|
||||
fn window_bounds(switches: &Switches, remembered: Option<WindowState>, cx: &App) -> WindowBounds {
|
||||
let sized = |(width, height): (f32, f32)| size(px(width), px(height));
|
||||
if let Some(forced) = switches.window {
|
||||
return WindowBounds::centered(sized(forced), cx);
|
||||
}
|
||||
let Some(state) = remembered else {
|
||||
return WindowBounds::centered(sized(DEFAULT_SIZE), cx);
|
||||
};
|
||||
let remembered_size =
|
||||
sized(((state.width as f32).max(MIN_SIZE.0), (state.height as f32).max(MIN_SIZE.1)));
|
||||
let at = state.x.zip(state.y).map(|(x, y)| point(px(x as f32), px(y as f32)));
|
||||
let bounds = match at {
|
||||
Some(origin)
|
||||
if cx.displays().iter().any(|display| {
|
||||
display.bounds().intersects(&Bounds::new(origin, size(px(64.0), px(32.0))))
|
||||
}) =>
|
||||
{
|
||||
Bounds::new(origin, remembered_size)
|
||||
}
|
||||
_ => Bounds::centered(None, remembered_size, cx),
|
||||
};
|
||||
if state.maximized { WindowBounds::Maximized(bounds) } else { WindowBounds::Windowed(bounds) }
|
||||
}
|
||||
|
||||
/// The main window's options: titled with the app's name (and the server
|
||||
/// shown), grouped by its id, opened where [`window_bounds`] says.
|
||||
fn window_options(
|
||||
switches: &Switches,
|
||||
remembered: Option<WindowState>,
|
||||
title: String,
|
||||
cx: &App,
|
||||
) -> WindowOptions {
|
||||
WindowOptions {
|
||||
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
|
||||
app_id: Some(voelin_platform::APP_ID.to_owned()),
|
||||
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
|
||||
window_bounds: Some(window_bounds(switches, remembered, 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,
|
||||
backend: Backend,
|
||||
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 setup = Setup {
|
||||
engine: Some(engine),
|
||||
events,
|
||||
counters: counters.clone(),
|
||||
backend,
|
||||
switches: switches.clone(),
|
||||
};
|
||||
move |cx| AppState::new(setup, cx)
|
||||
});
|
||||
// The global push-to-talk key, on the engine's runtime (docs/ui.md): once the
|
||||
// state exists, and never from a test of the state.
|
||||
app.update(cx, |app, _| app.start_global_ptt());
|
||||
let options = {
|
||||
let app = app.read(cx);
|
||||
window_options(switches, app.remembered_window(), app.window_title(), cx)
|
||||
};
|
||||
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.update(cx, |app, cx| app.shutdown(cx)));
|
||||
cx.quit();
|
||||
true
|
||||
}
|
||||
});
|
||||
cx.new(|cx| MainView::new(app, page, counters, window, cx))
|
||||
}
|
||||
})
|
||||
.context("cannot open the main window")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait `grace` on `runtime`, so that the engine's tasks run (they send the
|
||||
/// closes of the sessions) before the runtime drops them. The sleep is made
|
||||
/// inside the runtime: a `Sleep` made outside it, as an argument of
|
||||
/// `block_on`, panics ("there is no reactor running").
|
||||
fn give_the_engine_time(runtime: &tokio::runtime::Runtime, grace: Duration) {
|
||||
runtime.block_on(async move { tokio::time::sleep(grace).await });
|
||||
}
|
||||
|
||||
/// Run the app on the current thread until its window closes.
|
||||
pub fn run() -> Result<()> {
|
||||
init_logging();
|
||||
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);
|
||||
// The store and the settings, in the platform's data directory
|
||||
// (`VOELIN_DATA_DIR` moves it: every run of this binary that is not the
|
||||
// user's own sets it, and the XDG directories with it).
|
||||
let backend = Backend::open(&backend::data_dir(), backend::default_secrets(switches.demo_ui))
|
||||
.context("cannot open the client's store")?;
|
||||
backend.attach(&hosted.engine);
|
||||
let (theme, font_scale) = appearance(&backend.prefs, &switches);
|
||||
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
|
||||
let closed_sessions: Rc<Cell<usize>> = Rc::default();
|
||||
gpui_kit::application().with_assets(Assets).run({
|
||||
let failure = failure.clone();
|
||||
let closed_sessions = closed_sessions.clone();
|
||||
move |cx| {
|
||||
gpui_kit::init(cx);
|
||||
shell::bind_keys(cx);
|
||||
fonts::load(cx);
|
||||
// The mode and the text size are the settings', or a development
|
||||
// switch's.
|
||||
VoelinTheme::init(cx, theme, cx.window_appearance(), font_scale);
|
||||
if let Err(e) =
|
||||
open_main_window(cx, &switches, hosted, backend, counters, closed_sessions)
|
||||
{
|
||||
*failure.borrow_mut() = Some(e);
|
||||
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
|
||||
// before it starts its event loop, and the loop forgets a stop
|
||||
// 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 {
|
||||
give_the_engine_time(&runtime, CLOSE_GRACE);
|
||||
}
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
match failure.take() {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The grace after a close with open sessions is a wait on the engine's
|
||||
/// runtime from the GPUI thread, which is no runtime thread: it must not
|
||||
/// panic, and it must wait. (The first end-to-end close against a server,
|
||||
/// the first slice that opens a session, found the panic.)
|
||||
#[test]
|
||||
fn the_close_grace_waits_on_the_runtime_from_a_thread_that_is_none() {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
give_the_engine_time(&runtime, Duration::from_millis(30));
|
||||
assert!(started.elapsed() >= Duration::from_millis(30));
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
@@ -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,357 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times each pane of the window was rendered (per second). A pane
|
||||
/// is an entity of its own that the window draws again only when it was
|
||||
/// notified (`Entity::cached`), or when something below it was; the figures
|
||||
/// say which panes a change of the state cost.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Panes {
|
||||
/// The server rail.
|
||||
pub rail: Counter,
|
||||
/// The top bar.
|
||||
pub topbar: Counter,
|
||||
/// The sidebar (the server card, the voice and user cards; the tree is
|
||||
/// inside it).
|
||||
pub sidebar: Counter,
|
||||
/// The channel tree.
|
||||
pub tree: Counter,
|
||||
/// The main area.
|
||||
pub main: Counter,
|
||||
/// The members panel.
|
||||
pub members: Counter,
|
||||
/// The voice channel page.
|
||||
pub voice: Counter,
|
||||
}
|
||||
|
||||
impl Panes {
|
||||
/// The counters with the names the meter reports them under.
|
||||
pub fn named(&self) -> [(&'static str, Counter); 7] {
|
||||
[
|
||||
("rail", self.rail.clone()),
|
||||
("topbar", self.topbar.clone()),
|
||||
("sidebar", self.sidebar.clone()),
|
||||
("tree", self.tree.clone()),
|
||||
("main", self.main.clone()),
|
||||
("members", self.members.clone()),
|
||||
("voice", self.voice.clone()),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's own numbers the meter reports besides the process's.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counters {
|
||||
/// 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,
|
||||
/// Renders of each pane of the window (per second).
|
||||
pub panes: Panes,
|
||||
/// Jobs other threads handed to the foreground through
|
||||
/// [`crate::app::Later`] (per second).
|
||||
pub later_jobs: Counter,
|
||||
/// 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: Vec<(&str, Counter)> = [
|
||||
("engine_events", counters.engine_events.clone()),
|
||||
("ticks", counters.ticks.clone()),
|
||||
("renders", counters.renders.clone()),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(counters.panes.named())
|
||||
.chain([("later_jobs", counters.later_jobs.clone())])
|
||||
.collect();
|
||||
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
|
||||
loop {
|
||||
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 the_panes_are_counted_by_name() {
|
||||
let panes = Panes::default();
|
||||
panes.members.incr();
|
||||
let named = panes.named();
|
||||
let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect();
|
||||
assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]);
|
||||
let seen: Vec<u64> = named.iter().map(|(_, counter)| counter.get()).collect();
|
||||
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_drop_trailing_numbers() {
|
||||
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
|
||||
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,205 @@
|
||||
//! Pictures of the engine's cache on screen.
|
||||
//!
|
||||
//! The engine writes a picture that arrives again into the same file in its
|
||||
//! cache (an avatar or a server icon that changed), and GPUI's `img(path)`
|
||||
//! keeps what it decoded in the asset cache under the path alone, so the new
|
||||
//! picture would never show. Here the key of a decoded picture is the file
|
||||
//! and what the file was when the reference to it was made
|
||||
//! ([`PictureKey`]: the path and the [`Stamp`] of `voelin_ui_vm::image`, its
|
||||
//! length and time), so a reference made after the file changed is another
|
||||
//! picture: it is decoded, and the lists that show it compare unequal and
|
||||
//! draw the row again. What a changed file left in the cache (the decoded
|
||||
//! copy under the old key, and the texture the atlas made of it) is dropped
|
||||
//! when the engine says the file was written again
|
||||
//! ([`forget_stale`], for `Update::reloaded`).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::{
|
||||
App, Asset, Global, ImageAssetLoader, ImageCacheError, ImageSource, Img, RenderImage, Resource,
|
||||
img,
|
||||
};
|
||||
use voelin_ui_vm::image::{ImageRef, ImageSource as Picture, Stamp};
|
||||
|
||||
/// What identifies a decoded picture: the file in the engine's cache and what
|
||||
/// it was when the picture was referred to.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct PictureKey {
|
||||
path: Arc<Path>,
|
||||
stamp: Stamp,
|
||||
}
|
||||
|
||||
impl PictureKey {
|
||||
/// The key of a reference to a file of the cache; none for no picture, a
|
||||
/// picture that cannot be shown (missing or damaged: the reference's
|
||||
/// size is none) and the pictures that are not files, which the slices
|
||||
/// that decode them show.
|
||||
pub fn of(image: &ImageRef) -> Option<Self> {
|
||||
match &**image {
|
||||
Picture::File { path, stamp } if image.size().width > 0 => {
|
||||
Some(Self { path: Arc::from(path.as_path()), stamp: *stamp })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The file.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the file of a [`PictureKey`] as `img(path)` does, keeping the
|
||||
/// result under the whole key.
|
||||
enum PictureLoader {}
|
||||
|
||||
impl Asset for PictureLoader {
|
||||
type Source = PictureKey;
|
||||
type Output = Result<Arc<RenderImage>, ImageCacheError>;
|
||||
|
||||
fn load(
|
||||
source: PictureKey,
|
||||
cx: &mut App,
|
||||
) -> impl Future<Output = Self::Output> + Send + 'static {
|
||||
<ImageAssetLoader as Asset>::load(Resource::Path(source.path), cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys that were drawn, by file: what [`forget_stale`] has to look at.
|
||||
#[derive(Default)]
|
||||
struct Drawn(HashMap<Arc<Path>, Vec<PictureKey>>);
|
||||
|
||||
impl Global for Drawn {}
|
||||
|
||||
/// Note that `key` is being drawn.
|
||||
fn note(key: &PictureKey, cx: &mut App) {
|
||||
let known = cx.has_global::<Drawn>()
|
||||
&& cx.global::<Drawn>().0.get(key.path()).is_some_and(|keys| keys.contains(key));
|
||||
if !known {
|
||||
cx.default_global::<Drawn>().0.entry(key.path.clone()).or_default().push(key.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture at `key` as an image element: decoded once per key, and again
|
||||
/// when the file is another by the stamp. Give it a size and an object fit.
|
||||
pub fn picture(key: PictureKey) -> Img {
|
||||
img(ImageSource::Custom(Arc::new(move |window, cx| {
|
||||
note(&key, cx);
|
||||
window.use_asset::<PictureLoader>(&key, cx)
|
||||
})))
|
||||
}
|
||||
|
||||
/// The engine wrote the file at `path` again: drop what was decoded of it
|
||||
/// under a stamp it no longer has, and the textures the atlas made of that.
|
||||
/// The picture under the stamp it has now (a reference made after the write)
|
||||
/// is kept; one that is made from the old file is drawn again when it is next
|
||||
/// asked for.
|
||||
pub fn forget_stale(path: &Path, cx: &mut App) {
|
||||
if !cx.has_global::<Drawn>() {
|
||||
return;
|
||||
}
|
||||
let now = Stamp::of(path);
|
||||
let stale: Vec<PictureKey> = {
|
||||
let Some(keys) = cx.global_mut::<Drawn>().0.get_mut(path) else { return };
|
||||
let (stale, kept) = std::mem::take(keys).into_iter().partition(|key| key.stamp != now);
|
||||
*keys = kept;
|
||||
stale
|
||||
};
|
||||
for key in stale {
|
||||
if let Some(Ok(image)) = cx.fetch_asset::<PictureLoader>(&key) {
|
||||
cx.drop_image(image, None);
|
||||
}
|
||||
cx.remove_asset::<PictureLoader>(&key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the decoded copy of `key` is in the asset cache (the tests ask).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool {
|
||||
cx.has_asset::<PictureLoader>(key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use voelin_ui_vm::image::ImageSource as Source;
|
||||
|
||||
use super::*;
|
||||
use crate::backend::testing::TempDir;
|
||||
|
||||
/// A PNG of `width` by 2 pixels.
|
||||
fn png(width: u32) -> Vec<u8> {
|
||||
voelin_ui_vm::dev::logic::demo_picture(width, 2, 1)
|
||||
}
|
||||
|
||||
/// The key of a picture follows the file: a reference made after the
|
||||
/// engine wrote the file again is another picture, one made before still
|
||||
/// refers to the old, and what is not a file of the cache has none.
|
||||
#[test]
|
||||
fn the_key_of_a_picture_changes_when_the_file_does() {
|
||||
let dir = TempDir::new("picture-key");
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let path = dir.0.join("avatar");
|
||||
std::fs::write(&path, png(3)).unwrap();
|
||||
let first = Source::file(&path);
|
||||
let key = PictureKey::of(&first).expect("a picture in the cache");
|
||||
assert_eq!(key.path(), path);
|
||||
assert_eq!(PictureKey::of(&Source::file(&path)), Some(key.clone()), "same file, same key");
|
||||
|
||||
std::fs::write(&path, png(7)).unwrap();
|
||||
let second = PictureKey::of(&Source::file(&path)).unwrap();
|
||||
assert_ne!(second, key, "the file was written again");
|
||||
assert_eq!(PictureKey::of(&first), Some(key), "a reference made before keeps its own");
|
||||
|
||||
assert_eq!(PictureKey::of(&Source::none()), None);
|
||||
assert_eq!(PictureKey::of(&Source::file(dir.0.join("missing"))), None);
|
||||
std::fs::write(dir.0.join("damaged"), b"not a picture").unwrap();
|
||||
assert_eq!(PictureKey::of(&Source::file(dir.0.join("damaged"))), None);
|
||||
assert_eq!(PictureKey::of(&Source::rgba(1, 1, vec![0; 4])), None, "not a file");
|
||||
}
|
||||
|
||||
/// A picture rewritten into the same file is decoded again under its new
|
||||
/// key, and what was decoded of the old one is dropped when the engine says
|
||||
/// the file was written again; the key of the file as it is stays.
|
||||
#[gpui::test]
|
||||
fn a_picture_written_again_is_decoded_again_and_the_old_copy_goes(cx: &mut TestAppContext) {
|
||||
let dir = TempDir::new("picture-reload");
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let path = dir.0.join("avatar");
|
||||
std::fs::write(&path, png(3)).unwrap();
|
||||
let old = PictureKey::of(&Source::file(&path)).unwrap();
|
||||
let width = |cx: &mut TestAppContext, key: &PictureKey| {
|
||||
cx.update(|cx| match cx.fetch_asset::<PictureLoader>(key) {
|
||||
Some(Ok(image)) => Some(image.size(0).width.0),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
cx.update(|cx| note(&old, cx));
|
||||
assert_eq!(width(cx, &old), None, "loading");
|
||||
cx.run_until_parked();
|
||||
assert_eq!(width(cx, &old), Some(3));
|
||||
|
||||
// The engine writes the file again, and the window draws the picture
|
||||
// under the key of the file as it is now, before it is told so.
|
||||
std::fs::write(&path, png(7)).unwrap();
|
||||
let new = PictureKey::of(&Source::file(&path)).unwrap();
|
||||
cx.update(|cx| note(&new, cx));
|
||||
assert_eq!(width(cx, &new), None, "loading");
|
||||
cx.run_until_parked();
|
||||
assert_eq!(width(cx, &new), Some(7), "the new bytes, not the old ones");
|
||||
assert_eq!(width(cx, &old), Some(3), "the old copy is still there");
|
||||
|
||||
cx.update(|cx| forget_stale(&path, cx));
|
||||
assert!(!cx.update(|cx| cx.has_asset::<PictureLoader>(&old)), "the old copy is dropped");
|
||||
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)), "the current key is kept");
|
||||
assert_eq!(width(cx, &new), Some(7));
|
||||
|
||||
// Nothing more to forget; a file nobody drew is nothing to forget.
|
||||
cx.update(|cx| forget_stale(&path, cx));
|
||||
cx.update(|cx| forget_stale(&dir.0.join("never-drawn"), cx));
|
||||
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! What the user can ask of the shell, as GPUI actions: the callbacks of the
|
||||
//! Slint front end's `bind/servers.rs` that the desktop shell has (the first
|
||||
//! eleven below), and the shell's own affordances. A click dispatches the
|
||||
//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view
|
||||
//! ([`crate::view::MainView`]) handles it, and the handler asks the root state
|
||||
//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings
|
||||
//! and menus come to the same handlers later.
|
||||
//!
|
||||
//! The voice page and the call bar add `show_voice_view`, the page's own
|
||||
//! buttons (the smaller stage, Leave) and the two affordances of the call bar
|
||||
//! whose pages come with later slices (Share, the voice settings), which are
|
||||
//! logged.
|
||||
//!
|
||||
//! The channel tree and the members panel add `join_channel`,
|
||||
//! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and
|
||||
//! `open_client` (the last one only logs: the client's volume dialog is a
|
||||
//! dialog of its own slice). The callbacks of `bind/servers.rs` that are
|
||||
//! still not here belong to the slices after: `client_audio_changed` to the
|
||||
//! dialogs (the member card has the volume and the mute of a person,
|
||||
//! [`SetMemberVolume`] and [`SetMemberMuted`]), and `copied` (the toast that
|
||||
//! follows a copy) to whichever copies: [`Invite`] sets it itself.
|
||||
|
||||
use gpui_kit::{Action, actions};
|
||||
|
||||
actions!(
|
||||
voelin,
|
||||
[
|
||||
/// `connect_voice`: connect the server on screen with voice, into its default channel.
|
||||
ConnectVoice,
|
||||
/// `disconnect_voice`: leave voice on the server on screen.
|
||||
DisconnectVoice,
|
||||
/// `invite`: copy a link to the voice channel we are in.
|
||||
Invite,
|
||||
/// `save_bookmark`: save the server form (the form's own Save button).
|
||||
SaveServer,
|
||||
/// `save_and_connect`: save the server form, then connect.
|
||||
SaveAndConnect,
|
||||
/// Open the empty server form (the rail's plus button).
|
||||
AddServer,
|
||||
/// Close the server form without saving.
|
||||
CancelServerForm,
|
||||
/// The top bar's search box: the search comes with its slice, today it is logged.
|
||||
OpenSearch,
|
||||
/// The settings buttons: the settings come with their slice, today it is logged.
|
||||
OpenSettings,
|
||||
/// `join_with_password`: the password prompt's Join, with what it holds.
|
||||
SubmitChannelPassword,
|
||||
/// Close the password prompt without joining.
|
||||
CancelChannelPassword,
|
||||
/// The voice page's Leave (`Nav.show-voice(false)` then `disconnect_voice`).
|
||||
LeaveVoice,
|
||||
/// The voice page's Smaller stage / Larger stage (`ui.voice_compact`).
|
||||
ToggleVoiceCompact,
|
||||
/// The call bar's Share: the share menu comes with the stream slices, today it is logged.
|
||||
OpenShare,
|
||||
/// The call bar's voice settings: the settings come with their slice, today it is logged.
|
||||
OpenVoiceSettings,
|
||||
]
|
||||
);
|
||||
|
||||
/// `show_voice_view`: the voice channel page on (the main area) or off (back to
|
||||
/// the server page, where the chat will be).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct ShowVoiceView {
|
||||
/// Shown from now on.
|
||||
pub on: bool,
|
||||
}
|
||||
|
||||
/// The member card's volume slider: the person's playback volume, in percent
|
||||
/// (`member_volume` of the Slint card).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SetMemberVolume {
|
||||
/// The client's id on the server.
|
||||
pub client: u16,
|
||||
/// 0 to 200.
|
||||
pub percent: f32,
|
||||
}
|
||||
|
||||
/// The member card's Mute for me: stop playing the person (local only).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SetMemberMuted {
|
||||
/// The client's id on the server.
|
||||
pub client: u16,
|
||||
/// Muted from now on.
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
/// `select_server`: show a server (and observe it).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SelectServer {
|
||||
/// The bookmark's id.
|
||||
pub id: i64,
|
||||
}
|
||||
|
||||
/// `edit_bookmark`: open the server form with a saved server.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct EditServer {
|
||||
/// The bookmark's id.
|
||||
pub id: i64,
|
||||
}
|
||||
|
||||
/// `delete_bookmark`: remove a server.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct DeleteServer {
|
||||
/// The bookmark's id.
|
||||
pub id: i64,
|
||||
}
|
||||
|
||||
/// `set_input_muted`: mute or unmute our microphone.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SetInputMuted {
|
||||
/// Muted from now on.
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
/// `set_output_muted`: mute or unmute the sound.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SetOutputMuted {
|
||||
/// Muted from now on.
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
/// `push_to_talk`: transmit while the hold-to-talk button is held.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct PushToTalk {
|
||||
/// Transmitting from now on.
|
||||
pub on: bool,
|
||||
}
|
||||
|
||||
/// `join_channel`: join a channel of the server on screen (a double-click on
|
||||
/// its row, the context menu's Join).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct JoinChannel {
|
||||
/// The channel's id on the server.
|
||||
pub channel: u64,
|
||||
}
|
||||
|
||||
/// A click on a channel's row: select it (the Slint tree opens the channel's
|
||||
/// chat, which comes with the chat slice).
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SelectChannel {
|
||||
/// The channel's id on the server.
|
||||
pub channel: u64,
|
||||
}
|
||||
|
||||
/// `toggle_collapse`: fold or unfold a channel of the tree.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct ToggleChannel {
|
||||
/// The channel's id on the server.
|
||||
pub channel: u64,
|
||||
}
|
||||
|
||||
/// The context menu's Edit channel: the channel editor is a slice of its own,
|
||||
/// today it is logged.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct EditChannel {
|
||||
/// The channel's id on the server.
|
||||
pub channel: u64,
|
||||
}
|
||||
|
||||
/// The context menu's Move to my channel: moving another client needs a command
|
||||
/// the engine does not have yet, so today it is logged.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct MoveClient {
|
||||
/// The client's id on the server.
|
||||
pub client: u16,
|
||||
}
|
||||
|
||||
/// `open_client`: a click on a person in the tree opens their volume dialog,
|
||||
/// which is a dialog of its own slice: today it is logged.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct OpenClient {
|
||||
/// The client's id on the server.
|
||||
pub client: u16,
|
||||
}
|
||||
|
||||
/// `search_members`: the members panel's search text.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct SearchMembers {
|
||||
/// What the box holds; empty shows everyone.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// `open_member`: open the card of a person over the members panel; -1 closes it.
|
||||
#[derive(Clone, Debug, PartialEq, Action)]
|
||||
#[action(namespace = voelin, no_json)]
|
||||
pub struct OpenMember {
|
||||
/// The client's id on the server, or -1.
|
||||
pub client: i32,
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
//! The channel tree of the sidebar (`ChannelTree` of `screens/channels.slint`):
|
||||
//! the channels of the server on screen with the people in them, nested, with
|
||||
//! their spacers, pictures, passwords and counts, and the person's marks.
|
||||
//!
|
||||
//! A cached pane ([`gpui_kit::Entity::cached`], which needs the size the
|
||||
//! sidebar gives it) over a virtual list ([`gpui_kit::list`]: only the rows in
|
||||
//! view are built, the rows differ in height) that follows [`TreeModel`]: the
|
||||
//! model says which rows changed ([`TreeEvent::Rows`]) and the pane tells its
|
||||
//! list, so a person who joins is a row inserted and the scroll stays where it
|
||||
//! was. The pane reads nothing but its own fields while it renders, so
|
||||
//! nothing but its own notify draws it again. A click selects a channel, a
|
||||
//! double-click joins it, the chevron folds it, a right-click offers the
|
||||
//! same; a click on a person is logged (their volume dialog is a slice of
|
||||
//! its own).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::component::menu::ContextMenuExt as _;
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ListAlignment,
|
||||
ListState, ObjectFit, ParentElement as _, Render, SharedString,
|
||||
StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, div,
|
||||
list, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::TreeItem;
|
||||
use voelin_ui_vm::tree::ChannelId;
|
||||
|
||||
use super::actions::{
|
||||
EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel,
|
||||
};
|
||||
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
|
||||
use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture, speaking_bars};
|
||||
use crate::meter::Counters;
|
||||
use crate::pictures::{PictureKey, picture};
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// How far each level of the tree is indented.
|
||||
const INDENT: f32 = 14.0;
|
||||
|
||||
/// How opaque the hover and selection tints of a row with a banner are over
|
||||
/// the banner and its veil: the hover is `channels.slint`'s (`Theme.surface-3.
|
||||
/// transparentize(0.5)`), the selection, which Slint has no state for, is a
|
||||
/// stronger one of the same colour.
|
||||
const BANNER_HOVER: f32 = 0.5;
|
||||
const BANNER_SELECTED: f32 = 0.75;
|
||||
|
||||
/// The channel tree.
|
||||
pub struct ChannelTree {
|
||||
rows: Arc<Vec<TreeItem>>,
|
||||
selected: Option<ChannelId>,
|
||||
emptiness: Emptiness,
|
||||
list: ListState,
|
||||
/// The text size factor the list measured its rows at.
|
||||
measured_at: f32,
|
||||
counters: Counters,
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
impl ChannelTree {
|
||||
/// A tree that follows `model`.
|
||||
pub fn new(model: &Entity<TreeModel>, counters: Counters, cx: &mut Context<Self>) -> Self {
|
||||
let (rows, selected, emptiness) = {
|
||||
let model = model.read(cx);
|
||||
(model.rows().clone(), model.selected(), model.emptiness())
|
||||
};
|
||||
let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
|
||||
match event {
|
||||
TreeEvent::Rows(changes, rows) => this.apply(changes, rows.clone()),
|
||||
TreeEvent::Selection => this.selected = model.read(cx).selected(),
|
||||
// The count of people is the members panel's.
|
||||
TreeEvent::Lists => {
|
||||
let emptiness = model.read(cx).emptiness();
|
||||
if emptiness == this.emptiness {
|
||||
return;
|
||||
}
|
||||
this.emptiness = emptiness;
|
||||
}
|
||||
TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return,
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
Self {
|
||||
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
|
||||
rows,
|
||||
selected,
|
||||
emptiness,
|
||||
measured_at: 0.0,
|
||||
counters,
|
||||
_subscription: subscription,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows it shows.
|
||||
pub fn rows(&self) -> &[TreeItem] {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
/// The channel it shows selected.
|
||||
pub fn selected(&self) -> Option<ChannelId> {
|
||||
self.selected
|
||||
}
|
||||
|
||||
/// Why it shows no rows, were it empty.
|
||||
pub fn emptiness(&self) -> Emptiness {
|
||||
self.emptiness
|
||||
}
|
||||
|
||||
/// Take the new rows in (the rows `changes` lead to, carried by the event),
|
||||
/// telling the list which rows came, went or changed their height (a
|
||||
/// channel row and a person's differ).
|
||||
fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc<Vec<TreeItem>>) {
|
||||
use voelin_ui_vm::list::Change;
|
||||
|
||||
debug_check(self.rows.len(), changes, new.len());
|
||||
let mut channels: Vec<bool> = self.rows.iter().map(|row| row.is_channel).collect();
|
||||
for change in &changes.0 {
|
||||
match *change {
|
||||
Change::Update(i) => {
|
||||
if channels[i] != new[i].is_channel {
|
||||
self.list.splice(i..i + 1, 1);
|
||||
}
|
||||
channels[i] = new[i].is_channel;
|
||||
}
|
||||
Change::Remove(i) => {
|
||||
channels.remove(i);
|
||||
self.list.splice(i..i + 1, 0);
|
||||
}
|
||||
Change::Insert(i) => {
|
||||
channels.insert(i, new[i].is_channel);
|
||||
self.list.splice(i..i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.rows = new;
|
||||
}
|
||||
|
||||
/// The row at `ix`, for the list.
|
||||
fn row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
match self.rows.get(ix) {
|
||||
Some(item) if item.is_channel => {
|
||||
channel_row(&theme, item, self.selected == Some(item.id as ChannelId))
|
||||
}
|
||||
Some(item) => client_row(&theme, item),
|
||||
None => div().into_any_element(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The words of a tree with no rows.
|
||||
fn empty_words(emptiness: Emptiness) -> &'static str {
|
||||
match emptiness {
|
||||
Emptiness::NoServer => "No server yet.",
|
||||
Emptiness::Loading => "Loading the channels…",
|
||||
// The tree is not searched, so it is never `NoMatch` (the members
|
||||
// panel's, `TreeModel::people_emptiness`): the model gives it
|
||||
// `Emptiness::of`, which does not say it.
|
||||
Emptiness::Connect | Emptiness::NoMatch => "Connect to see the channels.",
|
||||
}
|
||||
}
|
||||
|
||||
/// The chevron of a channel, which folds it.
|
||||
fn chevron(item: &TreeItem, covered: bool, theme: &VoelinTheme) -> impl IntoElement {
|
||||
let c = &theme.colors;
|
||||
let id = item.id as ChannelId;
|
||||
div()
|
||||
.id(("tree-toggle", id))
|
||||
.debug_selector(move || format!("tree-toggle-{id}"))
|
||||
.w(px(18.0))
|
||||
.h(px(18.0))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.on_click(move |_, window, cx| {
|
||||
cx.stop_propagation();
|
||||
window.dispatch_action(Box::new(ToggleChannel { channel: id }), cx);
|
||||
})
|
||||
.child(icon(
|
||||
if item.collapsed { "chevron-right" } else { "chevron-down" },
|
||||
14.0,
|
||||
if covered { c.text } else { c.text_muted },
|
||||
))
|
||||
}
|
||||
|
||||
/// One channel: its icon (or a speaker, or a lock), its name as the server
|
||||
/// set it out, how many are in it, and the chevron.
|
||||
fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let id = item.id as ChannelId;
|
||||
let indent = item.depth as f32 * INDENT;
|
||||
let banner = PictureKey::of(&item.banner);
|
||||
let covered = banner.is_some();
|
||||
let strong = item.own || covered;
|
||||
let (hover, accent_soft, accent, selected_fill) =
|
||||
(hsla(c.surface_3), hsla(c.accent_soft), hsla(c.accent), hsla(c.surface_3));
|
||||
let own = item.own;
|
||||
let has_icon = PictureKey::of(&item.icon).is_some();
|
||||
let name_color = if strong { c.text } else { c.text_secondary };
|
||||
let weight = if strong { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM };
|
||||
let name = div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.text_size(px(m.font_body))
|
||||
.font_weight(weight)
|
||||
.text_color(hsla(name_color))
|
||||
.when(item.spacer == 2, |name| name.text_center())
|
||||
.when(item.spacer == 3, |name| name.text_right())
|
||||
// A line is cut where the row ends; it does not widen the list.
|
||||
.when(item.spacer == 4, |name| name.overflow_hidden().whitespace_nowrap())
|
||||
.when(item.spacer != 4, |name| name.truncate())
|
||||
.child(item.name.to_string());
|
||||
let counted = item.spacer == 0 && (item.members > 0 || item.max_members >= 0);
|
||||
let count = if item.max_members >= 0 {
|
||||
format!("{}/{}", item.members, item.max_members)
|
||||
} else {
|
||||
item.members.to_string()
|
||||
};
|
||||
let group = SharedString::from(format!("tree-row-{id}"));
|
||||
let row = div()
|
||||
.id(("tree-channel", id))
|
||||
.debug_selector(move || format!("tree-channel-{id}"))
|
||||
.group(group.clone())
|
||||
.relative()
|
||||
.w_full()
|
||||
.h(px(34.0 * m.font_scale))
|
||||
.flex_none()
|
||||
.overflow_hidden()
|
||||
.rounded(px(m.radius_md))
|
||||
.cursor_pointer()
|
||||
.when(own, |row| row.bg(accent_soft).border_1().border_color(accent))
|
||||
.when(!own && selected, |row| row.bg(selected_fill))
|
||||
.when(!own && !selected, |row| row.hover(move |style| style.bg(hover)))
|
||||
// Artwork behind the same compact row as its title, from the indent on,
|
||||
// under a veil of the surface colour that keeps the text readable over
|
||||
// any picture, and under the tints of the row: our own channel's, the
|
||||
// selected one and the one the pointer is over. The artwork covers the
|
||||
// row's own background (which only the indent shows), so the tints
|
||||
// are translucent children above the veil, as `channels.slint` does
|
||||
// for the hover.
|
||||
.when_some(banner, |row, key| {
|
||||
let tint = || {
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.bottom(px(0.0))
|
||||
.left(px(indent))
|
||||
.right(px(0.0))
|
||||
.rounded(px(m.radius_md))
|
||||
};
|
||||
row.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.bottom(px(0.0))
|
||||
.left(px(indent))
|
||||
.right(px(0.0))
|
||||
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id(("tree-scrim", id))
|
||||
.debug_selector(move || format!("tree-scrim-{id}"))
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.bottom(px(0.0))
|
||||
.left(px(indent))
|
||||
.right(px(0.0))
|
||||
.bg(banner_scrim(theme)),
|
||||
)
|
||||
.when(own, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.bottom(px(0.0))
|
||||
.left(px(indent))
|
||||
.right(px(0.0))
|
||||
.rounded(px(m.radius_md))
|
||||
.bg(accent_soft.opacity(0.65)),
|
||||
)
|
||||
})
|
||||
.when(!own && selected, |row| {
|
||||
row.child(
|
||||
tint()
|
||||
.debug_selector(move || format!("tree-selected-{id}"))
|
||||
.bg(selected_fill.opacity(BANNER_SELECTED)),
|
||||
)
|
||||
})
|
||||
.when(!own && !selected, |row| {
|
||||
row.child(
|
||||
tint().group_hover(group, move |style| style.bg(hover.opacity(BANNER_HOVER))),
|
||||
)
|
||||
})
|
||||
})
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.pl(px(m.space_2 + indent))
|
||||
.pr(px(m.space_3))
|
||||
.gap(px(m.space_2))
|
||||
// A centred spacer is balanced against the chevron.
|
||||
.when(item.spacer == 2, |row| row.child(div().w(px(18.0)).flex_none()))
|
||||
.when(item.spacer == 0, |row| match small_picture(&item.icon, 16.0) {
|
||||
Some(picture) => row.child(picture),
|
||||
None => row.child(icon(
|
||||
if item.locked { "lock" } else { "volume-2" },
|
||||
18.0,
|
||||
if strong { c.text } else { c.icon },
|
||||
)),
|
||||
})
|
||||
.child(name)
|
||||
.when(item.locked && (has_icon || item.spacer != 0), |row| {
|
||||
row.child(icon("lock", 14.0, if covered { c.text } else { c.icon }))
|
||||
})
|
||||
.when(counted, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(3.0))
|
||||
.when(own, |count| count.child(icon("users", 14.0, c.text_secondary)))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(if strong { c.text } else { c.text_muted }))
|
||||
.child(count),
|
||||
),
|
||||
)
|
||||
})
|
||||
.child(chevron(item, covered, theme))
|
||||
.on_click(move |event, window, cx| {
|
||||
if event.click_count() >= 2 {
|
||||
window.dispatch_action(Box::new(JoinChannel { channel: id }), cx);
|
||||
} else {
|
||||
window.dispatch_action(Box::new(SelectChannel { channel: id }), cx);
|
||||
}
|
||||
})
|
||||
.context_menu(move |menu, _, _| {
|
||||
menu.menu("Join channel", Box::new(JoinChannel { channel: id }))
|
||||
.menu("Fold or unfold", Box::new(ToggleChannel { channel: id }))
|
||||
.separator()
|
||||
.menu("Edit channel…", Box::new(EditChannel { channel: id }))
|
||||
});
|
||||
row.into_any_element()
|
||||
}
|
||||
|
||||
/// One person: their avatar, name and badges, and the marks of what they do.
|
||||
fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let id = item.id as u64;
|
||||
let indent = item.depth as f32 * INDENT;
|
||||
let (hover, myself) = (hsla(c.surface_3), item.myself);
|
||||
let name_color = if item.away {
|
||||
c.text_muted
|
||||
} else if myself {
|
||||
c.accent_text
|
||||
} else {
|
||||
c.text_secondary
|
||||
};
|
||||
let mark = |name: &'static str, color| icon(name, 14.0, color);
|
||||
div()
|
||||
.id(("tree-client", id))
|
||||
.debug_selector(move || format!("tree-client-{id}"))
|
||||
.w_full()
|
||||
.h(px(30.0 * m.font_scale))
|
||||
.flex_none()
|
||||
.rounded(px(m.radius_md))
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hover))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.pl(px(m.space_2 + indent + 12.0))
|
||||
.pr(px(m.space_3))
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint)
|
||||
.image(item.avatar.clone())
|
||||
.speaking(item.talking),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_body))
|
||||
.font_weight(if myself { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
|
||||
.text_color(hsla(name_color))
|
||||
.child(item.name.to_string()),
|
||||
)
|
||||
// Badges after the name, then the free room.
|
||||
.child(
|
||||
div().flex_1().min_w_0().flex().flex_row().items_center().gap(px(2.0)).children(
|
||||
[&item.badge, &item.badge_2, &item.badge_3]
|
||||
.into_iter()
|
||||
.filter_map(|badge| small_picture(badge, 14.0)),
|
||||
),
|
||||
)
|
||||
// The Slint bars move; these stand still (nothing here draws the window
|
||||
// anew with the clock).
|
||||
.when(item.talking, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.debug_selector(move || format!("tree-speaking-{id}"))
|
||||
.flex_none()
|
||||
.child(speaking_bars(theme, 14.0)),
|
||||
)
|
||||
})
|
||||
.when(item.streaming, |row| row.child(live_badge(theme)))
|
||||
.when(item.local_muted, |row| row.child(mark("volume-x", c.warning)))
|
||||
.when(!item.local_muted && item.local_volume != 100, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{}%", item.local_volume)),
|
||||
)
|
||||
})
|
||||
.when(item.muted, |row| row.child(mark("mic-off", c.danger)))
|
||||
.when(item.sound_off, |row| row.child(mark("headphone-off", c.danger)))
|
||||
.when(item.away, |row| {
|
||||
row.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child("away"))
|
||||
})
|
||||
.children(
|
||||
[&item.icon, &item.icon_2, &item.icon_3]
|
||||
.into_iter()
|
||||
.filter_map(|i| small_picture(i, 16.0)),
|
||||
)
|
||||
.on_click(move |_, window, cx| {
|
||||
if !myself {
|
||||
window.dispatch_action(Box::new(OpenClient { client: id as u16 }), cx);
|
||||
}
|
||||
})
|
||||
.context_menu(move |menu, _, _| {
|
||||
menu.menu("Show the card", Box::new(OpenMember { client: id as i32 }))
|
||||
.menu("Volume…", Box::new(OpenClient { client: id as u16 }))
|
||||
.separator()
|
||||
.menu("Move to my channel", Box::new(MoveClient { client: id as u16 }))
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
impl Render for ChannelTree {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.tree.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
// A new text size makes the rows another height.
|
||||
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
|
||||
if self.measured_at != 0.0 {
|
||||
self.list.remeasure();
|
||||
}
|
||||
self.measured_at = m.font_scale;
|
||||
}
|
||||
div()
|
||||
.id("sidebar-channels")
|
||||
.debug_selector(|| "sidebar-channels".into())
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.px(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.min_h(px(24.0))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.text_size(px(m.font_sm))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(icon("volume-2", m.icon_sm, c.text_secondary))
|
||||
.child("Channels"),
|
||||
)
|
||||
.map(|pane| {
|
||||
if self.rows.is_empty() {
|
||||
pane.child(
|
||||
div()
|
||||
.id("tree-empty")
|
||||
.debug_selector(|| "tree-empty".into())
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(empty_words(self.emptiness)),
|
||||
)
|
||||
} else {
|
||||
pane.child(
|
||||
list(
|
||||
self.list.clone(),
|
||||
cx.processor(|this, ix, _window, cx| this.row(ix, cx)),
|
||||
)
|
||||
.flex_1()
|
||||
.w_full()
|
||||
.min_h_0(),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! The server form: where a server is added or edited (the server dialog of
|
||||
//! the Slint front end, `bookmark_form` / `save_bookmark` /
|
||||
//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs
|
||||
//! come with their slice; until then the form takes the place of the main
|
||||
//! area, with gpui-component's text inputs: the address (the only thing a
|
||||
//! server needs), a name (empty: the server's own), the nickname and the
|
||||
//! server's password.
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::input::{Input, InputEvent, InputState};
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
|
||||
ParentElement as _, Render, SharedString, Styled as _, Window, div, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::BookmarkForm;
|
||||
|
||||
use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer};
|
||||
use super::widgets::{panel, tagged};
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// The form.
|
||||
pub struct ServerForm {
|
||||
id: i64,
|
||||
connected: bool,
|
||||
address: Entity<InputState>,
|
||||
name: Entity<InputState>,
|
||||
nickname: Entity<InputState>,
|
||||
password: Entity<InputState>,
|
||||
confirm_remove: bool,
|
||||
}
|
||||
|
||||
impl ServerForm {
|
||||
/// A form filled in with `form` (id -1: a new server). The address has the
|
||||
/// focus; Enter in any field saves.
|
||||
pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let field = |window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
placeholder: &str,
|
||||
value: &str,
|
||||
masked: bool| {
|
||||
let input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(SharedString::from(placeholder.to_owned()))
|
||||
.default_value(SharedString::from(value.to_owned()))
|
||||
.masked(masked)
|
||||
});
|
||||
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| {
|
||||
if matches!(event, InputEvent::PressEnter { .. }) {
|
||||
window.dispatch_action(Box::new(SaveServer), cx);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
input
|
||||
};
|
||||
let address =
|
||||
field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false);
|
||||
let name = field(window, cx, "Optional: the server tells its own", &form.name, false);
|
||||
let nickname = field(window, cx, "The name others see", &form.nickname, false);
|
||||
let password = field(window, cx, "Optional", &form.server_password, true);
|
||||
address.update(cx, |input, cx| input.focus(window, cx));
|
||||
Self {
|
||||
id: i64::from(form.id),
|
||||
connected: form.connected,
|
||||
address,
|
||||
name,
|
||||
nickname,
|
||||
password,
|
||||
confirm_remove: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bookmark this form edits; -1 for a new server.
|
||||
pub fn id(&self) -> i64 {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// The form as the fields hold it now, for `AppState::save_bookmark`.
|
||||
pub fn to_form(&self, cx: &App) -> BookmarkForm {
|
||||
let text = |input: &Entity<InputState>| input.read(cx).value().to_string();
|
||||
BookmarkForm {
|
||||
id: self.id as i32,
|
||||
name: text(&self.name).into(),
|
||||
address: text(&self.address).into(),
|
||||
nickname: text(&self.nickname).into(),
|
||||
server_password: text(&self.password).into(),
|
||||
connected: self.connected,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `text` in the address field (a link that fills the form comes with
|
||||
/// its slice; the tests type here).
|
||||
pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) {
|
||||
self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
|
||||
}
|
||||
}
|
||||
|
||||
fn labelled(
|
||||
theme: &VoelinTheme,
|
||||
label: &'static str,
|
||||
input: &Entity<InputState>,
|
||||
) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(label),
|
||||
)
|
||||
.child(Input::new(input))
|
||||
}
|
||||
|
||||
impl Render for ServerForm {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let new = self.id < 0;
|
||||
let id = self.id;
|
||||
let confirm = self.confirm_remove;
|
||||
panel(&theme)
|
||||
.id("server-form")
|
||||
.debug_selector(|| "server-form".into())
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.h_full()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(
|
||||
div()
|
||||
.w_full()
|
||||
.max_w(px(440.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_5))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xl))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(if new { "Add a server" } else { "Edit the server" }),
|
||||
)
|
||||
.child(labelled(&theme, "Address", &self.address))
|
||||
.child(labelled(&theme, "Name", &self.name))
|
||||
.child(labelled(&theme, "Nickname", &self.nickname))
|
||||
.child(labelled(&theme, "Server password", &self.password))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(tagged(
|
||||
"form-save",
|
||||
Button::new("form-save").primary().label("Save").on_click(
|
||||
|_, window, cx| {
|
||||
window.dispatch_action(Box::new(SaveServer), cx)
|
||||
},
|
||||
),
|
||||
))
|
||||
.when(!self.connected, |row| {
|
||||
row.child(tagged(
|
||||
"form-connect",
|
||||
Button::new("form-connect").label("Save and connect").on_click(
|
||||
|_, window, cx| {
|
||||
window.dispatch_action(Box::new(SaveAndConnect), cx)
|
||||
},
|
||||
),
|
||||
))
|
||||
})
|
||||
.child(tagged(
|
||||
"form-cancel",
|
||||
Button::new("form-cancel").ghost().label("Cancel").on_click(
|
||||
|_, window, cx| {
|
||||
window.dispatch_action(Box::new(CancelServerForm), cx)
|
||||
},
|
||||
),
|
||||
))
|
||||
.when(!new, |row| {
|
||||
row.child(div().flex_1()).child(tagged(
|
||||
"form-remove",
|
||||
Button::new("form-remove")
|
||||
.danger()
|
||||
.label(if confirm {
|
||||
"Click again to remove"
|
||||
} else {
|
||||
"Remove"
|
||||
})
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
if this.confirm_remove {
|
||||
window.dispatch_action(
|
||||
Box::new(DeleteServer { id }),
|
||||
cx,
|
||||
);
|
||||
} else {
|
||||
this.confirm_remove = true;
|
||||
cx.notify();
|
||||
}
|
||||
})),
|
||||
))
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The main area. Until the voice page, the chat and the rest come, it is the
|
||||
//! empty page: the "no server selected" state with the way to add one, and for
|
||||
//! a server on screen its name, address and state with the buttons that
|
||||
//! connect, disconnect and edit it. An entity of its own, drawn as a cached
|
||||
//! pane: it listens to the servers' signal and tells the window only when
|
||||
//! what it shows changed.
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
|
||||
Styled as _, Subscription, Window, div, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::ServerItem;
|
||||
use voelin_ui_vm::servers::logic;
|
||||
|
||||
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer, ShowVoiceView};
|
||||
use super::widgets::{Avatar, Presence, icon, panel, tagged};
|
||||
use crate::app::AppState;
|
||||
use crate::meter::Counters;
|
||||
use crate::signals::Area;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the main area shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum MainState {
|
||||
/// No server is on screen.
|
||||
NoServer,
|
||||
/// A server is.
|
||||
Server(ServerItem),
|
||||
}
|
||||
|
||||
impl MainState {
|
||||
/// The main area for the state.
|
||||
pub fn of(app: &AppState) -> Self {
|
||||
let current = app.vm.current;
|
||||
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
|
||||
.into_iter()
|
||||
.find(|item| Some(i64::from(item.id)) == current)
|
||||
.map_or(Self::NoServer, Self::Server)
|
||||
}
|
||||
}
|
||||
|
||||
/// The words for a server's state.
|
||||
fn state_words(status: &str) -> &'static str {
|
||||
match status {
|
||||
"connected" => "Connected with voice",
|
||||
"connecting" => "Connecting…",
|
||||
"observing" => "Observed without joining",
|
||||
_ => "Not connected",
|
||||
}
|
||||
}
|
||||
|
||||
/// The main area.
|
||||
pub struct MainPanel {
|
||||
state: MainState,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl MainPanel {
|
||||
/// A main area that follows the server on screen in `app`.
|
||||
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
let (state, counters, signals) = {
|
||||
let shown = app.read(cx);
|
||||
(MainState::of(shown), shown.counters().clone(), shown.signals().clone())
|
||||
};
|
||||
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
|
||||
let state = MainState::of(app.read(cx));
|
||||
if state != this.state {
|
||||
this.state = state;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
Self { state, counters, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// What it shows now.
|
||||
pub fn state(&self) -> &MainState {
|
||||
&self.state
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for MainPanel {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.main.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let body = match &self.state {
|
||||
MainState::NoServer => div()
|
||||
.id("main-empty")
|
||||
.debug_selector(|| "main-empty".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.size(px(72.0))
|
||||
.rounded(px(m.radius_xl))
|
||||
.bg(hsla(c.surface_2))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(icon("server", 32.0, c.text_muted)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xl))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child("No server selected"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.max_w(px(360.0))
|
||||
.text_center()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("Pick a server in the list, or add one to start talking."),
|
||||
)
|
||||
.child(tagged(
|
||||
"main-add",
|
||||
Button::new("main-add")
|
||||
.primary()
|
||||
.label("Add a server")
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)),
|
||||
)),
|
||||
MainState::Server(item) => {
|
||||
let id = i64::from(item.id);
|
||||
let connected = item.status.as_ref() == "connected";
|
||||
let connecting = item.status.as_ref() == "connecting";
|
||||
div()
|
||||
.id("main-server")
|
||||
.debug_selector(|| "main-server".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint)
|
||||
.image(item.icon.clone())
|
||||
.square()
|
||||
.presence(Presence::of_server(&item.status)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.max_w(px(480.0))
|
||||
.truncate()
|
||||
.text_size(px(m.font_2xl))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(item.name.to_string()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(item.address.to_string()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("main-server-state")
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(state_words(&item.status)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.max_w(px(360.0))
|
||||
.text_center()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("Its chat comes with a later slice."),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_3))
|
||||
.when(connected || connecting, |row| {
|
||||
row.child(tagged(
|
||||
"main-disconnect",
|
||||
Button::new("main-disconnect")
|
||||
.danger()
|
||||
.label("Disconnect")
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(DisconnectVoice), cx);
|
||||
}),
|
||||
))
|
||||
})
|
||||
.when(!connected && !connecting, |row| {
|
||||
row.child(tagged(
|
||||
"main-connect",
|
||||
Button::new("main-connect")
|
||||
.primary()
|
||||
.label("Connect")
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(ConnectVoice), cx);
|
||||
}),
|
||||
))
|
||||
})
|
||||
.when(connected, |row| {
|
||||
row.child(tagged(
|
||||
"main-voice",
|
||||
Button::new("main-voice")
|
||||
.primary()
|
||||
.label("Voice channel")
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(ShowVoiceView { on: true }),
|
||||
cx,
|
||||
);
|
||||
}),
|
||||
))
|
||||
})
|
||||
.child(tagged(
|
||||
"main-edit",
|
||||
Button::new("main-edit").label("Edit").on_click(
|
||||
move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(EditServer { id }), cx);
|
||||
},
|
||||
),
|
||||
)),
|
||||
)
|
||||
}
|
||||
};
|
||||
// The root of a cached pane takes the size its place gives it: laid out
|
||||
// on its own, `flex_1` would be as wide as its contents.
|
||||
panel(&theme).id("main").size_full().items_center().justify_center().child(body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,768 @@
|
||||
//! The members panel (`MembersPanel` and `MemberCardPopup` of
|
||||
//! `screens/members.slint`): everyone on the server in sections (those
|
||||
//! streaming first, then each server group), a search, and the card of one
|
||||
//! person over the panel.
|
||||
//!
|
||||
//! [`MembersPane`] is a cached pane over a virtual list that follows
|
||||
//! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations
|
||||
//! the list applies). A talker redraws it, with the tree: a person's row has
|
||||
//! the speaking ring, "Speaking" and the bars, and no other pane of the window
|
||||
//! is told. [`MemberCardView`] is the card, a card over the window with a scrim
|
||||
//! that a click outside closes; it has the volume and the mute of the person for
|
||||
//! us (`SetMemberVolume`, `SetMemberMuted`), and its other buttons (a message, a
|
||||
//! poke, friends, blocking) come with the slices that have those dialogs.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::component::input::{Input, InputEvent, InputState};
|
||||
use gpui_kit::component::slider::{Slider, SliderEvent, SliderState};
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
|
||||
ListAlignment, ListState, ParentElement as _, Render, SharedString,
|
||||
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, list, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::{MemberCard, MemberItem};
|
||||
use voelin_ui_vm::list::Changes;
|
||||
|
||||
use super::actions::{OpenMember, SearchMembers, SetMemberMuted, SetMemberVolume};
|
||||
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
|
||||
use super::widgets::{
|
||||
Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars,
|
||||
};
|
||||
use crate::meter::Counters;
|
||||
use crate::theme::tokens::Rgba;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// The colour of the shield of a moderator's role.
|
||||
const ROLE: Rgba = Rgba(0xc06c_ffff);
|
||||
|
||||
/// The members panel.
|
||||
pub struct MembersPane {
|
||||
rows: Arc<Vec<MemberItem>>,
|
||||
total: i32,
|
||||
emptiness: Emptiness,
|
||||
/// The person whose card is open.
|
||||
open: Option<i32>,
|
||||
list: ListState,
|
||||
search: Entity<InputState>,
|
||||
searching: bool,
|
||||
/// The text size factor the list measured its rows at.
|
||||
measured_at: f32,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl MembersPane {
|
||||
/// A panel that follows `model`.
|
||||
pub fn new(
|
||||
model: &Entity<TreeModel>,
|
||||
counters: Counters,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let (rows, total, emptiness, open) = {
|
||||
let model = model.read(cx);
|
||||
(
|
||||
model.people().clone(),
|
||||
model.total(),
|
||||
model.people_emptiness(),
|
||||
model.card().map(|c| c.id),
|
||||
)
|
||||
};
|
||||
let search = cx.new(|cx| {
|
||||
InputState::new(window, cx).placeholder(SharedString::from("Search members…"))
|
||||
});
|
||||
let subscriptions = vec![
|
||||
cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
|
||||
match event {
|
||||
TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()),
|
||||
TreeEvent::Lists => {
|
||||
let model = model.read(cx);
|
||||
let now = (model.total(), model.people_emptiness());
|
||||
if now == (this.total, this.emptiness) {
|
||||
return;
|
||||
}
|
||||
(this.total, this.emptiness) = now;
|
||||
}
|
||||
TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id),
|
||||
TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return,
|
||||
}
|
||||
cx.notify();
|
||||
}),
|
||||
cx.subscribe_in(&search, window, |_, input, event: &InputEvent, window, cx| {
|
||||
if matches!(event, InputEvent::Change) {
|
||||
let text = input.read(cx).value().to_string();
|
||||
window.dispatch_action(Box::new(SearchMembers { text }), cx);
|
||||
}
|
||||
}),
|
||||
];
|
||||
Self {
|
||||
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
|
||||
rows,
|
||||
total,
|
||||
emptiness,
|
||||
open,
|
||||
search,
|
||||
searching: false,
|
||||
measured_at: 0.0,
|
||||
counters,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows it shows.
|
||||
pub fn rows(&self) -> &[MemberItem] {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
/// The person whose card is open, as the panel marks them.
|
||||
pub fn open(&self) -> Option<i32> {
|
||||
self.open
|
||||
}
|
||||
|
||||
/// Why it shows no one, were it empty.
|
||||
pub fn emptiness(&self) -> Emptiness {
|
||||
self.emptiness
|
||||
}
|
||||
|
||||
/// Whether the search box is shown.
|
||||
pub fn searching(&self) -> bool {
|
||||
self.searching
|
||||
}
|
||||
|
||||
/// Take the new rows in (the rows `changes` lead to, carried by the event),
|
||||
/// telling the list which rows came, went or changed their height (the
|
||||
/// first row of a section has the heading above it).
|
||||
fn apply(&mut self, changes: &Changes, new: Arc<Vec<MemberItem>>) {
|
||||
use voelin_ui_vm::list::Change;
|
||||
|
||||
debug_check(self.rows.len(), changes, new.len());
|
||||
let mut headed: Vec<bool> = self.rows.iter().map(|row| row.first_in_group).collect();
|
||||
for change in &changes.0 {
|
||||
match *change {
|
||||
Change::Update(i) => {
|
||||
if headed[i] != new[i].first_in_group {
|
||||
self.list.splice(i..i + 1, 1);
|
||||
}
|
||||
headed[i] = new[i].first_in_group;
|
||||
}
|
||||
Change::Remove(i) => {
|
||||
headed.remove(i);
|
||||
self.list.splice(i..i + 1, 0);
|
||||
}
|
||||
Change::Insert(i) => {
|
||||
headed.insert(i, new[i].first_in_group);
|
||||
self.list.splice(i..i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.rows = new;
|
||||
}
|
||||
|
||||
/// The search box was opened or closed: closing it shows everyone again.
|
||||
fn toggle_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.searching = !self.searching;
|
||||
if self.searching {
|
||||
self.search.update(cx, |input, cx| input.focus(window, cx));
|
||||
} else {
|
||||
self.search.update(cx, |input, cx| input.set_value("", window, cx));
|
||||
window.dispatch_action(Box::new(SearchMembers { text: String::new() }), cx);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// The entry at `ix` for the list: the heading of its section if it opens
|
||||
/// one, then the person.
|
||||
fn entry(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let Some(item) = self.rows.get(ix) else { return div().into_any_element() };
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.w_full()
|
||||
.px(px(m.space_3))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.when(item.first_in_group, |entry| entry.child(group_header(&theme, item)))
|
||||
.child(member_row(&theme, item, self.open == Some(item.id)))
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
/// The words of a panel with nobody in it.
|
||||
fn empty_words(emptiness: Emptiness) -> &'static str {
|
||||
match emptiness {
|
||||
Emptiness::Loading => "Loading who is here…",
|
||||
Emptiness::NoMatch => "Nobody matches.",
|
||||
Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.",
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading above the first person of a section: "Moderator — 3".
|
||||
fn group_header(theme: &VoelinTheme, item: &MemberItem) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let words = if item.group_count > 0 {
|
||||
format!("{} — {}", item.group, item.group_count)
|
||||
} else {
|
||||
item.group.to_string()
|
||||
};
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.pt(px(m.space_5))
|
||||
.pb(px(m.space_2))
|
||||
.pl(px(m.space_2))
|
||||
.children(small_picture(&item.group_icon, 16.0))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(words),
|
||||
)
|
||||
}
|
||||
|
||||
/// One person: avatar, name with their badges and role, what they are doing.
|
||||
fn member_row(theme: &VoelinTheme, item: &MemberItem, open: bool) -> AnyElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let id = item.id;
|
||||
let hover = hsla(c.surface_3);
|
||||
let presence = if item.away {
|
||||
Presence::Idle
|
||||
} else if item.sound_off {
|
||||
Presence::Dnd
|
||||
} else {
|
||||
Presence::Online
|
||||
};
|
||||
let name_color = if item.myself {
|
||||
c.accent_text
|
||||
} else if !item.role.is_empty() {
|
||||
c.name_text
|
||||
} else {
|
||||
c.text
|
||||
};
|
||||
let crowns = div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(3.0))
|
||||
.when(item.admin, |row| row.child(icon("crown", 14.0, c.gold)))
|
||||
.when(item.priority, |row| row.child(icon("star", 14.0, c.accent_text)))
|
||||
.when(item.commander, |row| row.child(icon("flag", 14.0, c.info)))
|
||||
.when(item.recording, |row| row.child(icon("circle-dot", 14.0, c.danger)));
|
||||
let badges = div().flex().flex_row().items_center().gap(px(2.0)).children(
|
||||
[&item.badge, &item.badge_2, &item.badge_3]
|
||||
.into_iter()
|
||||
.filter_map(|b| small_picture(b, 14.0)),
|
||||
);
|
||||
div()
|
||||
.id(("member", id as u64))
|
||||
.debug_selector(move || format!("member-{id}"))
|
||||
.w_full()
|
||||
.h(px(52.0 * m.font_scale))
|
||||
.flex_none()
|
||||
.rounded(px(m.radius_md))
|
||||
.cursor_pointer()
|
||||
.when(open, |row| row.bg(hsla(c.accent_soft)))
|
||||
.when(!open, |row| row.hover(move |style| style.bg(hover)))
|
||||
.when(item.away, |row| row.opacity(0.6))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.px(px(m.space_2))
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
Avatar::new(("member-avatar", id as u64), 40.0, &item.initials, item.tint)
|
||||
.image(item.avatar.clone())
|
||||
.presence(presence)
|
||||
.speaking(item.talking),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(1.0))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(name_color))
|
||||
.child(item.name.to_string()),
|
||||
)
|
||||
.child(crowns)
|
||||
.child(badges),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(if item.talking {
|
||||
c.success
|
||||
} else {
|
||||
c.text_muted
|
||||
}))
|
||||
.child(item.status.to_string()),
|
||||
)
|
||||
.when(item.talking, |row| row.child(speaking_bars(theme, 12.0)))
|
||||
.when(item.streaming, |row| {
|
||||
row.child(icon("monitor", 14.0, c.text_secondary))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.when(!item.role.is_empty(), |row| {
|
||||
row.child(icon("shield-check", 18.0, ROLE)).child(chip(
|
||||
theme,
|
||||
item.role.to_string(),
|
||||
None,
|
||||
None,
|
||||
))
|
||||
})
|
||||
.when(item.streaming, |row| row.child(live_badge(theme)))
|
||||
.when(item.muted, |row| row.child(icon("mic-off", 16.0, c.danger)))
|
||||
.when(item.sound_off, |row| row.child(icon("headphone-off", 16.0, c.danger)))
|
||||
// A hand, as TeamSpeak asks for talk power; the card has the number.
|
||||
.when(item.cannot_talk, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.id(("member-hand", id as u64))
|
||||
.tooltip(|window, cx| {
|
||||
gpui_kit::component::tooltip::Tooltip::new("Needs talk power to speak")
|
||||
.build(window, cx)
|
||||
})
|
||||
.child(icon("hand", 16.0, c.text_muted)),
|
||||
)
|
||||
})
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(OpenMember { client: id }), cx)
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
impl Render for MembersPane {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.members.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
|
||||
if self.measured_at != 0.0 {
|
||||
self.list.remeasure();
|
||||
}
|
||||
self.measured_at = m.font_scale;
|
||||
}
|
||||
let searching = self.searching;
|
||||
let this = cx.entity();
|
||||
let search_button = IconButton::new("members-search", "search", "Search members")
|
||||
.size(32.0)
|
||||
.checked(searching)
|
||||
.on_click(move |_, window, cx| {
|
||||
this.update(cx, |pane, cx| pane.toggle_search(window, cx));
|
||||
});
|
||||
div()
|
||||
.id("members")
|
||||
.debug_selector(|| "members".into())
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.pt(px(m.space_4))
|
||||
.pb(px(m.space_2))
|
||||
.rounded(px(m.radius_xl))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(hsla(c.surface.with_alpha(235)))
|
||||
.overflow_hidden()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.pl(px(m.space_5))
|
||||
.pr(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.id("members-title")
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_lg))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("Members — {}", self.total)),
|
||||
)
|
||||
.child(search_button),
|
||||
)
|
||||
.when(searching, |pane| {
|
||||
pane.child(
|
||||
div()
|
||||
.id("members-search-box")
|
||||
.debug_selector(|| "members-search-box".into())
|
||||
.px(px(m.space_4))
|
||||
.child(Input::new(&self.search)),
|
||||
)
|
||||
})
|
||||
.map(|pane| {
|
||||
if self.rows.is_empty() {
|
||||
pane.child(
|
||||
div()
|
||||
.id("members-empty")
|
||||
.debug_selector(|| "members-empty".into())
|
||||
.px(px(m.space_5))
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(empty_words(self.emptiness)),
|
||||
)
|
||||
} else {
|
||||
pane.child(
|
||||
list(
|
||||
self.list.clone(),
|
||||
cx.processor(|this, ix, _window, cx| this.entry(ix, cx)),
|
||||
)
|
||||
.flex_1()
|
||||
.w_full()
|
||||
.min_h_0(),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The card over a member row, over the window: a scrim that a click outside
|
||||
/// the card closes, and the card with what is known of the person, and the
|
||||
/// volume and the mute of their voice for us (the Slint card's Volume rows).
|
||||
pub struct MemberCardView {
|
||||
card: Option<MemberCard>,
|
||||
/// How wide the members panel is: the card stands beside it.
|
||||
panel_width: f32,
|
||||
/// The volume slider, in percent (0 to 200, as the Slint card's).
|
||||
slider: Entity<SliderState>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
/// The loudest the card's slider plays a person, in percent.
|
||||
const LOUDEST: f32 = 200.0;
|
||||
|
||||
impl MemberCardView {
|
||||
/// A card that follows `model`, beside a panel `panel_width` pixels wide.
|
||||
pub fn new(
|
||||
model: &Entity<TreeModel>,
|
||||
panel_width: f32,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let card = model.read(cx).card().cloned();
|
||||
let slider = cx.new(|_| {
|
||||
SliderState::new()
|
||||
.min(0.0)
|
||||
.max(LOUDEST)
|
||||
.step(5.0)
|
||||
.default_value(card.as_ref().map_or(100.0, |card| card.volume))
|
||||
});
|
||||
let subscriptions = vec![
|
||||
cx.subscribe_in(
|
||||
model,
|
||||
window,
|
||||
|this: &mut Self, model, event: &TreeEvent, window, cx| {
|
||||
if matches!(event, TreeEvent::Card) {
|
||||
this.card = model.read(cx).card().cloned();
|
||||
// The slider shows the person's volume as it is now (a change
|
||||
// the slider itself made comes back the same).
|
||||
if let Some(card) = &this.card {
|
||||
let volume = card.volume.clamp(0.0, LOUDEST);
|
||||
this.slider
|
||||
.update(cx, |slider, cx| slider.set_value(volume, window, cx));
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
},
|
||||
),
|
||||
cx.subscribe_in(
|
||||
&slider,
|
||||
window,
|
||||
|this: &mut Self, _, event: &SliderEvent, window, cx| {
|
||||
if let (SliderEvent::Change(value), Some(card)) = (event, &this.card) {
|
||||
let client = u16::try_from(card.id).unwrap_or_default();
|
||||
let percent = value.end();
|
||||
window.dispatch_action(Box::new(SetMemberVolume { client, percent }), cx);
|
||||
}
|
||||
},
|
||||
),
|
||||
];
|
||||
Self { card, panel_width, slider, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// The card that is open.
|
||||
pub fn card(&self) -> Option<&MemberCard> {
|
||||
self.card.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading of a part of the card: "Groups", "Badges".
|
||||
fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(text)
|
||||
}
|
||||
|
||||
/// The card's Volume rows: what the person is played at, a mute for us and
|
||||
/// the slider. Both need a person the server gave a unique id (the choice is
|
||||
/// kept by it), as the Slint card's do.
|
||||
fn volume(
|
||||
theme: &VoelinTheme,
|
||||
person: &MemberCard,
|
||||
slider: &Entity<SliderState>,
|
||||
) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let client = u16::try_from(person.id).unwrap_or_default();
|
||||
let (muted, known) = (person.muted, person.known);
|
||||
div()
|
||||
.id("member-volume")
|
||||
.debug_selector(|| "member-volume".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.pt(px(m.space_3))
|
||||
.border_t_1()
|
||||
.border_color(hsla(c.border_popup))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child("Volume"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("member-volume-percent")
|
||||
.debug_selector(|| "member-volume-percent".into())
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{}%", person.volume.round() as i32)),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
IconButton::new(
|
||||
"member-mute",
|
||||
if muted { "volume-x" } else { "volume-2" },
|
||||
if muted { "Unmute for me" } else { "Mute for me" },
|
||||
)
|
||||
.size(30.0)
|
||||
.danger()
|
||||
.checked(muted)
|
||||
.enabled(known)
|
||||
.on_click(move |_, window, cx| {
|
||||
window
|
||||
.dispatch_action(Box::new(SetMemberMuted { client, muted: !muted }), cx)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("member-slider")
|
||||
.debug_selector(|| "member-slider".into())
|
||||
.flex_1()
|
||||
.child(Slider::new(slider).disabled(!known || muted)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
impl Render for MemberCardView {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let Some(person) = self.card.clone() else { return div().into_any_element() };
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let facts = div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.gap(px(m.space_2))
|
||||
.when(person.talk_power > 0, |row| {
|
||||
row.child(chip(
|
||||
&theme,
|
||||
format!("talk power {}", person.talk_power),
|
||||
Some("mic"),
|
||||
None,
|
||||
))
|
||||
})
|
||||
.when(!person.country.is_empty(), |row| {
|
||||
row.child(chip(&theme, person.country.to_string(), Some("globe"), None))
|
||||
});
|
||||
let body = div()
|
||||
.id("member-card")
|
||||
.debug_selector(|| "member-card".into())
|
||||
.w(px(300.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.p(px(m.space_4))
|
||||
.rounded(px(m.radius_lg))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup))
|
||||
.bg(hsla(c.surface_3))
|
||||
// Clicks inside stay inside.
|
||||
.on_click(|_, _, cx| cx.stop_propagation())
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
Avatar::new("member-card-avatar", 52.0, &person.initials, person.tint)
|
||||
.image(person.avatar.clone()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_lg))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(person.name.to_string()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(person.status.to_string()),
|
||||
),
|
||||
)
|
||||
.child(IconButton::new("member-card-close", "x", "Close").size(26.0).on_click(
|
||||
|_, window, cx| {
|
||||
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
|
||||
},
|
||||
)),
|
||||
)
|
||||
.when(!person.description.is_empty(), |card| {
|
||||
card.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(person.description.to_string()),
|
||||
)
|
||||
})
|
||||
.when(!person.groups.is_empty(), |card| {
|
||||
card.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.child(caption(&theme, "Groups"))
|
||||
.children(person.groups.iter().map(|group| {
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(group.to_string())
|
||||
})),
|
||||
)
|
||||
})
|
||||
.when(!person.badges.is_empty(), |card| {
|
||||
card.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_2))
|
||||
.child(caption(&theme, "Badges"))
|
||||
.child(div().flex().flex_row().flex_wrap().gap(px(m.space_2)).children(
|
||||
person.badges.iter().enumerate().map(|(i, badge)| {
|
||||
let description = badge.description.clone();
|
||||
div()
|
||||
.id(("member-badge", i as u64))
|
||||
.tooltip(move |window, cx| {
|
||||
gpui_kit::component::tooltip::Tooltip::new(
|
||||
description.to_string(),
|
||||
)
|
||||
.build(window, cx)
|
||||
})
|
||||
.child(chip(
|
||||
&theme,
|
||||
badge.name.to_string(),
|
||||
None,
|
||||
small_picture(&badge.icon, 14.0),
|
||||
))
|
||||
}),
|
||||
)),
|
||||
)
|
||||
})
|
||||
.child(facts)
|
||||
.child(volume(&theme, &person, &self.slider));
|
||||
// The card stands beside the panel, near the top.
|
||||
div()
|
||||
.id("member-card-scrim")
|
||||
.debug_selector(|| "member-card-scrim".into())
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(0.0))
|
||||
.size_full()
|
||||
.bg(hsla(c.scrim_light))
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
|
||||
})
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_end()
|
||||
.items_start()
|
||||
.pt(px(120.0))
|
||||
.pr(px(self.panel_width + 24.0))
|
||||
.child(body)
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// What an empty panel says for each reason it can be empty.
|
||||
#[test]
|
||||
fn an_empty_panel_says_why() {
|
||||
assert_eq!(empty_words(Emptiness::NoServer), "Connect to see who is here.");
|
||||
assert_eq!(empty_words(Emptiness::Connect), "Connect to see who is here.");
|
||||
assert_eq!(empty_words(Emptiness::Loading), "Loading who is here…");
|
||||
assert_eq!(empty_words(Emptiness::NoMatch), "Nobody matches.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and
|
||||
//! the server callbacks of `bind/servers.rs`): the server rail, the top bar,
|
||||
//! the sidebar, the main area, the voice channel page that takes its place
|
||||
//! while voice is on screen, the server form and the toast, each an entity
|
||||
//! that listens to the per-area signals of the root state
|
||||
//! ([`crate::signals`]) and tells the window only when what it shows changed,
|
||||
//! and the actions the user's moves are ([`actions`]). The rail, the top bar,
|
||||
//! the main area and the voice page are embedded cached (they have a size of
|
||||
//! their own), so gpui-pre 0.3.10 renders them again only when they were told
|
||||
//! something changed; [`crate::view::MainView`] puts them in the window.
|
||||
|
||||
pub mod actions;
|
||||
mod channels;
|
||||
mod form;
|
||||
mod main_panel;
|
||||
mod members;
|
||||
mod password;
|
||||
mod rail;
|
||||
mod sidebar;
|
||||
mod toast;
|
||||
mod topbar;
|
||||
mod tree_model;
|
||||
mod voice;
|
||||
pub mod widgets;
|
||||
|
||||
pub use channels::ChannelTree;
|
||||
pub use form::ServerForm;
|
||||
pub use main_panel::{MainPanel, MainState};
|
||||
pub use members::{MemberCardView, MembersPane};
|
||||
pub use password::ChannelPassword;
|
||||
|
||||
/// Bind the shell's keys (Escape in the password prompt): once, after the
|
||||
/// widget library's own are (`gpui_kit::init`).
|
||||
pub fn bind_keys(cx: &mut gpui_kit::App) {
|
||||
password::bind_keys(cx);
|
||||
}
|
||||
pub use rail::{RailView, ServerRail};
|
||||
pub use sidebar::{Sidebar, SidebarView};
|
||||
pub use toast::{TOAST_TIME, Toast};
|
||||
pub use topbar::TopBar;
|
||||
pub use tree_model::{Emptiness, TreeEvent, TreeModel};
|
||||
pub use voice::{SHORT_WINDOW, VoiceHead, VoicePage};
|
||||
@@ -0,0 +1,171 @@
|
||||
//! The password prompt of a locked channel (`ChannelPasswordDialog` of
|
||||
//! `screens/dialogs.slint`): what the transitions ask for with
|
||||
//! `Update::password` when a channel with a password is joined and the one
|
||||
//! given this connection (if any) is not at hand, or was refused. It is a
|
||||
//! card over the window with a scrim; until the dialogs slice makes every
|
||||
//! dialog one, it is this view's own. As in the Slint dialog, Join (and Enter)
|
||||
//! do nothing while the field is empty, and Escape closes the prompt.
|
||||
//!
|
||||
//! Escape is a key binding of the prompt's key context ([`bind_keys`]) that
|
||||
//! dispatches [`CancelChannelPassword`], and the prompt is a focus target of
|
||||
//! its own (its scrim, which the card is on): a click on the card, off the
|
||||
//! field, takes the focus from the field, and a click outside any focus target
|
||||
//! would hand it to the window's root, which the prompt is not under, so
|
||||
//! without a target the context would not be on the dispatch path and Escape
|
||||
//! would do nothing. With the field focused its own Escape (which has nothing
|
||||
//! to undo in a password) passes the key on, and the binding closes the prompt.
|
||||
|
||||
use gpui_kit::component::Disableable as _;
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::input::{Input, InputEvent, InputState};
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
App, AppContext as _, Context, Entity, FocusHandle, FontWeight, InteractiveElement as _,
|
||||
IntoElement, KeyBinding, ParentElement as _, Render, SharedString,
|
||||
StatefulInteractiveElement as _, Styled as _, Window, div, px,
|
||||
};
|
||||
use voelin_ui_vm::host::PasswordPrompt;
|
||||
|
||||
use super::actions::{CancelChannelPassword, SubmitChannelPassword};
|
||||
use super::widgets::tagged;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// The key context of the prompt.
|
||||
const CONTEXT: &str = "ChannelPassword";
|
||||
|
||||
/// The keys of the prompt: Escape closes it. Bound once, at start, with the
|
||||
/// widget library's own.
|
||||
pub fn bind_keys(cx: &mut App) {
|
||||
cx.bind_keys([KeyBinding::new("escape", CancelChannelPassword, Some(CONTEXT))]);
|
||||
}
|
||||
|
||||
/// The prompt for the password of one channel.
|
||||
pub struct ChannelPassword {
|
||||
channel: String,
|
||||
wrong: bool,
|
||||
input: Entity<InputState>,
|
||||
/// What the prompt's scrim holds the focus with, so that Escape reaches the
|
||||
/// prompt wherever in it the last click was.
|
||||
focus: FocusHandle,
|
||||
}
|
||||
|
||||
impl ChannelPassword {
|
||||
/// A prompt for what `ask` names, with the field focused: Enter joins.
|
||||
pub fn new(ask: &PasswordPrompt, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let input = cx.new(|cx| {
|
||||
InputState::new(window, cx).placeholder(SharedString::from("Password")).masked(true)
|
||||
});
|
||||
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| match event {
|
||||
InputEvent::PressEnter { .. } => {
|
||||
window.dispatch_action(Box::new(SubmitChannelPassword), cx);
|
||||
}
|
||||
// Join is there while there is something to join with.
|
||||
InputEvent::Change => cx.notify(),
|
||||
_ => {}
|
||||
})
|
||||
.detach();
|
||||
input.update(cx, |input, cx| input.focus(window, cx));
|
||||
Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() }
|
||||
}
|
||||
|
||||
/// The channel it asks for.
|
||||
pub fn channel(&self) -> &str {
|
||||
&self.channel
|
||||
}
|
||||
|
||||
/// Whether it says that the last password was refused.
|
||||
pub fn wrong(&self) -> bool {
|
||||
self.wrong
|
||||
}
|
||||
|
||||
/// What the field holds. The prompt joins only with something in it.
|
||||
pub fn text(&self, cx: &App) -> String {
|
||||
self.input.read(cx).value().to_string()
|
||||
}
|
||||
|
||||
/// Type `text` in the field (the tests type here).
|
||||
pub fn set_text(&self, text: &str, window: &mut Window, cx: &mut App) {
|
||||
self.input.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for ChannelPassword {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let empty = self.text(cx).is_empty();
|
||||
div()
|
||||
.id("password-prompt")
|
||||
.debug_selector(|| "password-prompt".into())
|
||||
.key_context(CONTEXT)
|
||||
.track_focus(&self.focus)
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(0.0))
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.bg(hsla(c.scrim))
|
||||
// A click outside the card closes the prompt.
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(CancelChannelPassword), cx))
|
||||
.child(
|
||||
div()
|
||||
.id("password-card")
|
||||
.debug_selector(|| "password-card".into())
|
||||
.w(px(380.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_5))
|
||||
.rounded(px(m.radius_lg))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup))
|
||||
.bg(hsla(c.surface_3))
|
||||
.on_click(|_, _, cx| cx.stop_propagation())
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_lg))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("{} has a password", self.channel)),
|
||||
)
|
||||
.when(self.wrong, |card| {
|
||||
card.child(
|
||||
div()
|
||||
.id("password-wrong")
|
||||
.debug_selector(|| "password-wrong".into())
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.danger))
|
||||
.child("That password was not accepted. Try again."),
|
||||
)
|
||||
})
|
||||
.child(Input::new(&self.input))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_end()
|
||||
.gap(px(m.space_3))
|
||||
.child(tagged(
|
||||
"password-cancel",
|
||||
Button::new("password-cancel").ghost().label("Cancel").on_click(
|
||||
|_, window, cx| {
|
||||
window.dispatch_action(Box::new(CancelChannelPassword), cx)
|
||||
},
|
||||
),
|
||||
))
|
||||
.child(tagged(
|
||||
"password-join",
|
||||
Button::new("password-join")
|
||||
.primary()
|
||||
.label("Join")
|
||||
.disabled(empty)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(SubmitChannelPassword), cx)
|
||||
}),
|
||||
)),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! The server rail: the saved servers as avatars with their state, the
|
||||
//! selection, the add-server button and the settings button (`ServerRail` of
|
||||
//! `ui/shells/desktop.slint`). An entity of its own, drawn as a cached pane:
|
||||
//! it listens to the servers' signal ([`crate::signals`]) and tells the window
|
||||
//! only when the servers it lists changed.
|
||||
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
|
||||
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::ServerItem;
|
||||
use voelin_ui_vm::servers::logic;
|
||||
|
||||
use super::actions::{AddServer, EditServer, OpenSettings, SelectServer};
|
||||
use super::widgets::{Avatar, IconButton, Presence};
|
||||
use crate::app::AppState;
|
||||
use crate::meter::Counters;
|
||||
use crate::signals::Area;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the rail shows: the servers in order, and which is on screen.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RailView {
|
||||
/// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them.
|
||||
pub servers: Vec<ServerItem>,
|
||||
/// The bookmark on screen.
|
||||
pub current: Option<i64>,
|
||||
}
|
||||
|
||||
impl RailView {
|
||||
/// The rail for the state.
|
||||
pub fn of(app: &AppState) -> Self {
|
||||
Self {
|
||||
servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)),
|
||||
current: app.vm.current,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rail.
|
||||
pub struct ServerRail {
|
||||
view: RailView,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl ServerRail {
|
||||
/// A rail that follows the servers of `app`.
|
||||
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
let (view, counters, signals) = {
|
||||
let state = app.read(cx);
|
||||
(RailView::of(state), state.counters().clone(), state.signals().clone())
|
||||
};
|
||||
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
|
||||
let view = RailView::of(app.read(cx));
|
||||
if view != this.view {
|
||||
this.view = view;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
Self { view, counters, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// What it shows now.
|
||||
pub fn view(&self) -> &RailView {
|
||||
&self.view
|
||||
}
|
||||
}
|
||||
|
||||
/// One server of the rail: the selection pill, the ring of the one on screen,
|
||||
/// the avatar with its state, the unread count and the live mark.
|
||||
fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let id = i64::from(item.id);
|
||||
let group = format!("rail-server-{id}");
|
||||
let name = item.name.to_string();
|
||||
let tooltip = format!("{name}\n{}", item.address);
|
||||
let pill = div()
|
||||
.absolute()
|
||||
.left(px(0.0))
|
||||
.w(px(4.0))
|
||||
.h(px(if selected { 36.0 } else { 0.0 }))
|
||||
.rounded(px(2.0))
|
||||
.bg(hsla(c.text))
|
||||
.when(!selected, |pill| {
|
||||
let group = group.clone();
|
||||
pill.group_hover(group, |style| style.h(px(18.0)))
|
||||
});
|
||||
div()
|
||||
.id(("rail-server", id as u64))
|
||||
.group(group)
|
||||
.relative()
|
||||
.w_full()
|
||||
.h(px(56.0))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.debug_selector(|| format!("rail-server-{id}"))
|
||||
.tooltip(move |window, cx| {
|
||||
gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx)
|
||||
})
|
||||
.on_click(move |event, window, cx| {
|
||||
// A second click on the server is the Slint rail's double click.
|
||||
if event.click_count() >= 2 {
|
||||
window.dispatch_action(Box::new(EditServer { id }), cx);
|
||||
} else {
|
||||
window.dispatch_action(Box::new(SelectServer { id }), cx);
|
||||
}
|
||||
})
|
||||
.child(pill)
|
||||
.when(selected, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.absolute()
|
||||
.size(px(52.0))
|
||||
.rounded(px(m.radius_lg + 2.0))
|
||||
.border_2()
|
||||
.border_color(hsla(c.accent))
|
||||
.bg(hsla(c.glow.with_alpha(0x66))),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint)
|
||||
.image(item.icon.clone())
|
||||
.square()
|
||||
.presence(Presence::of_server(&item.status)),
|
||||
)
|
||||
.when(item.unread > 0, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(50.0))
|
||||
.min_w(px(18.0))
|
||||
.h(px(18.0))
|
||||
.px(px(5.0))
|
||||
.rounded(px(9.0))
|
||||
.bg(hsla(c.live))
|
||||
.border_2()
|
||||
.border_color(hsla(c.bg_rail))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(m.font_xs))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(c.on_accent))
|
||||
.child(item.unread.to_string()),
|
||||
)
|
||||
})
|
||||
.when(item.live && item.unread == 0, |row| {
|
||||
row.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(4.0))
|
||||
.left(px(52.0))
|
||||
.size(px(12.0))
|
||||
.rounded(px(6.0))
|
||||
.bg(hsla(c.live))
|
||||
.border_2()
|
||||
.border_color(hsla(c.bg_rail)),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
impl Render for ServerRail {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.rail.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let current = self.view.current;
|
||||
let servers: Vec<_> = self
|
||||
.view
|
||||
.servers
|
||||
.iter()
|
||||
.map(|item| server(&theme, item, current == Some(i64::from(item.id))))
|
||||
.collect();
|
||||
div()
|
||||
.id("rail")
|
||||
.w(px(m.rail_width))
|
||||
.h_full()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.py(px(m.space_3))
|
||||
.gap(px(m.space_2))
|
||||
.bg(hsla(c.bg_rail.with_alpha(230)))
|
||||
.border_r_1()
|
||||
.border_color(hsla(c.border))
|
||||
// The app's mark. (Home, which the Slint rail opens from it, comes
|
||||
// with its slice.)
|
||||
.child(
|
||||
div()
|
||||
.size(px(48.0))
|
||||
.flex_none()
|
||||
.rounded(px(m.radius_lg))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(hsla(c.surface_2))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(gpui_kit::img("logo.svg").size(px(30.0))),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w(px(32.0))
|
||||
.h(px(2.0))
|
||||
.my(px(m.space_2))
|
||||
.rounded(px(1.0))
|
||||
.bg(hsla(c.border_strong)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("rail-servers")
|
||||
.flex_1()
|
||||
.min_h_0()
|
||||
.w_full()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.children(servers)
|
||||
.child(
|
||||
div().pt(px(m.space_2)).child(
|
||||
IconButton::new("rail-add", "plus", "Add a server")
|
||||
.size(46.0)
|
||||
.round()
|
||||
.filled()
|
||||
.tint(c.success)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(AddServer), cx);
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
IconButton::new("rail-settings", "settings", "Settings")
|
||||
.size(46.0)
|
||||
.round()
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(OpenSettings), cx);
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
|
||||
//! `shells/common.slint`): the server on screen (its card has the server's
|
||||
//! banner behind it, under the same veil as the tree's rows), its channel tree
|
||||
//! ([`super::ChannelTree`], a cached pane of its own), the voice card while
|
||||
//! voice is connecting or connected, and the user's own card with the voice
|
||||
//! buttons. An entity of its own: it listens to the servers' and the toolbar's
|
||||
//! signals and tells the window only when what it shows changed.
|
||||
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
|
||||
ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement,
|
||||
Styled as _, StyledImage as _, Subscription, Window, div, px,
|
||||
};
|
||||
use voelin_core::TransmitMode;
|
||||
use voelin_ui_vm::Rgb;
|
||||
use voelin_ui_vm::bridge::ServerItem;
|
||||
use voelin_ui_vm::image::ImageRef;
|
||||
use voelin_ui_vm::servers::logic;
|
||||
|
||||
use super::actions::{
|
||||
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
|
||||
};
|
||||
use super::channels::ChannelTree;
|
||||
use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel};
|
||||
use crate::app::AppState;
|
||||
use crate::meter::Counters;
|
||||
use crate::pictures::{PictureKey, picture};
|
||||
use crate::signals::Area;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the sidebar shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SidebarView {
|
||||
/// The server on screen, as the rail has it.
|
||||
pub server: Option<ServerItem>,
|
||||
/// "9 online · 7 channels" once its presence is known, else empty.
|
||||
pub stats: String,
|
||||
/// The server's banner, behind its card; empty without one.
|
||||
pub server_banner: ImageRef,
|
||||
/// Our nickname there; empty without a server.
|
||||
pub nickname: String,
|
||||
/// The channel we are in; empty while connecting.
|
||||
pub own_channel: String,
|
||||
/// Our picture on the server.
|
||||
pub own_avatar: ImageRef,
|
||||
/// Voice is connected.
|
||||
pub voice_connected: bool,
|
||||
/// Voice is connecting.
|
||||
pub voice_connecting: bool,
|
||||
/// The server is observed.
|
||||
pub observing: bool,
|
||||
/// Our microphone is muted.
|
||||
pub input_muted: bool,
|
||||
/// Our sound is muted.
|
||||
pub output_muted: bool,
|
||||
/// Voice goes out.
|
||||
pub transmitting: bool,
|
||||
/// The transmit mode is push-to-talk, so the card has a hold-to-talk button.
|
||||
pub hold_to_talk: bool,
|
||||
/// How our voice is sent, as the audio settings say: the card has the
|
||||
/// button for push-to-talk and says the mode otherwise.
|
||||
pub transmit: TransmitMode,
|
||||
}
|
||||
|
||||
impl SidebarView {
|
||||
/// The sidebar for the state.
|
||||
pub fn of(app: &AppState) -> Self {
|
||||
let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark));
|
||||
let server = app.vm.current.and_then(|id| {
|
||||
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
|
||||
.into_iter()
|
||||
.find(|item| i64::from(item.id) == id)
|
||||
});
|
||||
Self {
|
||||
server,
|
||||
stats: card.server_stats,
|
||||
server_banner: card.server_banner,
|
||||
nickname: card.nickname,
|
||||
own_channel: card.own_channel,
|
||||
own_avatar: card.own_avatar,
|
||||
voice_connected: card.voice_connected,
|
||||
voice_connecting: card.voice_connecting,
|
||||
observing: card.observing,
|
||||
input_muted: card.input_muted,
|
||||
output_muted: card.output_muted,
|
||||
transmitting: card.transmitting,
|
||||
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
|
||||
transmit: app.vm.audio.transmit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sidebar.
|
||||
pub struct Sidebar {
|
||||
view: SidebarView,
|
||||
/// The channel tree, a pane of its own between the server card and the
|
||||
/// voice card.
|
||||
tree: Entity<ChannelTree>,
|
||||
/// The hold-to-talk button is held down.
|
||||
holding: bool,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl Sidebar {
|
||||
/// A sidebar that follows the server on screen and the voice state in
|
||||
/// `app`, with `tree` between its cards.
|
||||
pub fn new(app: &Entity<AppState>, tree: Entity<ChannelTree>, cx: &mut Context<Self>) -> Self {
|
||||
let (view, counters, signals) = {
|
||||
let state = app.read(cx);
|
||||
(SidebarView::of(state), state.counters().clone(), state.signals().clone())
|
||||
};
|
||||
let subscriptions =
|
||||
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
|
||||
let state = app.read(cx);
|
||||
let view = SidebarView::of(state);
|
||||
// The button goes away when voice leaves `Connected`, transmit
|
||||
// leaves push-to-talk, or another server is shown; and a drop
|
||||
// and reconnect inside one batch ends the hold in `AppState`
|
||||
// while `view.voice_connected` stays true. Keep `holding` in
|
||||
// sync with the root state's own button hold (this observer
|
||||
// only sets its own fields).
|
||||
let same_server =
|
||||
view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id);
|
||||
let held_here = view
|
||||
.server
|
||||
.as_ref()
|
||||
.is_some_and(|s| state.button_held() == Some(i64::from(s.id)));
|
||||
if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here {
|
||||
this.holding = false;
|
||||
}
|
||||
if view != this.view {
|
||||
this.view = view;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
Self { view, tree, holding: false, counters, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// What it shows now.
|
||||
pub fn view(&self) -> &SidebarView {
|
||||
&self.view
|
||||
}
|
||||
|
||||
/// Whether the hold-to-talk button is currently held down.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_holding(&self) -> bool {
|
||||
self.holding
|
||||
}
|
||||
|
||||
/// Let go of the hold-to-talk button if it is held (the window lost the
|
||||
/// focus: the release will not come to it): whether it was held. The caller
|
||||
/// tells the session.
|
||||
pub fn release(&mut self) -> bool {
|
||||
std::mem::take(&mut self.holding)
|
||||
}
|
||||
|
||||
/// The hold-to-talk button was released, if it was held.
|
||||
fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if std::mem::take(&mut self.holding) {
|
||||
window.dispatch_action(Box::new(PushToTalk { on: false }), cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The server's name, its icon and how many are there, over its banner when it
|
||||
/// has one (`ServerHeader` of `channels.slint`: the picture covers the card,
|
||||
/// the surface veil of `banner-picture.slint` lies over it, and the stats read
|
||||
/// in the text colour instead of the secondary one).
|
||||
fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() };
|
||||
let banner = PictureKey::of(&view.server_banner);
|
||||
let ink = if banner.is_some() { c.text } else { c.text_muted };
|
||||
card(theme, 0xff)
|
||||
.id("sidebar-server")
|
||||
.debug_selector(|| "sidebar-server".into())
|
||||
.relative()
|
||||
.overflow_hidden()
|
||||
.p(px(m.space_3))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.when_some(banner, |card, key| {
|
||||
card.child(
|
||||
div()
|
||||
.id("sidebar-server-banner")
|
||||
.debug_selector(|| "sidebar-server-banner".into())
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(0.0))
|
||||
.size_full()
|
||||
// The picture covers the card and is cropped to it, not past
|
||||
// its border.
|
||||
.overflow_hidden()
|
||||
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
|
||||
)
|
||||
.child(div().absolute().top(px(0.0)).left(px(0.0)).size_full().bg(banner_scrim(theme)))
|
||||
})
|
||||
.child(
|
||||
Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint)
|
||||
.image(item.icon.clone())
|
||||
.square(),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_lg))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(item.name.to_string()),
|
||||
)
|
||||
.child(
|
||||
div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// How our voice is sent, in words, for the modes that have no button.
|
||||
fn transmit_words(mode: TransmitMode) -> &'static str {
|
||||
match mode {
|
||||
TransmitMode::PushToTalk => "Push to talk",
|
||||
TransmitMode::VoiceActivation => "Voice activity",
|
||||
TransmitMode::Continuous => "Open microphone",
|
||||
}
|
||||
}
|
||||
|
||||
/// "Voice Connected" and our channel, disconnect, and Hold to talk in the
|
||||
/// push-to-talk mode (the other modes say themselves).
|
||||
fn voice_card(
|
||||
theme: &VoelinTheme,
|
||||
view: &SidebarView,
|
||||
cx: &mut Context<Sidebar>,
|
||||
) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let (dot, words) = if view.voice_connected {
|
||||
(c.success, "Voice Connected")
|
||||
} else {
|
||||
(c.warning, "Connecting…")
|
||||
};
|
||||
let talking = view.transmitting;
|
||||
card(theme, 0xff)
|
||||
.id("sidebar-voice")
|
||||
.debug_selector(|| "sidebar-voice".into())
|
||||
.p(px(m.space_3))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot)))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(dot))
|
||||
.child(words),
|
||||
)
|
||||
.when(!view.own_channel.is_empty(), |column| {
|
||||
column.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(view.own_channel.clone()),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.when(view.voice_connected && !view.own_channel.is_empty(), |row| {
|
||||
row.child(
|
||||
IconButton::new("voice-invite", "link", "Copy an invite to this channel")
|
||||
.size(32.0)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(Invite), cx);
|
||||
}),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
IconButton::new("voice-disconnect", "phone-off", "Disconnect")
|
||||
.size(32.0)
|
||||
.tint(c.danger)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(DisconnectVoice), cx);
|
||||
}),
|
||||
),
|
||||
)
|
||||
.when(view.voice_connected && !view.hold_to_talk, |card| {
|
||||
card.child(
|
||||
div()
|
||||
.id("transmit-mode")
|
||||
.debug_selector(|| "transmit-mode".into())
|
||||
.h(px(m.control_height_sm))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(icon("mic", m.icon_sm, c.text_muted))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(transmit_words(view.transmit)),
|
||||
),
|
||||
)
|
||||
})
|
||||
.when(view.voice_connected && view.hold_to_talk, |card| {
|
||||
card.child(
|
||||
div()
|
||||
.id("hold-to-talk")
|
||||
.debug_selector(|| "hold-to-talk".into())
|
||||
.h(px(m.control_height))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_2))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(if talking { c.success } else { c.border }))
|
||||
.bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 }))
|
||||
.cursor_pointer()
|
||||
.hover(move |style| {
|
||||
style.bg(hsla(if talking { c.success } else { c.surface_3 }))
|
||||
})
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|this, _, window, cx| {
|
||||
this.holding = true;
|
||||
window.dispatch_action(Box::new(PushToTalk { on: true }), cx);
|
||||
}),
|
||||
)
|
||||
// Let go on the button or off it: the end of what was started.
|
||||
.on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go))
|
||||
.on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go))
|
||||
.child(icon(
|
||||
"mic",
|
||||
m.icon_sm,
|
||||
if talking { c.on_accent } else { c.text_secondary },
|
||||
))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_sm))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(if talking { c.on_accent } else { c.text_secondary }))
|
||||
.child(if talking { "Talking…" } else { "Hold to talk" }),
|
||||
),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Who we are, and the buttons for the microphone and the sound.
|
||||
fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let (words, presence) = if view.voice_connected {
|
||||
("Online", Presence::Online)
|
||||
} else if view.observing {
|
||||
("Observing", Presence::Info)
|
||||
} else {
|
||||
("Offline", Presence::Offline)
|
||||
};
|
||||
let name = if view.nickname.is_empty() {
|
||||
voelin_platform::APP_NAME.to_owned()
|
||||
} else {
|
||||
view.nickname.clone()
|
||||
};
|
||||
let (input_muted, output_muted) = (view.input_muted, view.output_muted);
|
||||
card(theme, 0xb3)
|
||||
.id("sidebar-user")
|
||||
.debug_selector(|| "sidebar-user".into())
|
||||
.min_h(px(60.0))
|
||||
.p(px(m.space_2))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.id("sidebar-profile")
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.px(px(m.space_2))
|
||||
.py(px(m.space_2))
|
||||
.rounded(px(m.radius_md))
|
||||
.cursor_pointer()
|
||||
.hover(|style| style.bg(hsla(c.surface_3)))
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
|
||||
.child(
|
||||
Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff))
|
||||
.image(view.own_avatar.clone())
|
||||
.presence(presence)
|
||||
.speaking(view.transmitting),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(name),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(words),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"user-mic",
|
||||
if input_muted { "mic-off" } else { "mic" },
|
||||
if input_muted { "Microphone off" } else { "Microphone on" },
|
||||
)
|
||||
.danger()
|
||||
.checked(input_muted)
|
||||
.enabled(view.voice_connected)
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx);
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"user-sound",
|
||||
if output_muted { "headphone-off" } else { "headphones" },
|
||||
if output_muted { "Sound off" } else { "Sound on" },
|
||||
)
|
||||
.danger()
|
||||
.checked(output_muted)
|
||||
.enabled(view.voice_connected)
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx);
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The initials of a nickname, for the avatar.
|
||||
fn name_initials(name: &str) -> String {
|
||||
voelin_ui_vm::avatar::initials(name)
|
||||
}
|
||||
|
||||
impl Render for Sidebar {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.sidebar.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let m = &theme.metrics;
|
||||
let view = &self.view;
|
||||
panel(&theme)
|
||||
.id("sidebar")
|
||||
.w(px(m.sidebar_width))
|
||||
.h_full()
|
||||
.flex_none()
|
||||
.p(px(m.space_3))
|
||||
.gap(px(m.space_3))
|
||||
.when_some(view.server.as_ref(), |sidebar, item| {
|
||||
sidebar.child(server_card(&theme, view, item))
|
||||
})
|
||||
// The tree has the room the cards leave, whatever their height.
|
||||
.child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full()))
|
||||
.when(view.voice_connected || view.voice_connecting, |sidebar| {
|
||||
sidebar.child(voice_card(&theme, view, cx))
|
||||
})
|
||||
.child(user_card(&theme, view))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! The status line as a toast: what the last move did ("Connecting to
|
||||
//! ts.example…", why a server was not saved), shown at the bottom of the
|
||||
//! window for a few seconds. It watches the root state's status line and its
|
||||
//! generation, so that the same words said twice are two toasts.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui_kit::{
|
||||
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _,
|
||||
Subscription, Window, div, px,
|
||||
};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// How long a toast stays.
|
||||
pub const TOAST_TIME: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The toast.
|
||||
pub struct Toast {
|
||||
text: String,
|
||||
generation: u64,
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
impl Toast {
|
||||
/// A toast that follows `app`'s status line from now on (what it said
|
||||
/// before is not shown).
|
||||
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
let generation = app.read(cx).status_generation;
|
||||
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
|
||||
let (generation, text) = {
|
||||
let app = app.read(cx);
|
||||
(app.status_generation, app.vm.status.clone())
|
||||
};
|
||||
if generation == this.generation {
|
||||
return;
|
||||
}
|
||||
this.generation = generation;
|
||||
this.text = text;
|
||||
cx.notify();
|
||||
if this.text.is_empty() {
|
||||
return;
|
||||
}
|
||||
cx.spawn(async move |this, cx| {
|
||||
cx.background_executor().timer(TOAST_TIME).await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
if this.generation == generation && !this.text.is_empty() {
|
||||
this.text.clear();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
Self { text: String::new(), generation, _subscription: subscription }
|
||||
}
|
||||
|
||||
/// What it shows now; empty when nothing is.
|
||||
pub fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Toast {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let toast =
|
||||
div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center();
|
||||
if self.text.is_empty() {
|
||||
return toast;
|
||||
}
|
||||
toast.child(
|
||||
div()
|
||||
.max_w(px(560.0))
|
||||
.px(px(m.space_5))
|
||||
.py(px(m.space_3))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup))
|
||||
.bg(hsla(c.surface_3))
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text))
|
||||
.child(self.text.clone()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! The bar at the top of the window: the page's title, the search box and the
|
||||
//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes
|
||||
//! with the notifications). The search and the settings are affordances until
|
||||
//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]).
|
||||
|
||||
use gpui_kit::{
|
||||
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
|
||||
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
|
||||
};
|
||||
|
||||
use super::actions::{OpenSearch, OpenSettings};
|
||||
use super::widgets::{IconButton, icon};
|
||||
use crate::app::AppState;
|
||||
use crate::meter::Counters;
|
||||
use crate::signals::Area;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// The page title: the server on screen, else the app's name.
|
||||
pub fn title(app: &AppState) -> String {
|
||||
match app.current_bookmark() {
|
||||
Some(bookmark) => bookmark.name.clone(),
|
||||
None => voelin_platform::APP_NAME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The top bar.
|
||||
pub struct TopBar {
|
||||
title: String,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl TopBar {
|
||||
/// A top bar that follows the server on screen in `app`.
|
||||
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
let (shown, counters, signals) = {
|
||||
let state = app.read(cx);
|
||||
(title(state), state.counters().clone(), state.signals().clone())
|
||||
};
|
||||
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
|
||||
let shown = title(app.read(cx));
|
||||
if shown != this.title {
|
||||
this.title = shown;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
Self { title: shown, counters, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// The title it shows now.
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for TopBar {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.topbar.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.id("topbar")
|
||||
.w_full()
|
||||
.h(px(m.topbar_height))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
// The main panel starts where the sidebar and the gaps around it end.
|
||||
.pl(px(m.sidebar_width + 2.0 * m.space_3))
|
||||
.pr(px(m.space_4))
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.id("topbar-title")
|
||||
.max_w(px(280.0 * m.font_scale.max(1.0)))
|
||||
.flex_none()
|
||||
.truncate()
|
||||
.text_size(px(m.font_lg))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(self.title.clone()),
|
||||
)
|
||||
.child(
|
||||
div().flex_1().min_w_0().flex().justify_center().child(
|
||||
div()
|
||||
.id("topbar-search")
|
||||
.w_full()
|
||||
.max_w(px(680.0))
|
||||
.h(px(m.control_height))
|
||||
.px(px(m.space_3))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(hsla(c.surface_2))
|
||||
.cursor_text()
|
||||
.hover(|style| style.border_color(hsla(c.border_strong)))
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx))
|
||||
.child(icon("search", m.icon_sm, c.text_muted))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.truncate()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("Search servers, channels, people or settings…"),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
IconButton::new("topbar-settings", "settings", "Settings")
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The narrow entity behind the channel tree and the members panel: what
|
||||
//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between
|
||||
//! one change and the next so that the two panes can be told what changed.
|
||||
//!
|
||||
//! It listens to the tree, toolbar and member-card signals
|
||||
//! ([`crate::signals`]), builds the rows once for both panes, compares them
|
||||
//! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the
|
||||
//! Slint front end applies to its `VecModel`) and emits what differs
|
||||
//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the
|
||||
//! operations to its list state, so a person who joins is a row that is
|
||||
//! inserted, not a list that starts again at the top. A change that moves none
|
||||
//! of what a pane shows emits nothing.
|
||||
//!
|
||||
//! The people of our voice channel (`TreeView::members`, the voice page's
|
||||
//! rows) come out of the same build as the other two lists: the model keeps
|
||||
//! them and emits them when they differ ([`TreeEvent::Voice`]), so the voice
|
||||
//! page needs no build of its own.
|
||||
//!
|
||||
//! **The tree marks who is talking**, as the Slint tree does (the ring on the
|
||||
//! avatar and the speaking bars on the row): someone who starts or stops
|
||||
//! talking changes one row of the tree and one of the members panel, so each
|
||||
//! of the two panes is drawn again once for it, and no other pane is
|
||||
//! (docs/ui.md, "What a change costs").
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::{App, Context, Entity, EventEmitter, Subscription};
|
||||
use voelin_core::{ObserveState, VoiceState};
|
||||
use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem};
|
||||
use voelin_ui_vm::list::{Changes, diff};
|
||||
use voelin_ui_vm::servers::logic;
|
||||
use voelin_ui_vm::tree::{ChannelId, member_card};
|
||||
|
||||
use crate::app::{AppState, VmState};
|
||||
use crate::signals::Area;
|
||||
|
||||
/// Why a list has no rows, which the pane says in words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Emptiness {
|
||||
/// No server is on screen.
|
||||
NoServer,
|
||||
/// The server is observed or being connected to, and its presence is on
|
||||
/// the way.
|
||||
Loading,
|
||||
/// Nothing is known of the server until it is connected.
|
||||
Connect,
|
||||
/// The server has people and the members' search matches none of them (the
|
||||
/// members panel's only: the tree is not searched).
|
||||
NoMatch,
|
||||
}
|
||||
|
||||
impl Emptiness {
|
||||
/// Why the lists of the server on screen are empty: never
|
||||
/// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s.
|
||||
pub fn of(vm: &VmState) -> Self {
|
||||
match vm.current {
|
||||
None => Self::NoServer,
|
||||
Some(id) => match vm.sessions.get(&id) {
|
||||
Some(view)
|
||||
if view.state.observe != ObserveState::Off
|
||||
|| view.state.voice == VoiceState::Connecting =>
|
||||
{
|
||||
Self::Loading
|
||||
}
|
||||
_ => Self::Connect,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the members panel is empty: as [`Emptiness::of`], except that a
|
||||
/// search that leaves nobody of the `total` on the server (`shown` rows
|
||||
/// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here"
|
||||
/// would be false.
|
||||
pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self {
|
||||
if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() {
|
||||
Self::NoMatch
|
||||
} else {
|
||||
Self::of(vm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What changed in the model, as the panes need it.
|
||||
///
|
||||
/// The list events carry the rows their operations lead to. A model that
|
||||
/// refreshed twice before the first event is delivered (an observer that
|
||||
/// changes the state inside a flush makes it) holds the second rows by the
|
||||
/// time a pane hears of the first operations, and operations applied to rows
|
||||
/// they were not made for index past their end. A pane applies them to the
|
||||
/// rows it has and keeps the rows the event carries, so the events, in the
|
||||
/// order they are delivered, lead from the rows the pane started with to the
|
||||
/// model's last.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TreeEvent {
|
||||
/// The tree's rows: the operations from the rows the pane has to the rows
|
||||
/// carried (the model's [`TreeModel::rows`] when it made them).
|
||||
Rows(Changes, Arc<Vec<TreeItem>>),
|
||||
/// The members panel's rows: the operations from the rows the pane has to
|
||||
/// the rows carried (the model's [`TreeModel::people`] when it made them).
|
||||
People(Changes, Arc<Vec<MemberItem>>),
|
||||
/// The people of our voice channel, the voice page's rows, as they are
|
||||
/// now (the whole list: the page lays its people out in a wrapping row, not
|
||||
/// a virtual list, and takes them as they come).
|
||||
Voice(Arc<Vec<MemberItem>>),
|
||||
/// The card over a member row opened, changed or closed
|
||||
/// ([`TreeModel::card`]).
|
||||
Card,
|
||||
/// The selected channel ([`TreeModel::selected`]).
|
||||
Selection,
|
||||
/// Why the lists are empty, or how many people there are
|
||||
/// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`],
|
||||
/// [`TreeModel::total`]).
|
||||
Lists,
|
||||
}
|
||||
|
||||
/// The areas the model listens to.
|
||||
const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard];
|
||||
|
||||
/// How many times each of [`AREAS`] was raised.
|
||||
fn generations(app: &Entity<AppState>, cx: &App) -> [u64; 3] {
|
||||
let signals = app.read(cx).signals();
|
||||
AREAS.map(|area| signals.of(area).read(cx).generation())
|
||||
}
|
||||
|
||||
/// The rows of the tree and of the members panel, the member card and the
|
||||
/// selection of the server on screen.
|
||||
pub struct TreeModel {
|
||||
app: Entity<AppState>,
|
||||
/// The generations of its signals it last built the rows at: a batch that
|
||||
/// raises several of them (a picture that arrives raises three) has them
|
||||
/// all raised before the first is heard, so the first refresh builds the
|
||||
/// rows and the others find nothing new.
|
||||
seen: [u64; 3],
|
||||
refreshes: u64,
|
||||
rows: Arc<Vec<TreeItem>>,
|
||||
people: Arc<Vec<MemberItem>>,
|
||||
voice: Arc<Vec<MemberItem>>,
|
||||
total: i32,
|
||||
card: Option<MemberCard>,
|
||||
selected: Option<ChannelId>,
|
||||
emptiness: Emptiness,
|
||||
people_emptiness: Emptiness,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl EventEmitter<TreeEvent> for TreeModel {}
|
||||
|
||||
/// Check that `changes` lead from a list of `old` rows to one of `new` rows
|
||||
/// (debug builds): a pane that applies operations to rows they were not made
|
||||
/// for finds the counts out of step, where a release build would index past
|
||||
/// the end or leave its list state out of step with its rows.
|
||||
pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) {
|
||||
debug_assert_eq!(
|
||||
old + changes.inserted(),
|
||||
new + changes.removed(),
|
||||
"{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \
|
||||
for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \
|
||||
inside a flush)"
|
||||
);
|
||||
}
|
||||
|
||||
/// Everything the model keeps, as the state gives it now.
|
||||
struct Snapshot {
|
||||
rows: Vec<TreeItem>,
|
||||
people: Vec<MemberItem>,
|
||||
voice: Vec<MemberItem>,
|
||||
total: i32,
|
||||
card: Option<MemberCard>,
|
||||
selected: Option<ChannelId>,
|
||||
emptiness: Emptiness,
|
||||
people_emptiness: Emptiness,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
fn of(app: &AppState) -> Self {
|
||||
let vm = &app.vm;
|
||||
let view = vm.current.and_then(|id| vm.sessions.get(&id));
|
||||
let (rows, people, voice, total) = match logic::tree_view(vm, false) {
|
||||
Some(tree) => (tree.rows, tree.server_members, tree.members, tree.member_total),
|
||||
None => (Vec::new(), Vec::new(), Vec::new(), 0),
|
||||
};
|
||||
Self {
|
||||
people_emptiness: Emptiness::of_people(vm, people.len(), total),
|
||||
rows,
|
||||
people,
|
||||
voice,
|
||||
total,
|
||||
card: view
|
||||
.and_then(|view| view.member_card.map(|id| (view, id)))
|
||||
.and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)),
|
||||
selected: app.selected_channel(),
|
||||
emptiness: Emptiness::of(vm),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeModel {
|
||||
/// A model of what `app` shows now, following its tree signals.
|
||||
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
let (snapshot, signals) = {
|
||||
let state = app.read(cx);
|
||||
(Snapshot::of(state), state.signals().clone())
|
||||
};
|
||||
let subscriptions =
|
||||
signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx));
|
||||
Self {
|
||||
app: app.clone(),
|
||||
seen: generations(app, cx),
|
||||
refreshes: 0,
|
||||
rows: Arc::new(snapshot.rows),
|
||||
people: Arc::new(snapshot.people),
|
||||
voice: Arc::new(snapshot.voice),
|
||||
total: snapshot.total,
|
||||
card: snapshot.card,
|
||||
selected: snapshot.selected,
|
||||
emptiness: snapshot.emptiness,
|
||||
people_emptiness: snapshot.people_emptiness,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the channel tree: channels with the clients in them.
|
||||
pub fn rows(&self) -> &Arc<Vec<TreeItem>> {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
/// The rows of the members panel: everyone on the server, in sections.
|
||||
pub fn people(&self) -> &Arc<Vec<MemberItem>> {
|
||||
&self.people
|
||||
}
|
||||
|
||||
/// The people of our voice channel, in the voice page's order (empty while
|
||||
/// voice is not connected).
|
||||
pub fn voice(&self) -> &Arc<Vec<MemberItem>> {
|
||||
&self.voice
|
||||
}
|
||||
|
||||
/// How many are on the server (the query clients not counted).
|
||||
pub fn total(&self) -> i32 {
|
||||
self.total
|
||||
}
|
||||
|
||||
/// The card over a member row, when one is open.
|
||||
pub fn card(&self) -> Option<&MemberCard> {
|
||||
self.card.as_ref()
|
||||
}
|
||||
|
||||
/// The channel selected in the tree.
|
||||
pub fn selected(&self) -> Option<ChannelId> {
|
||||
self.selected
|
||||
}
|
||||
|
||||
/// Why the tree is empty, were it.
|
||||
pub fn emptiness(&self) -> Emptiness {
|
||||
self.emptiness
|
||||
}
|
||||
|
||||
/// Why the members panel is empty, were it: the same as
|
||||
/// [`TreeModel::emptiness`], or that the search matches nobody.
|
||||
pub fn people_emptiness(&self) -> Emptiness {
|
||||
self.people_emptiness
|
||||
}
|
||||
|
||||
/// How many times the rows were built again since the model was made: one
|
||||
/// for each batch of changes, not one for each signal it raised.
|
||||
pub fn refreshes(&self) -> u64 {
|
||||
self.refreshes
|
||||
}
|
||||
|
||||
/// Build the rows again, and tell the panes what differs. Nothing, when
|
||||
/// none of the signals was raised since the last time.
|
||||
fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
let now = generations(&self.app, cx);
|
||||
if now == self.seen {
|
||||
return;
|
||||
}
|
||||
self.seen = now;
|
||||
self.refreshes += 1;
|
||||
let new = Snapshot::of(self.app.read(cx));
|
||||
let rows = diff(&self.rows, &new.rows);
|
||||
let people = diff(&self.people, &new.people);
|
||||
if !rows.is_empty() {
|
||||
self.rows = Arc::new(new.rows);
|
||||
}
|
||||
if !people.is_empty() {
|
||||
self.people = Arc::new(new.people);
|
||||
}
|
||||
let voice = *self.voice != new.voice;
|
||||
if voice {
|
||||
self.voice = Arc::new(new.voice);
|
||||
}
|
||||
let lists = (self.emptiness, self.people_emptiness, self.total)
|
||||
!= (new.emptiness, new.people_emptiness, new.total);
|
||||
(self.emptiness, self.people_emptiness, self.total) =
|
||||
(new.emptiness, new.people_emptiness, new.total);
|
||||
let card = self.card != new.card;
|
||||
self.card = new.card;
|
||||
let selection = self.selected != new.selected;
|
||||
self.selected = new.selected;
|
||||
if !rows.is_empty() {
|
||||
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
|
||||
}
|
||||
if !people.is_empty() {
|
||||
cx.emit(TreeEvent::People(people, self.people.clone()));
|
||||
}
|
||||
if voice {
|
||||
cx.emit(TreeEvent::Voice(self.voice.clone()));
|
||||
}
|
||||
if lists {
|
||||
cx.emit(TreeEvent::Lists);
|
||||
}
|
||||
if card {
|
||||
cx.emit(TreeEvent::Card);
|
||||
}
|
||||
if selection {
|
||||
cx.emit(TreeEvent::Selection);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! The voice channel page (`VoiceView` of `screens/voice.slint`, with its
|
||||
//! `Participant` of `voice-parts.slint` and the `CallBar`): the channel we are
|
||||
//! in, who is there and who talks, and the call's controls under them.
|
||||
//!
|
||||
//! [`VoicePage`] is a cached pane of its own, a sibling of the server page
|
||||
//! ([`super::MainPanel`]) that [`crate::view::MainView`] puts in the main
|
||||
//! area in its place while the page is asked for and voice is connected
|
||||
//! ([`crate::app::AppState::voice_page_shown`]). It takes its people from the
|
||||
//! tree model ([`TreeEvent::Voice`]: the rows `TreeView::members` gave the one
|
||||
//! build the tree and the members panel come from, so the page builds nothing
|
||||
//! of its own) and the header and the call bar from the servers' and the
|
||||
//! toolbar's signals, compares what it would show with what it showed, and
|
||||
//! tells the window only when they differ. A person who starts or stops
|
||||
//! talking, or mutes, is one row of the page and one render of this pane.
|
||||
//!
|
||||
//! The larger stage lays the people out as large avatars in a wrapping row;
|
||||
//! the smaller stage (`ui.voice_compact`, and always in a window under 800
|
||||
//! pixels tall) is one row of small avatars that scrolls sideways. The streams
|
||||
//! of the Slint page come with the stream slices and its chat with the chat's.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ObjectFit,
|
||||
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, StyledImage as _,
|
||||
Subscription, Window, div, px,
|
||||
};
|
||||
use voelin_ui_vm::bridge::MemberItem;
|
||||
use voelin_ui_vm::image::ImageRef;
|
||||
use voelin_ui_vm::servers::logic;
|
||||
|
||||
use super::actions::{
|
||||
Invite, LeaveVoice, OpenMember, OpenShare, OpenVoiceSettings, SetInputMuted, SetOutputMuted,
|
||||
ShowVoiceView, ToggleVoiceCompact,
|
||||
};
|
||||
use super::tree_model::{TreeEvent, TreeModel};
|
||||
use super::widgets::{Avatar, IconButton, banner_scrim, icon, live_badge, panel, speaking_bars_in};
|
||||
use crate::app::AppState;
|
||||
use crate::meter::Counters;
|
||||
use crate::pictures::{PictureKey, picture};
|
||||
use crate::signals::Area;
|
||||
use crate::theme::tokens::Rgba;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// A window under this tall (pixels) has the smaller stage whatever the
|
||||
/// setting says (`Nav.short` of the Slint front end).
|
||||
pub const SHORT_WINDOW: f32 = 800.0;
|
||||
|
||||
/// What the page's header and call bar show, from the state.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VoiceHead {
|
||||
/// The channel we are in, as the tree shows it.
|
||||
pub channel: String,
|
||||
/// Its topic.
|
||||
pub topic: String,
|
||||
/// Its banner, empty without one.
|
||||
pub banner: ImageRef,
|
||||
/// Its client limit, -1 without one.
|
||||
pub limit: i32,
|
||||
/// Voice is connected.
|
||||
pub connected: bool,
|
||||
/// Our microphone is muted.
|
||||
pub input_muted: bool,
|
||||
/// Our sound is muted.
|
||||
pub output_muted: bool,
|
||||
/// The server can stream (TeamSpeak 6 with voice): the call bar has Share.
|
||||
pub can_share: bool,
|
||||
}
|
||||
|
||||
impl VoiceHead {
|
||||
/// The header and the call bar for the state.
|
||||
pub fn of(app: &AppState) -> Self {
|
||||
let card = logic::toolbar(&app.vm, |_| ImageRef::default());
|
||||
let can_share = app
|
||||
.vm
|
||||
.current
|
||||
.and_then(|id| app.vm.sessions.get(&id))
|
||||
.is_some_and(|view| view.streams_available());
|
||||
Self {
|
||||
channel: card.own_channel,
|
||||
topic: card.own_channel_topic,
|
||||
banner: card.own_channel_banner,
|
||||
limit: card.own_channel_limit,
|
||||
connected: card.voice_connected,
|
||||
input_muted: card.input_muted,
|
||||
output_muted: card.output_muted,
|
||||
can_share,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice channel page.
|
||||
pub struct VoicePage {
|
||||
head: VoiceHead,
|
||||
people: Arc<Vec<MemberItem>>,
|
||||
/// The smaller stage by choice.
|
||||
compact: bool,
|
||||
/// The window is too short for the larger stage.
|
||||
short: bool,
|
||||
counters: Counters,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl VoicePage {
|
||||
/// A page that follows `app` for the header and the call bar and `model` for
|
||||
/// the people, on the stage the setting says (`compact`) in a window that is
|
||||
/// `short` or not.
|
||||
pub fn new(
|
||||
app: &Entity<AppState>,
|
||||
model: &Entity<TreeModel>,
|
||||
compact: bool,
|
||||
short: bool,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let (head, counters, signals) = {
|
||||
let state = app.read(cx);
|
||||
(VoiceHead::of(state), state.counters().clone(), state.signals().clone())
|
||||
};
|
||||
let mut subscriptions =
|
||||
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
|
||||
let head = VoiceHead::of(app.read(cx));
|
||||
if head != this.head {
|
||||
this.head = head;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
subscriptions.push(cx.subscribe(model, |this: &mut Self, _, event: &TreeEvent, cx| {
|
||||
if let TreeEvent::Voice(people) = event {
|
||||
this.people = people.clone();
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
let people = model.read(cx).voice().clone();
|
||||
Self { head, people, compact, short, counters, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
/// What the header and the call bar show.
|
||||
pub fn head(&self) -> &VoiceHead {
|
||||
&self.head
|
||||
}
|
||||
|
||||
/// The people it shows.
|
||||
pub fn people(&self) -> &[MemberItem] {
|
||||
&self.people
|
||||
}
|
||||
|
||||
/// Whether the page is on the smaller stage now: chosen, or the window is too
|
||||
/// short for the larger.
|
||||
pub fn compact_shown(&self) -> bool {
|
||||
self.compact || self.short
|
||||
}
|
||||
|
||||
/// Whether the window is too short for the larger stage (the stage button is
|
||||
/// off then).
|
||||
pub fn short(&self) -> bool {
|
||||
self.short
|
||||
}
|
||||
|
||||
/// The setting `ui.voice_compact` is `compact`: tells the window if the stage
|
||||
/// changes.
|
||||
pub fn set_compact(&mut self, compact: bool, cx: &mut Context<Self>) {
|
||||
if self.compact != compact {
|
||||
self.compact = compact;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// The window is `short` (under [`SHORT_WINDOW`] tall) or not.
|
||||
pub fn set_short(&mut self, short: bool, cx: &mut Context<Self>) {
|
||||
if self.short != short {
|
||||
self.short = short;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ring around a person's avatar: green while they talk, blue while they
|
||||
/// stream (3 pixels, 2 on the smaller stage), else the quiet border of the
|
||||
/// larger stage (2 pixels; the smaller has none).
|
||||
fn ring(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> (u8, Rgba) {
|
||||
let c = &theme.colors;
|
||||
let loud = if compact { 2 } else { 3 };
|
||||
if person.talking {
|
||||
(loud, c.success)
|
||||
} else if person.streaming {
|
||||
(loud, c.accent)
|
||||
} else {
|
||||
(if compact { 0 } else { 2 }, c.border_strong)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the corner of a person's avatar says: the bars while they talk, else
|
||||
/// that their sound or their microphone is off.
|
||||
fn corner(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> Option<AnyElement> {
|
||||
let (c, bars) = (&theme.colors, if compact { 12.0 } else { 14.0 });
|
||||
let size = if compact { 22.0 } else { 26.0 };
|
||||
if !(person.talking || person.muted || person.sound_off) {
|
||||
return None;
|
||||
}
|
||||
let (face, inside) = if person.talking {
|
||||
if compact {
|
||||
(c.accent, speaking_bars_in(theme, bars, c.on_accent).into_any_element())
|
||||
} else {
|
||||
(c.surface, speaking_bars_in(theme, bars, c.success).into_any_element())
|
||||
}
|
||||
} else {
|
||||
let name = if person.sound_off { "headphone-off" } else { "mic-off" };
|
||||
(c.surface, icon(name, if compact { 12.0 } else { 15.0 }, c.danger).into_any_element())
|
||||
};
|
||||
let (id, talking) = (person.id, person.talking);
|
||||
let inset = if compact { 0.0 } else { 2.0 };
|
||||
Some(
|
||||
div()
|
||||
.absolute()
|
||||
.right(px(inset))
|
||||
.bottom(px(inset))
|
||||
.debug_selector(move || {
|
||||
format!("voice-{}-{id}", if talking { "speaking" } else { "off" })
|
||||
})
|
||||
.size(px(size))
|
||||
.rounded(px(size / 2.0))
|
||||
.border_2()
|
||||
.border_color(hsla(c.surface))
|
||||
.bg(hsla(face))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(inside)
|
||||
.into_any_element(),
|
||||
)
|
||||
}
|
||||
|
||||
/// One person: an avatar with its ring, the mark in its corner, the name with
|
||||
/// the crown of an admin, and what they do. A click opens their card.
|
||||
fn participant(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> AnyElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let size = if compact { 54.0 } else { 80.0 };
|
||||
let width = if compact { 68.0 } else { 120.0 };
|
||||
let outer = size + 8.0;
|
||||
let id = person.id;
|
||||
let (ring_width, ring_color) = ring(theme, person, compact);
|
||||
let client = u16::try_from(id).unwrap_or_default();
|
||||
let name_width = width - if person.admin { 16.0 } else { 0.0 };
|
||||
let words = if person.talking {
|
||||
"Speaking"
|
||||
} else if person.streaming {
|
||||
"Streaming"
|
||||
} else if person.away {
|
||||
"Away"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut face = div()
|
||||
.relative()
|
||||
.size(px(outer))
|
||||
.flex_none()
|
||||
.rounded(px(outer / 2.0))
|
||||
.border_color(hsla(ring_color))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center();
|
||||
face = match ring_width {
|
||||
3 => face.border_3(),
|
||||
2 => face.border_2(),
|
||||
_ => face,
|
||||
};
|
||||
let mut face = face.child(
|
||||
Avatar::new(("voice-avatar", id as u64), size, &person.initials, person.tint)
|
||||
.image(person.avatar.clone()),
|
||||
);
|
||||
if let Some(mark) = corner(theme, person, compact) {
|
||||
face = face.child(mark);
|
||||
}
|
||||
div()
|
||||
.id(("voice-member", id as u64))
|
||||
.debug_selector(move || format!("voice-member-{id}"))
|
||||
.w(px(width))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(if compact { m.space_1 } else { m.space_2 }))
|
||||
.cursor_pointer()
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(OpenMember { client: i32::from(client) }), cx)
|
||||
})
|
||||
.child(face)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(if compact { m.space_1 } else { m.space_2 }))
|
||||
.child(
|
||||
div()
|
||||
.max_w(px(name_width))
|
||||
.truncate()
|
||||
.text_size(px(if compact { m.font_sm } else { m.font_md }))
|
||||
.font_weight(if compact { FontWeight::NORMAL } else { FontWeight::MEDIUM })
|
||||
.text_color(hsla(if person.myself { c.accent_text } else { c.text }))
|
||||
.child(person.name.to_string()),
|
||||
)
|
||||
.when(person.admin, |row| {
|
||||
row.child(icon("crown", if compact { 13.0 } else { 15.0 }, c.gold))
|
||||
}),
|
||||
)
|
||||
.when(!compact, |column| {
|
||||
column.child(
|
||||
div()
|
||||
.h(px(m.font_sm + 4.0))
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_2))
|
||||
.when(person.talking, |row| row.child(speaking_bars_in(theme, 12.0, c.success)))
|
||||
.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(if person.talking {
|
||||
c.success
|
||||
} else {
|
||||
c.text_secondary
|
||||
}))
|
||||
.child(words),
|
||||
)
|
||||
.when(person.streaming && !person.talking, |row| {
|
||||
row.child(icon("monitor", 14.0, c.text_secondary))
|
||||
}),
|
||||
)
|
||||
})
|
||||
.when(compact && person.streaming, |column| column.child(live_badge(theme)))
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
/// The channel's name, its topic and how many are in voice, over its banner.
|
||||
fn header(
|
||||
theme: &VoelinTheme,
|
||||
head: &VoiceHead,
|
||||
people: usize,
|
||||
page: &VoicePage,
|
||||
) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let banner = PictureKey::of(&head.banner);
|
||||
let ink = if banner.is_some() { c.text } else { c.text_secondary };
|
||||
let compact = page.compact_shown();
|
||||
let count = if head.limit >= 0 {
|
||||
format!("{people} in voice / {} total", head.limit)
|
||||
} else {
|
||||
format!("{people} in voice")
|
||||
};
|
||||
let stage = if page.short() {
|
||||
"The window is too short for the larger stage"
|
||||
} else if compact {
|
||||
"Larger stage"
|
||||
} else {
|
||||
"Smaller stage"
|
||||
};
|
||||
div()
|
||||
.id("voice-header")
|
||||
.debug_selector(|| "voice-header".into())
|
||||
.relative()
|
||||
.w_full()
|
||||
.flex_none()
|
||||
.overflow_hidden()
|
||||
.when_some(banner, |header, key| {
|
||||
header
|
||||
.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(0.0))
|
||||
.size_full()
|
||||
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("voice-banner")
|
||||
.debug_selector(|| "voice-banner".into())
|
||||
.absolute()
|
||||
.top(px(0.0))
|
||||
.left(px(0.0))
|
||||
.size_full()
|
||||
.bg(banner_scrim(theme)),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.relative()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_5))
|
||||
.pl(px(m.space_7))
|
||||
.pr(px(m.space_5))
|
||||
.pt(px(m.space_5))
|
||||
.pb(px(m.space_3))
|
||||
.child(div().pt(px(m.space_1)).child(icon("volume-2", 40.0, c.text_secondary)))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_1))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.id("voice-channel")
|
||||
.debug_selector(|| "voice-channel".into())
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_size(px(m.font_3xl))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child(head.channel.clone()),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"voice-invite",
|
||||
"user-plus",
|
||||
"Copy invite link",
|
||||
)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(Invite), cx)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"voice-stage",
|
||||
if compact { "chevron-down" } else { "chevron-up" },
|
||||
stage,
|
||||
)
|
||||
.enabled(!page.short())
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(ToggleVoiceCompact), cx)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"voice-chat-only",
|
||||
"message-square",
|
||||
"Chat only",
|
||||
)
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(ShowVoiceView { on: false }),
|
||||
cx,
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
.when(!head.topic.is_empty(), |column| {
|
||||
column.child(
|
||||
div()
|
||||
.truncate()
|
||||
.text_size(px(m.font_md))
|
||||
.text_color(hsla(ink))
|
||||
.child(head.topic.clone()),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(icon("users", 16.0, c.text_secondary))
|
||||
.child(
|
||||
div()
|
||||
.id("voice-count")
|
||||
.debug_selector(|| "voice-count".into())
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(ink))
|
||||
.child(count),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Mute, deafen, share, the voice settings and Leave, under the people.
|
||||
fn call_bar(theme: &VoelinTheme, head: &VoiceHead) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let (input_muted, output_muted) = (head.input_muted, head.output_muted);
|
||||
let leave = c.danger;
|
||||
div()
|
||||
.id("voice-callbar")
|
||||
.debug_selector(|| "voice-callbar".into())
|
||||
.w_full()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.px(px(m.space_6))
|
||||
.pb(px(m.space_3))
|
||||
.child(
|
||||
IconButton::new(
|
||||
"call-mic",
|
||||
if input_muted { "mic-off" } else { "mic" },
|
||||
if input_muted { "Microphone off" } else { "Microphone on" },
|
||||
)
|
||||
.size(44.0)
|
||||
.round()
|
||||
.filled()
|
||||
.danger()
|
||||
.checked(input_muted)
|
||||
.enabled(head.connected)
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
IconButton::new(
|
||||
"call-sound",
|
||||
if output_muted { "headphone-off" } else { "headphones" },
|
||||
if output_muted { "Sound off" } else { "Sound on" },
|
||||
)
|
||||
.size(44.0)
|
||||
.round()
|
||||
.filled()
|
||||
.danger()
|
||||
.checked(output_muted)
|
||||
.enabled(head.connected)
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx)
|
||||
}),
|
||||
)
|
||||
.when(head.can_share, |bar| {
|
||||
bar.child(
|
||||
IconButton::new("call-share", "monitor-up", "Share or go live")
|
||||
.size(44.0)
|
||||
.round()
|
||||
.filled()
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenShare), cx)),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
IconButton::new("call-settings", "settings", "Voice Settings")
|
||||
.size(44.0)
|
||||
.round()
|
||||
.filled()
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenVoiceSettings), cx)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("call-leave")
|
||||
.debug_selector(|| "call-leave".into())
|
||||
.h(px(m.control_height))
|
||||
.px(px(m.space_5))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_3))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(leave.with_alpha(0x73)))
|
||||
.bg(hsla(c.danger_soft))
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hsla(c.danger_soft.mix(leave, 0.25))))
|
||||
.on_click(|_, window, cx| window.dispatch_action(Box::new(LeaveVoice), cx))
|
||||
.child(icon("phone-off", m.icon_md, leave))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_body))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(leave))
|
||||
.child("Leave"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
impl Render for VoicePage {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.panes.voice.incr();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let compact = self.compact_shown();
|
||||
let stage = if compact {
|
||||
// One row, scrolling sideways when there are many; centred while it fits.
|
||||
div()
|
||||
.id("voice-people")
|
||||
.debug_selector(|| "voice-people".into())
|
||||
.w_full()
|
||||
.h(px(112.0))
|
||||
.flex_none()
|
||||
.overflow_x_scroll()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.child(
|
||||
div()
|
||||
.h_full()
|
||||
.flex_none()
|
||||
.mx_auto()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_3))
|
||||
.px(px(m.space_6))
|
||||
.pt(px(m.space_2))
|
||||
.children(
|
||||
self.people.iter().map(|person| participant(&theme, person, true)),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
// Centred, wrapping into more rows when there are many.
|
||||
div()
|
||||
.id("voice-people")
|
||||
.debug_selector(|| "voice-people".into())
|
||||
.w_full()
|
||||
// Rows taller than the page scroll; the header and the call bar keep
|
||||
// their places.
|
||||
.flex_shrink(1.0)
|
||||
.min_h_0()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.justify_center()
|
||||
.gap_x(px(m.space_6))
|
||||
.gap_y(px(m.space_4))
|
||||
.px(px(m.space_6))
|
||||
.pt(px(m.space_3))
|
||||
.pb(px(m.space_4))
|
||||
.children(self.people.iter().map(|person| participant(&theme, person, false)))
|
||||
};
|
||||
// A cached pane's root takes the size its place gives it.
|
||||
panel(&theme)
|
||||
.id("voice-page")
|
||||
.debug_selector(|| "voice-page".into())
|
||||
.size_full()
|
||||
.child(header(&theme, &self.head, self.people.len(), self))
|
||||
.child(stage)
|
||||
.child(call_bar(&theme, &self.head))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("The channel's chat comes with a later slice."),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
//! The few pieces the shell is made of, drawn from the theme's tokens
|
||||
//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a
|
||||
//! person, the icon button, the panel and the Lucide icon. They are the GPUI
|
||||
//! counterparts of `ui/components/avatar.slint`, `button.slint` and
|
||||
//! `shells/common.slint`'s `Panel`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::{
|
||||
AnyElement, App, Background, ClickEvent, FontWeight, InteractiveElement as _, IntoElement,
|
||||
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _,
|
||||
Window, div, linear_color_stop, linear_gradient, px, svg,
|
||||
};
|
||||
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
|
||||
use voelin_ui_vm::Rgb;
|
||||
use voelin_ui_vm::avatar::first_letter;
|
||||
use voelin_ui_vm::image::ImageRef;
|
||||
|
||||
use crate::pictures::{PictureKey, picture};
|
||||
|
||||
use crate::theme::tokens::Rgba;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// A Lucide icon of the client's set, `size` pixels square, in `color`.
|
||||
pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement {
|
||||
svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color))
|
||||
}
|
||||
|
||||
/// What the dot on an avatar says (`Status` of `avatar.slint`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Presence {
|
||||
/// No dot.
|
||||
None,
|
||||
/// Connected with voice.
|
||||
Online,
|
||||
/// Connecting.
|
||||
Idle,
|
||||
/// Observed invisibly.
|
||||
Info,
|
||||
/// Not connected.
|
||||
Offline,
|
||||
/// Their sound is off (a person who does not hear).
|
||||
Dnd,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
/// The dot of a server's state as the engine names it
|
||||
/// (`voelin_ui_vm::servers::status`): connected is online, observing is
|
||||
/// blue, connecting is idle, offline has none.
|
||||
pub fn of_server(status: &str) -> Self {
|
||||
match status {
|
||||
"connected" => Self::Online,
|
||||
"observing" => Self::Info,
|
||||
"connecting" => Self::Idle,
|
||||
_ => Self::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The dot's colour.
|
||||
fn color(self, theme: &VoelinTheme) -> Option<Rgba> {
|
||||
let c = &theme.colors;
|
||||
match self {
|
||||
Self::None => None,
|
||||
Self::Online => Some(c.success),
|
||||
Self::Idle => Some(c.idle),
|
||||
Self::Info => Some(c.info),
|
||||
Self::Offline => Some(c.offline),
|
||||
Self::Dnd => Some(c.dnd),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour a server or person is drawn in.
|
||||
pub fn tint(color: Rgb) -> Rgba {
|
||||
Rgba(color.0 << 8 | 0xff)
|
||||
}
|
||||
|
||||
/// How opaque the veil over a banner is at its left edge and at its right
|
||||
/// (`components/banner-picture.slint`: `transparentize(0.26)` and `(0.34)`).
|
||||
const BANNER_VEIL: (f32, f32) = (0.74, 0.66);
|
||||
|
||||
/// The veil over a banner picture: the surface colour, left to right from 74 %
|
||||
/// to 66 % opaque. A row's text (`text`) keeps more than 4.5 to 1 against it
|
||||
/// whatever the picture, even white behind the dark theme's light text or
|
||||
/// black behind the light theme's dark text. It lies over the picture and
|
||||
/// under the row's own tint.
|
||||
pub fn banner_scrim(theme: &VoelinTheme) -> Background {
|
||||
let surface = hsla(theme.colors.surface);
|
||||
linear_gradient(
|
||||
90.0,
|
||||
linear_color_stop(surface.opacity(BANNER_VEIL.0), 0.0),
|
||||
linear_color_stop(surface.opacity(BANNER_VEIL.1), 1.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// Under this size (pixels) an avatar shows one letter, larger (`avatar.slint`).
|
||||
const SMALL_AVATAR: f32 = 28.0;
|
||||
|
||||
/// What an avatar of `size` pixels writes on its colour, and how large:
|
||||
/// the initials at 0.38 of the size, but only the first letter at half of it
|
||||
/// under 28 pixels, where two letters at 0.38 are a few pixels high and cramped
|
||||
/// (`avatar.slint`'s `small`, with `Images.first-letter`).
|
||||
fn initials_for(initials: &str, size: f32) -> (SharedString, f32) {
|
||||
if size < SMALL_AVATAR {
|
||||
(first_letter(initials).into(), size * 0.5)
|
||||
} else {
|
||||
(initials.to_owned().into(), size * 0.38)
|
||||
}
|
||||
}
|
||||
|
||||
/// An avatar: the picture when there is one (a file of the engine's cache),
|
||||
/// else the initials on `tint` (one letter under 28 pixels), square with
|
||||
/// rounded corners for a server and round for a person, with a presence dot and
|
||||
/// a green ring while the person's voice goes out. The picture is keyed by the
|
||||
/// file and its stamp ([`crate::pictures`]), so a picture the engine writes
|
||||
/// again shows. Pictures other than files of the cache are drawn as initials
|
||||
/// until the slices that decode them (the chat's).
|
||||
#[derive(IntoElement)]
|
||||
pub struct Avatar {
|
||||
id: ElementId,
|
||||
size: f32,
|
||||
initials: SharedString,
|
||||
tint: Rgb,
|
||||
image: ImageRef,
|
||||
square: bool,
|
||||
presence: Presence,
|
||||
speaking: bool,
|
||||
}
|
||||
|
||||
impl Avatar {
|
||||
/// An avatar of `size` pixels with these initials on `tint`.
|
||||
pub fn new(id: impl Into<ElementId>, size: f32, initials: &str, tint: Rgb) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
size,
|
||||
initials: initials.to_owned().into(),
|
||||
tint,
|
||||
image: ImageRef::default(),
|
||||
square: false,
|
||||
presence: Presence::None,
|
||||
speaking: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw this picture when it is a file of the cache.
|
||||
pub fn image(mut self, image: ImageRef) -> Self {
|
||||
self.image = image;
|
||||
self
|
||||
}
|
||||
|
||||
/// A server's rounded square, not a person's circle.
|
||||
pub fn square(mut self) -> Self {
|
||||
self.square = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The dot at the corner.
|
||||
pub fn presence(mut self, presence: Presence) -> Self {
|
||||
self.presence = presence;
|
||||
self
|
||||
}
|
||||
|
||||
/// The green ring.
|
||||
pub fn speaking(mut self, speaking: bool) -> Self {
|
||||
self.speaking = speaking;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Avatar {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
|
||||
let key = PictureKey::of(&self.image);
|
||||
let face = div()
|
||||
.size(px(self.size))
|
||||
.flex_none()
|
||||
.rounded(px(radius))
|
||||
.overflow_hidden()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
|
||||
let face = match key {
|
||||
// The picture rounds its own corners: a parent's `overflow_hidden`
|
||||
// clips to a rectangle.
|
||||
Some(key) => face
|
||||
.child(picture(key).size_full().rounded(px(radius)).object_fit(ObjectFit::Cover)),
|
||||
None => {
|
||||
let (letters, size) = initials_for(&self.initials, self.size);
|
||||
face.child(
|
||||
div()
|
||||
.text_size(px(size))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(Rgba(0xffff_ffff)))
|
||||
.child(letters),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none();
|
||||
if self.speaking {
|
||||
avatar = avatar.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(-3.0))
|
||||
.left(px(-3.0))
|
||||
.size(px(self.size + 6.0))
|
||||
.rounded(px(radius + 3.0))
|
||||
.border_2()
|
||||
.border_color(hsla(c.success)),
|
||||
);
|
||||
}
|
||||
avatar = avatar.child(face);
|
||||
if let Some(color) = self.presence.color(theme) {
|
||||
let dot = (self.size * 0.3).max(10.0);
|
||||
avatar = avatar.child(
|
||||
div()
|
||||
.absolute()
|
||||
.top(px(self.size - dot + 1.0))
|
||||
.left(px(self.size - dot + 1.0))
|
||||
.size(px(dot))
|
||||
.rounded(px(dot / 2.0))
|
||||
.border_2()
|
||||
.border_color(hsla(c.surface))
|
||||
.bg(hsla(color)),
|
||||
);
|
||||
}
|
||||
avatar
|
||||
}
|
||||
}
|
||||
|
||||
type Handler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
|
||||
|
||||
/// A button that is an icon: 36 pixels (or `size`) square, round or with
|
||||
/// rounded corners, with a tooltip. Without a handler or disabled it draws
|
||||
/// dimmed and does nothing, and keeps its tooltip.
|
||||
#[derive(IntoElement)]
|
||||
pub struct IconButton {
|
||||
id: ElementId,
|
||||
icon: &'static str,
|
||||
label: SharedString,
|
||||
size: f32,
|
||||
tint: Option<Rgba>,
|
||||
danger: bool,
|
||||
round: bool,
|
||||
filled: bool,
|
||||
checked: bool,
|
||||
enabled: bool,
|
||||
on_click: Option<Handler>,
|
||||
}
|
||||
|
||||
impl IconButton {
|
||||
/// The Lucide icon `icon` (a file name without `.svg`), named `label` for
|
||||
/// the tooltip.
|
||||
pub fn new(
|
||||
id: impl Into<ElementId>,
|
||||
icon: &'static str,
|
||||
label: impl Into<SharedString>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
icon,
|
||||
label: label.into(),
|
||||
size: 34.0,
|
||||
tint: None,
|
||||
danger: false,
|
||||
round: false,
|
||||
filled: false,
|
||||
checked: false,
|
||||
enabled: true,
|
||||
on_click: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The button's side in pixels.
|
||||
pub fn size(mut self, size: f32) -> Self {
|
||||
self.size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// The icon's colour, instead of the theme's icon colour.
|
||||
pub fn tint(mut self, tint: Rgba) -> Self {
|
||||
self.tint = Some(tint);
|
||||
self
|
||||
}
|
||||
|
||||
/// A button that turns danger-coloured when checked (mute).
|
||||
pub fn danger(mut self) -> Self {
|
||||
self.danger = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// A circle.
|
||||
pub fn round(mut self) -> Self {
|
||||
self.round = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// A button with a border and a face of its own (the rail's plus).
|
||||
pub fn filled(mut self) -> Self {
|
||||
self.filled = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether it is on.
|
||||
pub fn checked(mut self, checked: bool) -> Self {
|
||||
self.checked = checked;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether it can be used.
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// What a click does.
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.on_click = Some(Box::new(handler));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for IconButton {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let (face, ink, hover) = match (self.checked, self.danger, self.filled) {
|
||||
(true, true, _) => (c.danger_soft, c.danger, c.danger_soft),
|
||||
(true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover),
|
||||
(false, _, true) => {
|
||||
let ink = self.tint.unwrap_or(c.icon);
|
||||
(c.surface_2, ink, ink.with_alpha(0x33))
|
||||
}
|
||||
(false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3),
|
||||
};
|
||||
let radius = if self.round { self.size / 2.0 } else { m.radius_md };
|
||||
let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) };
|
||||
let label = self.label.clone();
|
||||
let selector = self.id.to_string();
|
||||
#[cfg(test)]
|
||||
let tooltip_selector = selector.clone();
|
||||
// Key the element by both its id and its label so GPUI drops stale
|
||||
// hover/tooltip state when a toggle button's label changes, while
|
||||
// keeping the debug selector stable for tests.
|
||||
let id = ElementId::NamedChild(Arc::new(self.id), self.label);
|
||||
let mut button = div()
|
||||
.id(id)
|
||||
.debug_selector(move || selector)
|
||||
.size(px(self.size))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.rounded(px(radius))
|
||||
.bg(hsla(face))
|
||||
.child(icon(self.icon, icon_size, ink));
|
||||
if self.filled {
|
||||
button = button.border_1().border_color(hsla(ink));
|
||||
}
|
||||
// The tooltip is there while the button is off too: it says why (the voice
|
||||
// page's stage button in a window too short for the larger stage).
|
||||
button = button.tooltip(move |window, cx| {
|
||||
#[cfg(test)]
|
||||
tests::record_tooltip(&tooltip_selector, &label);
|
||||
gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
|
||||
});
|
||||
if !self.enabled {
|
||||
return button.opacity(0.4).into_any_element();
|
||||
}
|
||||
button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover)));
|
||||
match self.on_click {
|
||||
Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)),
|
||||
None => button,
|
||||
}
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
/// A rounded panel of the frame (sidebar, main area): `surface` a little
|
||||
/// see-through over the backdrop, a border, clipped.
|
||||
pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.rounded(px(m.radius_xl))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(hsla(c.surface.with_alpha(235)))
|
||||
.overflow_hidden()
|
||||
}
|
||||
|
||||
/// What a card of the sidebar is drawn on.
|
||||
pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.rounded(px(m.radius_lg))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(hsla(c.surface_2.with_alpha(alpha)))
|
||||
}
|
||||
|
||||
/// `element` in a box of its own that tests find by `selector` (a debug
|
||||
/// selector costs nothing in a build without debug assertions): for the
|
||||
/// components of gpui-component, which have none of their own.
|
||||
pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement {
|
||||
div().flex_none().debug_selector(|| selector.into()).child(element)
|
||||
}
|
||||
|
||||
/// A picture of the cache in its own colours, `size` pixels square (a group's
|
||||
/// or a client's icon, a badge); none when it is no picture that shows.
|
||||
pub fn small_picture(image: &ImageRef, size: f32) -> Option<AnyElement> {
|
||||
let key = PictureKey::of(image)?;
|
||||
Some(
|
||||
picture(key)
|
||||
.w(px(size))
|
||||
.h(px(size))
|
||||
.flex_none()
|
||||
.object_fit(ObjectFit::Contain)
|
||||
.into_any_element(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The red LIVE tag.
|
||||
pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.h(px(18.0))
|
||||
.px(px(5.0))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.rounded(px(m.radius_xs))
|
||||
.bg(hsla(c.live))
|
||||
.text_size(px(m.font_xs))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(Rgba(0xffff_ffff)))
|
||||
.child("LIVE")
|
||||
}
|
||||
|
||||
/// Three bars: someone speaks. (The Slint bars move; these stand still, as
|
||||
/// nothing here may draw the window anew with the clock.)
|
||||
pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement {
|
||||
speaking_bars_in(theme, size, theme.colors.success)
|
||||
}
|
||||
|
||||
/// The speaking bars in `color`, for a ground the green does not stand out on
|
||||
/// (the accent of the voice page's corner badge).
|
||||
pub fn speaking_bars_in(_theme: &VoelinTheme, size: f32, color: Rgba) -> impl IntoElement {
|
||||
let bar = move |height: f32| {
|
||||
div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color))
|
||||
};
|
||||
div()
|
||||
.w(px(size))
|
||||
.h(px(size))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.child(bar(1.0))
|
||||
.child(bar(0.6))
|
||||
.child(bar(0.8))
|
||||
}
|
||||
|
||||
/// A small rounded label: a role, a fact (talk power, a country), a badge.
|
||||
/// `picture` is a badge's own picture, `icon` a Lucide icon in the label's
|
||||
/// colour.
|
||||
pub fn chip(
|
||||
theme: &VoelinTheme,
|
||||
text: impl Into<SharedString>,
|
||||
icon_name: Option<&'static str>,
|
||||
picture: Option<AnyElement>,
|
||||
) -> gpui_kit::Div {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.h(px(22.0))
|
||||
.px(px(m.space_3))
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.rounded(px(m.radius_pill))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_strong))
|
||||
.bg(hsla(c.surface_3))
|
||||
.text_size(px(m.font_xs))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.children(icon_name.map(|name| icon(name, 12.0, c.text_secondary).into_any_element()))
|
||||
.children(picture)
|
||||
.child(text.into())
|
||||
}
|
||||
|
||||
/// Tooltips built by [`IconButton`] since the last call, as `(selector, label)`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn take_tooltips() -> Vec<(String, String)> {
|
||||
tests::TOOLTIPS.with(|log| std::mem::take(&mut *log.borrow_mut()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::RefCell;
|
||||
|
||||
use super::*;
|
||||
use crate::theme::Choice;
|
||||
|
||||
thread_local! {
|
||||
pub(super) static TOOLTIPS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
pub(super) fn record_tooltip(selector: &str, label: &str) {
|
||||
TOOLTIPS.with(|log| log.borrow_mut().push((selector.to_owned(), label.to_owned())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_letters_are_written_large_enough_and_one_letter_under_28_pixels() {
|
||||
// The tree's 22 pixel avatars: one letter, half the size.
|
||||
assert_eq!(initials_for("DE", 22.0), (SharedString::from("D"), 11.0));
|
||||
assert_eq!(initials_for("GP", 27.9).0, SharedString::from("G"));
|
||||
// 28 pixels and up: the initials at 0.38 of the size.
|
||||
let (letters, size) = initials_for("NS", 28.0);
|
||||
assert_eq!((letters, size), (SharedString::from("NS"), 28.0 * 0.38));
|
||||
assert_eq!(initials_for("NS", 46.0).0, SharedString::from("NS"));
|
||||
// What the engine gave when there is none, and a letter with a mark.
|
||||
assert_eq!(initials_for("", 22.0).0, SharedString::from(""));
|
||||
assert_eq!(initials_for("A\u{308}B", 22.0).0, SharedString::from("A\u{308}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_banner_veil_keeps_the_text_readable_over_any_picture() {
|
||||
for choice in [Choice::Dark, Choice::Light] {
|
||||
let theme = VoelinTheme::new(choice, choice == Choice::Dark, 1.0);
|
||||
let c = &theme.colors;
|
||||
// The weakest end of the veil, over the two pictures that are the
|
||||
// worst for light and dark text.
|
||||
for picture in [Rgba(0x0000_00ff), Rgba(0xffff_ffff)] {
|
||||
let seen = c.surface.mix(picture, 1.0 - BANNER_VEIL.1);
|
||||
assert!(
|
||||
c.text.contrast(seen) > 4.5,
|
||||
"{choice:?}: text on {picture:?} under the veil is {}",
|
||||
c.text.contrast(seen)
|
||||
);
|
||||
}
|
||||
// Left to right, from the stronger end to the weaker, in the surface's colour.
|
||||
let surface = hsla(c.surface);
|
||||
assert_eq!(
|
||||
banner_scrim(&theme),
|
||||
linear_gradient(
|
||||
90.0,
|
||||
linear_color_stop(surface.opacity(0.74), 0.0),
|
||||
linear_color_stop(surface.opacity(0.66), 1.0),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Per-area signals: `Update.refresh` of the transitions
|
||||
//! ([`voelin_ui_vm::host::Refresh`]) turned into what the window's parts
|
||||
//! listen to.
|
||||
//!
|
||||
//! The Slint front end draws again what a transition's `refresh` flags name.
|
||||
//! Here a part of the window is an entity, and gpui-pre 0.3.10 draws a part
|
||||
//! again when its entity is notified, so each area has an entity of its own,
|
||||
//! a [`Signal`] with a generation, that the root state raises for the flags
|
||||
//! of an update ([`Signals::raise`]) and that the parts observe
|
||||
//! ([`Signals::watch`]): a change of the channel tree notifies the tree's
|
||||
//! listeners, and the rail, the top bar and the main area are not asked
|
||||
//! whether anything changed for them. A part still compares what it would show
|
||||
//! with what it showed before it tells the window, for the many events that
|
||||
//! set a flag and change nothing it shows.
|
||||
//!
|
||||
//! Only the flags of areas this front end has parts for are signals; the
|
||||
//! others (`chat`, `streams`, ...) are dropped until their slices come, as
|
||||
//! `perform` dropped all of them before.
|
||||
|
||||
use gpui_kit::{App, AppContext as _, Context, Entity, Subscription};
|
||||
use voelin_ui_vm::host::Refresh;
|
||||
|
||||
use crate::app::AppState;
|
||||
|
||||
/// An area of the window that a change of the state can concern.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Area {
|
||||
/// The servers: the rail, the top bar's title, the main area, the server
|
||||
/// card (`Refresh::servers`).
|
||||
Servers,
|
||||
/// The voice and user cards of the sidebar (`Refresh::toolbar`).
|
||||
Toolbar,
|
||||
/// The channel tree and the members panel (`Refresh::tree`).
|
||||
Tree,
|
||||
/// The card over a member row (`Refresh::member_card`).
|
||||
MemberCard,
|
||||
}
|
||||
|
||||
impl Area {
|
||||
/// Every area.
|
||||
pub const ALL: [Area; 4] = [Area::Servers, Area::Toolbar, Area::Tree, Area::MemberCard];
|
||||
}
|
||||
|
||||
/// The entity of an area: it has nothing but a count of how many times it was
|
||||
/// raised, so that what observes it is told.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Signal {
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
/// How many times it was raised.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
}
|
||||
|
||||
/// The signals of the areas, owned by the root state.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Signals {
|
||||
servers: Entity<Signal>,
|
||||
toolbar: Entity<Signal>,
|
||||
tree: Entity<Signal>,
|
||||
member_card: Entity<Signal>,
|
||||
}
|
||||
|
||||
impl Signals {
|
||||
/// One signal per area, made in the entity `cx` belongs to.
|
||||
pub fn new<T: 'static>(cx: &mut Context<T>) -> Self {
|
||||
Self {
|
||||
servers: cx.new(|_| Signal::default()),
|
||||
toolbar: cx.new(|_| Signal::default()),
|
||||
tree: cx.new(|_| Signal::default()),
|
||||
member_card: cx.new(|_| Signal::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signal of an area.
|
||||
pub fn of(&self, area: Area) -> &Entity<Signal> {
|
||||
match area {
|
||||
Area::Servers => &self.servers,
|
||||
Area::Toolbar => &self.toolbar,
|
||||
Area::Tree => &self.tree,
|
||||
Area::MemberCard => &self.member_card,
|
||||
}
|
||||
}
|
||||
|
||||
/// The areas an update's flags name.
|
||||
pub fn areas(refresh: &Refresh) -> Vec<Area> {
|
||||
[
|
||||
(refresh.servers, Area::Servers),
|
||||
(refresh.toolbar, Area::Toolbar),
|
||||
(refresh.tree, Area::Tree),
|
||||
(refresh.member_card, Area::MemberCard),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(flagged, area)| flagged.then_some(area))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Raise one area: whatever observes it is told.
|
||||
pub fn raise_area(&self, area: Area, cx: &mut App) {
|
||||
self.of(area).update(cx, |signal, cx| {
|
||||
signal.generation += 1;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
/// Raise the areas `refresh` names, each once however many flags a batch
|
||||
/// of events merged into it.
|
||||
pub fn raise(&self, refresh: &Refresh, cx: &mut App) {
|
||||
for area in Self::areas(refresh) {
|
||||
self.raise_area(area, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `on` whenever one of `areas` is raised, with the root state; the
|
||||
/// subscriptions end with the part that holds them. `on` reads the state
|
||||
/// outside of the part's render: a part that read the root entity while it
|
||||
/// renders would be drawn again with every change of the root, which is
|
||||
/// what the signals are for not doing.
|
||||
pub fn watch<T: 'static>(
|
||||
&self,
|
||||
app: &Entity<AppState>,
|
||||
areas: &[Area],
|
||||
cx: &mut Context<T>,
|
||||
on: impl Fn(&mut T, &Entity<AppState>, &mut Context<T>) + Clone + 'static,
|
||||
) -> Vec<Subscription> {
|
||||
areas
|
||||
.iter()
|
||||
.map(|&area| {
|
||||
let (app, on) = (app.clone(), on.clone());
|
||||
cx.observe(self.of(area), move |this, _, cx| on(this, &app, cx))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_flags_of_an_update_name_the_areas_this_front_end_has() {
|
||||
assert!(Signals::areas(&Refresh::default()).is_empty());
|
||||
let refresh = Refresh { tree: true, servers: true, chat: true, ..Default::default() };
|
||||
assert_eq!(Signals::areas(&refresh), [Area::Servers, Area::Tree], "chat has no part yet");
|
||||
assert_eq!(Signals::areas(&Refresh::ALL), Area::ALL);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 321 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user