Compare commits
196
Commits
No files matched your search
@@ -1,135 +1,21 @@
|
||||
name: Linux checks
|
||||
description: Shared Linux validation for Gitea CI and release packaging.
|
||||
inputs:
|
||||
protocol-deploy-key:
|
||||
description: >
|
||||
Private half of the read-only deploy key registered on the private
|
||||
Voelin/VoelinProtocol repository (the repository secret
|
||||
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
|
||||
visible inside a composite action). The action fails when it is empty.
|
||||
required: true
|
||||
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:
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
|
||||
# in seconds and before anything runs cargo.
|
||||
- name: Install the VoelinProtocol deploy key
|
||||
# The key reaches this step through the environment only: never in the
|
||||
# script text, never echoed, no `set -x`.
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh ssh-keygen; do
|
||||
command -v "$tool" > /dev/null || {
|
||||
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
ssh_dir="$HOME/.ssh"
|
||||
key_file="$ssh_dir/voelin_protocol"
|
||||
mkdir -p "$ssh_dir"
|
||||
chmod 700 "$ssh_dir"
|
||||
|
||||
# Whatever the secret store did to the line ends and the final newline,
|
||||
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
chmod 600 "$key_file"
|
||||
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
|
||||
rm -f "$key_file"
|
||||
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
|
||||
exit 1
|
||||
fi
|
||||
# The fingerprint of the public half, to compare with the deploy key in
|
||||
# the VoelinProtocol settings.
|
||||
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
|
||||
|
||||
# The reviewed host key from the repository, never one fetched now.
|
||||
known_hosts="$ssh_dir/known_hosts"
|
||||
touch "$known_hosts"
|
||||
chmod 600 "$known_hosts"
|
||||
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
|
||||
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
|
||||
exit 1
|
||||
}
|
||||
while IFS= read -r line; do
|
||||
case "$line" in '' | '#'*) continue ;; esac
|
||||
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
|
||||
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
|
||||
|
||||
# Use this key, and only this one, for the Gitea server; fail rather than
|
||||
# ask when its host key is unknown or changed. The block goes first: ssh
|
||||
# takes the first value it finds for each option.
|
||||
config="$ssh_dir/config"
|
||||
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
|
||||
touch "$config"
|
||||
if ! grep -qxF -- "$marker" "$config"; then
|
||||
{
|
||||
cat << EOF
|
||||
$marker
|
||||
Host git.faumaray.com
|
||||
User gitea
|
||||
IdentityFile $key_file
|
||||
IdentitiesOnly yes
|
||||
UserKnownHostsFile $known_hosts
|
||||
StrictHostKeyChecking yes
|
||||
BatchMode yes
|
||||
ConnectTimeout 30
|
||||
|
||||
EOF
|
||||
cat "$config"
|
||||
} > "$config.new"
|
||||
mv "$config.new" "$config"
|
||||
fi
|
||||
chmod 600 "$config"
|
||||
|
||||
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
|
||||
# system git runs ssh, which reads the config above. `-F` names it
|
||||
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
|
||||
# in $HOME, and a job image may set the two apart.
|
||||
{
|
||||
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
|
||||
echo "GIT_SSH_COMMAND=ssh -F '$config'"
|
||||
} >> "$GITHUB_ENV"
|
||||
shell: bash
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Check read access to VoelinProtocol
|
||||
# The first thing cargo does, with the same git and ssh configuration, so
|
||||
# that a wrong key or a changed host key fails here with a clear message
|
||||
# and not minutes later inside a cargo command.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
|
||||
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
|
||||
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Voelin/VoelinProtocol is readable with the deploy key."
|
||||
shell: bash
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
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)
|
||||
@@ -137,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
|
||||
|
||||
+4
-3
@@ -4,7 +4,8 @@
|
||||
#
|
||||
# Committed, never fetched while a job runs, so a CI or release build trusts the
|
||||
# key reviewed here and not whatever answers on the network at that moment.
|
||||
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
|
||||
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
|
||||
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
|
||||
# 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==
|
||||
+244
-9
@@ -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"]
|
||||
@@ -21,9 +36,8 @@ on:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
# Cargo fetches the private VoelinProtocol dependency with the system git and
|
||||
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
|
||||
# too; set here as well, it does not depend on the runner handing a composite
|
||||
# action's GITHUB_ENV on to the later steps.
|
||||
# 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:
|
||||
@@ -31,14 +45,235 @@ jobs:
|
||||
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
|
||||
with:
|
||||
# A repository secret is not visible inside the composite action, so
|
||||
# it is passed in. Pull requests from forks get no secrets: the
|
||||
# action then fails at once with a message that says so.
|
||||
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
@@ -33,13 +33,56 @@ jobs:
|
||||
# Remove only output owned by this workflow in its checkout.
|
||||
rm -rf dist
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
|
||||
# this agent (`docker build --ssh default`): the key lives in the agent's
|
||||
# memory, never on disk and never in an image layer. Stopped by the last
|
||||
# step; the lifetime below ends the key anyway if the runner dies first.
|
||||
- name: Start ssh-agent with the VoelinProtocol deploy key
|
||||
# (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:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
# 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
|
||||
@@ -112,6 +155,27 @@ jobs:
|
||||
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
|
||||
@@ -136,9 +200,3 @@ jobs:
|
||||
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: scripts/gitea-release.sh dist/release
|
||||
- name: Stop the ssh-agent
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
|
||||
ssh-agent -k > /dev/null || true
|
||||
fi
|
||||
@@ -16,7 +16,8 @@ runs:
|
||||
- name: apt packages
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
|
||||
# by the GPUI front end), libvpx + dav1d
|
||||
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
|
||||
# (bindgen), Xvfb (X11 tests).
|
||||
run: |
|
||||
@@ -27,7 +28,7 @@ runs:
|
||||
"${sudo[@]}" apt-get update
|
||||
"${sudo[@]}" apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates cmake curl git jq pkg-config python3 \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
|
||||
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
|
||||
xvfb xauth
|
||||
|
||||
|
||||
+114
-7
@@ -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,13 +132,35 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- The view models, the app's state and the decisions of the settings pages and
|
||||
of the Stream Studio moved out of `voelin-ui` into a new crate,
|
||||
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
|
||||
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
|
||||
the Bridge writes and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Nothing changes on screen. See
|
||||
docs/ui.md, "Two crates".
|
||||
- The desktop portals (screen capture and camera through PipeWire, the push to
|
||||
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
|
||||
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
|
||||
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
|
||||
have both. Every D-Bus connection of the apps, the desktop notifications'
|
||||
included, now runs on an I/O thread of its own, whichever part of the app
|
||||
asks first.
|
||||
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
|
||||
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
|
||||
front end, which is being built, depends on a library that calls a function
|
||||
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
|
||||
builds from `rust:1.95-bookworm`.
|
||||
- The key store now keeps the device key when signing out of an account,
|
||||
unbound, whether it was in use before the account or was made for it; "Forget
|
||||
this device's identity" is the only way a key is deleted. The identity store
|
||||
also reports a damaged TeamSpeak identity by the kind of damage and never
|
||||
repeats its key in an error. Nothing changes on screen yet: accounts and
|
||||
sign-in are later steps.
|
||||
- The view models, the app's state, the state change of every engine event and
|
||||
the decisions of the settings pages, the Stream Studio, the streams, the chat,
|
||||
the servers, the audio settings page, the friends and the development
|
||||
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
|
||||
depends on no UI toolkit (a second front end can use it); `voelin-ui`
|
||||
converts its plain rows into Slint's and keeps the window, the Bridge writes
|
||||
and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Two things change on screen: the chat of
|
||||
a server that is gone takes the colour of its title instead of opaque
|
||||
black, and a cached avatar file cut after a valid header shows the
|
||||
initials instead of a broken picture. See docs/ui.md, "Two crates".
|
||||
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
|
||||
key, the signed-in account) with the account each belongs to, as a
|
||||
`voelin-identity` key store, in two database migrations. Existing
|
||||
@@ -183,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
|
||||
|
||||
|
||||
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
|
||||
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
|
||||
project's own crates (`scripts/own-crates.sh`) green.
|
||||
|
||||
Two front ends run on one engine until the second reaches parity:
|
||||
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
|
||||
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
|
||||
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
|
||||
view models and the state, with no UI toolkit (`docs/ui.md`).
|
||||
|
||||
## Hosting: Gitea, not GitHub
|
||||
|
||||
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
|
||||
|
||||
Generated
+3683
-143
File diff suppressed because it is too large.
Load diff
+18
-7
@@ -15,6 +15,7 @@ members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
@@ -36,6 +37,7 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
@@ -48,7 +50,7 @@ default-members = [
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
rust-version = "1.95"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Faumaray/Voelin"
|
||||
publish = false
|
||||
@@ -57,14 +59,23 @@ publish = false
|
||||
# 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 commit until the protocol tags a release:
|
||||
# the three crates below are at one revision (main c8e0e5a: the account-bound
|
||||
# KeyStore of Phase 2 task 28, the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# 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", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
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", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
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.
|
||||
|
||||
@@ -48,6 +48,11 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
|
||||
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
|
||||
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
|
||||
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
|
||||
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
|
||||
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
|
||||
([docs/ui.md](docs/ui.md), "The GPUI front end")
|
||||
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
|
||||
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
|
||||
clients through a TS6 server
|
||||
@@ -79,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
|
||||
```sh
|
||||
# Desktop app
|
||||
cargo run -p voelin-ui --bin voelin
|
||||
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
|
||||
cargo run -p voelin-gpui --release
|
||||
|
||||
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
|
||||
docker compose -f dev/docker-compose.yml up -d
|
||||
|
||||
+3261
-45
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,13 @@ archive in crates/voelin-ui-vm):
|
||||
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
|
||||
Contributors, under the ISC License; the icons derived from Feather are
|
||||
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
|
||||
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
|
||||
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
|
||||
client's own set above), Copyright (c) Lucide Icons and Contributors, under
|
||||
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
|
||||
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
|
||||
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
|
||||
the crates).
|
||||
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
|
||||
contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
|
||||
|
||||
@@ -23,6 +23,10 @@ accepted = [
|
||||
"LicenseRef-Slint-Royalty-free-2.0",
|
||||
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
|
||||
"bzip2-1.0.6",
|
||||
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
|
||||
# (notify 8, tiny-keccak); see deny.toml.
|
||||
"0BSD",
|
||||
"CC0-1.0",
|
||||
]
|
||||
|
||||
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
|
||||
|
||||
@@ -313,7 +313,7 @@ async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
}
|
||||
let report = conformance::run(&through_the_registry).await;
|
||||
assert_eq!(report.cases.len(), conformance::CASES.len());
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
|
||||
assert_eq!(report.cases.len(), 17, "the suite of v0.2.0 has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
|
||||
@@ -1962,20 +1962,38 @@ async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() {
|
||||
const CHANNELS: u64 = 5_000;
|
||||
let (conns, mut seen) = mpsc::unbounded_channel();
|
||||
let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]);
|
||||
let (mut params, _media) = connect_params("ts3server://fake.test?port=9987");
|
||||
let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987");
|
||||
params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() };
|
||||
params.push_capacity = 1;
|
||||
let connecting = tokio::spawn(connector.connect(params));
|
||||
let inner = within("the link to be asked", seen.recv()).await;
|
||||
inner.events.send(connected(everything())).unwrap();
|
||||
// Made before the link is told it is connected: the connector waits only
|
||||
// 250 ms for the first snapshot, and making 5,000 channels can take longer
|
||||
// than that on a busy machine, which left the session without them.
|
||||
let mut big = presence();
|
||||
for id in 100..100 + CHANNELS {
|
||||
let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() };
|
||||
big.channels.insert(id, channel);
|
||||
}
|
||||
inner.events.send(connected(everything())).unwrap();
|
||||
inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap();
|
||||
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
|
||||
let (session, mut pushes) = (connected.session, connected.pushes);
|
||||
// The scope is sent whole only if the presence is in the host's state when
|
||||
// it is asked for. The link takes its events in order, and a voice packet
|
||||
// of one of the presence's clients comes through only once the presence
|
||||
// is in: the packet says it is.
|
||||
inner
|
||||
.events
|
||||
.send(LinkEvent::Audio(VoicePacket {
|
||||
talker: TalkerId(8),
|
||||
seq: 1,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: OPUS_20_MS.to_vec(),
|
||||
}))
|
||||
.unwrap();
|
||||
within("the voice", media.recv()).await;
|
||||
|
||||
let server = ScopeId::Server(1);
|
||||
session.request(subscribe(server)).await.unwrap();
|
||||
@@ -2184,12 +2202,48 @@ async fn event_of<T>(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Asks for the file list of the lobby until the answer is one `wanted` takes,
|
||||
/// one question at a time: the next goes out only when the last is answered.
|
||||
/// Asked every few milliseconds instead, the answers fell behind the 16
|
||||
/// events the bus holds (and the host's work), and the one that counted was
|
||||
/// lost in the backlog.
|
||||
async fn ask_files_until(
|
||||
cmd_tx: &mpsc::UnboundedSender<LinkCmd>,
|
||||
bus: &mut broadcast::Receiver<Event>,
|
||||
request: &mut crate::files::RequestId,
|
||||
wanted: impl Fn(&Result<Vec<FileEntry>, String>) -> bool,
|
||||
) {
|
||||
within("the file list to be answered as wanted", async {
|
||||
loop {
|
||||
*request += 1;
|
||||
let dir = remote(10, None, "/");
|
||||
cmd_tx.send(LinkCmd::ListFiles { request: *request, dir }).ok()?;
|
||||
let result = loop {
|
||||
match bus.recv().await {
|
||||
Ok(Event::FileList { request: answered, result, .. })
|
||||
if answered == *request =>
|
||||
{
|
||||
break result;
|
||||
}
|
||||
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(broadcast::error::RecvError::Closed) => return None,
|
||||
}
|
||||
};
|
||||
if wanted(&result) {
|
||||
return Some(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `Server.features` narrows what the host offers (protocol 1.3,
|
||||
/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
|
||||
use v1::entity::Kind;
|
||||
use voelin_proto::test_util::{FakeConnector, eventually};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
|
||||
let connector = FakeConnector::new();
|
||||
let host = connector.host();
|
||||
@@ -2241,55 +2295,26 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let ask = |request| {
|
||||
let dir = remote(10, None, "/");
|
||||
cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap();
|
||||
};
|
||||
let refusal = "not offered by this server: files";
|
||||
let refused =
|
||||
|event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal);
|
||||
|result: &Result<Vec<FileEntry>, String>| matches!(result, Err(why) if why == refusal);
|
||||
let mut request = 0;
|
||||
|
||||
// Refused here: nothing reaches the host.
|
||||
ask(1);
|
||||
loop {
|
||||
let event = within("the refusal", async { bus.recv().await.ok() }).await;
|
||||
if refused(&event) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
|
||||
assert_eq!(file_lists(), 0);
|
||||
|
||||
// The server lifts its list (an empty one keeps all the host's): files work.
|
||||
put_server(&[]);
|
||||
let mut request = 1;
|
||||
eventually(WAIT, "a file list to reach the host", || {
|
||||
request += 1;
|
||||
ask(request);
|
||||
file_lists() > 0
|
||||
})
|
||||
.await;
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, |result| !refused(result)).await;
|
||||
assert!(file_lists() > 0, "the answer did not come from the host");
|
||||
|
||||
// The host narrows what it offers this user. A refusal counts only for a
|
||||
// request made after the update: the earlier ones were answered by the host's
|
||||
// wider set (or, before the server lifted its list, refused for that).
|
||||
// The host narrows what it offers this user. Every question is answered
|
||||
// before the next is asked, so those asked from here on are the ones the
|
||||
// update can refuse; the earlier ones were answered by the host's wider set.
|
||||
let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None };
|
||||
handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap();
|
||||
let after = request;
|
||||
within("the narrower set to apply", async {
|
||||
loop {
|
||||
request += 1;
|
||||
ask(request);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
while let Ok(event) = bus.try_recv() {
|
||||
if matches!(&event, Event::FileList { request, .. } if *request > after)
|
||||
&& refused(&event)
|
||||
{
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
|
||||
}
|
||||
|
||||
/// A port that is no port is refused in words, not dropped: the connection
|
||||
|
||||
+105
-37
@@ -3257,9 +3257,13 @@ impl LocalPreview {
|
||||
}
|
||||
|
||||
/// The first and last column of the rectangle in the middle row of a
|
||||
/// decoded test pattern. Checks that pixels further than two columns from
|
||||
/// its edges (which the codec blurs) have the colour of the rectangle or
|
||||
/// the background.
|
||||
/// decoded test pattern, after checking the row's structure: background, one
|
||||
/// run of the rectangle, background. A pixel is whichever of the pattern's two
|
||||
/// colours it is nearer to; it is not asked to be within some distance of one,
|
||||
/// because an encoder that falls behind lowers its quality (the VP8 speed
|
||||
/// control of the streamer does) and then moves a flat colour by 30 and more
|
||||
/// per channel, still nowhere near the other colour. The two columns at each
|
||||
/// edge, which the codec blurs, may be either.
|
||||
#[cfg(all(test, feature = "media-desktop"))]
|
||||
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
|
||||
@@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
let i = ((y * picture.width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
};
|
||||
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
|
||||
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
|
||||
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
|
||||
for x in 0..picture.width {
|
||||
if x + 2 < a || x > b + 2 {
|
||||
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
|
||||
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
|
||||
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
|
||||
}
|
||||
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
|
||||
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
|
||||
};
|
||||
let rectangle = |x: u32| {
|
||||
let p = pixel(x);
|
||||
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
|
||||
};
|
||||
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
|
||||
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
|
||||
// One run: everything between its ends, but the blurred edges, is the
|
||||
// rectangle's. Whatever is outside is the background by the choice of a and b.
|
||||
for x in a + 2..=b.saturating_sub(2) {
|
||||
assert!(
|
||||
rectangle(x),
|
||||
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
|
||||
pixel(x)
|
||||
);
|
||||
}
|
||||
(a, b)
|
||||
}
|
||||
@@ -3536,10 +3548,24 @@ 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);
|
||||
// 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) {
|
||||
@@ -3716,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
|
||||
@@ -4148,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) {
|
||||
@@ -4158,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
|
||||
@@ -4182,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);
|
||||
@@ -4226,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);
|
||||
}
|
||||
|
||||
@@ -1342,7 +1342,11 @@ mod tests {
|
||||
.await
|
||||
.expect("the layer did not change");
|
||||
sink.layer_format(0, format(9_000_000));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
// The stream task takes its commands in order: its answer to this one
|
||||
// (an error, nobody is viewer 65535) comes after all that the format
|
||||
// above set going, and nothing is left to wait out.
|
||||
handles[0].send(StreamCmd::Kick { viewer: u16::MAX });
|
||||
wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await;
|
||||
assert!(!keyframes(), "nothing changed");
|
||||
handles[0].send(StreamCmd::Stop);
|
||||
}
|
||||
|
||||
@@ -259,7 +259,8 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; every reader of that text refuses it through here.
|
||||
/// 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
|
||||
|
||||
@@ -333,7 +333,7 @@ enum Expect {
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
|
||||
/// Every case of the suite of the protocol repository at `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.
|
||||
///
|
||||
|
||||
@@ -1650,8 +1650,10 @@ mod account_tests {
|
||||
events,
|
||||
));
|
||||
let mut packet = [0; 2048];
|
||||
let (_, first) =
|
||||
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
|
||||
let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet))
|
||||
.await
|
||||
.expect("the first handshake packet within 5 s")
|
||||
.unwrap();
|
||||
// A logout/clear notification must cancel the old socket and restart.
|
||||
account.send_replace(None);
|
||||
let second = timeout(Duration::from_secs(5), async {
|
||||
@@ -1663,11 +1665,14 @@ mod account_tests {
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
.expect("a handshake packet from a new socket within 5 s of the account change");
|
||||
assert_ne!(first, second);
|
||||
// Losing the account authority fails closed immediately, not after connect timeout.
|
||||
drop(account);
|
||||
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
|
||||
timeout(Duration::from_secs(2), task)
|
||||
.await
|
||||
.expect("the connection to end within 2 s of the account source closing")
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
|
||||
);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! What more than one integration test of this crate needs (a test binary
|
||||
//! that uses it declares `mod common;`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
pub async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
@@ -24,6 +24,8 @@ use voelin_gateway_proto::{
|
||||
};
|
||||
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
|
||||
|
||||
mod common;
|
||||
|
||||
const LOBBY: ChatTarget = ChatTarget::Channel(1);
|
||||
const ME: &str = "me-uid";
|
||||
|
||||
@@ -529,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
|
||||
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
|
||||
history.flush();
|
||||
drop((engine, history));
|
||||
// Dropping the engine does not close the database yet (see `closed`).
|
||||
common::closed(&path).await;
|
||||
|
||||
// After a restart, with the gateway down: the stored page, found by the
|
||||
// gateway's URL, which is remembered with the server's id.
|
||||
@@ -812,7 +816,16 @@ async fn not_found_proxy() -> String {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
// A port that is taken and never listened on: connecting is refused at once,
|
||||
// and no other test of this process can be given it meanwhile (one that was
|
||||
// only free for a moment could be, the listeners of the others bind port 0).
|
||||
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
|
||||
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
|
||||
let closed = reserved.local_addr().unwrap().port();
|
||||
assert!(
|
||||
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
|
||||
"something listens on port {closed}"
|
||||
);
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Engine against the development servers (dev/docker-compose.yml).
|
||||
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::broadcast::Receiver;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_core::{
|
||||
@@ -15,6 +17,17 @@ fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
|
||||
/// unsets them there. While it does, whatever else connects to the server is
|
||||
/// told the addresses of those banners, and an engine fetches what it is told
|
||||
/// (as it should): the requests of such an engine reached the HTTP server of
|
||||
/// `ts6_banners`, which counts the requests of the engine under test, and the
|
||||
/// test failed on `disabled policy must prevent HTTP requests` in every run
|
||||
/// that had the tests of this file run side by side (as they do). The tests
|
||||
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
|
||||
/// runs with the server to itself, and the others before or after it.
|
||||
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
|
||||
|
||||
/// Wait for an event matching `f`, failing after 20 s.
|
||||
async fn wait_for(
|
||||
rx: &mut Receiver<Event>,
|
||||
@@ -131,6 +144,7 @@ async fn ts6_engine() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
|
||||
.await;
|
||||
}
|
||||
@@ -258,6 +272,7 @@ async fn ts6_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
|
||||
}
|
||||
|
||||
@@ -329,6 +344,7 @@ async fn ts6_banners() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.write().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let query_addr =
|
||||
@@ -512,6 +528,7 @@ async fn ts6_avatars() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
//! in the client database). The round trips against real servers are in
|
||||
//! `scripts/it-smoke.sh` (`voelinctl engine`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
@@ -11,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 {
|
||||
@@ -23,29 +26,6 @@ async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// 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).
|
||||
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");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_without_voice_fail_with_their_ids() {
|
||||
let engine = Engine::start();
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# -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 git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
# voelin-identity comes from the private VoelinProtocol repository, fetched
|
||||
@@ -17,13 +17,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends cmake git libas
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this, although this crate does not use
|
||||
# voelin-identity.
|
||||
# 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 . .
|
||||
# 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 build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
//! The swatch page: every colour token of the theme with its name and value,
|
||||
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
|
||||
//! from the second layer of the theme) and the client's icons, in the mode
|
||||
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
|
||||
//! of a theme change, and what the screenshots in docs/ui/ show.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::checkbox::Checkbox;
|
||||
use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::{
|
||||
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
|
||||
StatefulInteractiveElement as _, Styled as _, div, px, svg,
|
||||
};
|
||||
|
||||
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
|
||||
|
||||
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
|
||||
pub const GROUPS: [(&str, &[&str]); 6] = [
|
||||
(
|
||||
"Backgrounds",
|
||||
&[
|
||||
"bg-app",
|
||||
"bg-rail",
|
||||
"surface",
|
||||
"surface-2",
|
||||
"surface-3",
|
||||
"surface-4",
|
||||
"scrim",
|
||||
"scrim-light",
|
||||
"overlay",
|
||||
],
|
||||
),
|
||||
("Lines", &["border", "border-strong", "border-popup", "glow"]),
|
||||
(
|
||||
"Accent",
|
||||
&[
|
||||
"accent",
|
||||
"accent-hover",
|
||||
"accent-pressed",
|
||||
"accent-soft",
|
||||
"accent-soft-hover",
|
||||
"accent-text",
|
||||
"name-text",
|
||||
"on-accent",
|
||||
],
|
||||
),
|
||||
(
|
||||
"States",
|
||||
&[
|
||||
"live",
|
||||
"live-soft",
|
||||
"danger",
|
||||
"danger-soft",
|
||||
"success",
|
||||
"success-soft",
|
||||
"warning",
|
||||
"warning-soft",
|
||||
"idle",
|
||||
"dnd",
|
||||
"offline",
|
||||
"gold",
|
||||
"info",
|
||||
],
|
||||
),
|
||||
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
|
||||
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
|
||||
];
|
||||
|
||||
/// Icons shown, by the name of the client's file.
|
||||
const ICONS: [&str; 16] = [
|
||||
"mic.svg",
|
||||
"mic-off.svg",
|
||||
"headphones.svg",
|
||||
"volume-2.svg",
|
||||
"settings.svg",
|
||||
"search.svg",
|
||||
"bell.svg",
|
||||
"users.svg",
|
||||
"message-square.svg",
|
||||
"monitor-up.svg",
|
||||
"hash.svg",
|
||||
"lock.svg",
|
||||
"crown.svg",
|
||||
"plus.svg",
|
||||
"x.svg",
|
||||
"check.svg",
|
||||
];
|
||||
|
||||
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(theme.colors.text))
|
||||
.child(text.to_owned())
|
||||
}
|
||||
|
||||
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.w(px(100.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.child(
|
||||
div()
|
||||
.h(px(24.0))
|
||||
.rounded(px(m.radius_xs))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_strong))
|
||||
.bg(hsla(color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(name.to_owned()),
|
||||
)
|
||||
.child(
|
||||
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn colours(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
|
||||
let mut column = div().flex().flex_col().gap(px(m.space_4));
|
||||
for (group, names) in GROUPS {
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
|
||||
for name in names {
|
||||
row = row.child(chip(theme, name, by_name[name]));
|
||||
}
|
||||
column = column.child(
|
||||
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
|
||||
);
|
||||
}
|
||||
column
|
||||
}
|
||||
|
||||
fn radii(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().gap(px(m.space_4));
|
||||
for (name, radius) in [
|
||||
("xs", m.radius_xs),
|
||||
("sm", m.radius_sm),
|
||||
("md", m.radius_md),
|
||||
("lg", m.radius_lg),
|
||||
("xl", m.radius_xl),
|
||||
("pill", m.radius_pill),
|
||||
] {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.size(px(40.0))
|
||||
.rounded(px(radius))
|
||||
.bg(hsla(c.surface_4))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup)),
|
||||
)
|
||||
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
|
||||
}
|
||||
|
||||
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col().gap(px(m.space_1));
|
||||
for (name, space) in [
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.w(px(56.0))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(name),
|
||||
)
|
||||
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{space} px")),
|
||||
),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
|
||||
}
|
||||
|
||||
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col();
|
||||
for (name, size, weight) in [
|
||||
("font-3xl", m.font_3xl, FontWeight::BOLD),
|
||||
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
|
||||
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
|
||||
("font-lg", m.font_lg, FontWeight::MEDIUM),
|
||||
("font-md", m.font_md, FontWeight::MEDIUM),
|
||||
("font-body", m.font_body, FontWeight::NORMAL),
|
||||
("font-sm", m.font_sm, FontWeight::NORMAL),
|
||||
("font-xs", m.font_xs, FontWeight::NORMAL),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.text_size(px(size))
|
||||
.font_weight(weight)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("{name} {size}: Raid tonight at 21:00")),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
|
||||
}
|
||||
|
||||
fn components(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.gap(px(m.space_3))
|
||||
.child(Button::new("primary").primary().label("Primary"))
|
||||
.child(Button::new("secondary").label("Secondary"))
|
||||
.child(Button::new("danger").danger().label("Danger"))
|
||||
.child(Button::new("success").success().label("Success"))
|
||||
.child(Button::new("warning").warning().label("Warning"))
|
||||
.child(Button::new("info").info().label("Info")),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_5))
|
||||
.child(Switch::new("on").checked(true))
|
||||
.child(Switch::new("off").checked(false))
|
||||
.child(Checkbox::new("checked").checked(true).label("Checked"))
|
||||
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
|
||||
)
|
||||
}
|
||||
|
||||
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
|
||||
let [first, _, last] = b.stops;
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
|
||||
div()
|
||||
.h(px(36.0))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(b.to_gpui())
|
||||
.px(px(m.space_3))
|
||||
.py(px(m.space_2))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(format!(
|
||||
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
|
||||
b.angle,
|
||||
first.0,
|
||||
last.0,
|
||||
b.stops[1].0,
|
||||
(b.stops[1].1 * 100.0).round()
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn icons(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
|
||||
for name in ICONS {
|
||||
row = row.child(
|
||||
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
|
||||
);
|
||||
}
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
|
||||
.child(row)
|
||||
}
|
||||
|
||||
/// The page: the colours on the left, the rest on the right; it scrolls when
|
||||
/// the window is smaller than it.
|
||||
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.id("swatch")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_6))
|
||||
.bg(hsla(c.bg_app))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_baseline()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_2xl))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child("Voelin theme"),
|
||||
)
|
||||
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
|
||||
format!(
|
||||
"{} (setting {}), text size {}",
|
||||
if theme.is_dark() { "dark" } else { "light" },
|
||||
theme.choice().name(),
|
||||
m.font_scale
|
||||
),
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_8))
|
||||
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
|
||||
.child(
|
||||
div()
|
||||
.w(px(600.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.child(backdrop(theme))
|
||||
.child(radii(theme))
|
||||
.child(spacing(theme))
|
||||
.child(type_scale(theme))
|
||||
.child(components(theme))
|
||||
.child(icons(theme)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
use crate::assets::client_icon;
|
||||
use crate::theme::Palette;
|
||||
|
||||
#[test]
|
||||
fn every_colour_token_is_in_exactly_one_group() {
|
||||
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
|
||||
let unique: BTreeSet<&str> = shown.iter().copied().collect();
|
||||
assert_eq!(shown.len(), unique.len(), "a token in two groups");
|
||||
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(unique, tokens);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_icons_shown_are_the_clients() {
|
||||
for name in ICONS {
|
||||
assert!(client_icon(name).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! The second layer of the theme: the colours gpui-component's widgets read,
|
||||
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
|
||||
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
|
||||
//! for the list, one for the table, one for each kind of button); the
|
||||
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
|
||||
//! What has no counterpart stays as the registered theme of the mode has it
|
||||
//! (charts' bullish and bearish colours, the cyan and magenta of the base
|
||||
//! palette).
|
||||
//!
|
||||
//! gpui-component's "accent" is a hover background, not a brand colour: the
|
||||
//! client's `accent` is its `primary`.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use gpui_kit::component::ThemeColor;
|
||||
|
||||
use super::tokens::{Palette, Rgba};
|
||||
|
||||
/// A palette colour as GPUI's.
|
||||
pub fn hsla(color: Rgba) -> Hsla {
|
||||
gpui_kit::rgba(color.0).into()
|
||||
}
|
||||
|
||||
/// Of `base`, the colours a status button needs: hover, active, and a text
|
||||
/// that reads on it (white or the window's ink, whichever contrasts more).
|
||||
struct Status {
|
||||
base: Hsla,
|
||||
hover: Hsla,
|
||||
active: Hsla,
|
||||
foreground: Hsla,
|
||||
}
|
||||
|
||||
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
|
||||
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
|
||||
Status {
|
||||
base: hsla(base),
|
||||
hover: hsla(base.mix(toward_hover, 0.14)),
|
||||
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
|
||||
foreground: hsla(base.readable(ink)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the palette's colours into `colors`, over what the registered theme
|
||||
/// of the mode left there. Every field that gpui-component's themes derive
|
||||
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
|
||||
/// too, so that none keeps the default theme's blue.
|
||||
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
|
||||
let c = colors;
|
||||
let h = hsla;
|
||||
let clear = Hsla::transparent_black();
|
||||
|
||||
// The window and its text.
|
||||
c.background = h(p.bg_app);
|
||||
c.foreground = h(p.text);
|
||||
c.border = h(p.border);
|
||||
c.input = h(p.border_strong);
|
||||
c.ring = h(p.glow);
|
||||
c.overlay = h(p.scrim);
|
||||
c.window_border = h(p.border);
|
||||
c.caret = h(p.text);
|
||||
c.selection = h(p.accent_soft);
|
||||
c.drag_border = h(p.accent);
|
||||
c.drop_target = h(p.accent_soft);
|
||||
|
||||
// Links: one colour for all three states, as the client has one.
|
||||
c.link = h(p.accent_text);
|
||||
c.link_hover = h(p.accent_text);
|
||||
c.link_active = h(p.accent_text);
|
||||
|
||||
// The brand colour, and gpui-component's hover "accent".
|
||||
c.primary = h(p.accent);
|
||||
c.primary_hover = h(p.accent_hover);
|
||||
c.primary_active = h(p.accent_pressed);
|
||||
c.primary_foreground = h(p.on_accent);
|
||||
c.accent = h(p.surface_3);
|
||||
c.accent_foreground = h(p.text);
|
||||
|
||||
// Cards, inputs, menus, popovers.
|
||||
c.secondary = h(p.surface_2);
|
||||
c.secondary_hover = h(p.surface_3);
|
||||
c.secondary_active = h(p.surface_4);
|
||||
c.secondary_foreground = h(p.text);
|
||||
c.muted = h(p.surface_2);
|
||||
c.muted_foreground = h(p.text_muted);
|
||||
c.popover = h(p.surface_3);
|
||||
c.popover_foreground = h(p.text);
|
||||
c.group_box = h(p.surface_2);
|
||||
c.group_box_foreground = h(p.text);
|
||||
c.accordion = h(p.surface_2);
|
||||
c.description_list_label = h(p.surface_2);
|
||||
c.description_list_label_foreground = h(p.text_secondary);
|
||||
|
||||
// The status colours, with the text that reads on each.
|
||||
let [danger, success, warning, info] =
|
||||
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
|
||||
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
|
||||
(danger.base, danger.hover, danger.active, danger.foreground);
|
||||
(c.success, c.success_hover, c.success_active, c.success_foreground) =
|
||||
(success.base, success.hover, success.active, success.foreground);
|
||||
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
|
||||
(warning.base, warning.hover, warning.active, warning.foreground);
|
||||
(c.info, c.info_hover, c.info_active, c.info_foreground) =
|
||||
(info.base, info.hover, info.active, info.foreground);
|
||||
|
||||
// Lists and tables: rows on the panel, hovered rows raised, the selected
|
||||
// row the soft accent with the accent's edge.
|
||||
c.list = h(p.surface);
|
||||
c.list_hover = h(p.surface_3);
|
||||
c.list_active = h(p.accent_soft);
|
||||
c.list_active_border = h(p.accent);
|
||||
c.list_even = h(p.surface);
|
||||
c.list_head = h(p.surface_2);
|
||||
c.table = h(p.surface);
|
||||
c.table_hover = h(p.surface_3);
|
||||
c.table_active = h(p.accent_soft);
|
||||
c.table_active_border = h(p.accent);
|
||||
c.table_even = h(p.surface);
|
||||
c.table_head = h(p.surface_2);
|
||||
c.table_head_foreground = h(p.text_secondary);
|
||||
c.table_foot = h(p.surface_2);
|
||||
c.table_foot_foreground = h(p.text_secondary);
|
||||
c.table_row_border = h(p.border);
|
||||
|
||||
// The panels around the content: the sidebar, the title and status bars.
|
||||
c.sidebar = h(p.surface);
|
||||
c.sidebar_foreground = h(p.text);
|
||||
c.sidebar_border = h(p.border);
|
||||
c.sidebar_accent = h(p.surface_3);
|
||||
c.sidebar_accent_foreground = h(p.text);
|
||||
c.sidebar_primary = h(p.accent);
|
||||
c.sidebar_primary_foreground = h(p.on_accent);
|
||||
c.title_bar = h(p.surface);
|
||||
c.title_bar_border = h(p.border);
|
||||
c.status_bar = h(p.surface);
|
||||
c.status_bar_border = h(p.border);
|
||||
|
||||
// Small widgets.
|
||||
c.scrollbar = clear;
|
||||
c.scrollbar_thumb = h(p.border_strong);
|
||||
c.scrollbar_thumb_hover = h(p.text_muted);
|
||||
c.slider_bar = h(p.accent);
|
||||
c.slider_thumb = h(p.on_accent);
|
||||
c.switch = h(p.surface_4);
|
||||
c.switch_thumb = h(p.on_accent);
|
||||
c.progress_bar = h(p.accent);
|
||||
c.skeleton = h(p.surface_3);
|
||||
c.tab = clear;
|
||||
c.tab_active = h(p.surface_2);
|
||||
c.tab_active_foreground = h(p.text);
|
||||
c.tab_bar = h(p.surface);
|
||||
c.tab_bar_segmented = h(p.surface_2);
|
||||
c.tab_foreground = h(p.text_secondary);
|
||||
|
||||
// The base palette and the charts: the client's state colours.
|
||||
c.red = h(p.danger);
|
||||
c.red_light = h(p.danger_soft);
|
||||
c.green = h(p.success);
|
||||
c.green_light = h(p.success_soft);
|
||||
c.yellow = h(p.warning);
|
||||
c.yellow_light = h(p.warning_soft);
|
||||
c.blue = h(p.info);
|
||||
c.blue_light = h(p.accent_soft);
|
||||
c.chart_1 = h(p.accent);
|
||||
c.chart_2 = h(p.success);
|
||||
c.chart_3 = h(p.warning);
|
||||
c.chart_4 = h(p.danger);
|
||||
c.chart_5 = h(p.info);
|
||||
|
||||
// The buttons: what a theme file leaves out they take from the colours
|
||||
// above, so they are written from them here.
|
||||
c.button = c.secondary;
|
||||
c.button_hover = c.secondary_hover;
|
||||
c.button_active = c.secondary_active;
|
||||
c.button_foreground = c.secondary_foreground;
|
||||
c.button_primary = c.primary;
|
||||
c.button_primary_hover = c.primary_hover;
|
||||
c.button_primary_active = c.primary_active;
|
||||
c.button_primary_foreground = c.primary_foreground;
|
||||
c.button_secondary = c.secondary;
|
||||
c.button_secondary_hover = c.secondary_hover;
|
||||
c.button_secondary_active = c.secondary_active;
|
||||
c.button_secondary_foreground = c.secondary_foreground;
|
||||
c.button_danger = c.danger;
|
||||
c.button_danger_hover = c.danger_hover;
|
||||
c.button_danger_active = c.danger_active;
|
||||
c.button_danger_foreground = c.danger_foreground;
|
||||
c.button_success = c.success;
|
||||
c.button_success_hover = c.success_hover;
|
||||
c.button_success_active = c.success_active;
|
||||
c.button_success_foreground = c.success_foreground;
|
||||
c.button_warning = c.warning;
|
||||
c.button_warning_hover = c.warning_hover;
|
||||
c.button_warning_active = c.warning_active;
|
||||
c.button_warning_foreground = c.warning_foreground;
|
||||
c.button_info = c.info;
|
||||
c.button_info_hover = c.info_hover;
|
||||
c.button_info_active = c.info_active;
|
||||
c.button_info_foreground = c.info_foreground;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn written(dark: bool) -> (Palette, ThemeColor) {
|
||||
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
|
||||
let mut colors = ThemeColor::default();
|
||||
write(&palette, dark, &mut colors);
|
||||
(palette, colors)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_tokens_land_where_the_table_says() {
|
||||
for dark in [true, false] {
|
||||
let (p, c) = written(dark);
|
||||
assert_eq!(c.background, hsla(p.bg_app));
|
||||
assert_eq!(c.foreground, hsla(p.text));
|
||||
assert_eq!(c.primary, hsla(p.accent));
|
||||
assert_eq!(c.primary_hover, hsla(p.accent_hover));
|
||||
assert_eq!(c.primary_active, hsla(p.accent_pressed));
|
||||
assert_eq!(c.primary_foreground, hsla(p.on_accent));
|
||||
assert_eq!(
|
||||
c.accent,
|
||||
hsla(p.surface_3),
|
||||
"gpui-component's accent is a hover background"
|
||||
);
|
||||
assert_eq!(c.secondary, hsla(p.surface_2));
|
||||
assert_eq!(c.secondary_active, hsla(p.surface_4));
|
||||
assert_eq!(c.border, hsla(p.border));
|
||||
assert_eq!(c.input, hsla(p.border_strong));
|
||||
assert_eq!(c.ring, hsla(p.glow));
|
||||
assert_eq!(c.overlay, hsla(p.scrim));
|
||||
assert_eq!(c.list_active, hsla(p.accent_soft));
|
||||
assert_eq!(c.link, hsla(p.accent_text));
|
||||
assert_eq!(c.muted_foreground, hsla(p.text_muted));
|
||||
assert_eq!(c.sidebar, hsla(p.surface));
|
||||
assert_eq!(c.danger, hsla(p.danger));
|
||||
assert_eq!(c.success, hsla(p.success));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_buttons_follow_the_colours_they_fall_back_to() {
|
||||
let (_, c) = written(true);
|
||||
assert_eq!(c.button_primary, c.primary);
|
||||
assert_eq!(c.button_primary_hover, c.primary_hover);
|
||||
assert_eq!(c.button_danger_foreground, c.danger_foreground);
|
||||
assert_eq!(c.button, c.secondary);
|
||||
assert_eq!(c.button_info_active, c.info_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
|
||||
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
|
||||
for base in [p.danger, p.success, p.warning, p.info] {
|
||||
let s = status(base, p.bg_app, dark);
|
||||
let chosen = base.readable(p.bg_app);
|
||||
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
|
||||
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
|
||||
assert_eq!(s.foreground, hsla(chosen));
|
||||
assert_ne!(s.hover, s.base);
|
||||
assert_ne!(s.active, s.base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixing_and_contrast_do_what_they_say() {
|
||||
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
|
||||
assert_eq!(black.mix(white, 0.0), black);
|
||||
assert_eq!(black.mix(white, 1.0), white);
|
||||
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
|
||||
assert!((black.contrast(white) - 21.0).abs() < 0.01);
|
||||
assert_eq!(black.readable(black), white);
|
||||
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
|
||||
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
|
||||
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
|
||||
//!
|
||||
//! 1. [`VoelinTheme`], a GPUI global with every token of
|
||||
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
|
||||
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
|
||||
//! elements (the server rail, presence dots, meters, the backdrop) read it.
|
||||
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
|
||||
//! menus, dialogs) read, written from the first on every change
|
||||
//! ([`components`]), so that they look like ours.
|
||||
//!
|
||||
//! The mode is the client's `ui.theme`: `system` follows the window's
|
||||
//! appearance (and its changes), `light` and `dark` do not.
|
||||
|
||||
mod components;
|
||||
#[cfg(test)]
|
||||
mod slint_parity;
|
||||
pub mod tokens;
|
||||
|
||||
pub use components::hsla;
|
||||
use gpui_kit::component::{Theme, ThemeMode};
|
||||
use gpui_kit::{App, Background, Global, WindowAppearance, linear_color_stop, linear_gradient, px};
|
||||
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
impl Backdrop {
|
||||
/// What GPUI draws: its gradient has two colour stops, so the first and the
|
||||
/// last of the three; the middle one is not drawn.
|
||||
pub fn to_gpui(&self) -> Background {
|
||||
let [first, _, last] = self.stops;
|
||||
linear_gradient(
|
||||
self.angle,
|
||||
linear_color_stop(hsla(first.0), first.1),
|
||||
linear_color_stop(hsla(last.0), last.1),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode setting (`ui.theme` of the Slint front end).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Choice {
|
||||
/// Follow the window's appearance.
|
||||
System,
|
||||
/// Always light.
|
||||
Light,
|
||||
/// Always dark.
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
/// `system`, `light` or `dark`.
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text {
|
||||
"system" => Some(Self::System),
|
||||
"light" => Some(Self::Light),
|
||||
"dark" => Some(Self::Dark),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The setting's value.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the theme is dark, given whether the window's appearance is.
|
||||
pub fn resolve(self, system_dark: bool) -> bool {
|
||||
match self {
|
||||
Self::System => system_dark,
|
||||
Self::Light => false,
|
||||
Self::Dark => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a window's appearance is a dark one.
|
||||
pub fn is_dark(appearance: WindowAppearance) -> bool {
|
||||
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
|
||||
}
|
||||
|
||||
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
|
||||
/// global.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoelinTheme {
|
||||
choice: Choice,
|
||||
dark: bool,
|
||||
/// The colours of the resolved mode.
|
||||
pub colors: Palette,
|
||||
/// The window's backdrop gradient of the resolved mode.
|
||||
pub backdrop: Backdrop,
|
||||
/// The sizes, radii, type and durations at the text size factor.
|
||||
pub metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Global for VoelinTheme {}
|
||||
|
||||
impl VoelinTheme {
|
||||
/// The tokens for a mode (resolved against `system_dark`) and a text size
|
||||
/// factor.
|
||||
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
|
||||
let dark = choice.resolve(system_dark);
|
||||
Self {
|
||||
choice,
|
||||
dark,
|
||||
colors: if dark { Palette::DARK } else { Palette::LIGHT },
|
||||
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
|
||||
metrics: Metrics::new(font_scale),
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode that was set.
|
||||
pub fn choice(&self) -> Choice {
|
||||
self.choice
|
||||
}
|
||||
|
||||
/// Whether the colours are the dark ones.
|
||||
pub fn is_dark(&self) -> bool {
|
||||
self.dark
|
||||
}
|
||||
|
||||
/// Install the theme as the global and write it into gpui-component, which
|
||||
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
|
||||
/// the system's before there is a window).
|
||||
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The theme global.
|
||||
pub fn global(cx: &App) -> &Self {
|
||||
cx.global::<Self>()
|
||||
}
|
||||
|
||||
/// Change the mode (a setting changed), given the window's appearance now.
|
||||
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
|
||||
let (scale, current) = {
|
||||
let this = Self::global(cx);
|
||||
(this.metrics.font_scale, this.choice)
|
||||
};
|
||||
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
|
||||
return;
|
||||
}
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The window's appearance changed; it matters only in `system` mode.
|
||||
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
|
||||
let this = Self::global(cx);
|
||||
if this.choice == Choice::System && this.dark != is_dark(appearance) {
|
||||
let (choice, scale) = (this.choice, this.metrics.font_scale);
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text size factor changed (`ui.font_scale`).
|
||||
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
|
||||
let this = Self::global(cx);
|
||||
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
|
||||
return;
|
||||
}
|
||||
// `dark` is what the mode resolved to: for every mode, resolving it again
|
||||
// against it gives the same.
|
||||
let (choice, dark) = (this.choice, this.dark);
|
||||
cx.set_global(Self::new(choice, dark, font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// Write the global into gpui-component's theme: the mode, the colours of
|
||||
/// the second layer, the font, the base size and the radii.
|
||||
fn apply(cx: &mut App) {
|
||||
let this = Self::global(cx).clone();
|
||||
// The registered theme of the mode first (it sets whatever the second
|
||||
// layer leaves alone), then our colours over it in a second update, as
|
||||
// `Theme::update` says a mode change must be.
|
||||
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
|
||||
Theme::update(cx, |theme| {
|
||||
components::write(&this.colors, this.dark, &mut theme.colors);
|
||||
theme.font_family = FONT_FAMILY.into();
|
||||
theme.font_size = px(this.metrics.font_body);
|
||||
theme.radius = px(this.metrics.radius_sm);
|
||||
theme.radius_lg = px(this.metrics.radius_lg);
|
||||
});
|
||||
// Where the platform draws the window's frame itself (macOS), it follows
|
||||
// the mode; elsewhere this does nothing.
|
||||
cx.set_window_appearance(match this.choice {
|
||||
Choice::System => None,
|
||||
Choice::Light => Some(WindowAppearance::Light),
|
||||
Choice::Dark => Some(WindowAppearance::Dark),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::component::ActiveTheme as _;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
|
||||
cx.update(|cx| {
|
||||
gpui_kit::init(cx);
|
||||
VoelinTheme::init(cx, choice, appearance, 1.0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mode_resolves_against_the_window() {
|
||||
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
|
||||
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
|
||||
for choice in [Choice::System, Choice::Light, Choice::Dark] {
|
||||
assert_eq!(Choice::parse(choice.name()), Some(choice));
|
||||
}
|
||||
assert_eq!(Choice::parse("blue"), None);
|
||||
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_draws_the_first_and_the_last_of_its_three_stops() {
|
||||
let b = Backdrop::DARK;
|
||||
let [first, middle, last] = b.stops;
|
||||
assert_eq!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(last.0), 1.0)
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(middle.0), 1.0)
|
||||
),
|
||||
"the middle stop is not the end one"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Light);
|
||||
cx.update(|cx| {
|
||||
let theme = cx.theme();
|
||||
assert!(theme.is_dark());
|
||||
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
|
||||
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.font_family.as_ref(), "Inter");
|
||||
assert_eq!(theme.font_size, px(14.0));
|
||||
assert_eq!(theme.radius, px(6.0));
|
||||
assert_eq!(theme.radius_lg, px(12.0));
|
||||
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
|
||||
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::System, WindowAppearance::Light);
|
||||
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Dark);
|
||||
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
|
||||
cx.update(|cx| {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
assert!(theme.is_dark(), "the mode stays");
|
||||
assert_eq!(theme.metrics.font_body, 17.5);
|
||||
assert_eq!(theme.metrics.control_height, 45.0);
|
||||
assert_eq!(cx.theme().font_size, px(17.5));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
|
||||
//! read and every token in it is compared with the Rust value of the same
|
||||
//! name, light and dark and at four text sizes; a token on one side only, a
|
||||
//! value that differs, or a declaration of a kind this test does not know
|
||||
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
|
||||
//! `font-family`) fails it. While both front ends live, a token changed in
|
||||
//! one place and not the other is caught here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
|
||||
|
||||
/// What `theme.slint` declares: the kind and the expression of each property
|
||||
/// of the `Theme` global, in file order.
|
||||
fn declarations() -> Vec<(String, String, String)> {
|
||||
declarations_of(SLINT)
|
||||
}
|
||||
|
||||
/// The same for the text of a `.slint` file (the tests below also read
|
||||
/// altered copies of `theme.slint`).
|
||||
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
|
||||
let without_comments: String = source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
|
||||
let mut found = Vec::new();
|
||||
for statement in body.split(';') {
|
||||
let statement = statement.trim();
|
||||
let Some(rest) = ["in-out property", "out property", "in property"]
|
||||
.iter()
|
||||
.find_map(|prefix| statement.strip_prefix(prefix))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (kind, rest) =
|
||||
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
|
||||
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
|
||||
// One line, single spaces: `backdrop` is written over several.
|
||||
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `#rgb`-style literal as `Rgba`.
|
||||
fn colour(text: &str) -> Rgba {
|
||||
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
|
||||
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
|
||||
match hex.len() {
|
||||
6 => Rgba(value << 8 | 0xff),
|
||||
8 => Rgba(value),
|
||||
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
|
||||
fn by_mode(expr: &str) -> (String, String) {
|
||||
let Some(rest) = expr.strip_prefix("dark ?") else {
|
||||
return (expr.to_owned(), expr.to_owned());
|
||||
};
|
||||
let mut depth = 0;
|
||||
for (i, c) in rest.char_indices() {
|
||||
match c {
|
||||
'(' => depth += 1,
|
||||
')' => depth -= 1,
|
||||
':' if depth == 0 => {
|
||||
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("no `:` in {expr:?}");
|
||||
}
|
||||
|
||||
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
|
||||
/// `*`, `+`, `max(a, b)` and parentheses.
|
||||
struct Eval<'a> {
|
||||
tokens: Vec<String>,
|
||||
at: usize,
|
||||
env: &'a BTreeMap<String, String>,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl<'a> Eval<'a> {
|
||||
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
|
||||
let mut tokens = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in expr.chars() {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
|
||||
word.push(c);
|
||||
} else {
|
||||
if !word.is_empty() {
|
||||
tokens.push(std::mem::take(&mut word));
|
||||
}
|
||||
if !c.is_whitespace() {
|
||||
tokens.push(c.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
tokens.push(word);
|
||||
}
|
||||
let mut eval = Eval { tokens, at: 0, env, scale };
|
||||
let value = eval.sum();
|
||||
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
|
||||
value
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<&str> {
|
||||
self.tokens.get(self.at).map(String::as_str)
|
||||
}
|
||||
|
||||
fn take(&mut self) -> String {
|
||||
self.at += 1;
|
||||
self.tokens[self.at - 1].clone()
|
||||
}
|
||||
|
||||
fn sum(&mut self) -> f64 {
|
||||
let mut value = self.product();
|
||||
while self.peek() == Some("+") {
|
||||
self.take();
|
||||
value += self.product();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn product(&mut self) -> f64 {
|
||||
let mut value = self.factor();
|
||||
while self.peek() == Some("*") {
|
||||
self.take();
|
||||
value *= self.factor();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn factor(&mut self) -> f64 {
|
||||
let token = self.take();
|
||||
if token == "(" {
|
||||
let value = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return value;
|
||||
}
|
||||
if token == "max" {
|
||||
assert_eq!(self.take(), "(");
|
||||
let a = self.sum();
|
||||
assert_eq!(self.take(), ",");
|
||||
let b = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return a.max(b);
|
||||
}
|
||||
if token == "font-scale" {
|
||||
return self.scale;
|
||||
}
|
||||
if token.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
let number: String =
|
||||
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
|
||||
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
|
||||
}
|
||||
let expr =
|
||||
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
|
||||
Eval::run(&expr, self.env, self.scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names `theme.slint` declares that are state, not tokens: the mode and
|
||||
/// what it resolves to, and the text size factor (the factor is a parameter
|
||||
/// of [`Metrics`]).
|
||||
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
|
||||
|
||||
#[test]
|
||||
fn every_colour_is_the_same_in_both_files() {
|
||||
let slint: Vec<(String, String, String)> =
|
||||
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
|
||||
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
|
||||
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
|
||||
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &slint {
|
||||
let (d, l) = by_mode(expr);
|
||||
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
|
||||
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let ours: BTreeSet<&str> = dark.keys().copied().collect();
|
||||
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_length_weight_and_duration_is_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let env: BTreeMap<String, String> =
|
||||
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
|
||||
let numeric: Vec<&(String, String, String)> = all
|
||||
.iter()
|
||||
.filter(|(name, kind, _)| {
|
||||
matches!(kind.as_str(), "length" | "int" | "duration")
|
||||
&& !STATE.contains(&name.as_str())
|
||||
})
|
||||
.collect();
|
||||
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
|
||||
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
|
||||
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &numeric {
|
||||
let slint = Eval::run(expr, &env, f64::from(scale));
|
||||
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
|
||||
assert!(
|
||||
(slint - ours).abs() < 1e-3,
|
||||
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
|
||||
);
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let rust: BTreeSet<&str> = ours.keys().copied().collect();
|
||||
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let get = |name: &str| {
|
||||
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
|
||||
};
|
||||
let gradient = |text: &str| -> Backdrop {
|
||||
let inner = text
|
||||
.trim()
|
||||
.strip_prefix("@linear-gradient(")
|
||||
.and_then(|t| t.strip_suffix(')'))
|
||||
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
|
||||
let mut parts = inner.split(',').map(str::trim);
|
||||
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
|
||||
let stops: Vec<(Rgba, f32)> = parts
|
||||
.map(|stop| {
|
||||
let (colour_text, position) = stop.split_once(' ').unwrap();
|
||||
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
|
||||
(colour(colour_text), percent / 100.0)
|
||||
})
|
||||
.collect();
|
||||
Backdrop { angle, stops: stops.try_into().expect("three stops") }
|
||||
};
|
||||
let (dark, light) = by_mode(&get("backdrop"));
|
||||
assert_eq!(gradient(&dark), Backdrop::DARK);
|
||||
assert_eq!(gradient(&light), Backdrop::LIGHT);
|
||||
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
|
||||
}
|
||||
|
||||
/// What the declarations hold that no comparison above covers, one sentence
|
||||
/// each; empty when there is none: a kind of declaration this test does not
|
||||
/// know, a brush other than `backdrop` or a string other than `mode` and
|
||||
/// `font-family` (the two comparisons of those go by name, so a second one
|
||||
/// would pass unseen), a state name that is no longer declared.
|
||||
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
let kinds: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
|
||||
.map(|(_, kind, _)| kind.as_str())
|
||||
.collect();
|
||||
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
|
||||
if kinds != known {
|
||||
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
|
||||
}
|
||||
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
|
||||
let found: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(_, declared_kind, _)| declared_kind == kind)
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.collect();
|
||||
let expected: BTreeSet<&str> = expected.iter().copied().collect();
|
||||
for name in found.symmetric_difference(&expected) {
|
||||
problems.push(format!(
|
||||
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
for name in STATE {
|
||||
if !declared.iter().any(|(declared, _, _)| declared == name) {
|
||||
problems.push(format!("{name} is not declared"));
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_declares_nothing_this_test_does_not_know() {
|
||||
let problems = unknown_to_this_test(&declarations());
|
||||
assert!(problems.is_empty(), "{problems:#?}");
|
||||
}
|
||||
|
||||
/// `theme.slint` with one more declaration in its `Theme` global.
|
||||
fn with_declaration(declaration: &str) -> String {
|
||||
let opening = "export global Theme {";
|
||||
assert!(SLINT.contains(opening));
|
||||
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_brush_or_string_is_not_passed_unseen() {
|
||||
// Mutants of the Slint file: a token on one side only.
|
||||
for (declaration, name) in [
|
||||
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
|
||||
("out property <string> font-mono: \"Mono\";", "font-mono"),
|
||||
] {
|
||||
let mutant = declarations_of(&with_declaration(declaration));
|
||||
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
|
||||
let problems = unknown_to_this_test(&mutant);
|
||||
assert!(
|
||||
problems.iter().any(|problem| problem.contains(name)),
|
||||
"{name} goes unnoticed: {problems:#?}"
|
||||
);
|
||||
}
|
||||
// And the file as it is has neither.
|
||||
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
|
||||
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
|
||||
//! the original while the Slint front end lives; the test in
|
||||
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
|
||||
//! formula here differs from it, so the two cannot drift apart.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
|
||||
/// is opaque).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Rgba(pub u32);
|
||||
|
||||
impl fmt::Debug for Rgba {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Rgba {
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.alpha() == 255 {
|
||||
write!(f, "#{:06x}", self.0 >> 8)
|
||||
} else {
|
||||
write!(f, "#{:08x}", self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
/// Transparent black, for the widgets that draw nothing.
|
||||
pub const TRANSPARENT: Self = Self(0);
|
||||
|
||||
/// The opacity, 0 to 255.
|
||||
pub fn alpha(self) -> u8 {
|
||||
(self.0 & 0xff) as u8
|
||||
}
|
||||
|
||||
/// The same colour with another opacity.
|
||||
pub fn with_alpha(self, alpha: u8) -> Self {
|
||||
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
|
||||
}
|
||||
|
||||
/// The channels, 0 to 1.
|
||||
pub fn channels(self) -> [f32; 3] {
|
||||
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
|
||||
/// from `self`.
|
||||
pub fn mix(self, other: Self, amount: f32) -> Self {
|
||||
let (a, b) = (self.channels(), other.channels());
|
||||
let channel =
|
||||
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
|
||||
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
|
||||
}
|
||||
|
||||
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
|
||||
pub fn luminance(self) -> f32 {
|
||||
let [r, g, b] = self
|
||||
.channels()
|
||||
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
|
||||
pub fn contrast(self, other: Self) -> f32 {
|
||||
let (a, b) = (self.luminance(), other.luminance());
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05)
|
||||
}
|
||||
|
||||
/// Of white and `ink`, the one that reads better on `self`.
|
||||
pub fn readable(self, ink: Self) -> Self {
|
||||
let white = Self(0xffff_ffff);
|
||||
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! palette {
|
||||
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
|
||||
/// Every colour token of `theme.slint` for one mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Palette {
|
||||
$(
|
||||
#[doc = concat!("`", $name, "` of `theme.slint`.")]
|
||||
pub $field: Rgba,
|
||||
)*
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The dark palette.
|
||||
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
|
||||
/// The light palette.
|
||||
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
|
||||
|
||||
/// Every colour by the name it has in `theme.slint`, in its order.
|
||||
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
|
||||
vec![$(($name, self.$field),)*]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
palette! {
|
||||
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
|
||||
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
|
||||
surface "surface": 0x0b1330ff, 0xf7f9feff;
|
||||
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
|
||||
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
|
||||
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
|
||||
scrim "scrim": 0x02050fc0, 0x0b132b80;
|
||||
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
|
||||
overlay "overlay": 0x060a18c8, 0x0b1330b0;
|
||||
border "border": 0x1b2750ff, 0xd3dceeff;
|
||||
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
|
||||
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
|
||||
accent "accent": 0x2d6bffff, 0x2458e6ff;
|
||||
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
|
||||
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
|
||||
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
|
||||
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
|
||||
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
|
||||
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
|
||||
on_accent "on-accent": 0xffffffff, 0xffffffff;
|
||||
glow "glow": 0x3f7bff90, 0x2458e660;
|
||||
live "live": 0xff2d55ff, 0xe0203fff;
|
||||
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
|
||||
danger "danger": 0xff4d5eff, 0xd92c3cff;
|
||||
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
|
||||
success "success": 0x22d36bff, 0x16a557ff;
|
||||
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
|
||||
warning "warning": 0xf5b301ff, 0xb77f00ff;
|
||||
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
|
||||
idle "idle": 0xf5b301ff, 0xc98b00ff;
|
||||
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
|
||||
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
|
||||
gold "gold": 0xffc233ff, 0xd99a00ff;
|
||||
info "info": 0x3fb3ffff, 0x1180d6ff;
|
||||
text "text": 0xeef2ffff, 0x0e1733ff;
|
||||
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
|
||||
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
|
||||
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
|
||||
icon "icon": 0xb9c4e2ff, 0x43506fff;
|
||||
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
|
||||
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
|
||||
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
|
||||
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
|
||||
}
|
||||
|
||||
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
|
||||
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
|
||||
/// (`Backdrop::to_gpui`, in the theme module) is the first and the last; the
|
||||
/// middle one stays here for a front end that can use it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
|
||||
pub angle: f32,
|
||||
/// Three stops: colour and position (0 to 1).
|
||||
pub stops: [(Rgba, f32); 3],
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// The dark backdrop.
|
||||
pub const DARK: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
|
||||
};
|
||||
/// The light backdrop.
|
||||
pub const LIGHT: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
|
||||
};
|
||||
}
|
||||
|
||||
/// The family of the UI font (`font-family` of `theme.slint`).
|
||||
pub const FONT_FAMILY: &str = "Inter";
|
||||
|
||||
/// Every size, radius, weight and duration token of `theme.slint` for one
|
||||
/// text size factor: lengths in logical pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Metrics {
|
||||
/// `font-scale`: multiplies every type size and the sizes that follow text.
|
||||
pub font_scale: f32,
|
||||
/// `radius-xs`.
|
||||
pub radius_xs: f32,
|
||||
/// `radius-sm`.
|
||||
pub radius_sm: f32,
|
||||
/// `radius-md`.
|
||||
pub radius_md: f32,
|
||||
/// `radius-lg`.
|
||||
pub radius_lg: f32,
|
||||
/// `radius-xl`.
|
||||
pub radius_xl: f32,
|
||||
/// `radius-pill`.
|
||||
pub radius_pill: f32,
|
||||
/// `space-1`.
|
||||
pub space_1: f32,
|
||||
/// `space-2`.
|
||||
pub space_2: f32,
|
||||
/// `space-3`.
|
||||
pub space_3: f32,
|
||||
/// `space-4`.
|
||||
pub space_4: f32,
|
||||
/// `space-5`.
|
||||
pub space_5: f32,
|
||||
/// `space-6`.
|
||||
pub space_6: f32,
|
||||
/// `space-7`.
|
||||
pub space_7: f32,
|
||||
/// `space-8`.
|
||||
pub space_8: f32,
|
||||
/// `font-xs` (scaled).
|
||||
pub font_xs: f32,
|
||||
/// `font-sm` (scaled).
|
||||
pub font_sm: f32,
|
||||
/// `font-body` (scaled).
|
||||
pub font_body: f32,
|
||||
/// `font-md` (scaled).
|
||||
pub font_md: f32,
|
||||
/// `font-lg` (scaled).
|
||||
pub font_lg: f32,
|
||||
/// `font-xl` (scaled).
|
||||
pub font_xl: f32,
|
||||
/// `font-2xl` (scaled).
|
||||
pub font_2xl: f32,
|
||||
/// `font-3xl` (scaled).
|
||||
pub font_3xl: f32,
|
||||
/// `weight-regular`.
|
||||
pub weight_regular: u16,
|
||||
/// `weight-medium`.
|
||||
pub weight_medium: u16,
|
||||
/// `weight-semibold`.
|
||||
pub weight_semibold: u16,
|
||||
/// `weight-bold`.
|
||||
pub weight_bold: u16,
|
||||
/// `row-height` (scaled).
|
||||
pub row_height: f32,
|
||||
/// `control-height` (scaled).
|
||||
pub control_height: f32,
|
||||
/// `control-height-sm` (scaled).
|
||||
pub control_height_sm: f32,
|
||||
/// `icon-sm`.
|
||||
pub icon_sm: f32,
|
||||
/// `icon-md`.
|
||||
pub icon_md: f32,
|
||||
/// `icon-lg`.
|
||||
pub icon_lg: f32,
|
||||
/// `glow-width`: the ring around focused and selected items.
|
||||
pub glow_width: f32,
|
||||
/// `rail-width`.
|
||||
pub rail_width: f32,
|
||||
/// `sidebar-width`: 264 and more with large text.
|
||||
pub sidebar_width: f32,
|
||||
/// `topbar-height`: 44, taller when large text makes the controls taller.
|
||||
pub topbar_height: f32,
|
||||
/// `right-panel-min`.
|
||||
pub right_panel_min: f32,
|
||||
/// `fast`, in milliseconds.
|
||||
pub fast_ms: u32,
|
||||
/// `normal`, in milliseconds.
|
||||
pub normal_ms: u32,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
/// The tokens at a text size factor (1 is the default).
|
||||
pub fn new(font_scale: f32) -> Self {
|
||||
let s = font_scale;
|
||||
let control_height = 36.0 * s;
|
||||
let space_3 = 8.0;
|
||||
Self {
|
||||
font_scale,
|
||||
radius_xs: 4.0,
|
||||
radius_sm: 6.0,
|
||||
radius_md: 8.0,
|
||||
radius_lg: 12.0,
|
||||
radius_xl: 16.0,
|
||||
radius_pill: 999.0,
|
||||
space_1: 2.0,
|
||||
space_2: 4.0,
|
||||
space_3,
|
||||
space_4: 12.0,
|
||||
space_5: 16.0,
|
||||
space_6: 20.0,
|
||||
space_7: 24.0,
|
||||
space_8: 32.0,
|
||||
font_xs: 11.0 * s,
|
||||
font_sm: 12.0 * s,
|
||||
font_body: 14.0 * s,
|
||||
font_md: 15.0 * s,
|
||||
font_lg: 17.0 * s,
|
||||
font_xl: 20.0 * s,
|
||||
font_2xl: 24.0 * s,
|
||||
font_3xl: 30.0 * s,
|
||||
weight_regular: 400,
|
||||
weight_medium: 500,
|
||||
weight_semibold: 600,
|
||||
weight_bold: 700,
|
||||
row_height: 32.0 * s,
|
||||
control_height,
|
||||
control_height_sm: 28.0 * s,
|
||||
icon_sm: 16.0,
|
||||
icon_md: 20.0,
|
||||
icon_lg: 24.0,
|
||||
glow_width: 2.0,
|
||||
rail_width: 72.0,
|
||||
sidebar_width: 264.0 * s.max(1.0),
|
||||
topbar_height: 44.0_f32.max(control_height + space_3),
|
||||
right_panel_min: 220.0,
|
||||
fast_ms: 120,
|
||||
normal_ms: 200,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every number token by the name it has in `theme.slint`, in its order:
|
||||
/// lengths in pixels, weights as they are, durations in milliseconds.
|
||||
pub fn entries(&self) -> Vec<(&'static str, f64)> {
|
||||
let m = self;
|
||||
[
|
||||
("radius-xs", m.radius_xs),
|
||||
("radius-sm", m.radius_sm),
|
||||
("radius-md", m.radius_md),
|
||||
("radius-lg", m.radius_lg),
|
||||
("radius-xl", m.radius_xl),
|
||||
("radius-pill", m.radius_pill),
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
("font-xs", m.font_xs),
|
||||
("font-sm", m.font_sm),
|
||||
("font-body", m.font_body),
|
||||
("font-md", m.font_md),
|
||||
("font-lg", m.font_lg),
|
||||
("font-xl", m.font_xl),
|
||||
("font-2xl", m.font_2xl),
|
||||
("font-3xl", m.font_3xl),
|
||||
("row-height", m.row_height),
|
||||
("control-height", m.control_height),
|
||||
("control-height-sm", m.control_height_sm),
|
||||
("icon-sm", m.icon_sm),
|
||||
("icon-md", m.icon_md),
|
||||
("icon-lg", m.icon_lg),
|
||||
("glow-width", m.glow_width),
|
||||
("rail-width", m.rail_width),
|
||||
("sidebar-width", m.sidebar_width),
|
||||
("topbar-height", m.topbar_height),
|
||||
("right-panel-min", m.right_panel_min),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, f64::from(value)))
|
||||
.chain([
|
||||
("weight-regular", f64::from(m.weight_regular)),
|
||||
("weight-medium", f64::from(m.weight_medium)),
|
||||
("weight-semibold", f64::from(m.weight_semibold)),
|
||||
("weight-bold", f64::from(m.weight_bold)),
|
||||
("fast", f64::from(m.fast_ms)),
|
||||
("normal", f64::from(m.normal_ms)),
|
||||
])
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self::new(1.0)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,154 @@
|
||||
//! The binary's failure path, end to end: when the main window cannot be
|
||||
//! opened (no display server, no Vulkan or GL driver), `voelin-gpui` prints
|
||||
//! why and exits with status 1 instead of staying alive with no window and no
|
||||
//! message.
|
||||
//!
|
||||
//! It has to start the real binary. GPUI's Linux platform runs the launch
|
||||
//! callback before it starts its event loop, and the loop forgets a quit asked
|
||||
//! for before it started, so a failure handled by quitting inside the
|
||||
//! callback hung the process; the test platform of the unit tests has no such
|
||||
//! loop and cannot show it.
|
||||
//!
|
||||
//! The no-driver test needs a test X server in `VOELIN_X11_TEST_DISPLAY` (an
|
||||
//! Xvfb, as CI has; never the desktop's display) and is skipped without one.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Where the drivers are not: the Vulkan loader, EGL's vendor library
|
||||
/// directory and Mesa's driver directory all point here.
|
||||
const NOWHERE: &str = "/nonexistent-voelin-gpui-test";
|
||||
|
||||
/// Loaded machines are slow, so the wait is generous; a run that works takes a
|
||||
/// second or two.
|
||||
const WAIT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The scratch directory of one run, removed at the end.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// How a run of the binary went.
|
||||
enum Outcome {
|
||||
/// It ended, with this status and this much of the log.
|
||||
Ended(ExitStatus, String),
|
||||
/// It picked a GPU: the window can open, so nothing failed.
|
||||
Opened,
|
||||
/// It was still running after [`WAIT`] with no GPU picked.
|
||||
Hung(String),
|
||||
}
|
||||
|
||||
/// Run the binary with the drivers hidden (`hide_drivers`) on `display`
|
||||
/// (none: no display server at all) and wait for it to end, to pick a GPU or
|
||||
/// to run out of time. Nothing of the user's state, display or session bus is
|
||||
/// in its environment.
|
||||
fn run_binary(name: &str, display: Option<&str>, hide_drivers: bool) -> Outcome {
|
||||
let scratch = Scratch(
|
||||
Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())),
|
||||
);
|
||||
let home = scratch.0.join("home");
|
||||
let runtime = scratch.0.join("runtime");
|
||||
fs::create_dir_all(&runtime).unwrap();
|
||||
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let log = scratch.0.join("stderr.log");
|
||||
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_voelin-gpui"));
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("XDG_SESSION_TYPE")
|
||||
.env_remove("DBUS_SESSION_BUS_ADDRESS")
|
||||
.env_remove("RUST_LOG")
|
||||
.env("HOME", &home)
|
||||
.env("XDG_RUNTIME_DIR", &runtime)
|
||||
.env("XDG_CONFIG_HOME", home.join("config"))
|
||||
.env("XDG_DATA_HOME", home.join("data"))
|
||||
.env("XDG_STATE_HOME", home.join("state"))
|
||||
.env("XDG_CACHE_HOME", home.join("cache"))
|
||||
.env("VOELIN_DATA_DIR", home.join("voelin"))
|
||||
// The log line that tells a GPU was picked.
|
||||
.env("VOELIN_LOG", "warn,voelin_gpui=info,gpui_wgpu=info")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(fs::File::create(&log).unwrap());
|
||||
if let Some(display) = display {
|
||||
command.env("DISPLAY", display);
|
||||
}
|
||||
if hide_drivers {
|
||||
command
|
||||
.env("VK_DRIVER_FILES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("VK_ICD_FILENAMES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("__EGL_VENDOR_LIBRARY_DIRS", NOWHERE)
|
||||
.env("__EGL_VENDOR_LIBRARY_FILENAMES", format!("{NOWHERE}/egl.json"))
|
||||
.env("LIBGL_DRIVERS_PATH", NOWHERE);
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
|
||||
let deadline = Instant::now() + WAIT;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
return Outcome::Ended(status, fs::read_to_string(&log).unwrap_or_default());
|
||||
}
|
||||
let seen = fs::read_to_string(&log).unwrap_or_default();
|
||||
let outcome = if seen.contains("Selected GPU adapter") {
|
||||
Outcome::Opened
|
||||
} else if Instant::now() > deadline {
|
||||
Outcome::Hung(seen)
|
||||
} else {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
};
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_cannot_open_for_want_of_a_driver_ends_the_binary_with_an_error() {
|
||||
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
|
||||
else {
|
||||
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
|
||||
return;
|
||||
};
|
||||
match run_binary("no-driver", Some(&display), true) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => eprintln!(
|
||||
"skipped: this machine's driver was found in spite of the environment, \
|
||||
so the window can open"
|
||||
),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window and no GPU: a quit asked for in the \
|
||||
launch callback is lost\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_display_server_the_binary_ends_with_an_error() {
|
||||
match run_binary("no-display", None, false) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
assert!(seen.contains("no display"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => panic!("a GPU was picked without a display server"),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window: GPUI's headless platform keeps \
|
||||
the app alive\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,13 @@ tracing = "0.1.44"
|
||||
yuv = "0.8.19"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
|
||||
# `async-io`, not `tokio`: GPUI's Linux backend enables ashpd's `async-io`, ashpd
|
||||
# refuses both at once, and a front end holds the portals and GPUI in one binary.
|
||||
# zbus then runs every connection on an I/O thread of its own, whichever thread
|
||||
# builds it: no crate of the workspace turns zbus's `tokio` feature on (with it
|
||||
# zbus would pick tokio for a connection made inside a tokio runtime, and ashpd
|
||||
# shares one connection per process with every later caller).
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "async-io"], optional = true }
|
||||
memmap2 = { version = "0.9.11", optional = true }
|
||||
pipewire = { version = "0.10.1", optional = true }
|
||||
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
|
||||
|
||||
@@ -279,14 +279,14 @@ impl FrameSink for QueueSink {
|
||||
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
|
||||
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
|
||||
loop {
|
||||
match frames.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(frame) => {
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
let Some(frame) = frames.recv_timeout(Duration::from_millis(100)) else {
|
||||
if frames.is_closed() {
|
||||
break;
|
||||
}
|
||||
None if frames.is_closed() => break,
|
||||
None => {}
|
||||
continue;
|
||||
};
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
@@ -181,7 +181,9 @@ impl ScreenCapture for PortalCapture {
|
||||
}
|
||||
|
||||
/// Asks the user through the portal dialog (unless a restore token
|
||||
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
|
||||
/// applies). Any executor will do: ashpd runs on zbus's `async-io` in every
|
||||
/// binary of the workspace (no crate turns zbus's `tokio` feature on), whose
|
||||
/// connection has an I/O thread of its own, whichever thread builds it.
|
||||
fn start(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
|
||||
@@ -446,7 +446,7 @@ fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
|
||||
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
@@ -466,7 +466,7 @@ fn ldconfig(base: &str) -> Vec<PathBuf> {
|
||||
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -603,8 +603,8 @@ mod v4l2 {
|
||||
// Seconds per frame; a stepwise range starts with its smallest
|
||||
// interval, which is the highest rate.
|
||||
let (num, den) = (entry.interval[0], entry.interval[1]);
|
||||
if num > 0 {
|
||||
best = best.max(den / num);
|
||||
if let Some(rate) = den.checked_div(num) {
|
||||
best = best.max(rate);
|
||||
}
|
||||
if entry.type_ != FRMIVAL_DISCRETE {
|
||||
break;
|
||||
|
||||
@@ -1180,19 +1180,32 @@ mod tests {
|
||||
scenes
|
||||
}
|
||||
|
||||
/// The first preview frame that `wanted` takes. The preview keeps the latest
|
||||
/// frame only, so few older ones are waiting or on their way: the number of
|
||||
/// frames looked at is the bound (the work), and the wait for each, which a
|
||||
/// busy machine can stretch, only ends a hang.
|
||||
fn preview_until(
|
||||
preview: &Handoff<VideoFrame>,
|
||||
wanted: impl Fn(&VideoFrame) -> bool,
|
||||
) -> Arc<VideoFrame> {
|
||||
for _ in 0..20 {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
|
||||
if wanted(&frame) {
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
panic!("the preview never showed what was asked for");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_composes_into_the_preview_and_follows_commands() {
|
||||
let studio = Studio::start(one_colour_scene()).await.unwrap();
|
||||
let preview = studio.preview();
|
||||
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
|
||||
let started = Instant::now();
|
||||
let frame = loop {
|
||||
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
|
||||
};
|
||||
assert_eq!((frame.width, frame.height), (32, 24));
|
||||
// The studio composes from the moment it starts, at the size and rate the
|
||||
// preview has then (480x270, 15 fps): a frame of that size can be the
|
||||
// first one there is.
|
||||
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
|
||||
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
|
||||
|
||||
@@ -1211,15 +1224,12 @@ mod tests {
|
||||
.unwrap();
|
||||
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
|
||||
assert_eq!(studio.status().active_scene, break_id);
|
||||
// The new scene's source draws.
|
||||
let frame = loop {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
|
||||
if p.data[..3] == [1, 2, 3] {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
|
||||
};
|
||||
// The new scene's source draws, from the first frame composed after the
|
||||
// command.
|
||||
let frame = preview_until(
|
||||
&preview,
|
||||
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
|
||||
);
|
||||
drop(frame);
|
||||
|
||||
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
|
||||
@@ -1402,9 +1412,16 @@ mod tests {
|
||||
assert_eq!((listed[0].width, listed[0].height), (64, 48));
|
||||
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
|
||||
let mut frames = frames;
|
||||
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
|
||||
// (The wait only ends a hang.)
|
||||
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
|
||||
assert_eq!((frame.width, frame.height), (64, 48));
|
||||
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
|
||||
// A frame is counted once it has been handed over, so the count can still be
|
||||
// behind when the frame is in the hands of the test.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
|
||||
assert!(Instant::now() < deadline, "the frame handed over was never counted");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
capture.stop();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
@@ -24,9 +24,11 @@ tokio = { version = "1", features = ["rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
|
||||
# `async-io`, not `tokio`, as in voelin-media: GPUI enables ashpd's `async-io` and
|
||||
# ashpd refuses both features at once.
|
||||
ashpd = { version = "0.13", default-features = false, features = ["async-io", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
|
||||
futures-util = { version = "0.3", optional = true }
|
||||
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
|
||||
notify-rust = { version = "4.18", default-features = false, features = ["z"] }
|
||||
x11rb = { version = "0.13", features = ["xinput"], optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
@@ -46,8 +48,11 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
|
||||
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
|
||||
# A stand-in desktop portal on a private session bus (tests/proxy.rs); the
|
||||
# zbus ashpd uses.
|
||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||
# zbus ashpd uses, on `async-io` like every other zbus in the workspace: a
|
||||
# `tokio` here would put the executor choice of ashpd's connection (zbus picks
|
||||
# tokio when a tokio runtime is current where it builds the connection) into
|
||||
# the tests alone, and tests/proxy.rs checks that the choice does not matter.
|
||||
zbus = { version = "5", default-features = false, features = ["async-io"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -5,6 +5,11 @@
|
||||
//! the real one is started and answers instead. Without `dbus-run-session`,
|
||||
//! or a bus daemon for it, the test says so and checks nothing. Its own test
|
||||
//! binary: answers are kept process-wide.
|
||||
//!
|
||||
//! The second and third tests call ashpd from a thread with no tokio runtime,
|
||||
//! as GPUI's executor would: ashpd runs on zbus's `async-io`, whichever thread
|
||||
//! built its connection (the third lets a tokio caller build it first;
|
||||
//! docs/design/gpui-spikes.md, "Dependencies").
|
||||
|
||||
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
|
||||
@@ -61,17 +66,17 @@ fn bus_config(dir: &std::path::Path) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Run this test again under `dbus-run-session` on a bus of its own, and say
|
||||
/// nothing was checked when that bus cannot be had.
|
||||
fn on_a_bus_of_its_own() {
|
||||
/// Run the test `name` again under `dbus-run-session` on a bus of its own, and
|
||||
/// say nothing was checked when that bus cannot be had.
|
||||
fn on_a_bus_of_its_own(name: &str) {
|
||||
let dir = std::env::temp_dir();
|
||||
let config = dir.join(format!("voelin-proxy-test-bus-{}.conf", std::process::id()));
|
||||
let config = dir.join(format!("voelin-proxy-test-bus-{}-{name}.conf", std::process::id()));
|
||||
std::fs::write(&config, bus_config(&dir)).unwrap();
|
||||
let run = std::process::Command::new("dbus-run-session")
|
||||
.arg(format!("--config-file={}", config.display()))
|
||||
.arg("--")
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "the_portal_names_the_proxy", "--nocapture", "--test-threads=1"])
|
||||
.args(["--exact", name, "--nocapture", "--test-threads=1"])
|
||||
.env(ON_ITS_OWN_BUS, "1")
|
||||
.output();
|
||||
let _ = std::fs::remove_file(&config);
|
||||
@@ -85,6 +90,11 @@ fn on_a_bus_of_its_own() {
|
||||
let text =
|
||||
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
if run.status.success() {
|
||||
// A child that ran no test (its filter matched nothing) exits 0 as well.
|
||||
assert!(
|
||||
text.contains("test result: ok. 1 passed;"),
|
||||
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
// The test ran and failed, or the bus never came up.
|
||||
@@ -99,7 +109,7 @@ fn on_a_bus_of_its_own() {
|
||||
#[tokio::test]
|
||||
async fn the_portal_names_the_proxy() {
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own();
|
||||
on_a_bus_of_its_own("the_portal_names_the_proxy");
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
@@ -128,3 +138,96 @@ async fn the_portal_names_the_proxy() {
|
||||
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// Run `future` on the calling thread, which parks while it waits: an executor
|
||||
/// of no runtime at all, as a GPUI foreground task is to ashpd.
|
||||
fn block_on<F: std::future::Future>(future: F) -> F::Output {
|
||||
struct Unpark(std::thread::Thread);
|
||||
impl std::task::Wake for Unpark {
|
||||
fn wake(self: Arc<Self>) {
|
||||
self.0.unpark();
|
||||
}
|
||||
}
|
||||
let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current())));
|
||||
let mut cx = std::task::Context::from_waker(&waker);
|
||||
let mut future = std::pin::pin!(future);
|
||||
loop {
|
||||
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
|
||||
return output;
|
||||
}
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stand-in portal on the bus of its own, served from the calling task.
|
||||
async fn stand_in_portal(lookups: &Arc<AtomicU32>) -> zbus::Connection {
|
||||
zbus::connection::Builder::session()
|
||||
.unwrap()
|
||||
.name("org.freedesktop.portal.Desktop")
|
||||
.unwrap()
|
||||
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
|
||||
.unwrap()
|
||||
.build()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A lookup through ashpd, from the calling task.
|
||||
async fn lookup() -> Vec<ashpd::Uri> {
|
||||
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
|
||||
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
|
||||
resolver.lookup(&uri).await.unwrap()
|
||||
}
|
||||
|
||||
/// A lookup through ashpd from a thread of its own with no runtime, blocking
|
||||
/// the caller's task for it (the pool's threads, `spawn_blocking`, have the
|
||||
/// runtime in reach). The stand-in portal runs on the test's runtime: keep it
|
||||
/// free while waiting.
|
||||
async fn lookup_without_a_runtime() -> Vec<String> {
|
||||
let caller = std::thread::spawn(|| {
|
||||
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
|
||||
block_on(lookup()).iter().map(|uri| uri.as_str().to_owned()).collect::<Vec<_>>()
|
||||
});
|
||||
tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap()
|
||||
}
|
||||
|
||||
/// ashpd with `async-io`: a caller outside any tokio runtime gets its answer,
|
||||
/// the connection's I/O running on zbus's own thread.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_portal_answers_a_caller_without_a_runtime() {
|
||||
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime";
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own(TEST);
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
let _portal = stand_in_portal(&lookups).await;
|
||||
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// ashpd keeps one session connection for the process, and zbus picks the
|
||||
/// executor of a connection once, when it builds it: tokio if a tokio runtime
|
||||
/// is current on that thread and zbus has its `tokio` feature on, its own
|
||||
/// `async-io` thread otherwise. If the engine's runtime made the connection
|
||||
/// first, a later caller with no runtime (a GPUI foreground task) would find a
|
||||
/// tokio connection with no reactor to run on and panic ("there is no reactor
|
||||
/// running" in zbus's property cache). With zbus on `async-io` alone in every
|
||||
/// binary (notify-rust without `z-with-tokio`, no zbus `tokio` here either)
|
||||
/// the order does not matter.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller() {
|
||||
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller";
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own(TEST);
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
let _portal = stand_in_portal(&lookups).await;
|
||||
// The tokio caller first: it builds the process's session connection.
|
||||
let answer: Vec<_> = lookup().await.iter().map(|uri| uri.as_str().to_owned()).collect();
|
||||
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
|
||||
// Then the caller with no runtime, on the same connection.
|
||||
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
||||
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
@@ -35,44 +35,119 @@
|
||||
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
|
||||
//! record and the device key with [`KeyStore::get`]: one damaged row, the
|
||||
//! record's own included, would otherwise keep a sign-out from ever finishing,
|
||||
//! and with it the deletion of the key the user asked to forget. Unbound is the
|
||||
//! reading that never deletes on a guess: a sign-out neither deletes such a row
|
||||
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
|
||||
//! four good binding columns. A `data` column that is not text (a BLOB, or text
|
||||
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
|
||||
//! that a record that cannot be read is deleted by the sign-out, as the trait
|
||||
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! and with it the deletion of the synced copies and of the record, and the
|
||||
//! forgetting of the key the user asked to forget. Unbound is the reading that
|
||||
//! never deletes on a guess: a sign-out neither deletes such a row as a synced
|
||||
//! copy nor writes it, it stays as it is until a `put` of it writes four good
|
||||
//! binding columns. A `data` column that is not text (a BLOB, or text of bytes
|
||||
//! that are no UTF-8) is read as text with the odd bytes replaced, so that a
|
||||
//! record that cannot be read is deleted by the sign-out, as the trait says,
|
||||
//! instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! [`KeyStore::get`] returned for such a row is taken for the data that is
|
||||
//! there: it changes the binding and keeps the stored bytes, where any other
|
||||
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
|
||||
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
|
||||
//! out with a warning.
|
||||
//!
|
||||
//! # Signing out keeps every key
|
||||
//!
|
||||
//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since
|
||||
//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts
|
||||
//! design, answered by the owner on 2026-10-24) it keeps every key of the
|
||||
//! device. The device key stays, unbound and byte for byte, whether it was in
|
||||
//! use before the account existed or the client made it for the account:
|
||||
//! `AccountRecord::bound_existing_key` only records which, for the client's
|
||||
//! wording, and no rule reads it. At every host without accounts that the user
|
||||
//! reached with it, either key is the user's identity, and deleting it would
|
||||
//! lose their servers, roles and memberships there. The identities that only
|
||||
//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user
|
||||
//! kept local) are unbound and kept as well.
|
||||
//!
|
||||
//! What a sign-out deletes is not a key of the device: the synced copies of
|
||||
//! integration secrets, which the account service holds and every device can
|
||||
//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted
|
||||
//! like one, see below), and the account record, which holds no secret. A
|
||||
//! sign-out does not release the device key at the account service either: the
|
||||
//! key stays registered with the account there. The release is its own
|
||||
//! operation, see below.
|
||||
//!
|
||||
//! # Releasing a device key
|
||||
//!
|
||||
//! The release of the device key from its account (part 2 of open question 10)
|
||||
//! is the account service's operation followed by a local unbind, and the unbind
|
||||
//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls
|
||||
//! `POST /v1/devices/<own>/release` after a password check, and then runs
|
||||
//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key,
|
||||
//! unbound. So the store needs nothing of its own for it: no call that unbinds
|
||||
//! one key (a [`KeyStore::put`] of the blob without its binding does that, and
|
||||
//! keeps the data, as the sign-out does), and no record that the key was
|
||||
//! released. The accounts design asks the client to remember nothing of the
|
||||
//! kind: the service holds the registration of the key (after a release it is
|
||||
//! registered with no account, after a sign-out with the account that was
|
||||
//! signed out of), and the client learns which at the next sign-in or sign-up,
|
||||
//! from the service's answer (`CONFLICT`, field `device`), not from a note kept
|
||||
//! here. The deletion of the account (`AccountClient::delete_account`) is the
|
||||
//! same: the service writes a DEVICE and a RELEASED entry for every device key
|
||||
//! of the account, and the local half is this sign-out, which keeps this
|
||||
//! device's key.
|
||||
//!
|
||||
//! # Forgetting the device's identity
|
||||
//!
|
||||
//! "Forget this device's identity" is the user's explicit choice and the only
|
||||
//! deletion of a key of the device; the UI offers to export the key first and
|
||||
//! asks before it deletes.
|
||||
//!
|
||||
//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of
|
||||
//! the device key. The caller names the key, because the key goes before the
|
||||
//! record is read: a record that cannot be read does not keep it.
|
||||
//! - Signed out, or with a key that no account ever bound, it is
|
||||
//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is
|
||||
//! [`Store::delete_identity`]. Neither looks at an account record, so a UI
|
||||
//! that forgets the device key of the account it is signed in to does it
|
||||
//! through the sign-out, not through `remove`.
|
||||
//!
|
||||
//! The store has no call that exports, because it would only wrap what the
|
||||
//! caller can read before it deletes: a Voelin key is
|
||||
//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that
|
||||
//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is
|
||||
//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by
|
||||
//! `voelin_core::ts::identity::export` or `write_export`. The same two calls,
|
||||
//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes
|
||||
//! the account: it offers an export of the device keys before the service is
|
||||
//! asked.
|
||||
//!
|
||||
//! # Deleted keys leave no trace
|
||||
//!
|
||||
//! The rows are private keys, so a removed row is not left behind in the file:
|
||||
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
|
||||
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
|
||||
//! [`Store::delete_identity`] does, so that the frame of the log that held the
|
||||
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
|
||||
//! `remove`, truncates the log once, after its last step, not after each
|
||||
//! removal. The checkpoint waits for another connection for a moment at most
|
||||
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
|
||||
//! and then the removal still succeeds and a warning says that the deleted
|
||||
//! bytes may stay in the log file, until a later checkpoint truncates the log,
|
||||
//! later writes overwrite those frames, or the last connection to the database
|
||||
//! closes and the log is deleted.
|
||||
//! page with the key is gone too. A forgotten key needs exactly that. So does
|
||||
//! the one deletion a sign-out still makes of a key: a synced copy of a
|
||||
//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out
|
||||
//! deletes with `remove` on a `SignOutPass` and truncates the log once, after
|
||||
//! its last step, not after each removal; one that deletes nothing (the record
|
||||
//! was gone, no copies) truncates nothing. The checkpoint waits for another
|
||||
//! connection for a moment at most (`Store::truncate_wal`): one that keeps
|
||||
//! reading an old snapshot blocks it, and then the removal still succeeds and a
|
||||
//! warning says that the deleted bytes may stay in the log file, until a later
|
||||
//! checkpoint truncates the log, later writes overwrite those frames, or the
|
||||
//! last connection to the database closes and the log is deleted.
|
||||
//!
|
||||
//! The device key is never a synced copy. The account record names the Voelin key
|
||||
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
|
||||
//! every identity bound with `synced = true` in its first step, before it reads
|
||||
//! the record, so a key stored that way would be deleted whatever the record
|
||||
//! says (a key that predates the account is to be kept). The store therefore
|
||||
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
|
||||
//! with `synced = true` while an account record names its uid as the device, or
|
||||
//! while a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! # The device key is never a synced copy
|
||||
//!
|
||||
//! A sign-out keeps the device key, but its first step deletes every identity
|
||||
//! bound with `synced = true`, before it reads the account record that names
|
||||
//! the device key. A device key stored that way would be deleted by that step,
|
||||
//! whether it predates the account or not, which is what the rule that a
|
||||
//! sign-out keeps every device key forbids. The store therefore refuses, with an
|
||||
//! error that says why, a [`KeyStore::put`] of a `voelin` blob with
|
||||
//! `synced = true` while an account record names its uid as the device, or while
|
||||
//! a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! account record that names a key which is stored as a synced copy. A binding
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
|
||||
//! follows the record. The check and the write are done under the store's lock;
|
||||
//! a second process writing the same file at the same moment is not covered.
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps
|
||||
//! it. The check and the write are done under the store's lock; a second
|
||||
//! process writing the same file at the same moment is not covered.
|
||||
//!
|
||||
//! A TeamSpeak blob that is refused says why in words that carry none of its
|
||||
//! input: its `data` is the identity's private key, and an error reaches log
|
||||
@@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities
|
||||
/// access to the TeamSpeak methods of the same connection.
|
||||
///
|
||||
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
|
||||
/// `voelin-identity` defines them, on top of the five methods here; the
|
||||
/// sign-out only truncates the write-ahead log once, at its end.
|
||||
/// `voelin-identity` defines them, on top of the five methods here: a sign-out
|
||||
/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the
|
||||
/// device key), and only truncates the write-ahead log once, at its end, when
|
||||
/// it deleted something.
|
||||
pub struct SqliteKeyStore {
|
||||
store: Mutex<Store>,
|
||||
}
|
||||
@@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore {
|
||||
|
||||
/// The trait's sign-out, with the log truncated once after its last step
|
||||
/// instead of after each of its removals: it removes up to a handful of
|
||||
/// rows, and a checkpoint that another connection blocks costs a moment
|
||||
/// rows (the synced copies, the account record and, with
|
||||
/// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and
|
||||
/// a checkpoint that another connection blocks costs a moment
|
||||
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
|
||||
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
|
||||
/// the checkpoint to this method.
|
||||
/// the checkpoint to this method. A sign-out that deleted nothing does not
|
||||
/// checkpoint.
|
||||
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
|
||||
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
|
||||
let outcome = KeyStore::sign_out(&pass, account, device_key);
|
||||
@@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
|
||||
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
|
||||
/// rows, but `remove` only notes that it deleted something, so that the sign-out
|
||||
/// truncates the log once at its end.
|
||||
/// truncates the log once at its end. What a sign-out removes is the synced
|
||||
/// copies of integration secrets, the account record and, when the user chose
|
||||
/// to forget it, the device key; unbinding goes through `put`, which deletes
|
||||
/// nothing.
|
||||
struct SignOutPass<'a> {
|
||||
store: &'a SqliteKeyStore,
|
||||
/// Whether a row was deleted.
|
||||
@@ -470,26 +553,28 @@ enum Refused {
|
||||
/// `uid` is unique across kinds in this table.
|
||||
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
|
||||
UidHeld { uid: String, kind: String },
|
||||
/// The Voelin key is the device key of an account record. A sign-out
|
||||
/// deletes a synced copy without reading the record, so the key the record
|
||||
/// says to keep would be deleted.
|
||||
/// The Voelin key is the device key of an account record. A sign-out keeps
|
||||
/// the device key, but it deletes a synced copy without reading the record,
|
||||
/// so a device key stored as one would be deleted all the same.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
|
||||
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
||||
reads the record, so it would delete the device key that it keeps"
|
||||
)]
|
||||
SyncedDeviceKey { uid: String, record: String },
|
||||
/// An account record cannot be read, so the store cannot tell whether the
|
||||
/// Voelin key is its device key.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
|
||||
record {record:?} cannot be read, so it may name this key as the device key"
|
||||
record {record:?} cannot be read, so it may name this key as the device key, which a \
|
||||
sign-out keeps but would delete as a synced copy"
|
||||
)]
|
||||
UnreadableRecord { uid: String, record: String },
|
||||
/// The device key of the record is stored as a synced copy already.
|
||||
#[error(
|
||||
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
|
||||
says"
|
||||
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
||||
reads the record, so it would delete the device key that it keeps"
|
||||
)]
|
||||
RecordNamesSyncedKey { record: String, device: String },
|
||||
}
|
||||
|
||||
@@ -27,18 +27,54 @@ pub use chat::{
|
||||
pub use contacts::{Contact, ContactSeen, Relation};
|
||||
pub use keystore::SqliteKeyStore;
|
||||
#[cfg(feature = "keyring")]
|
||||
pub use secrets::KeyringSecrets;
|
||||
pub use secrets::{FallbackSecrets, KeyringSecrets};
|
||||
pub use secrets::{MemorySecrets, Secrets};
|
||||
pub use store::{
|
||||
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
|
||||
};
|
||||
|
||||
/// How the JSON of a stored TeamSpeak identity is wrong: the category of the
|
||||
/// reader's complaint and nothing of the text, which holds a private key.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum IdentityDamage {
|
||||
/// The text is not JSON.
|
||||
Malformed,
|
||||
/// The text ends before the JSON does.
|
||||
CutShort,
|
||||
/// The JSON is not that of an identity: a field is missing or of another
|
||||
/// type, or the key does not import.
|
||||
NotAnIdentity,
|
||||
/// The text could not be read.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IdentityDamage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Malformed => "malformed",
|
||||
Self::CutShort => "cut short",
|
||||
Self::NotAnIdentity => "not an identity",
|
||||
Self::Unreadable => "unreadable",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("database: {0}")]
|
||||
Db(#[from] rusqlite::Error),
|
||||
#[error("serialization: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
/// The JSON of a stored TeamSpeak identity cannot be read, which only damage
|
||||
/// outside the client can cause. It says how the text is wrong and where, and
|
||||
/// never what it holds: the text is a private key, and the message of the
|
||||
/// JSON reader quotes the value it refuses (`tsproto` reports a key that does
|
||||
/// not import as an invalid value, the key string and all), so that message is
|
||||
/// not kept, not here and not in a log line.
|
||||
#[error(
|
||||
"the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}"
|
||||
)]
|
||||
Identity { damage: IdentityDamage, line: usize, column: usize },
|
||||
#[error("{0} {1} not found")]
|
||||
NotFound(&'static str, i64),
|
||||
#[error("secret store: {0}")]
|
||||
|
||||
@@ -74,6 +74,47 @@ impl Secrets for KeyringSecrets {
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyring first, memory when the keyring cannot keep a secret (no Secret
|
||||
/// Service on a headless Linux): what the desktop front ends keep the servers'
|
||||
/// passwords in. A secret the keyring refused is kept for this run only.
|
||||
#[cfg(feature = "keyring")]
|
||||
pub struct FallbackSecrets {
|
||||
keyring: KeyringSecrets,
|
||||
memory: MemorySecrets,
|
||||
}
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
impl FallbackSecrets {
|
||||
/// Secrets in the keyring entries of `service` (the app's name), with
|
||||
/// memory behind them.
|
||||
pub fn new(service: impl Into<String>) -> Self {
|
||||
Self { keyring: KeyringSecrets::new(service), memory: MemorySecrets::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
impl Secrets for FallbackSecrets {
|
||||
fn get(&self, key: &str) -> Result<Option<String>> {
|
||||
match self.memory.get(key)? {
|
||||
Some(v) => Ok(Some(v)),
|
||||
None => Ok(self.keyring.get(key).unwrap_or(None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&self, key: &str, value: &str) -> Result<()> {
|
||||
if let Err(error) = self.keyring.set(key, value) {
|
||||
tracing::warn!(%error, "keyring unavailable, keeping the secret for this session only");
|
||||
return self.memory.set(key, value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&self, key: &str) -> Result<()> {
|
||||
let _ = self.keyring.delete(key);
|
||||
self.memory.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsclientlib::Identity;
|
||||
|
||||
use crate::{Error, Result};
|
||||
use crate::{Error, IdentityDamage, Result};
|
||||
|
||||
/// A schema migration: SQL, or code for what SQL alone cannot do.
|
||||
enum Migration {
|
||||
@@ -244,6 +244,28 @@ impl Bookmark {
|
||||
/// waits.
|
||||
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
|
||||
|
||||
/// The TeamSpeak identity in the JSON of a stored row.
|
||||
///
|
||||
/// A text that does not read (it could only have been damaged outside the
|
||||
/// client: [`Store::add_identity`] writes what `serde_json` makes of an
|
||||
/// identity) is refused with [`Error::Identity`], which says how it is wrong and
|
||||
/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json`
|
||||
/// does for the text it is handed. The reader's own message is dropped: it
|
||||
/// quotes a value it refuses, and `tsproto` reports a key that does not import
|
||||
/// as an invalid value, the key string and all, which would reach a status line
|
||||
/// or a log.
|
||||
fn identity_from_json(json: &str) -> Result<Identity> {
|
||||
serde_json::from_str(json).map_err(|error| {
|
||||
let damage = match error.classify() {
|
||||
serde_json::error::Category::Syntax => IdentityDamage::Malformed,
|
||||
serde_json::error::Category::Eof => IdentityDamage::CutShort,
|
||||
serde_json::error::Category::Data => IdentityDamage::NotAnIdentity,
|
||||
serde_json::error::Category::Io => IdentityDamage::Unreadable,
|
||||
};
|
||||
Error::Identity { damage, line: error.line(), column: error.column() }
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
pub(crate) db: Connection,
|
||||
}
|
||||
@@ -348,7 +370,7 @@ impl Store {
|
||||
})?;
|
||||
rows.map(|row| {
|
||||
let (id, name, uid, data, origin, is_default) = row?;
|
||||
let identity: Identity = serde_json::from_str(&data)?;
|
||||
let identity = identity_from_json(&data)?;
|
||||
let origin = IdentityOrigin::parse(&origin);
|
||||
Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default })
|
||||
})
|
||||
@@ -385,6 +407,24 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The identity entry a connection uses: `named` (the identity a
|
||||
/// bookmark names) if the store still has it, else the default identity's.
|
||||
/// None when the store has no identity.
|
||||
pub fn identity_id_for(&self, named: Option<i64>) -> Option<i64> {
|
||||
let entries = self.identities().unwrap_or_default();
|
||||
named
|
||||
.filter(|id| entries.iter().any(|e| e.id == *id))
|
||||
.or_else(|| entries.iter().find(|e| e.is_default).or(entries.first()).map(|e| e.id))
|
||||
}
|
||||
|
||||
/// The identity a connection uses ([`Store::identity_id_for`]); `fallback`
|
||||
/// when the store has none it can read.
|
||||
pub fn identity_for(&self, named: Option<i64>, fallback: &Identity) -> Identity {
|
||||
self.identity_id_for(named)
|
||||
.and_then(|id| self.identity(id).ok())
|
||||
.unwrap_or_else(|| fallback.clone())
|
||||
}
|
||||
|
||||
pub fn identity(&self, id: i64) -> Result<Identity> {
|
||||
let data: Option<String> = self
|
||||
.db
|
||||
@@ -395,7 +435,7 @@ impl Store {
|
||||
)
|
||||
.optional()?;
|
||||
let data = data.ok_or(Error::NotFound("identity", id))?;
|
||||
Ok(serde_json::from_str(&data)?)
|
||||
identity_from_json(&data)
|
||||
}
|
||||
|
||||
/// Store an identity again, e.g. after its security level was improved.
|
||||
@@ -630,23 +670,43 @@ mod tests {
|
||||
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
|
||||
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A value that is not the default, so that restoring a constant would show.
|
||||
// A value that is not the default, so that restoring a constant would
|
||||
// show, and one so long that a checkpoint that waited as long as the
|
||||
// connection allows would not come back by itself.
|
||||
const HOUR_MS: i64 = 3_600_000;
|
||||
let timeout = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
|
||||
};
|
||||
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
store.truncate_wal();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
|
||||
store.db.busy_timeout(Duration::from_secs(3600)).unwrap();
|
||||
|
||||
// "Briefly" is not a time: a checkpoint ends in two fsyncs, which take
|
||||
// seconds under disk pressure (it took 6 s here beside `dd conv=fsync`
|
||||
// loops), and only a checkpoint that comes back while the reader still
|
||||
// holds its snapshot has not waited for it. So the reader lets go from
|
||||
// another thread after 30 s, which ends a checkpoint that does not give
|
||||
// up with a failure here and not with an hour's wait.
|
||||
let (back, hear) = std::sync::mpsc::channel::<()>();
|
||||
let watchdog = std::thread::spawn(move || {
|
||||
let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok();
|
||||
if !in_time {
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
}
|
||||
(reader, in_time)
|
||||
});
|
||||
// One attempt, which the reader blocks (`1`).
|
||||
let blocked = store.checkpoint_truncate();
|
||||
back.send(()).ok();
|
||||
let (reader, in_time) = watchdog.join().unwrap();
|
||||
assert!(in_time, "the checkpoint waited for the reader instead of giving up");
|
||||
assert_eq!(blocked.unwrap(), 1, "the reader should block the reset");
|
||||
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
assert_eq!(timeout(&store), HOUR_MS);
|
||||
|
||||
// Without the reader the same call resets the log.
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
store.truncate_wal();
|
||||
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
assert_eq!(timeout(&store), HOUR_MS);
|
||||
drop(reader);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
@@ -676,6 +736,28 @@ mod tests {
|
||||
assert_eq!(store.default_identity().unwrap().unwrap().id, made);
|
||||
}
|
||||
|
||||
/// A bookmark's own identity if the store has it, else the default one,
|
||||
/// else the fallback.
|
||||
#[test]
|
||||
fn a_connection_uses_the_named_identity_else_the_default_else_the_fallback() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
|
||||
let fallback = Identity::create();
|
||||
assert_eq!(store.identity_id_for(Some(1)), None);
|
||||
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&fallback), "no identity at all");
|
||||
let (default, alt) = (Identity::create(), Identity::create());
|
||||
let default_id = store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
|
||||
let alt_id = store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
|
||||
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&default), "the default");
|
||||
assert_eq!(store.identity_id_for(Some(alt_id)), Some(alt_id));
|
||||
assert_eq!(uid(&store.identity_for(Some(alt_id), &fallback)), uid(&alt), "the named one");
|
||||
let gone = alt_id + 100;
|
||||
assert_eq!(store.identity_id_for(Some(gone)), Some(default_id), "one that is gone");
|
||||
assert_eq!(uid(&store.identity_for(Some(gone), &fallback)), uid(&default));
|
||||
store.set_default_identity(alt_id, false).unwrap();
|
||||
assert_eq!(store.identity_id_for(None), Some(alt_id), "the default moved");
|
||||
}
|
||||
|
||||
/// A database of version 3 learns where its identities came from: the
|
||||
/// first one, named `Default`, is the one the app made; the others were
|
||||
/// imported; the first stays the default.
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! A damaged identity row: what the store returns and logs about it says how
|
||||
//! the row is wrong and never what it holds.
|
||||
//!
|
||||
//! The `data` of a TeamSpeak row is the JSON of a private key. Only something
|
||||
//! outside the client can damage it, but when that happens the error of the
|
||||
//! JSON reader quotes the value it refuses (`tsproto` reports a key that does
|
||||
//! not import as an invalid value, the key string and all), and an error
|
||||
//! reaches a status line, an event or a log. `Store::identity` and
|
||||
//! `Store::identities` used to return that error as it was.
|
||||
//!
|
||||
//! Every case here damages a row of a database file through a second
|
||||
//! connection, calls everything of the store that reads or writes the row, and
|
||||
//! looks through the errors (their text, their `Debug` text and their sources)
|
||||
//! and the logs at TRACE for any 8 characters in a row of what the row held.
|
||||
|
||||
use rusqlite::types::Value;
|
||||
use rusqlite::{Connection, params};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_identity::{
|
||||
AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK,
|
||||
KeyStore, Uid, account_uid,
|
||||
};
|
||||
use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store};
|
||||
|
||||
mod support;
|
||||
|
||||
/// A directory of its own that is removed again.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("voelin-identity-text-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn db(&self) -> std::path::PathBuf {
|
||||
self.0.join("client.db")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Letters and digits that no message of this crate, of `serde_json` or of
|
||||
/// SQLite is made of in a run of eight.
|
||||
const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga";
|
||||
const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za";
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that
|
||||
/// string: the reader quotes it in its message.
|
||||
fn json_with_a_counter_of_the_wrong_type() -> String {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
json["counter"] = SECRET.into();
|
||||
json.to_string()
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity cut in the middle of its key, and the key.
|
||||
fn json_cut_inside_its_key() -> (String, String) {
|
||||
let json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let text = json.to_string();
|
||||
let cut = text.find(&key).unwrap() + key.len() / 2;
|
||||
(text[..cut].to_owned(), key)
|
||||
}
|
||||
|
||||
/// How a row's `data` is damaged: what is stored, as which storage class, and
|
||||
/// the text of it that must never be repeated.
|
||||
struct Damage {
|
||||
label: &'static str,
|
||||
value: Value,
|
||||
/// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB.
|
||||
as_text: bool,
|
||||
secret: String,
|
||||
/// What the store says of it, when it reads it as JSON.
|
||||
damage: Option<IdentityDamage>,
|
||||
}
|
||||
|
||||
fn damages() -> Vec<Damage> {
|
||||
let (cut, cut_key) = json_with_a_cut_key();
|
||||
let (cut_short, whole_key) = json_cut_inside_its_key();
|
||||
let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes();
|
||||
not_utf8.push(0xff);
|
||||
vec![
|
||||
Damage {
|
||||
label: "a key that does not import",
|
||||
value: Value::Text(cut),
|
||||
as_text: false,
|
||||
secret: cut_key,
|
||||
damage: Some(IdentityDamage::NotAnIdentity),
|
||||
},
|
||||
Damage {
|
||||
label: "a field of the wrong type",
|
||||
value: Value::Text(json_with_a_counter_of_the_wrong_type()),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: Some(IdentityDamage::NotAnIdentity),
|
||||
},
|
||||
Damage {
|
||||
label: "syntax",
|
||||
value: Value::Text(format!("not json: {SECRET}")),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: Some(IdentityDamage::Malformed),
|
||||
},
|
||||
Damage {
|
||||
label: "cut short",
|
||||
value: Value::Text(cut_short),
|
||||
as_text: false,
|
||||
secret: whole_key,
|
||||
damage: Some(IdentityDamage::CutShort),
|
||||
},
|
||||
Damage {
|
||||
label: "bytes that are no UTF-8, stored as a BLOB",
|
||||
value: Value::Blob(not_utf8.clone()),
|
||||
as_text: false,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: None,
|
||||
},
|
||||
Damage {
|
||||
label: "bytes that are no UTF-8, stored as TEXT",
|
||||
value: Value::Blob(not_utf8),
|
||||
as_text: true,
|
||||
secret: SECRET.to_owned(),
|
||||
damage: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data");
|
||||
}
|
||||
}
|
||||
|
||||
/// The texts an error shows to a caller: how it reads, its `Debug` text and
|
||||
/// those of everything it was caused by.
|
||||
fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec<String> {
|
||||
let mut texts = vec![error.to_string(), format!("{error:?}")];
|
||||
let mut source = error.source();
|
||||
while let Some(cause) = source {
|
||||
texts.push(cause.to_string());
|
||||
texts.push(format!("{cause:?}"));
|
||||
source = cause.source();
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
fn binding() -> AccountBinding {
|
||||
let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16]));
|
||||
AccountBinding {
|
||||
account,
|
||||
integration: Some(IntegrationId::from_bytes([7; 16])),
|
||||
rev: 3,
|
||||
synced: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A database file with one TeamSpeak identity, its `data` replaced by `damage`
|
||||
/// through a second connection. Returns the id and uid of the row.
|
||||
fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) {
|
||||
let store = Store::open(&scratch.db()).unwrap();
|
||||
let identity = Identity::create();
|
||||
let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap();
|
||||
let uid = identity.key().to_pub().get_uid();
|
||||
drop(store);
|
||||
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
let sql = if damage.as_text {
|
||||
"UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2"
|
||||
} else {
|
||||
"UPDATE identities SET data = ?1 WHERE id = ?2"
|
||||
};
|
||||
assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1);
|
||||
(id, uid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_json_readers_own_message_quotes_what_it_refuses() {
|
||||
// Without this the cases below could not fail: serde's message for a key
|
||||
// that does not import and for a field of the wrong type repeats the value.
|
||||
let (json, cut_key) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}");
|
||||
let typed = json_with_a_counter_of_the_wrong_type();
|
||||
let raw = serde_json::from_str::<Identity>(&typed).unwrap_err().to_string();
|
||||
assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() {
|
||||
for damage in damages() {
|
||||
let scratch = Scratch::new("store");
|
||||
let (id, _) = damaged_database(&scratch, &damage);
|
||||
let label = damage.label;
|
||||
let store = Store::open(&scratch.db()).unwrap();
|
||||
|
||||
let ((one, all, default), lines) = support::at_trace(|| {
|
||||
(
|
||||
store.identity(id).unwrap_err(),
|
||||
store.identities().unwrap_err(),
|
||||
store.default_identity().unwrap_err(),
|
||||
)
|
||||
});
|
||||
for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] {
|
||||
for text in texts_of(error) {
|
||||
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}"));
|
||||
}
|
||||
if let Some(expected) = damage.damage {
|
||||
// The kind of damage and where, in the store's own words.
|
||||
match error {
|
||||
Error::Identity { damage, line, column } => {
|
||||
assert_eq!(*damage, expected, "{label}: {call}");
|
||||
assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}");
|
||||
let shown = error.to_string();
|
||||
assert!(
|
||||
shown.starts_with(&format!(
|
||||
"the stored TeamSpeak identity cannot be read: {expected} at line 1, column "
|
||||
)),
|
||||
"{label}: {call}: {shown}"
|
||||
);
|
||||
}
|
||||
other => panic!("{label}: {call}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() {
|
||||
for damage in damages() {
|
||||
let scratch = Scratch::new("keystore");
|
||||
let (_id, uid) = damaged_database(&scratch, &damage);
|
||||
let label = damage.label;
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
|
||||
// Everything that reads or writes the row, in the order a sign-out would,
|
||||
// with the errors and the logs of all of it kept.
|
||||
let (results, lines) = support::at_trace(|| {
|
||||
let mut errors: Vec<Box<dyn std::error::Error + Send + Sync>> = Vec::new();
|
||||
let mut note = |result: Result<(), voelin_identity::KeyStoreError>| {
|
||||
if let Err(error) = result {
|
||||
errors.push(Box::new(error));
|
||||
}
|
||||
};
|
||||
let listed = store.list().unwrap();
|
||||
let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed");
|
||||
assert_eq!(entry.level, 0, "{label}: damage reads as level 0");
|
||||
|
||||
// What `get` hands out is the data itself; a `put` of it rebinds the row.
|
||||
let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read");
|
||||
note(store.put(&blob.clone().with_binding(binding())));
|
||||
// Other data over the row is checked and refused, and the refusal does
|
||||
// not repeat it.
|
||||
let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#);
|
||||
note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other)));
|
||||
note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET)));
|
||||
// The sign-out that unbinds it, and the delete that removes it.
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
store.remove(KIND_TEAMSPEAK, &uid).unwrap();
|
||||
errors
|
||||
});
|
||||
assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}");
|
||||
for error in &results {
|
||||
for text in texts_of(error.as_ref()) {
|
||||
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal"));
|
||||
assert_holds_no_piece_of(
|
||||
&text,
|
||||
SECRET,
|
||||
&format!("{label}: a refusal of other data"),
|
||||
);
|
||||
assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data"));
|
||||
}
|
||||
}
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
|
||||
assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_capture_sees_what_the_store_logs() {
|
||||
// A control for the cases above: a row whose binding columns are damaged is
|
||||
// listed with a warning that names it, and the capture takes it in at TRACE.
|
||||
let scratch = Scratch::new("control");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#));
|
||||
store.put(&blob).unwrap();
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
assert_eq!(
|
||||
db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
let (listed, lines) = support::at_trace(|| store.list().unwrap());
|
||||
assert_eq!(listed.len(), 1);
|
||||
let warning = lines
|
||||
.iter()
|
||||
.find(|line| line.contains("the binding columns of an identity cannot be read"))
|
||||
.unwrap_or_else(|| panic!("no warning in {lines:?}"));
|
||||
assert!(warning.starts_with("WARN "), "{warning}");
|
||||
assert!(warning.contains("future:one"), "{warning}");
|
||||
// And it does not carry the row's data either.
|
||||
for line in &lines {
|
||||
assert_holds_no_piece_of(line, SECRET, "a log line");
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ use voelin_identity::{
|
||||
};
|
||||
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
|
||||
|
||||
mod support;
|
||||
|
||||
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
|
||||
/// identity of tsproto's own `identity_tests`.
|
||||
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
|
||||
@@ -789,6 +791,11 @@ fn pair(blob: &IdentityBlob) -> (String, String) {
|
||||
(blob.kind.clone(), blob.uid.clone())
|
||||
}
|
||||
|
||||
/// How many times a sign-out's list names the identity `key` (by kind and uid).
|
||||
fn times_listed(infos: &[IdentityInfo], key: &IdentityInfo) -> usize {
|
||||
infos.iter().filter(|info| info.kind == key.kind && info.uid == key.uid).count()
|
||||
}
|
||||
|
||||
/// The record of the install replaced by damaged JSON.
|
||||
fn damage_the_record(store: &SqliteKeyStore, json: &str) {
|
||||
let mut damaged = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap();
|
||||
@@ -803,8 +810,9 @@ fn the_record_fixture_is_what_the_protocol_writes() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
// The device key was made for the account: signing out deletes it.
|
||||
fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() {
|
||||
// The device key was made for the account: signing out keeps it all the
|
||||
// same, unbound (open question 10 of the accounts design).
|
||||
let Install { store, synced, device_only, local } = signed_in_install(false);
|
||||
let mine = binding().account;
|
||||
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
|
||||
@@ -815,19 +823,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
store.put_voelin_key(&other_key).unwrap();
|
||||
|
||||
let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap();
|
||||
let mut expected_removed = vec![
|
||||
(KIND_ACCOUNT.to_owned(), record().blob_uid()),
|
||||
pair(&synced),
|
||||
(KIND_VOELIN.to_owned(), key().uid().to_base32()),
|
||||
];
|
||||
let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
|
||||
expected_removed.sort();
|
||||
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
|
||||
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
|
||||
assert_eq!(
|
||||
sorted(done.unbound.clone()),
|
||||
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
|
||||
"{done:?}"
|
||||
);
|
||||
|
||||
// What is left: the device secret unbound and byte for byte as it was, the
|
||||
// local and the other account's identities as they were, the other key.
|
||||
// What is left: the device key, the device secret unbound and byte for
|
||||
// byte as it was, the local and the other account's identities as they
|
||||
// were, the other key.
|
||||
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid());
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
|
||||
assert_eq!(kept, device_only.clone().with_binding(None));
|
||||
@@ -835,11 +844,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
|
||||
assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local);
|
||||
assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob);
|
||||
assert!(store.voelin_key(&other_key.uid()).unwrap().is_some());
|
||||
assert_eq!(store.list().unwrap().len(), 4);
|
||||
assert_eq!(store.list().unwrap().len(), 5);
|
||||
|
||||
// Signing out again finds nothing to do.
|
||||
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
|
||||
assert_eq!(store.list().unwrap().len(), 4);
|
||||
assert_eq!(store.list().unwrap().len(), 5);
|
||||
// Another account's sign-out acts on that account's identities only.
|
||||
assert_eq!(
|
||||
store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed,
|
||||
@@ -892,17 +901,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_out_deletes_a_device_key_the_client_made_for_the_account() {
|
||||
fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() {
|
||||
// Open question 10 of the accounts design (answered 2026-10-24): a key that
|
||||
// the client made for the account is the user's identity at every host
|
||||
// without accounts that the user reached with it as well, so `Auto` keeps
|
||||
// it like a key that predates the account. Only `Forget` deletes it.
|
||||
let Install { store, device_only, local, .. } = signed_in_install(false);
|
||||
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
|
||||
let signature = key().sign(b"the same key, signed before and after");
|
||||
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert!(!done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
|
||||
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
|
||||
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
|
||||
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
|
||||
assert_eq!(key_after, key_before, "the stored blob is untouched");
|
||||
assert_eq!(key_after.binding, None);
|
||||
let mut left = sorted(store.list().unwrap());
|
||||
left.sort();
|
||||
let mut expected = vec![pair(&device_only), pair(&local)];
|
||||
let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)];
|
||||
expected.sort();
|
||||
assert_eq!(left, expected, "the device secret and the local one");
|
||||
assert_eq!(left, expected, "the key, the device secret and the local one");
|
||||
|
||||
// The flag changes nothing: a key that predates the account gets the same
|
||||
// treatment. (The other identities of the two installs are fresh ones, so
|
||||
// the reports differ in them.)
|
||||
let existing = signed_in_install(true);
|
||||
let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(again.unbound.contains(&device_key_info()), "{again:?}");
|
||||
assert!(!again.removed.contains(&device_key_info()), "{again:?}");
|
||||
assert_eq!(again.removed.len(), done.removed.len());
|
||||
assert_eq!(again.unbound.len(), done.unbound.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1282,16 +1312,10 @@ impl OnFile {
|
||||
/// What a sign-out of `choice` must have done, whatever else was damaged:
|
||||
/// the record and the synced copy are gone, the device-only secret is
|
||||
/// unbound and the local identity is as it was; the device key is deleted
|
||||
/// when the user forgot it or the client made it for the account, and
|
||||
/// reported as kept and unbound otherwise.
|
||||
fn assert_signed_out(
|
||||
&self,
|
||||
done: &SignOut,
|
||||
bound_existing_key: bool,
|
||||
choice: DeviceKeyChoice,
|
||||
label: &str,
|
||||
) {
|
||||
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key;
|
||||
/// when the user forgot it, and reported as kept and unbound otherwise,
|
||||
/// whether it predates the account or not.
|
||||
fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) {
|
||||
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_));
|
||||
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)];
|
||||
let mut unbound = vec![pair(&self.device_only)];
|
||||
let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32());
|
||||
@@ -1335,7 +1359,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [
|
||||
fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
// The record carries no binding, so damage in those columns says nothing
|
||||
// about the record: it is read, and the sign-out does what it always does.
|
||||
// `Forget` deletes the key it names; `Auto` follows the record.
|
||||
// `Forget` deletes the key it names; `Auto` keeps it.
|
||||
for bound_existing_key in [true, false] {
|
||||
for damage in RECORD_ROW_DAMAGE {
|
||||
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
|
||||
@@ -1346,7 +1370,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
.store
|
||||
.sign_out(&binding().account, choice)
|
||||
.unwrap_or_else(|error| panic!("{label}: {error}"));
|
||||
install.assert_signed_out(&done, bound_existing_key, choice, &label);
|
||||
install.assert_signed_out(&done, choice, &label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1354,8 +1378,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
|
||||
#[test]
|
||||
fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
// With `Auto` and a key that predates the account, the trait reads the key
|
||||
// to report it as kept. Damage in its binding columns must not fail that.
|
||||
// With `Auto` the trait reads the key to report it as kept, whether it
|
||||
// predates the account or not. Damage in its binding columns must not fail
|
||||
// that.
|
||||
for bound_existing_key in [true, false] {
|
||||
for damage in [
|
||||
"UPDATE identities SET synced = 2 WHERE kind = 'voelin'",
|
||||
@@ -1369,12 +1394,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
|
||||
.store
|
||||
.sign_out(&binding().account, DeviceKeyChoice::Auto)
|
||||
.unwrap_or_else(|error| panic!("{label}: {error}"));
|
||||
install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label);
|
||||
if bound_existing_key {
|
||||
// The key was kept, as it was stored.
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label);
|
||||
// The key was kept, as it was stored.
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1423,7 +1446,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record()
|
||||
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}");
|
||||
let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap();
|
||||
assert_eq!(secret.binding, None, "{label}");
|
||||
// `Auto` cannot find the key the record named, and keeps it.
|
||||
// `Auto` keeps the key, as it always does; `Forget` deleted it first.
|
||||
let forgot = matches!(choice, DeviceKeyChoice::Forget(_));
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}");
|
||||
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
|
||||
@@ -1623,14 +1646,13 @@ fn key_text(json: &str, field: &str) -> String {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
|
||||
// The device key the client made for the account goes with `Auto`, and a
|
||||
// key that predates the account goes when the user forgets it. Either way
|
||||
// its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the
|
||||
// free pages of `client.db` or in a frame of `client.db-wal`.
|
||||
for (bound_existing_key, choice) in
|
||||
[(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))]
|
||||
{
|
||||
fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
|
||||
// The device key goes when the user forgets it, whether it predates the
|
||||
// account or the client made it for the account. Its PKCS#8 text, and a
|
||||
// synced TeamSpeak copy's key, must not stay in the free pages of
|
||||
// `client.db` or in a frame of `client.db-wal`.
|
||||
for bound_existing_key in [true, false] {
|
||||
let choice = DeviceKeyChoice::Forget(key().uid());
|
||||
let scratch = Scratch::new("scrub-signout");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device = IdentityBlob::voelin(&key()).unwrap();
|
||||
@@ -1697,13 +1719,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() {
|
||||
fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() {
|
||||
// A connection that keeps a read snapshot (a long query of the UI, a backup)
|
||||
// keeps the checkpoint that truncates the log from finishing. The sign-out
|
||||
// still deletes and warns that the bytes may stay in the log, and it waits
|
||||
// for the checkpoint a moment, not for the busy timeout of five seconds once
|
||||
// per removed row. While the checkpoint waits it holds the writer lock of the
|
||||
// log, so a second connection that writes meanwhile must get through.
|
||||
// still deletes and warns that the bytes may stay in the log, and it makes
|
||||
// one checkpoint for all its removals, not one per removed row. While the
|
||||
// checkpoint waits it holds the writer lock of the log, so a second
|
||||
// connection that writes meanwhile must get through.
|
||||
//
|
||||
// No clock decides anything here. A checkpoint ends in two fsyncs, and under
|
||||
// disk pressure (a build or a copy writing beside the tests) they take
|
||||
// seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O
|
||||
// pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A
|
||||
// bound on the sign-out or a short busy timeout on the writer failed this
|
||||
// test with "database is locked" for a checkpoint that was only slow. That a
|
||||
// checkpoint gives up on a reader after a moment and does not wait out the
|
||||
// connection's busy timeout is pinned where that timeout can be set to an
|
||||
// hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`.
|
||||
let scratch = Scratch::new("blocked-checkpoint");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
@@ -1718,37 +1750,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
|
||||
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 4);
|
||||
|
||||
/// Stops the writer when dropped, so that a failed assertion of the test does
|
||||
/// not leave the scope waiting for it.
|
||||
struct StopsTheWriter<'a>(&'a AtomicBool);
|
||||
impl Drop for StopsTheWriter<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let stop = AtomicBool::new(false);
|
||||
let (done, elapsed, writes, errors) = std::thread::scope(|scope| {
|
||||
let written = AtomicUsize::new(0);
|
||||
let (done, elapsed, errors, lines) = std::thread::scope(|scope| {
|
||||
let _stops = StopsTheWriter(&stop);
|
||||
let writer = scope.spawn(|| {
|
||||
// Its own connection, which gives up on a lock after one second.
|
||||
// Its own connection, set up as the app's are (`Store::open`: the log
|
||||
// and `synchronous = NORMAL`, so that a commit does not wait for the
|
||||
// disk), with a busy timeout that a slow checkpoint does not reach.
|
||||
let db = Connection::open(scratch.db()).unwrap();
|
||||
db.busy_timeout(Duration::from_secs(1)).unwrap();
|
||||
db.pragma_update(None, "synchronous", "NORMAL").unwrap();
|
||||
db.busy_timeout(Duration::from_secs(60)).unwrap();
|
||||
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
|
||||
let (mut writes, mut errors) = (0, Vec::new());
|
||||
let mut errors = Vec::new();
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
match db.execute(sql, [writes.to_string()]) {
|
||||
Ok(_) => writes += 1,
|
||||
let began = Instant::now();
|
||||
match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) {
|
||||
Ok(_) => {
|
||||
written.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(error) => errors.push(error.to_string()),
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
// It pauses ten times as long as the write took, and 5 ms at least.
|
||||
// Under disk pressure a commit takes 100 ms and more, and a writer
|
||||
// that paused 5 ms after each would hold the writer lock nearly all
|
||||
// the time and keep the sign-out, whose busy timeout is the default
|
||||
// five seconds, from getting it (`DatabaseBusy`).
|
||||
let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5));
|
||||
while Instant::now() < wake && !stop.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
(writes, errors)
|
||||
errors
|
||||
});
|
||||
// The sign-out starts when the writer is up and has written, not when
|
||||
// the thread was spawned: a thread of a busy machine can start late.
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while written.load(Ordering::Relaxed) == 0 {
|
||||
assert!(Instant::now() < deadline, "the writer never ran");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
|
||||
let (done, lines) = support::at_trace(|| {
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid()))
|
||||
});
|
||||
let elapsed = started.elapsed();
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let (writes, errors) = writer.join().unwrap();
|
||||
(done.unwrap(), elapsed, writes, errors)
|
||||
let errors = writer.join().unwrap();
|
||||
(done.unwrap(), elapsed, errors, lines)
|
||||
});
|
||||
|
||||
// Four removals: the two copies, the device key the client made, the record.
|
||||
// Four removals: the two copies, the device key the user forgot, the record.
|
||||
assert_eq!(done.removed.len(), 4, "{done:?}");
|
||||
assert!(store.list().unwrap().is_empty());
|
||||
assert!(writes > 0, "the writer never ran");
|
||||
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
|
||||
assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}");
|
||||
// One checkpoint for the four removals: each one that is blocked says so.
|
||||
let blocked = support::blocked_checkpoints(&lines);
|
||||
assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})");
|
||||
|
||||
// Nothing is lost by the wait: once the reader is gone, the next removal
|
||||
// truncates the log.
|
||||
@@ -1758,6 +1824,286 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
|
||||
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
|
||||
}
|
||||
|
||||
// ------------------------- the keys a sign-out keeps, and the one the user forgets
|
||||
//
|
||||
// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps
|
||||
// every device key, and "Forget this device's identity" is the only deletion.
|
||||
|
||||
/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name.
|
||||
fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> {
|
||||
db.query_row(
|
||||
"SELECT * FROM identities WHERE kind = ?1 AND uid = ?2",
|
||||
params![kind, uid],
|
||||
|row| {
|
||||
let names: Vec<String> =
|
||||
row.as_ref().column_names().iter().map(|n| n.to_string()).collect();
|
||||
names
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, name)| Ok((name, row.get(index)?)))
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() {
|
||||
// Whether it predates the account or the client made it for the account, no
|
||||
// column of its row changes: the key never carried a binding, and a sign-out
|
||||
// writes nothing to it.
|
||||
for bound_existing_key in [true, false] {
|
||||
let install = signed_in_install_on_file(bound_existing_key);
|
||||
let uid = key().uid().to_base32();
|
||||
let db = Connection::open(install.scratch.db()).unwrap();
|
||||
let before = named_row(&db, KIND_VOELIN, &uid);
|
||||
assert!(before.len() >= 8, "{before:?}");
|
||||
|
||||
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}");
|
||||
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
|
||||
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() {
|
||||
// The store accepts a binding with `synced = false` on the device key (a
|
||||
// binding with `synced = true` is refused, see the last section). A sign-out
|
||||
// unbinds it and keeps it: the four binding columns are the only ones that
|
||||
// change.
|
||||
const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"];
|
||||
for bound_existing_key in [true, false] {
|
||||
let install = signed_in_install_on_file(bound_existing_key);
|
||||
let uid = key().uid().to_base32();
|
||||
let device_only = AccountBinding { synced: false, ..binding() };
|
||||
install
|
||||
.store
|
||||
.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only))
|
||||
.unwrap();
|
||||
let db = Connection::open(install.scratch.db()).unwrap();
|
||||
let before = named_row(&db, KIND_VOELIN, &uid);
|
||||
let bound = |row: &[(String, rusqlite::types::Value)]| {
|
||||
row.iter().any(|(name, value)| {
|
||||
name == "account" && !matches!(value, rusqlite::types::Value::Null)
|
||||
})
|
||||
};
|
||||
assert!(bound(&before), "the setup binds the key");
|
||||
|
||||
// It is listed once, as kept: VoelinProtocol before v0.2.0 listed a key whose
|
||||
// row carried the binding twice in `unbound`.
|
||||
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert_eq!(
|
||||
times_listed(&done.unbound, &device_key_info()),
|
||||
1,
|
||||
"{bound_existing_key}: {done:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
times_listed(&done.removed, &device_key_info()),
|
||||
0,
|
||||
"{bound_existing_key}: {done:?}"
|
||||
);
|
||||
|
||||
let after = named_row(&db, KIND_VOELIN, &uid);
|
||||
assert!(!bound(&after), "{bound_existing_key}: unbound");
|
||||
assert_eq!(before.len(), after.len());
|
||||
for ((name, was), (_, is)) in before.iter().zip(&after) {
|
||||
if !BINDING_COLUMNS.contains(&name.as_str()) {
|
||||
assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column");
|
||||
}
|
||||
}
|
||||
let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap());
|
||||
assert!(install.store.bound_to(&binding().account).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_key_that_carries_a_binding_is_listed_once_as_deleted_when_it_is_forgotten() {
|
||||
// The same row, named by `Forget`: the sign-out unbinds it in its loop over
|
||||
// the account's identities and deletes it after. It is listed once, as
|
||||
// deleted; VoelinProtocol before v0.2.0 also left it in `unbound`.
|
||||
for bound_existing_key in [true, false] {
|
||||
let Install { store, .. } = signed_in_install(bound_existing_key);
|
||||
let device_only = AccountBinding { synced: false, ..binding() };
|
||||
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
|
||||
|
||||
let done =
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())).unwrap();
|
||||
assert_eq!(
|
||||
times_listed(&done.removed, &device_key_info()),
|
||||
1,
|
||||
"{bound_existing_key}: {done:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
times_listed(&done.unbound, &device_key_info()),
|
||||
0,
|
||||
"{bound_existing_key}: {done:?}"
|
||||
);
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "the key is deleted");
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
assert_eq!(
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
|
||||
SignOut::default()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() {
|
||||
// What a sign-out still deletes is a synced copy (a private key, which
|
||||
// the service holds again) and the record: those are gone from the file and
|
||||
// its log. The device key and the device-only secret are kept, so their text
|
||||
// is still there.
|
||||
let scratch = Scratch::new("scrub-keeps");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device = IdentityBlob::voelin(&key()).unwrap();
|
||||
let synced = fresh_teamspeak(binding());
|
||||
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
|
||||
let device_text = key_text(&device.json, "pkcs8");
|
||||
let (synced_text, device_only_text) =
|
||||
(key_text(&synced.json, "key"), key_text(&device_only.json, "key"));
|
||||
for blob in [&device, &synced, &device_only] {
|
||||
store.put(blob).unwrap();
|
||||
}
|
||||
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
|
||||
let neighbour = Store::open(&scratch.db()).unwrap();
|
||||
let before = RawFiles::read(&scratch);
|
||||
assert!(before.holds(&device_text) && before.holds(&synced_text));
|
||||
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
let after = RawFiles::read(&scratch);
|
||||
assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy");
|
||||
assert!(after.holds(&device_text), "the device key is kept");
|
||||
assert!(after.holds(&device_only_text), "the device-only secret is kept");
|
||||
assert!(after.wal.is_empty(), "the log is truncated");
|
||||
drop(neighbour);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_out_that_deletes_nothing_does_not_checkpoint() {
|
||||
// With no record and no synced copy a sign-out only unbinds. The checkpoint
|
||||
// belongs to deletions: with a reader that blocks it, a deletion says so, and
|
||||
// the sign-out does not.
|
||||
let scratch = Scratch::new("no-deletion");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
|
||||
store.put(&device_only).unwrap();
|
||||
let reader = Connection::open(scratch.db()).unwrap();
|
||||
reader.execute_batch("BEGIN").unwrap();
|
||||
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
let (done, lines) =
|
||||
support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap());
|
||||
assert!(done.removed.is_empty(), "{done:?}");
|
||||
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
|
||||
assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}");
|
||||
|
||||
// The same reader does block the checkpoint of a deletion, so the count above
|
||||
// would have shown one.
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
let (removed, lines) =
|
||||
support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
|
||||
assert!(removed);
|
||||
assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}");
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() {
|
||||
// The flow of "Forget this device's identity" after a sign-out: the key is
|
||||
// still there, unbound; the UI exports it, then deletes it. The export is
|
||||
// what `voelin_key` and `to_pkcs8` give, and it restores the key.
|
||||
let scratch = Scratch::new("export-forget");
|
||||
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
||||
store.put_voelin_key(&key()).unwrap();
|
||||
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
let uid = key().uid();
|
||||
let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap();
|
||||
let text = key_text(&stored.json, "pkcs8");
|
||||
|
||||
let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap();
|
||||
assert!(RawFiles::read(&scratch).holds(&text));
|
||||
assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap());
|
||||
assert!(store.voelin_key(&uid).unwrap().is_none());
|
||||
let after = RawFiles::read(&scratch);
|
||||
assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left");
|
||||
assert!(after.wal.is_empty(), "the log is truncated");
|
||||
|
||||
// The export brings the same key back.
|
||||
let restored = IdentityKey::from_pkcs8(&exported).unwrap();
|
||||
assert_eq!(restored.uid(), uid);
|
||||
assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key"));
|
||||
store.put_voelin_key(&restored).unwrap();
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored);
|
||||
}
|
||||
|
||||
// ------------------------------------------ releasing the device key from its account
|
||||
//
|
||||
// `AccountClient::release` asks the service to release the key and then runs the
|
||||
// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so
|
||||
// the store's part is the sign-out of the tests above, and the key has to be
|
||||
// usable for another account afterwards.
|
||||
|
||||
#[test]
|
||||
fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() {
|
||||
let Install { store, .. } = signed_in_install(false);
|
||||
let uid = key().uid().to_base32();
|
||||
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
let signature = key().sign(b"the same key, before and after the release");
|
||||
|
||||
// The service released the key; the device finishes with a local sign-out.
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
|
||||
// The key is registered with no account and signs up for another one: its
|
||||
// record names the same key, and a copy of the new account's material is
|
||||
// bound to it.
|
||||
let other_id = AccountId::from_bytes([42; 16]);
|
||||
let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() };
|
||||
store.put_account_record(&other).unwrap();
|
||||
assert_eq!(store.account_record().unwrap(), Some(other.clone()));
|
||||
let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() };
|
||||
let other_copy = fresh_teamspeak(other_binding);
|
||||
store.put(&other_copy).unwrap();
|
||||
|
||||
// Signing out of the new account keeps the key again, and the copy goes.
|
||||
let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}");
|
||||
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
|
||||
assert_eq!(kept.sign(b"the same key, before and after the release"), signature);
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() {
|
||||
// The service released the device and the call was dropped before the local
|
||||
// sign-out took the slot: the record and the copies are still here, and the
|
||||
// key is still the record's device key. A sign-out with `Auto` finishes it
|
||||
// and keeps the key; running it again finds nothing to do.
|
||||
let Install { store, synced, device_only, .. } = signed_in_install(true);
|
||||
let uid = key().uid().to_base32();
|
||||
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
|
||||
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert!(done.removed.contains(&info_of(&synced)), "{done:?}");
|
||||
assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}");
|
||||
assert_eq!(store.account_record().unwrap(), None);
|
||||
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before);
|
||||
assert_eq!(
|
||||
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
|
||||
SignOut::default()
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------- the device key is never a synced copy
|
||||
//
|
||||
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its
|
||||
@@ -1798,15 +2144,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() {
|
||||
assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0);
|
||||
|
||||
// A binding that is not synced is a device-only secret: accepted, and a
|
||||
// sign-out unbinds it and keeps it (or deletes it, as the record says).
|
||||
// sign-out unbinds it and keeps it.
|
||||
let device_only = AccountBinding { synced: false, ..binding() };
|
||||
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
|
||||
store.put(&before).unwrap();
|
||||
|
||||
// So the sign-out still does what the record says with the key.
|
||||
// So the sign-out keeps the key, whether it predates the account or not.
|
||||
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
|
||||
assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}");
|
||||
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key);
|
||||
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
|
||||
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Helpers the integration tests of this crate share.
|
||||
|
||||
// Each integration test crate of this directory uses some of these helpers.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::span::{Attributes, Id, Record};
|
||||
use tracing::{Event, Metadata, Subscriber};
|
||||
|
||||
/// A subscriber that keeps every event and span it sees as one line of text
|
||||
/// each: level, target and every field with its `Debug` text, as a log line
|
||||
/// would show them.
|
||||
struct Capture {
|
||||
lines: Arc<Mutex<Vec<String>>>,
|
||||
spans: AtomicU64,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
fn push(&self, line: String) {
|
||||
self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of an event or a span as ` name=value` text.
|
||||
struct Fields<'a>(&'a mut String);
|
||||
|
||||
impl Visit for Fields<'_> {
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
|
||||
let _ = write!(self.0, " {}={value:?}", field.name());
|
||||
}
|
||||
}
|
||||
|
||||
impl Subscriber for Capture {
|
||||
fn enabled(&self, _: &Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn max_level_hint(&self) -> Option<LevelFilter> {
|
||||
Some(LevelFilter::TRACE)
|
||||
}
|
||||
|
||||
fn new_span(&self, attributes: &Attributes<'_>) -> Id {
|
||||
let mut line = format!("span {}", attributes.metadata().name());
|
||||
attributes.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
|
||||
fn record(&self, _: &Id, values: &Record<'_>) {
|
||||
let mut line = String::from("span record");
|
||||
values.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
}
|
||||
|
||||
fn record_follows_from(&self, _: &Id, _: &Id) {}
|
||||
|
||||
fn event(&self, event: &Event<'_>) {
|
||||
let metadata = event.metadata();
|
||||
let mut line = format!("{} {}:", metadata.level(), metadata.target());
|
||||
event.record(&mut Fields(&mut line));
|
||||
self.push(line);
|
||||
}
|
||||
|
||||
fn enter(&self, _: &Id) {}
|
||||
|
||||
fn exit(&self, _: &Id) {}
|
||||
}
|
||||
|
||||
/// Run `f` on this thread with a subscriber that takes in everything logged at
|
||||
/// TRACE and above, and return what `f` returned with the lines logged.
|
||||
pub fn at_trace<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
|
||||
let lines = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) };
|
||||
let out = tracing::subscriber::with_default(subscriber, f);
|
||||
let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
(out, lines)
|
||||
}
|
||||
|
||||
/// How many of the lines say that a checkpoint was blocked.
|
||||
pub fn blocked_checkpoints(lines: &[String]) -> usize {
|
||||
lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count()
|
||||
}
|
||||
@@ -1075,7 +1075,8 @@ impl Task {
|
||||
}
|
||||
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
|
||||
Event::MediaAdded(m) => {
|
||||
if !self.mids.iter().any(|(mid, _)| *mid == m.mid) {
|
||||
let known = self.mids.iter().any(|(mid, _)| *mid == m.mid);
|
||||
if !known {
|
||||
self.mids.push((m.mid, m.kind));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,7 +801,8 @@ impl StreamerSession {
|
||||
}
|
||||
StreamNotification::JoinRequest { viewer, remove: true, .. }
|
||||
| StreamNotification::ViewerLeft { viewer, .. } => {
|
||||
if self.viewers.remove(&viewer.0).is_some() {
|
||||
let was_viewer = self.viewers.remove(&viewer.0).is_some();
|
||||
if was_viewer {
|
||||
self.emit_viewers(out);
|
||||
self.update_targets(out);
|
||||
}
|
||||
|
||||
@@ -16,24 +16,29 @@ path = "src/lib.rs"
|
||||
# must show neither. The front ends convert these types (docs/ui.md).
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
|
||||
# Picture sizes (the header of a file); PNG and JPEG are listed as the
|
||||
# front end's toolkit used to bring them.
|
||||
# Whether a picture file decodes, and its size; PNG and JPEG are listed as
|
||||
# the front end's toolkit used to bring them.
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# JSON values of the settings and the gateway's configuration keys.
|
||||
serde_json = "1"
|
||||
# Whether an SVG document is XML with an svg root (the vector renderers read
|
||||
# it with this parser too).
|
||||
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
|
||||
# The Twemoji archive's blocks (raw deflate).
|
||||
miniz_oxide = "0.8"
|
||||
# Grapheme clusters for emoji in chat text.
|
||||
unicode-segmentation = "1.13"
|
||||
# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests.
|
||||
png = "0.18"
|
||||
# What the shared server sequences (`servers::sequence`) log, as both front
|
||||
# ends log it.
|
||||
tracing = "0.1.44"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500;
|
||||
/// How a span of text looks.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
/// Bold (`[b]`).
|
||||
pub bold: bool,
|
||||
/// Italic (`[i]`).
|
||||
pub italic: bool,
|
||||
/// Underlined (`[u]`).
|
||||
pub underline: bool,
|
||||
/// Struck through (`[s]`).
|
||||
pub strike: bool,
|
||||
/// Code: on a background.
|
||||
pub code: bool,
|
||||
@@ -51,12 +55,16 @@ pub struct Style {
|
||||
/// A piece of a block.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Span {
|
||||
/// Text with one style.
|
||||
Text {
|
||||
/// The characters.
|
||||
text: String,
|
||||
/// How they look.
|
||||
style: Style,
|
||||
},
|
||||
/// A picture at an address (`[img]…[/img]`).
|
||||
Image {
|
||||
/// Where the picture is.
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
@@ -68,7 +76,10 @@ pub enum BlockKind {
|
||||
Text,
|
||||
/// A line of a quote; the first names who said it (`[quote=Name]`), when
|
||||
/// the quote does.
|
||||
Quote { author: String },
|
||||
Quote {
|
||||
/// Who said it, empty when the quote does not say.
|
||||
author: String,
|
||||
},
|
||||
/// Code: all its lines in one span.
|
||||
Code,
|
||||
/// An item of a list.
|
||||
@@ -80,13 +91,16 @@ pub enum BlockKind {
|
||||
/// A line, a quote's line, code, a list item or a rule.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Block {
|
||||
/// What the block is.
|
||||
pub kind: BlockKind,
|
||||
/// Its pieces, left to right.
|
||||
pub spans: Vec<Span>,
|
||||
}
|
||||
|
||||
/// A message's text: its blocks, top to bottom.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Doc {
|
||||
/// The lines, quotes, code and rules in order.
|
||||
pub blocks: Vec<Block>,
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,9 @@
|
||||
//! Chat lines: one [`ChatLine`] per message, with its text in blocks of
|
||||
//! styled runs (`vm::bbcode`), its reactions and the files and pictures it
|
||||
//! links.
|
||||
//! links; [`logic`] has what happens to a session's chats when the engine
|
||||
//! tells something.
|
||||
|
||||
pub mod logic;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
@@ -9,7 +12,7 @@ use std::path::PathBuf;
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence};
|
||||
use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails};
|
||||
|
||||
use crate::avatar;
|
||||
use crate::bbcode::{self, BlockKind, Doc, Span, Style};
|
||||
@@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
|
||||
use crate::color::Rgb;
|
||||
use crate::emoji;
|
||||
use crate::image::ImageRef;
|
||||
use crate::state::{SessionView, Tab};
|
||||
|
||||
/// Where the server's welcome and host message keep what their lines were
|
||||
/// built from (`LineCache`), apart from the messages' ids.
|
||||
pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1];
|
||||
|
||||
/// What the server says to everyone who connects, with where its line keeps
|
||||
/// its parts: its welcome message, and its host message when that goes to
|
||||
/// the chat log.
|
||||
pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> {
|
||||
let host = details.host_message_mode == HostMessageMode::Log;
|
||||
[Some(&details.welcome_message), host.then_some(&details.host_message)]
|
||||
.into_iter()
|
||||
.zip(SERVER_LINES)
|
||||
.filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text of the server's line `key` (-1, -2, ...) of a server chat, if
|
||||
/// `tab` is one.
|
||||
pub fn server_text<'a, L>(view: &'a SessionView<L>, tab: &Tab<L>, key: i32) -> Option<&'a str> {
|
||||
if tab.target != ChatTarget::Server || key >= 0 {
|
||||
return None;
|
||||
}
|
||||
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
|
||||
}
|
||||
|
||||
/// Lines of the same author within this time are grouped (no header).
|
||||
const GROUP_MS: i64 = 5 * 60 * 1000;
|
||||
@@ -24,7 +53,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000;
|
||||
/// The author and time of the line before, for grouping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Previous {
|
||||
/// Who wrote it.
|
||||
pub author: String,
|
||||
/// When, in milliseconds since the epoch.
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
||||
//! The sample data of `VOELIN_DEMO_UI` and the helpers of the development
|
||||
//! switches that only look at the state. [`logic`] has the sample servers,
|
||||
//! people, chats, contacts, notices and pictures as plain values and as the
|
||||
//! events a server would send.
|
||||
|
||||
pub mod logic;
|
||||
@@ -298,7 +298,9 @@ pub fn first_key(text: &str) -> Option<String> {
|
||||
/// A piece of text: plain, or one emoji (`emoji` is its key).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Run {
|
||||
/// The text: the word with its space, or the emoji's own characters.
|
||||
pub text: String,
|
||||
/// The key of the Twemoji picture, none for plain text.
|
||||
pub emoji: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! What a server's gateway tells besides chat: its events (the events page,
|
||||
//! RSVP, reminders), the stream directory and the activity feed (the home
|
||||
//! page), our permissions there, its configuration (gateway administration).
|
||||
//! The pins, reactions and topics are in `chat::logic`.
|
||||
|
||||
use voelin_core::{GatewayRequest, GatewayUpdate};
|
||||
use voelin_gateway_proto::{EventQuery, feature};
|
||||
|
||||
use crate::host::Cx;
|
||||
use crate::social::{NoticeKind, NoticeRequest, NoticeTarget, server_name};
|
||||
use crate::state::{AppState, Lines};
|
||||
|
||||
/// Keep what a gateway update tells the home, events and administration
|
||||
/// screens (before the chat handles its part), and ask for what a new
|
||||
/// connection needs.
|
||||
pub fn extra<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, update: &GatewayUpdate) {
|
||||
use GatewayUpdate as U;
|
||||
let mut ask: Vec<GatewayRequest> = Vec::new();
|
||||
let mut remind = None;
|
||||
let extra = &mut state.sessions.entry(id).or_default().extra;
|
||||
match update {
|
||||
U::Connected { uid, capabilities, .. } => {
|
||||
extra.gateway_uid = Some(uid.clone());
|
||||
let has = |f: &str| capabilities.iter().any(|c| c == f);
|
||||
ask.push(GatewayRequest::Permissions { channel: None });
|
||||
if has(feature::EVENTS) {
|
||||
ask.push(GatewayRequest::Events { query: EventQuery::default() });
|
||||
}
|
||||
if has(feature::STREAMS) {
|
||||
ask.push(GatewayRequest::Streams);
|
||||
}
|
||||
if has(feature::ACTIVITY) {
|
||||
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
|
||||
}
|
||||
}
|
||||
U::Disconnected { .. } => {
|
||||
extra.directory.clear();
|
||||
extra.events.clear();
|
||||
extra.events_loaded = false;
|
||||
extra.activity.clear();
|
||||
extra.actions.clear();
|
||||
extra.config.clear();
|
||||
extra.perms.clear();
|
||||
}
|
||||
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
|
||||
U::Events { events } => {
|
||||
extra.events = events.clone();
|
||||
extra.events.sort_by_key(|e| e.spec.start_ms);
|
||||
extra.events_loaded = true;
|
||||
}
|
||||
U::Event { event } => {
|
||||
match extra.events.iter().position(|e| e.id == event.id) {
|
||||
Some(i) => extra.events[i] = event.clone(),
|
||||
None => extra.events.push(event.clone()),
|
||||
}
|
||||
extra.events.sort_by_key(|e| e.spec.start_ms);
|
||||
}
|
||||
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
|
||||
U::EventReminder { event, starts_in_ms } => remind = Some((event.clone(), *starts_in_ms)),
|
||||
U::Streams { streams } => extra.directory = streams.clone(),
|
||||
U::StreamStarted { stream }
|
||||
| U::StreamUpdated { stream }
|
||||
| U::StreamRegistered { stream } => {
|
||||
extra.directory.retain(|e| e.id != stream.id);
|
||||
extra.directory.push(stream.clone());
|
||||
}
|
||||
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
|
||||
U::Activity { entries, .. } => extra.activity = entries.clone(),
|
||||
U::ActivityAdded { entry } => {
|
||||
extra.activity.insert(0, entry.clone());
|
||||
extra.activity.truncate(100);
|
||||
}
|
||||
U::Config { entries } => extra.config = entries.clone(),
|
||||
U::ConfigValue { entry } => match extra.config.iter().position(|e| e.key == entry.key) {
|
||||
Some(i) => extra.config[i] = entry.clone(),
|
||||
None => extra.config.push(entry.clone()),
|
||||
},
|
||||
U::PermRules { rules } => extra.perms = rules.clone(),
|
||||
_ => return,
|
||||
}
|
||||
for request in ask {
|
||||
cx.gateway_to(id, request);
|
||||
}
|
||||
if let Some((event, starts_in_ms)) = remind {
|
||||
let minutes = starts_in_ms / 60_000;
|
||||
let title = if minutes <= 0 {
|
||||
format!("{} starts now", event.spec.title)
|
||||
} else {
|
||||
format!("{} starts in {minutes} min", event.spec.title)
|
||||
};
|
||||
cx.update.notices.push(NoticeRequest {
|
||||
kind: NoticeKind::Event,
|
||||
title,
|
||||
body: format!("on {}", server_name(state, id)),
|
||||
target: NoticeTarget::Event(id, event.id),
|
||||
name: event.creator.name.clone(),
|
||||
uid: Some(event.creator.uid.clone()),
|
||||
});
|
||||
}
|
||||
cx.update.refresh.home = true;
|
||||
cx.update.refresh.events = true;
|
||||
cx.update.refresh.gateways = true;
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
//! What the engine's events do to the client's state. [`handle`] takes an
|
||||
//! [`Event`], changes the [`AppState`] and the [`Social`] state and returns
|
||||
//! an [`Update`]: what to draw again, the status line, the commands for the
|
||||
//! engine, what to keep. A front end calls it for every event and then does
|
||||
//! what the update says; it has no dispatch of its own, so the Slint client
|
||||
//! and a GPUI one change the state the same way. [`apply`] is the part that
|
||||
//! changes the [`AppState`] alone; [`handle`] first lets
|
||||
//! [`crate::social::logic::event`] look at the event (the friends, the
|
||||
//! pokes, the notices and the offline messages), which has to see the state
|
||||
//! as it was before the event.
|
||||
//!
|
||||
//! In [`Update::rest`] come back the events whose state is not in the
|
||||
//! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a
|
||||
//! setting that changed (the settings service), and the answers to the
|
||||
//! offline message requests (the list that failed, a request that is done),
|
||||
//! which the messages page keeps (docs/ui.md, "Controllers still to split").
|
||||
//! A front end handles them before it draws what the update says is to be
|
||||
//! drawn again. The text of an offline message is not among them: it is
|
||||
//! state of the [`Social`], changed by [`handle`].
|
||||
|
||||
mod gateway;
|
||||
|
||||
use voelin_core::{BackendInfo, Command, Event, GatewayUpdate, JoinFailure, Source, VoiceState};
|
||||
use voelin_model::{ChannelId, ChatTarget};
|
||||
use voelin_store::Bookmark;
|
||||
|
||||
use crate::chat::logic::{
|
||||
add_message, gateway_update, history_batch, load_reads, open_chat, save_reads, track_reading,
|
||||
transfer_progress,
|
||||
};
|
||||
use crate::host::{Cx, Host, Persist, Update};
|
||||
use crate::previews::fetch_previews;
|
||||
use crate::servers::{AfterConnect, JoinStep, after_connect, join_password};
|
||||
use crate::settings::LastVoice;
|
||||
use crate::social::logic::Social;
|
||||
use crate::state::{AppState, Lines, SessionView};
|
||||
use crate::streams::logic as streams;
|
||||
|
||||
/// Apply an event to the [`AppState`]; see the [module](self).
|
||||
pub fn apply<L: Lines>(state: &mut AppState<L>, host: &dyn Host, event: Event) -> Update {
|
||||
let mut cx = Cx::new(host);
|
||||
dispatch(state, &mut cx, event);
|
||||
finish(state, cx)
|
||||
}
|
||||
|
||||
/// Take an event in: what the social screens make of it first
|
||||
/// ([`crate::social::logic::event`]), then [`apply`]. The one entry point
|
||||
/// of a front end.
|
||||
pub fn handle<L: Lines, D>(
|
||||
state: &mut AppState<L>,
|
||||
social: &mut Social<D>,
|
||||
host: &dyn Host,
|
||||
event: Event,
|
||||
) -> Update {
|
||||
let mut cx = Cx::new(host);
|
||||
crate::social::logic::event(state, social, &mut cx, &event);
|
||||
dispatch(state, &mut cx, event);
|
||||
finish(state, cx)
|
||||
}
|
||||
|
||||
/// The status line shows what the update says.
|
||||
fn finish<L>(state: &mut AppState<L>, cx: Cx<'_>) -> Update {
|
||||
if let Some(text) = &cx.update.status {
|
||||
state.status.clone_from(text);
|
||||
}
|
||||
cx.update
|
||||
}
|
||||
|
||||
fn dispatch<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, event: Event) {
|
||||
// The Stream Studio's stream is the studio's.
|
||||
if let Event::StreamState { session, .. } | Event::StreamViewers { session, .. } = &event
|
||||
&& cx.host.studio_streams_to(*session as i64)
|
||||
{
|
||||
cx.update.rest = Some(event);
|
||||
return;
|
||||
}
|
||||
match event {
|
||||
Event::State { session, state: now } => session_state(state, cx, session as i64, now),
|
||||
Event::ServerInfo { session, name, backend, capabilities } => {
|
||||
let id = session as i64;
|
||||
state.sessions.entry(id).or_default().capabilities = capabilities;
|
||||
adopt_server_name(state, cx, id, &name);
|
||||
if state.current == Some(id) {
|
||||
cx.status(connected_status(&name, &backend));
|
||||
}
|
||||
cx.update.refresh.streams = true;
|
||||
cx.update.autoshare = true;
|
||||
}
|
||||
Event::Presence { session, presence } => {
|
||||
let id = session as i64;
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
// The server chat shows its welcome and host message, with their
|
||||
// pictures.
|
||||
let said = crate::chat::server_texts(&view.presence.server)
|
||||
!= crate::chat::server_texts(&presence.server);
|
||||
// Our channel's path: known only now (a new connection), or
|
||||
// renamed.
|
||||
let path = |v: &SessionView<L>| {
|
||||
v.state.own_channel.map(|c| crate::tree::channel_path(&v.presence, c))
|
||||
};
|
||||
let path_before = path(view);
|
||||
view.presence = presence;
|
||||
let renamed = path(view) != path_before;
|
||||
apply_client_playback(state, cx, id);
|
||||
join_after_connect(state, cx, id);
|
||||
if renamed && remember_voice(state, cx, id) {
|
||||
cx.update.refresh.servers = true;
|
||||
}
|
||||
if state.current == Some(id) {
|
||||
if said {
|
||||
fetch_previews(state, cx, id);
|
||||
}
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true);
|
||||
cx.update.first_client = true;
|
||||
}
|
||||
}
|
||||
Event::Talking { session, client, talking } => {
|
||||
let id = session as i64;
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
if talking {
|
||||
view.talking.insert(client);
|
||||
} else {
|
||||
view.talking.remove(&client);
|
||||
}
|
||||
if state.current == Some(id) {
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
}
|
||||
Event::InputLevel { session, level_db, sending } => {
|
||||
let shown = match session {
|
||||
Some(s) => state.current == Some(s as i64),
|
||||
None => state.mic_test,
|
||||
};
|
||||
if shown {
|
||||
cx.update.input_level = Some((level_db, sending));
|
||||
}
|
||||
}
|
||||
Event::MicrophoneTestError { message } => {
|
||||
cx.status(format!("Microphone test: {message}"));
|
||||
}
|
||||
// Only for sessions the engine keeps no history for (it does not
|
||||
// know the server yet): those get ids and reactions instead.
|
||||
Event::Chat { session, message } => {
|
||||
let id = session as i64;
|
||||
if !state.sessions.entry(id).or_default().has_history() {
|
||||
add_message(state, cx, id, message);
|
||||
}
|
||||
}
|
||||
Event::ChatHistory { session, target, messages, source, complete } => {
|
||||
history_batch(state, cx, session as i64, &target, messages, source, complete);
|
||||
}
|
||||
Event::Gateway { session, update } => {
|
||||
let id = session as i64;
|
||||
if let GatewayUpdate::Connected { url, .. } = &update {
|
||||
gateway_in_use(state, cx, id, url);
|
||||
}
|
||||
gateway::extra(state, cx, id, &update);
|
||||
gateway_update(state, cx, id, update);
|
||||
}
|
||||
Event::Groups { session, server_groups, channel_groups } => {
|
||||
let id = session as i64;
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
view.server_groups = (*server_groups).clone();
|
||||
// Display order, as TeamSpeak sorts them.
|
||||
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
|
||||
view.channel_groups = (*channel_groups).clone();
|
||||
if state.current == Some(id) {
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
}
|
||||
Event::ServerDetails { session, address, details } => {
|
||||
remember_server_icon(state, cx, session as i64, &address, details.icon);
|
||||
cx.update.refresh.servers = true;
|
||||
cx.update.refresh.toolbar = true;
|
||||
}
|
||||
// Pictures can arrive after the rows were built: draw them again.
|
||||
Event::AvatarReady { session, client_uid, path, .. } => {
|
||||
let id = session as i64;
|
||||
// A file that arrives again is decoded again if it changed.
|
||||
cx.update.reloaded.push(path.clone());
|
||||
state.sessions.entry(id).or_default().avatars.insert(client_uid, path);
|
||||
if state.current == Some(id) {
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.tree, r.chat, r.toolbar, r.member_card, r.streams) =
|
||||
(true, true, true, true, true);
|
||||
}
|
||||
}
|
||||
Event::IconReady { session, icon, path } => {
|
||||
let id = session as i64;
|
||||
cx.update.reloaded.push(path.clone());
|
||||
state.sessions.entry(id).or_default().icons.insert(icon, path);
|
||||
cx.update.refresh.servers = true;
|
||||
if state.current == Some(id) {
|
||||
cx.update.refresh.tree = true;
|
||||
cx.update.refresh.toolbar = true;
|
||||
}
|
||||
}
|
||||
Event::PictureReady { session, url, path } => {
|
||||
let id = session as i64;
|
||||
// The host banner reloads into the same file.
|
||||
cx.update.reloaded.push(path.clone());
|
||||
state.sessions.entry(id).or_default().pictures.insert(url, path);
|
||||
if state.current == Some(id) {
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.toolbar, r.tree, r.chat, r.member_card) = (true, true, true, true);
|
||||
}
|
||||
}
|
||||
Event::Transfer { session, transfer, state: progress } => {
|
||||
transfer_progress(state, cx, session as i64, transfer, progress);
|
||||
}
|
||||
// The engine's contacts would replace the sample ones.
|
||||
Event::ContactsChanged { .. } if cx.host.demo_ui() && !state.contacts.is_empty() => {}
|
||||
Event::ContactsChanged { contacts } => {
|
||||
state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
|
||||
cx.update.refresh.member_card = true;
|
||||
}
|
||||
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
|
||||
Event::Error { .. } if cx.host.demo_ui() => {}
|
||||
Event::Error { message, .. } => cx.status(message),
|
||||
Event::JoinFailed { session, channel, reason } => {
|
||||
join_failed(state, cx, session as i64, channel, reason);
|
||||
}
|
||||
Event::SettingRejected { key, message } => {
|
||||
cx.status(format!("Setting {key}: {message}"));
|
||||
}
|
||||
Event::StreamsChanged { session, streams } => {
|
||||
let id = session as i64;
|
||||
// Development switch: watch the first stream that shows up.
|
||||
let autowatch = cx.host.autowatch() && !cx.host.watching() && state.current == Some(id);
|
||||
// A client whose stream was asked for while it was looked up.
|
||||
let pending = state
|
||||
.pending_watch
|
||||
.filter(|(s, _)| *s == id)
|
||||
.and_then(|(_, client)| streams.iter().find(|s| s.streamer == client))
|
||||
.map(|s| s.id.clone());
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
let first = streams
|
||||
.iter()
|
||||
.find(|s| view.state.own_client != Some(s.streamer))
|
||||
.map(|s| s.id.clone());
|
||||
view.streams = streams;
|
||||
cx.update.refresh.streams = true;
|
||||
cx.update.refresh.servers = true;
|
||||
if let Some(stream) = pending {
|
||||
state.pending_watch = None;
|
||||
cx.update.watch = Some(stream);
|
||||
} else if autowatch && let Some(stream) = first {
|
||||
cx.update.watch = Some(stream);
|
||||
}
|
||||
}
|
||||
// The streams we share and watch.
|
||||
Event::StreamState { session, state: now } => {
|
||||
streams::share_state(state, cx, session as i64, now);
|
||||
}
|
||||
Event::StreamViewerRequest { session, viewer, .. } => {
|
||||
streams::viewer_request(state, cx, session as i64, viewer);
|
||||
}
|
||||
Event::StreamViewers { session, viewers } => {
|
||||
streams::viewers(state, cx, session as i64, viewers);
|
||||
}
|
||||
Event::WatchState { session, stream_id, state: now } => {
|
||||
streams::watch_state(state, cx, session as i64, &stream_id, now);
|
||||
}
|
||||
Event::WatchLayers { session, stream_id, layers, layer } => {
|
||||
streams::watch_layers(state, cx, session as i64, &stream_id, layers, layer);
|
||||
}
|
||||
// Also flagged on the sink, which the encoder reads.
|
||||
Event::StreamKeyframeRequest { .. } | Event::StreamLayerBitrate { .. } => {}
|
||||
// The text of an offline message is in the `Social` state, which
|
||||
// `handle` has changed before (`social::logic::event`).
|
||||
Event::OfflineMessage { .. } => {}
|
||||
// What the settings service and the offline messages' requests make
|
||||
// of the rest, the front end keeps (see the module's note).
|
||||
event => cx.update.rest = Some(event),
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's connections changed.
|
||||
fn session_state<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
id: i64,
|
||||
now: voelin_core::SessionState,
|
||||
) {
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
let was_voice = view.state.voice;
|
||||
let was_observe = view.state.observe;
|
||||
let was_channel = view.state.own_channel;
|
||||
view.state = now.clone();
|
||||
if now.voice != VoiceState::Connected {
|
||||
view.focused_own_channel = false;
|
||||
}
|
||||
if now.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected {
|
||||
view.channel_passwords.clear();
|
||||
view.join_after_connect = None;
|
||||
}
|
||||
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
|
||||
// A new connection: volumes are sent again.
|
||||
view.applied_playback.clear();
|
||||
}
|
||||
// Where its chats were read, once the server is known; kept when the
|
||||
// session ends.
|
||||
load_reads(state, cx, id);
|
||||
let off = |voice: VoiceState, observe: voelin_core::ObserveState| {
|
||||
voice == VoiceState::Disconnected && observe == voelin_core::ObserveState::Off
|
||||
};
|
||||
if off(now.voice, now.observe) && !off(was_voice, was_observe) {
|
||||
save_reads(state, cx, id);
|
||||
}
|
||||
let focus = !state.sessions.entry(id).or_default().focused_own_channel;
|
||||
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
|
||||
cx.status("Connected");
|
||||
}
|
||||
if state.current == Some(id) {
|
||||
if track_reading(state, cx) {
|
||||
cx.update.refresh.chat = true;
|
||||
}
|
||||
// The voice channel's chat is always at hand, and focused once per
|
||||
// connection.
|
||||
if let (Some(cid), VoiceState::Connected) = (now.own_channel, now.voice) {
|
||||
open_chat(state, cx, ChatTarget::Channel(cid), focus);
|
||||
state.sessions.entry(id).or_default().focused_own_channel = true;
|
||||
}
|
||||
}
|
||||
// Where we are with voice, when it changed here: home's last place,
|
||||
// which the rail's refresh shows (voice on another server does not take
|
||||
// it back at each of its events).
|
||||
if (now.voice, now.own_channel) != (was_voice, was_channel) {
|
||||
remember_voice(state, cx, id);
|
||||
}
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.servers, r.toolbar, r.tree, r.streams) = (true, true, true, true);
|
||||
cx.update.autoshare = true;
|
||||
if state.current == Some(id) {
|
||||
cx.update.first_client = true;
|
||||
}
|
||||
join_after_connect(state, cx, id);
|
||||
}
|
||||
|
||||
/// The status line once a server answered: "Connected to Nightfall Guild
|
||||
/// (TeamSpeak 6 6.0.0-beta13.1)".
|
||||
pub fn connected_status(name: &str, backend: &BackendInfo) -> String {
|
||||
format!("Connected to {name} ({})", backend.label())
|
||||
}
|
||||
|
||||
/// The gateway logged in at `url`: it is the one in use from now on.
|
||||
fn gateway_in_use<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, url: &str) {
|
||||
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
|
||||
if b.gateway_in_use(url) {
|
||||
cx.persist(Persist::Bookmark { id, what: "gateway in use" });
|
||||
}
|
||||
}
|
||||
|
||||
/// The server told its name: a server still named by its address takes it,
|
||||
/// so the address is all a user has to type.
|
||||
fn adopt_server_name<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, name: &str) {
|
||||
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
|
||||
return;
|
||||
};
|
||||
if name.trim().is_empty() || cx.host.demo_ui() {
|
||||
return;
|
||||
}
|
||||
b.name = name.trim().to_owned();
|
||||
cx.persist(Persist::Bookmark { id, what: "server named" });
|
||||
cx.update.refresh.servers = true;
|
||||
cx.update.refresh.toolbar = true;
|
||||
}
|
||||
|
||||
/// Apply only details originating from the bookmark's current address.
|
||||
/// Returns whether its persisted metadata changed.
|
||||
pub fn apply_server_icon<L>(
|
||||
bookmark: &mut Bookmark,
|
||||
view: &mut SessionView<L>,
|
||||
address: &str,
|
||||
icon: u32,
|
||||
) -> bool {
|
||||
if bookmark.address != address {
|
||||
return false;
|
||||
}
|
||||
view.icon_address = Some(address.to_owned());
|
||||
view.server_icon = icon;
|
||||
let before = bookmark.cached_server_icon.clone();
|
||||
bookmark.remember_server_icon(icon);
|
||||
bookmark.cached_server_icon != before
|
||||
}
|
||||
|
||||
/// Keep only metadata supplied by the bookmark's current server.
|
||||
fn remember_server_icon<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
id: i64,
|
||||
address: &str,
|
||||
icon: u32,
|
||||
) {
|
||||
let Some(bookmark) = state.bookmarks.iter_mut().find(|b| b.id == id) else {
|
||||
return;
|
||||
};
|
||||
let changed = apply_server_icon(bookmark, state.sessions.entry(id).or_default(), address, icon);
|
||||
if changed && !cx.host.demo_ui() {
|
||||
cx.persist(Persist::Bookmark { id, what: "server icon" });
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep where we are with voice in `session` as the last place
|
||||
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
|
||||
pub fn remember_voice<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) -> bool {
|
||||
if cx.host.demo_ui() {
|
||||
return false;
|
||||
}
|
||||
let Some(view) = state.sessions.get(&session) else { return false };
|
||||
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
|
||||
return false;
|
||||
};
|
||||
let channel = crate::tree::channel_path(&view.presence, cid);
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == session).filter(|_| !channel.is_empty())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
|
||||
if state.settings.last_voice.as_ref() == Some(&last) {
|
||||
return false;
|
||||
}
|
||||
state.settings.last_voice = Some(last);
|
||||
cx.persist(Persist::Settings);
|
||||
true
|
||||
}
|
||||
|
||||
/// Send the stored volumes of clients that appeared in a voice session.
|
||||
pub fn apply_client_playback<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
|
||||
let Some(view) = state.sessions.get_mut(&session) else { return };
|
||||
if view.state.voice != VoiceState::Connected
|
||||
|| view.state.presence_source != Some(Source::Voice)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let presence = view.presence.clone();
|
||||
view.applied_playback.retain(|id| presence.clients.contains_key(id));
|
||||
for client in presence.clients.values() {
|
||||
if !view.applied_playback.insert(client.id) {
|
||||
continue;
|
||||
}
|
||||
let stored = client.uid.as_ref().and_then(|uid| state.playback.get(uid));
|
||||
let Some(playback) = stored else { continue };
|
||||
let (s, c) = (session as u64, client.id);
|
||||
cx.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume });
|
||||
if playback.muted {
|
||||
cx.send(Command::SetClientMuted { session: s, client: c, muted: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connected into another channel than the one asked for
|
||||
/// (`SessionView::join_after_connect`): the server says nothing when, for
|
||||
/// one, the password was wrong, so it is joined again, and that move says
|
||||
/// why. Once the channel shows in the voice connection's presence, which
|
||||
/// can come after the own channel.
|
||||
pub fn join_after_connect<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
|
||||
let Some(view) = state.sessions.get_mut(&session) else { return };
|
||||
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect) else {
|
||||
return;
|
||||
};
|
||||
let known = view.presence.channels.contains_key(&asked);
|
||||
match after_connect(view.state.own_channel, asked, known) {
|
||||
AfterConnect::Wait => {}
|
||||
AfterConnect::Joined => view.join_after_connect = None,
|
||||
AfterConnect::JoinAgain => {
|
||||
view.join_after_connect = None;
|
||||
move_into(state, cx, session, asked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move into a channel of a session connected with voice: with its
|
||||
/// password, or asking for one when it is locked and none was given this
|
||||
/// connection.
|
||||
fn move_into<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64, channel: ChannelId) {
|
||||
let Some(view) = state.sessions.get(&session) else { return };
|
||||
let Some(info) = view.presence.channels.get(&channel) else { return };
|
||||
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
|
||||
match join_password(info, remembered) {
|
||||
JoinStep::Send(password) => {
|
||||
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
|
||||
}
|
||||
JoinStep::Ask => ask_password(state, cx, session, channel, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the password dialog for a locked channel; `wrong`: the one given
|
||||
/// was refused.
|
||||
pub fn ask_password<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
wrong: bool,
|
||||
) {
|
||||
let Some(info) = state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let name = crate::tree::channel_title(info).0.to_owned();
|
||||
state.join_target = Some((session, channel));
|
||||
cx.ask_password(name, wrong);
|
||||
}
|
||||
|
||||
/// The server refused a move ([`Event::JoinFailed`]): a password asks again
|
||||
/// (the one given is forgotten), the rest is a toast.
|
||||
pub fn join_failed<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
reason: JoinFailure,
|
||||
) {
|
||||
match reason {
|
||||
JoinFailure::Password => {
|
||||
let given = state
|
||||
.sessions
|
||||
.get_mut(&session)
|
||||
.and_then(|v| v.channel_passwords.remove(&channel))
|
||||
.is_some();
|
||||
ask_password(state, cx, session, channel, given);
|
||||
}
|
||||
JoinFailure::Full => cx.status("The channel is full"),
|
||||
JoinFailure::Other(text) => cx.status(text),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,725 @@
|
||||
//! Tapes of engine events replayed through [`apply`] against a fake host:
|
||||
//! the state they leave, and what each update asks of a front end.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::StreamState;
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::stream::StreamInfo;
|
||||
use voelin_core::{
|
||||
BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
|
||||
JoinFailure, TransferState, VoiceState,
|
||||
};
|
||||
use voelin_gateway_proto::{UserRef, feature};
|
||||
use voelin_model::{Capabilities, ChatMessage, ChatTarget};
|
||||
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget};
|
||||
|
||||
use super::*;
|
||||
use crate::host::Refresh;
|
||||
use crate::host::testing::Fake;
|
||||
use crate::settings::{ClientPlayback, LastVoice};
|
||||
|
||||
use crate::host::testing::{State, presence, said, session, state};
|
||||
|
||||
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
|
||||
Event::ChatHistory {
|
||||
session: 1,
|
||||
target: ChatTarget::Channel(2),
|
||||
messages,
|
||||
source,
|
||||
complete: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(state: &mut State, host: &Fake, tape: Vec<Event>) -> Vec<Update> {
|
||||
tape.into_iter().map(|event| apply(state, host, event)).collect()
|
||||
}
|
||||
|
||||
fn gateway(update: GatewayUpdate) -> Event {
|
||||
Event::Gateway { session: 1, update }
|
||||
}
|
||||
|
||||
fn open_chats(update: &Update) -> Vec<ChatTarget> {
|
||||
update
|
||||
.commands
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
Command::OpenChat { target, .. } => Some(target.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A first connection to a server, event by event: what the session knows
|
||||
/// after each, and what the front end is told to do.
|
||||
#[test]
|
||||
fn a_first_connection() {
|
||||
let mut st = state();
|
||||
let host = Fake {
|
||||
reads: HashMap::from([(
|
||||
"srv=".to_owned(),
|
||||
vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })],
|
||||
)]),
|
||||
..Default::default()
|
||||
};
|
||||
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() };
|
||||
let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() };
|
||||
|
||||
// Connecting: the rail and the bar change, nothing is sent.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }],
|
||||
);
|
||||
assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting);
|
||||
assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree);
|
||||
assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare);
|
||||
|
||||
// The server answers: it gives its name to a bookmark that has only the
|
||||
// address, and says what it runs.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::ServerInfo {
|
||||
session: 1,
|
||||
name: " Nightfall Guild ".into(),
|
||||
backend,
|
||||
capabilities: caps,
|
||||
}],
|
||||
);
|
||||
assert_eq!(st.bookmarks[0].name, "Nightfall Guild");
|
||||
assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]);
|
||||
assert_eq!(
|
||||
ups[0].status.as_deref(),
|
||||
Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)")
|
||||
);
|
||||
assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)");
|
||||
assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams);
|
||||
|
||||
// Its presence: the bar, the tree and the chat are drawn; the stored
|
||||
// volume of Alice is sent once voice is connected, not before.
|
||||
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
|
||||
let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
assert_eq!(st.sessions[&1].presence.clients.len(), 2);
|
||||
assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client);
|
||||
assert!(ups[0].commands.is_empty());
|
||||
|
||||
// Voice connected into Games: its chat opens and is shown, with the
|
||||
// store's read marker; the place is remembered.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
|
||||
);
|
||||
let view = &st.sessions[&1];
|
||||
assert_eq!(view.reads_of.as_deref(), Some("srv="));
|
||||
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
|
||||
assert_eq!(view.tabs[view.current_tab].read, Some((200, 7)));
|
||||
assert_eq!(view.channel_tab, ChatTarget::Channel(2));
|
||||
assert!(view.focused_own_channel);
|
||||
assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]);
|
||||
assert_eq!(ups[0].status.as_deref(), Some("Connected"));
|
||||
assert_eq!(
|
||||
st.settings.last_voice,
|
||||
Some(LastVoice {
|
||||
bookmark: 1,
|
||||
address: "ts.example".into(),
|
||||
channel: vec!["Games".into()]
|
||||
})
|
||||
);
|
||||
assert!(ups[0].persist.contains(&Persist::Settings));
|
||||
assert!(ups[0].refresh.chat && ups[0].refresh.servers);
|
||||
|
||||
// The presence again, now that voice is connected: Alice's volume goes
|
||||
// to the engine, once.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Presence { session: 1, presence: presence() },
|
||||
Event::Presence { session: 1, presence: presence() },
|
||||
],
|
||||
);
|
||||
assert!(matches!(
|
||||
ups[0].commands.as_slice(),
|
||||
[
|
||||
Command::SetClientVolume { session: 1, client: 11, volume },
|
||||
Command::SetClientMuted { session: 1, client: 11, muted: true },
|
||||
] if *volume == 0.5
|
||||
));
|
||||
assert!(ups[1].commands.is_empty());
|
||||
}
|
||||
|
||||
/// The messages of a chat: a stored page, then live ones, with the chat on
|
||||
/// screen or not, and what is kept of how far it was read.
|
||||
#[test]
|
||||
fn messages_are_counted_read_and_kept() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Presence { session: 1, presence: presence() },
|
||||
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
|
||||
],
|
||||
);
|
||||
// The stored page: two read before, one new. (Its marker came from the
|
||||
// store: nothing here, so what the tab held when the page came counts as
|
||||
// read.)
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![games(
|
||||
vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")],
|
||||
HistorySource::Local,
|
||||
)],
|
||||
);
|
||||
let tab = &st.sessions[&1].tabs[1];
|
||||
assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::<Vec<_>>(), [6, 7, 8]);
|
||||
assert!(tab.complete && !tab.loading);
|
||||
assert_eq!(tab.unread, 0, "a first page is what was read");
|
||||
assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]);
|
||||
assert!(ups[0].refresh.chat);
|
||||
|
||||
// A live message while the chat is not on screen is new.
|
||||
let ups =
|
||||
run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]);
|
||||
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
|
||||
assert!(ups[0].refresh.servers, "the rail counts it");
|
||||
// Our own is not.
|
||||
st.own_uids.insert("me=".into());
|
||||
run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]);
|
||||
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
|
||||
|
||||
// The chat comes on screen: read up to its end, a divider over the new.
|
||||
host.shown.set(true);
|
||||
let mut cx = Cx::new(&host);
|
||||
assert!(crate::chat::logic::track_reading(&mut st, &mut cx));
|
||||
let tab = &st.sessions[&1].tabs[1];
|
||||
assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10))));
|
||||
assert_eq!(st.reading, Some((1, ChatTarget::Channel(2))));
|
||||
// A live one now is read at once.
|
||||
run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]);
|
||||
assert_eq!(st.sessions[&1].tabs[1].unread, 0);
|
||||
assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11)));
|
||||
|
||||
// The session ends: where the chats were read is stored, and what the
|
||||
// store has is what the tab then says it has.
|
||||
let mut ended = session(VoiceState::Disconnected, None);
|
||||
ended.server_uid = Some("srv=".into());
|
||||
let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]);
|
||||
let written = host.written.borrow();
|
||||
assert_eq!(written.len(), 1, "{written:?}");
|
||||
assert_eq!(written[0].0, "srv=");
|
||||
assert_eq!(written[0].1, StoredTarget::Channel(2));
|
||||
assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11));
|
||||
assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11)));
|
||||
assert!(ups[0].refresh.servers);
|
||||
}
|
||||
|
||||
/// Where the chat lines go when the engine keeps no history (it does not
|
||||
/// know the server yet): one row appended per message.
|
||||
#[test]
|
||||
fn a_session_without_history_appends_lines() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let message = |text: &str| ChatMessage {
|
||||
target: ChatTarget::Server,
|
||||
author_name: "Alice".into(),
|
||||
author_uid: Some("alice=".into()),
|
||||
author_id: Some(11),
|
||||
text: text.into(),
|
||||
ts_ms: 1000,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Chat { session: 1, message: message("one") },
|
||||
Event::Chat { session: 1, message: message("two") },
|
||||
],
|
||||
);
|
||||
let tab = &st.sessions[&1].tabs[0];
|
||||
assert_eq!(tab.lines.len(), 2);
|
||||
assert_eq!(tab.unread, 2);
|
||||
assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]);
|
||||
assert!(ups[1].refresh.chat && ups[1].refresh.servers);
|
||||
// With a server unique id the engine has the history, and the live
|
||||
// message arrives as `ChatHistory`.
|
||||
st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into());
|
||||
run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]);
|
||||
assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2);
|
||||
}
|
||||
|
||||
/// What a gateway brings: capabilities, requests for what the screens
|
||||
/// show, pins, the stream directory, reminders for the bell.
|
||||
#[test]
|
||||
fn a_gateway_connects_and_tells() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Presence { session: 1, presence: presence() },
|
||||
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
|
||||
],
|
||||
);
|
||||
let caps: Vec<String> = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS]
|
||||
.map(String::from)
|
||||
.into();
|
||||
st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()];
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![gateway(GatewayUpdate::Connected {
|
||||
url: "wss://gw.example/v1".into(),
|
||||
gateway_id: "g".into(),
|
||||
server_uid: "srv=".into(),
|
||||
server_name: "Nightfall Guild".into(),
|
||||
uid: "me=".into(),
|
||||
capabilities: caps,
|
||||
})],
|
||||
);
|
||||
let view = &st.sessions[&1];
|
||||
assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS));
|
||||
assert_eq!(view.extra.gateway_uid.as_deref(), Some("me="));
|
||||
assert_eq!(
|
||||
st.bookmarks[0].gateway_url.as_deref(),
|
||||
Some("wss://gw.example/v1"),
|
||||
"the gateway in use is kept"
|
||||
);
|
||||
assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" }));
|
||||
// The permissions, the events and the directory, then the current
|
||||
// chat's pins and topics.
|
||||
let asked: Vec<&GatewayRequest> = ups[0]
|
||||
.commands
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
Command::Gateway { session: 1, request } => Some(request),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(matches!(
|
||||
asked.as_slice(),
|
||||
[
|
||||
GatewayRequest::Permissions { channel: None },
|
||||
GatewayRequest::Events { .. },
|
||||
GatewayRequest::Streams,
|
||||
GatewayRequest::Pins { target: ChatTarget::Channel(2) },
|
||||
GatewayRequest::Topics { target: ChatTarget::Channel(2), .. },
|
||||
]
|
||||
));
|
||||
assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways);
|
||||
|
||||
// The answers: pins (newest first), the directory's viewer counts, a
|
||||
// failed request of the user.
|
||||
let pin = |id: i64, ts_ms: i64| Pin {
|
||||
message: said(id, ts_ms, false, "pinned"),
|
||||
by: UserRef { uid: "alice=".into(), name: "Alice".into() },
|
||||
ts_ms,
|
||||
};
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
gateway(GatewayUpdate::Pins {
|
||||
target: ChatTarget::Channel(2),
|
||||
pins: vec![pin(3, 10), pin(4, 20)],
|
||||
}),
|
||||
gateway(GatewayUpdate::Failed {
|
||||
request: "pin".into(),
|
||||
code: Some(voelin_gateway_proto::ErrorCode::Forbidden),
|
||||
message: "no".into(),
|
||||
}),
|
||||
],
|
||||
);
|
||||
let tab = &st.sessions[&1].tabs[1];
|
||||
assert!(tab.pins_loaded);
|
||||
assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [4, 3]);
|
||||
assert!(ups[0].refresh.chat);
|
||||
assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server."));
|
||||
|
||||
// Gone: nothing of the gateway stays.
|
||||
run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]);
|
||||
let view = &st.sessions[&1];
|
||||
assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded);
|
||||
}
|
||||
|
||||
/// A password that was refused asks again, and says so the second time.
|
||||
#[test]
|
||||
fn a_locked_channel_asks_for_its_password() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password };
|
||||
let ups = run(&mut st, &host, vec![failed()]);
|
||||
let prompt = ups[0].password.clone().unwrap();
|
||||
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
|
||||
assert_eq!(st.join_target, Some((1, 1)));
|
||||
// A password was given and refused: it is forgotten, the prompt says so.
|
||||
st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into());
|
||||
let ups = run(&mut st, &host, vec![failed()]);
|
||||
assert!(ups[0].password.as_ref().unwrap().wrong);
|
||||
assert!(st.sessions[&1].channel_passwords.is_empty());
|
||||
// The others are a toast.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }],
|
||||
);
|
||||
assert_eq!(ups[0].status.as_deref(), Some("The channel is full"));
|
||||
}
|
||||
|
||||
/// Connected into another channel than the one asked for: joined again,
|
||||
/// with the password given this connection.
|
||||
#[test]
|
||||
fn a_channel_asked_for_and_not_entered_is_joined_again() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
let view = st.sessions.get_mut(&1).unwrap();
|
||||
view.join_after_connect = Some(1);
|
||||
view.channel_passwords.insert(1, "pw".into());
|
||||
// Connected into Games, not the Lobby that was asked for.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
|
||||
);
|
||||
assert!(ups[0].commands.iter().any(|c| matches!(
|
||||
c,
|
||||
Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw"
|
||||
)));
|
||||
assert_eq!(st.sessions[&1].join_after_connect, None);
|
||||
// The sample sessions send nothing to the engine.
|
||||
let mut demo = state();
|
||||
let host = Fake { demo: true, ..Default::default() };
|
||||
run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1);
|
||||
let ups = run(
|
||||
&mut demo,
|
||||
&host,
|
||||
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
|
||||
);
|
||||
assert!(open_chats(&ups[0]).is_empty());
|
||||
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. })));
|
||||
}
|
||||
|
||||
/// Pictures and files: the engine's cache, an upload from the composer, a
|
||||
/// download that runs, the contacts, errors.
|
||||
#[test]
|
||||
fn pictures_files_contacts_and_errors() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
let path = PathBuf::from("/cache/avatars/ab");
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::AvatarReady {
|
||||
session: 1,
|
||||
client_uid: "alice=".into(),
|
||||
path: path.clone(),
|
||||
hash: "ab".into(),
|
||||
},
|
||||
Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() },
|
||||
Event::PictureReady {
|
||||
session: 1,
|
||||
url: "https://e.com/a.png".into(),
|
||||
path: "/cache/pictures/a".into(),
|
||||
},
|
||||
],
|
||||
);
|
||||
let view = &st.sessions[&1];
|
||||
assert_eq!(view.avatars.get("alice="), Some(&path));
|
||||
assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png"));
|
||||
assert_eq!(ups[0].reloaded, [path]);
|
||||
assert_eq!(
|
||||
ups[0].refresh,
|
||||
Refresh {
|
||||
tree: true,
|
||||
chat: true,
|
||||
toolbar: true,
|
||||
member_card: true,
|
||||
streams: true,
|
||||
..Refresh::default()
|
||||
}
|
||||
);
|
||||
assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat);
|
||||
|
||||
// An upload from the composer posts its link once it is up.
|
||||
st.uploads.insert(7, (1, 2, "notes.txt".into()));
|
||||
let done = TransferState::Done { size: 12, data: None, path: None };
|
||||
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]);
|
||||
assert!(st.uploads.is_empty());
|
||||
assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared"));
|
||||
assert!(matches!(
|
||||
ups[0].commands.as_slice(),
|
||||
[Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt")
|
||||
));
|
||||
st.uploads.insert(8, (1, 2, "big.iso".into()));
|
||||
let failed = TransferState::Failed("full".into());
|
||||
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]);
|
||||
assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full"));
|
||||
|
||||
// Errors and rejected settings reach the status line, but not the sample
|
||||
// sessions' (the engine does not know them).
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Error { session: 1, message: "kicked".into() },
|
||||
Event::SettingRejected { key: "audio".into(), message: "no".into() },
|
||||
Event::MicrophoneTestError { message: "no device".into() },
|
||||
],
|
||||
);
|
||||
assert_eq!(ups[0].status.as_deref(), Some("kicked"));
|
||||
assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no"));
|
||||
assert_eq!(st.status, "Microphone test: no device");
|
||||
let demo = Fake { demo: true, ..Default::default() };
|
||||
let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]);
|
||||
assert!(ups[0].status.is_none());
|
||||
}
|
||||
|
||||
/// A client that talks, the meter, the groups in the order TeamSpeak sorts
|
||||
/// them.
|
||||
#[test]
|
||||
fn talking_the_meter_and_groups() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::Talking { session: 1, client: 11, talking: true },
|
||||
Event::Talking { session: 1, client: 11, talking: false },
|
||||
Event::InputLevel { session: Some(1), level_db: -20.0, sending: true },
|
||||
Event::InputLevel { session: None, level_db: -30.0, sending: false },
|
||||
Event::InputLevel { session: Some(2), level_db: -10.0, sending: true },
|
||||
],
|
||||
);
|
||||
assert!(st.sessions[&1].talking.is_empty());
|
||||
assert!(ups[0].refresh.tree);
|
||||
assert_eq!(ups[2].input_level, Some((-20.0, true)));
|
||||
assert_eq!(ups[3].input_level, None, "no microphone test is running");
|
||||
assert_eq!(ups[4].input_level, None, "another server's");
|
||||
st.mic_test = true;
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }],
|
||||
);
|
||||
assert_eq!(ups[0].input_level, Some((-30.0, false)));
|
||||
|
||||
let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() };
|
||||
run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::Groups {
|
||||
session: 1,
|
||||
server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]),
|
||||
channel_groups: Arc::new(vec![group(5, 0)]),
|
||||
}],
|
||||
);
|
||||
let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect();
|
||||
assert_eq!(ids, [9, 6, 7]);
|
||||
}
|
||||
|
||||
/// The streams the voice connection lists: the one a lookup waited for is
|
||||
/// to be watched; the rest of the stream events are the front end's.
|
||||
#[test]
|
||||
fn streams_are_listed_and_a_lookup_is_watched() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
let stream = |id: &str, streamer| StreamInfo {
|
||||
id: id.into(),
|
||||
streamer,
|
||||
name: "screen".into(),
|
||||
kind: voelin_core::stream::StreamKind::Screen,
|
||||
bitrate: 0,
|
||||
viewer_limit: 0,
|
||||
audio: false,
|
||||
viewers: Some(1),
|
||||
};
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }],
|
||||
);
|
||||
assert_eq!(st.sessions[&1].streams.len(), 1);
|
||||
assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none());
|
||||
// A client's stream was asked for before the list knew it.
|
||||
st.pending_watch = Some((1, 11));
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }],
|
||||
);
|
||||
assert_eq!(ups[0].watch.as_deref(), Some("s2"));
|
||||
assert_eq!(st.pending_watch, None);
|
||||
// The development switch watches the first stream that is not ours.
|
||||
let host = Fake { autowatch: true, ..Default::default() };
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }],
|
||||
);
|
||||
assert_eq!(ups[0].watch.as_deref(), Some("s3"));
|
||||
// Keyframe requests are the encoder's, read from the sink; a setting that
|
||||
// changed is the settings service's: the front end keeps it.
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::StreamKeyframeRequest { session: 1, layer: 0 },
|
||||
Event::SettingChanged { key: "audio".into() },
|
||||
],
|
||||
);
|
||||
assert!(ups[0].rest.is_none() && ups[0].refresh.is_empty() && ups[0].commands.is_empty());
|
||||
assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio"));
|
||||
}
|
||||
|
||||
/// The streams of the events: the studio's stream is the studio's; ours and
|
||||
/// the one we watch change the state and say what the capture and the
|
||||
/// decoder are to do.
|
||||
#[test]
|
||||
fn the_streams_we_share_and_watch_follow_the_events() {
|
||||
use crate::streams::logic::{Sharing, Watching, demo_viewers};
|
||||
use voelin_core::WatchState;
|
||||
use voelin_core::stream::EndReason;
|
||||
|
||||
let mut st = state();
|
||||
run(&mut st, &Fake::default(), vec![Event::Presence { session: 1, presence: presence() }]);
|
||||
st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false });
|
||||
st.watch = Some(Watching {
|
||||
session: Some(1),
|
||||
stream_id: "s1".into(),
|
||||
title: "Speedrun".into(),
|
||||
streamer: "Alice".into(),
|
||||
status: String::new(),
|
||||
connected: true,
|
||||
ended: false,
|
||||
has_frame: true,
|
||||
shown: true,
|
||||
since: None,
|
||||
layers: Vec::new(),
|
||||
layer: None,
|
||||
});
|
||||
// The studio streams to the server: its events are handed back as they
|
||||
// are, and our share is not touched.
|
||||
let studio = Fake { studio: Some(1), ..Default::default() };
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&studio,
|
||||
vec![
|
||||
Event::StreamViewers { session: 1, viewers: demo_viewers() },
|
||||
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) },
|
||||
],
|
||||
);
|
||||
assert!(matches!(ups[0].rest, Some(Event::StreamViewers { .. })));
|
||||
assert!(matches!(ups[1].rest, Some(Event::StreamState { .. })));
|
||||
assert!(st.share.as_ref().unwrap().viewers.is_empty() && st.share.as_ref().unwrap().live);
|
||||
// Elsewhere they are ours.
|
||||
let host = Fake::default();
|
||||
let ups = run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::StreamViewers { session: 1, viewers: demo_viewers() },
|
||||
Event::StreamViewerRequest { session: 1, viewer: 11, message: "hi".into() },
|
||||
Event::WatchState {
|
||||
session: 1,
|
||||
stream_id: "s1".into(),
|
||||
state: WatchState::Ended(EndReason::Stopped),
|
||||
},
|
||||
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) },
|
||||
],
|
||||
);
|
||||
assert!(ups[0].refresh.streams && ups[0].rest.is_none());
|
||||
assert_eq!(ups[1].status.as_deref(), Some("Alice wants to watch your stream"));
|
||||
let watch = st.watch.as_ref().unwrap();
|
||||
assert!(watch.ended && ups[2].stream.drop_decoder);
|
||||
assert_eq!(watch.status, "The stream has ended.");
|
||||
assert!(st.share.is_none() && ups[3].stream.drop_share && ups[3].stream.mixer);
|
||||
assert_eq!(ups[3].status.as_deref(), Some("You stopped sharing"));
|
||||
}
|
||||
|
||||
/// Pictures linked in a chat are downloaded once, up to the limit.
|
||||
#[test]
|
||||
fn linked_pictures_are_fetched_once() {
|
||||
let mut st = state();
|
||||
let host = Fake { limit: 100 * 1024, ..Default::default() };
|
||||
let mut connected = session(VoiceState::Connected, Some(2));
|
||||
connected.server_uid = Some("srv=".into());
|
||||
run(
|
||||
&mut st,
|
||||
&host,
|
||||
vec![
|
||||
Event::ServerInfo {
|
||||
session: 1,
|
||||
name: "S".into(),
|
||||
backend: BackendInfo::default(),
|
||||
capabilities: Capabilities { file_transfer: true, ..Default::default() },
|
||||
},
|
||||
Event::Presence { session: 1, presence: presence() },
|
||||
Event::State { session: 1, state: connected },
|
||||
],
|
||||
);
|
||||
let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]";
|
||||
let ups =
|
||||
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
|
||||
let downloads: Vec<_> =
|
||||
ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect();
|
||||
assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands);
|
||||
// Asked once: the same page again asks for nothing.
|
||||
let ups =
|
||||
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
|
||||
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_status_line_names_the_servers_software() {
|
||||
let backend = |product: &str, version: &str| BackendInfo {
|
||||
product: product.into(),
|
||||
version: version.into(),
|
||||
};
|
||||
assert_eq!(
|
||||
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
|
||||
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
|
||||
);
|
||||
assert_eq!(
|
||||
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
|
||||
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
|
||||
);
|
||||
// Not recognised: the version string the server sent.
|
||||
assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
|
||||
std::fs::write(
|
||||
&path,
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
|
||||
let mut view = SessionView::<()>::default();
|
||||
view.icons.insert(1234, path.clone());
|
||||
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
|
||||
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
|
||||
// Details from another address, queued before an edit, change nothing.
|
||||
assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77));
|
||||
assert_eq!(view.server_icon, 1234);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
@@ -18,9 +18,11 @@ pub enum ResumeAction {
|
||||
/// The card: the server, the channel and the button.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Resume {
|
||||
/// The id of the server's bookmark.
|
||||
pub bookmark: i64,
|
||||
/// The channel's path, its names from the top as the server has them.
|
||||
pub path: Vec<String>,
|
||||
/// What the button does.
|
||||
pub action: ResumeAction,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
//! What the transitions of the client's state need from the front end and
|
||||
//! tell it. A transition (`events::apply`, the functions of `chat::logic`)
|
||||
//! changes the [`AppState`](crate::state::AppState) it is given and puts
|
||||
//! everything else into an [`Update`]: what to redraw, the status line, the
|
||||
//! engine commands to send, what to keep; the little it must ask a front end
|
||||
//! for while it runs (is the chat on screen, what the store knows) goes
|
||||
//! through [`Host`]. Neither the engine nor the store nor a toolkit is
|
||||
//! touched here, so the transitions are tested with a fake host
|
||||
//! (`events::tests`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use voelin_core::{Command, Event, GatewayRequest, StreamSink};
|
||||
use voelin_model::ChatTarget;
|
||||
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
|
||||
|
||||
use crate::social::NoticeRequest;
|
||||
|
||||
/// What a transition asks of its front end while it runs.
|
||||
pub trait Host {
|
||||
/// The sample data of `VOELIN_DEMO_UI` is shown: nothing is sent to the
|
||||
/// engine or kept in the store.
|
||||
fn demo_ui(&self) -> bool;
|
||||
|
||||
/// The current chat's messages are on screen (a page shows the chat).
|
||||
fn chat_shown(&self) -> bool;
|
||||
|
||||
/// A stream is in the viewer.
|
||||
fn watching(&self) -> bool;
|
||||
|
||||
/// The development switch `VOELIN_AUTOWATCH=1`: watch the first stream
|
||||
/// that shows up.
|
||||
fn autowatch(&self) -> bool;
|
||||
|
||||
/// The Stream Studio streams to this session: the events of that stream
|
||||
/// are its own.
|
||||
fn studio_streams_to(&self, session: i64) -> bool;
|
||||
|
||||
/// The largest picture previewed in chats, in bytes (0: none), from
|
||||
/// `ui.image_preview_kb`.
|
||||
fn preview_limit(&self) -> u64;
|
||||
|
||||
/// Pictures on the web are fetched and shown (`cache.fetch_images`).
|
||||
fn fetch_images(&self) -> bool;
|
||||
|
||||
/// The private chat with this peer (unique id) of this session is on
|
||||
/// screen, in the messages page.
|
||||
fn dm_shown(&self, session: i64, uid: &str) -> bool;
|
||||
|
||||
/// Now, in milliseconds since the epoch.
|
||||
fn now_ms(&self) -> i64 {
|
||||
crate::social::now_ms()
|
||||
}
|
||||
|
||||
/// How far the chats of a server were read, from the store.
|
||||
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String>;
|
||||
|
||||
/// Keep how far a chat of a server was read.
|
||||
fn set_chat_read(
|
||||
&self,
|
||||
server_uid: &str,
|
||||
target: &StoredTarget,
|
||||
read: &ChatRead,
|
||||
) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// The parts of the screen to draw again. Each is a function of the state,
|
||||
/// so a front end draws each flagged part once, however many events set it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Refresh {
|
||||
/// The server rail.
|
||||
pub servers: bool,
|
||||
/// The top bar of the server page.
|
||||
pub toolbar: bool,
|
||||
/// The channel tree and the members.
|
||||
pub tree: bool,
|
||||
/// The chat tabs, the lines and what belongs to them (pins, topics).
|
||||
pub chat: bool,
|
||||
/// The streams panel and the voice card's streams.
|
||||
pub streams: bool,
|
||||
/// The stream viewer's header.
|
||||
pub viewer: bool,
|
||||
/// The open member card.
|
||||
pub member_card: bool,
|
||||
/// The home page.
|
||||
pub home: bool,
|
||||
/// The events page.
|
||||
pub events: bool,
|
||||
/// The gateway pages of the settings.
|
||||
pub gateways: bool,
|
||||
/// The friends page, home's friends and activity, the block list.
|
||||
pub people: bool,
|
||||
/// The lists of direct messages and the offline messages (asked for
|
||||
/// again when a voice connection came up).
|
||||
pub conversations: bool,
|
||||
/// The peer card of the open direct message.
|
||||
pub dm: bool,
|
||||
}
|
||||
|
||||
impl Refresh {
|
||||
/// Every part.
|
||||
pub const ALL: Self = Self {
|
||||
servers: true,
|
||||
toolbar: true,
|
||||
tree: true,
|
||||
chat: true,
|
||||
streams: true,
|
||||
viewer: true,
|
||||
member_card: true,
|
||||
home: true,
|
||||
events: true,
|
||||
gateways: true,
|
||||
people: true,
|
||||
conversations: true,
|
||||
dm: true,
|
||||
};
|
||||
|
||||
/// Whether nothing is to be drawn.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// Every part either of the two names: what a front end that handles a
|
||||
/// batch of events draws once, however many events set a part.
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
let Self {
|
||||
servers,
|
||||
toolbar,
|
||||
tree,
|
||||
chat,
|
||||
streams,
|
||||
viewer,
|
||||
member_card,
|
||||
home,
|
||||
events,
|
||||
gateways,
|
||||
people,
|
||||
conversations,
|
||||
dm,
|
||||
} = other;
|
||||
self.servers |= servers;
|
||||
self.toolbar |= toolbar;
|
||||
self.tree |= tree;
|
||||
self.chat |= chat;
|
||||
self.streams |= streams;
|
||||
self.viewer |= viewer;
|
||||
self.member_card |= member_card;
|
||||
self.home |= home;
|
||||
self.events |= events;
|
||||
self.gateways |= gateways;
|
||||
self.people |= people;
|
||||
self.conversations |= conversations;
|
||||
self.dm |= dm;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refresh_tests {
|
||||
use super::Refresh;
|
||||
|
||||
#[test]
|
||||
fn merging_names_the_parts_of_both() {
|
||||
let mut a = Refresh { tree: true, chat: true, ..Default::default() };
|
||||
a.merge(Refresh { toolbar: true, tree: true, ..Default::default() });
|
||||
assert_eq!(a, Refresh { toolbar: true, tree: true, chat: true, ..Default::default() });
|
||||
let mut none = Refresh::default();
|
||||
none.merge(Refresh::default());
|
||||
assert!(none.is_empty());
|
||||
none.merge(Refresh::ALL);
|
||||
assert_eq!(none, Refresh::ALL);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a transition wants kept.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Persist {
|
||||
/// The bookmark with this id changed (the store has the old one).
|
||||
Bookmark {
|
||||
/// The bookmark.
|
||||
id: i64,
|
||||
/// What it was changed for, for the log.
|
||||
what: &'static str,
|
||||
},
|
||||
/// The UI's own settings changed (`AppState::settings`).
|
||||
Settings,
|
||||
/// The audio settings changed (`AppState::audio`).
|
||||
Audio,
|
||||
/// The clients' local volumes changed (`AppState::playback`).
|
||||
Playback,
|
||||
}
|
||||
|
||||
/// The password dialog of a locked channel is to open
|
||||
/// (`AppState::join_target` names the channel).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PasswordPrompt {
|
||||
/// The channel's name as the tree shows it.
|
||||
pub name: String,
|
||||
/// The password given before was refused.
|
||||
pub wrong: bool,
|
||||
}
|
||||
|
||||
/// What the streams we share and watch need of the front end, which owns the
|
||||
/// capture and the decoder.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct StreamEffects {
|
||||
/// Encode into the live stream: the sink of our stream.
|
||||
pub attach: Option<StreamSink>,
|
||||
/// Our stream is over: the capture stops.
|
||||
pub drop_share: bool,
|
||||
/// The watched stream is over, or left: its decoder stops.
|
||||
pub drop_decoder: bool,
|
||||
/// The audio mixer's rows follow the capture again.
|
||||
pub mixer: bool,
|
||||
/// The player leaves full screen.
|
||||
pub leave_fullscreen: bool,
|
||||
}
|
||||
|
||||
/// What a transition tells its front end, besides the changed state.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Update {
|
||||
/// What to draw again.
|
||||
pub refresh: Refresh,
|
||||
/// The status line's new text.
|
||||
pub status: Option<String>,
|
||||
/// Commands for the engine, in order.
|
||||
pub commands: Vec<Command>,
|
||||
/// What to keep, in order.
|
||||
pub persist: Vec<Persist>,
|
||||
/// Pictures the engine wrote again: a front end drops what it decoded
|
||||
/// of them.
|
||||
pub reloaded: Vec<PathBuf>,
|
||||
/// Servers whose gateway is to be looked up in DNS (bookmark id and
|
||||
/// address; [`crate::servers::logic::discover_wanted`] said so): the front
|
||||
/// end runs [`crate::servers::sequence::find_gateways`] on the engine's
|
||||
/// runtime and, when it finds some, calls
|
||||
/// [`crate::servers::sequence::gateway_found`] on its own thread.
|
||||
pub discover: Vec<(i64, String)>,
|
||||
/// The microphone meter: level in dBFS, and whether voice is sent.
|
||||
pub input_level: Option<(f32, bool)>,
|
||||
/// Open the password dialog.
|
||||
pub password: Option<PasswordPrompt>,
|
||||
/// Notices for the bell, in order.
|
||||
pub notices: Vec<NoticeRequest>,
|
||||
/// What went wrong that nothing else shows, for the log.
|
||||
pub warnings: Vec<String>,
|
||||
/// Chats whose messages changed (session, chat): the Stream Studio
|
||||
/// follows the chat of its channel.
|
||||
pub chats: Vec<(i64, ChatTarget)>,
|
||||
/// A stream to watch (its id): the one a lookup was waiting for, or the
|
||||
/// development switch's.
|
||||
pub watch: Option<String>,
|
||||
/// The capture and the decoder.
|
||||
pub stream: StreamEffects,
|
||||
/// A server connected or answered: the development switch that shares
|
||||
/// the test pattern may start now.
|
||||
pub autoshare: bool,
|
||||
/// The session on screen got its state or its presence: the development
|
||||
/// switch that opens the volume dialog of the first client may act.
|
||||
pub first_client: bool,
|
||||
/// The event, when its state is not in the [`AppState`]: the Stream
|
||||
/// Studio's stream (`Host::studio_streams_to`), a setting that changed (the
|
||||
/// settings service) and the answers to the offline message requests, which
|
||||
/// the messages page keeps. The watched and shared streams are not among
|
||||
/// them: they are state here and go through the stream effects. The front
|
||||
/// end handles these itself ([`crate::events`] lists them), before it draws
|
||||
/// what `refresh` names, as what it keeps may be on screen.
|
||||
pub rest: Option<Event>,
|
||||
}
|
||||
|
||||
/// The host and the update of a transition in progress.
|
||||
pub struct Cx<'a> {
|
||||
/// What the front end answers.
|
||||
pub host: &'a dyn Host,
|
||||
/// What is collected.
|
||||
pub update: Update,
|
||||
}
|
||||
|
||||
impl<'a> Cx<'a> {
|
||||
/// A transition that starts with nothing to tell.
|
||||
pub fn new(host: &'a dyn Host) -> Self {
|
||||
Self { host, update: Update::default() }
|
||||
}
|
||||
|
||||
/// The status line says this from now on.
|
||||
pub fn status(&mut self, text: impl Into<String>) {
|
||||
self.update.status = Some(text.into());
|
||||
}
|
||||
|
||||
/// A command for the engine.
|
||||
pub fn send(&mut self, command: Command) {
|
||||
self.update.commands.push(command);
|
||||
}
|
||||
|
||||
/// A command for the engine, but not for the sample sessions of
|
||||
/// `VOELIN_DEMO_UI`: the engine would open them for real.
|
||||
pub fn send_real(&mut self, command: Command) {
|
||||
if !self.host.demo_ui() {
|
||||
self.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
/// A request to a session's gateway (not for the sample sessions).
|
||||
pub fn gateway_to(&mut self, session: i64, request: GatewayRequest) {
|
||||
self.send_real(Command::Gateway { session: session as u64, request });
|
||||
}
|
||||
|
||||
/// Something went wrong that nothing else shows: it is logged.
|
||||
pub fn warn(&mut self, text: impl Into<String>) {
|
||||
self.update.warnings.push(text.into());
|
||||
}
|
||||
|
||||
/// Keep this.
|
||||
pub fn persist(&mut self, what: Persist) {
|
||||
self.update.persist.push(what);
|
||||
}
|
||||
|
||||
/// The password dialog of a locked channel opens.
|
||||
pub fn ask_password(&mut self, channel_name: String, wrong: bool) {
|
||||
self.update.password = Some(PasswordPrompt { name: channel_name, wrong });
|
||||
}
|
||||
|
||||
/// The chat `target` of session `id` changed.
|
||||
pub fn chat_changed(&mut self, id: i64, target: &ChatTarget) {
|
||||
self.update.chats.push((id, target.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A front end for the tests of the transitions.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod testing {
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
|
||||
|
||||
use super::Host;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::{
|
||||
AudioSettings, HistoryMessage, ObserveState, SessionState, Source, VoiceState,
|
||||
};
|
||||
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails};
|
||||
use voelin_store::{Bookmark, MessageSource};
|
||||
|
||||
use crate::bridge::ChatLine;
|
||||
use crate::settings::{ClientPlaybackMap, UiSettings};
|
||||
use crate::state::AppState;
|
||||
|
||||
/// The front end of the tests: answers what the transitions ask and keeps
|
||||
/// what they store.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Fake {
|
||||
pub(crate) demo: bool,
|
||||
pub(crate) shown: Cell<bool>,
|
||||
pub(crate) watching: bool,
|
||||
pub(crate) autowatch: bool,
|
||||
/// The session the Stream Studio streams to.
|
||||
pub(crate) studio: Option<i64>,
|
||||
pub(crate) limit: u64,
|
||||
/// The private chat on screen: session and peer.
|
||||
pub(crate) dm: Option<(i64, String)>,
|
||||
/// What time it is.
|
||||
pub(crate) now: Cell<i64>,
|
||||
/// What the store has: server unique id, its chats' reads.
|
||||
pub(crate) reads: HashMap<String, Vec<(StoredTarget, ChatRead)>>,
|
||||
/// What was stored.
|
||||
pub(crate) written: RefCell<Vec<(String, StoredTarget, ChatRead)>>,
|
||||
}
|
||||
|
||||
impl Host for Fake {
|
||||
fn demo_ui(&self) -> bool {
|
||||
self.demo
|
||||
}
|
||||
|
||||
fn chat_shown(&self) -> bool {
|
||||
self.shown.get()
|
||||
}
|
||||
|
||||
fn watching(&self) -> bool {
|
||||
self.watching
|
||||
}
|
||||
|
||||
fn autowatch(&self) -> bool {
|
||||
self.autowatch
|
||||
}
|
||||
|
||||
fn studio_streams_to(&self, session: i64) -> bool {
|
||||
self.studio == Some(session)
|
||||
}
|
||||
|
||||
fn preview_limit(&self) -> u64 {
|
||||
self.limit
|
||||
}
|
||||
|
||||
fn fetch_images(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn dm_shown(&self, session: i64, uid: &str) -> bool {
|
||||
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
|
||||
}
|
||||
|
||||
fn now_ms(&self) -> i64 {
|
||||
self.now.get()
|
||||
}
|
||||
|
||||
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
|
||||
Ok(self.reads.get(server_uid).cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn set_chat_read(
|
||||
&self,
|
||||
server_uid: &str,
|
||||
target: &StoredTarget,
|
||||
read: &ChatRead,
|
||||
) -> Result<(), String> {
|
||||
self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type State = AppState<Vec<ChatLine>>;
|
||||
|
||||
pub(crate) fn state() -> State {
|
||||
let bookmark = Bookmark {
|
||||
id: 1,
|
||||
name: "ts.example".into(),
|
||||
address: "ts.example".into(),
|
||||
nickname: "Me".into(),
|
||||
..Default::default()
|
||||
};
|
||||
AppState::new(
|
||||
vec![bookmark],
|
||||
UiSettings::default(),
|
||||
AudioSettings::default(),
|
||||
ClientPlaybackMap::new(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn session(voice: VoiceState, own_channel: Option<u64>) -> SessionState {
|
||||
let connected = voice == VoiceState::Connected;
|
||||
SessionState {
|
||||
voice,
|
||||
observe: ObserveState::Off,
|
||||
presence_source: connected.then_some(Source::Voice),
|
||||
own_channel,
|
||||
own_client: connected.then_some(10),
|
||||
server_uid: connected.then(|| "srv=".to_owned()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in
|
||||
/// Games).
|
||||
pub(crate) fn presence() -> Arc<Presence> {
|
||||
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
|
||||
for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] {
|
||||
p.channels
|
||||
.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() });
|
||||
}
|
||||
for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] {
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
channel: 2,
|
||||
nickname: name.into(),
|
||||
uid: Some(uid.into()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() };
|
||||
Arc::new(p)
|
||||
}
|
||||
|
||||
/// A message of Games, by Alice unless `mine`.
|
||||
pub(crate) fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage {
|
||||
HistoryMessage {
|
||||
id,
|
||||
message: ChatMessage {
|
||||
target: ChatTarget::Channel(2),
|
||||
author_name: if mine { "Me" } else { "Alice" }.into(),
|
||||
author_uid: Some(if mine { "me=" } else { "alice=" }.into()),
|
||||
author_id: Some(if mine { 10 } else { 11 }),
|
||||
text: text.into(),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
},
|
||||
source: MessageSource::Voice,
|
||||
remote_id: Some(id + 1000),
|
||||
topic_id: None,
|
||||
reactions: Vec::new(),
|
||||
pinned: false,
|
||||
rev: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::SystemTime;
|
||||
@@ -28,15 +30,8 @@ pub enum ImageSource {
|
||||
/// What the file was when the reference was made.
|
||||
stamp: Stamp,
|
||||
},
|
||||
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
|
||||
Rgba {
|
||||
/// Width in pixels.
|
||||
w: u32,
|
||||
/// Height in pixels.
|
||||
h: u32,
|
||||
/// `w * h * 4` bytes.
|
||||
bytes: Arc<[u8]>,
|
||||
},
|
||||
/// Decoded pixels; [`ImageSource::rgba`] makes them.
|
||||
Rgba(Pixels),
|
||||
/// An SVG document.
|
||||
Svg(Arc<[u8]>),
|
||||
/// A picture file held in memory (a chat picture downloaded for its
|
||||
@@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource {
|
||||
match self {
|
||||
Self::None => f.write_str("None"),
|
||||
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
|
||||
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
|
||||
Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()),
|
||||
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
|
||||
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
|
||||
}
|
||||
@@ -64,7 +59,7 @@ impl fmt::Debug for ImageSource {
|
||||
|
||||
/// What identifies a file's content without reading it: its length and the
|
||||
/// time it was last written. Both zero for a file that is missing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Stamp {
|
||||
len: u64,
|
||||
modified: Option<SystemTime>,
|
||||
@@ -88,6 +83,39 @@ pub struct Size {
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
|
||||
/// The length always fits the size (`width * height * 4`), so a front end
|
||||
/// can hand the bytes to its toolkit without checking them.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Pixels {
|
||||
w: u32,
|
||||
h: u32,
|
||||
bytes: Arc<[u8]>,
|
||||
}
|
||||
|
||||
impl Pixels {
|
||||
/// The pixels `bytes` hold, if there are `w * h * 4` of them.
|
||||
pub fn new(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> Option<Self> {
|
||||
let bytes = bytes.into();
|
||||
(bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes })
|
||||
}
|
||||
|
||||
/// Width in pixels.
|
||||
pub fn width(&self) -> u32 {
|
||||
self.w
|
||||
}
|
||||
|
||||
/// Height in pixels.
|
||||
pub fn height(&self) -> u32 {
|
||||
self.h
|
||||
}
|
||||
|
||||
/// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row.
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageSource {
|
||||
/// A reference to no picture.
|
||||
pub fn none() -> ImageRef {
|
||||
@@ -104,27 +132,24 @@ impl ImageSource {
|
||||
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
|
||||
/// alpha); no picture if the length does not fit.
|
||||
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
|
||||
let bytes = bytes.into();
|
||||
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
|
||||
Arc::new(Self::Rgba { w, h, bytes })
|
||||
} else {
|
||||
Self::none()
|
||||
}
|
||||
Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels)))
|
||||
}
|
||||
|
||||
/// The size the picture shows with; 0 by 0 when there is none or it can
|
||||
/// not be shown: a file that is missing, is not a picture, or is too
|
||||
/// large to decode (a front end drops those, as it would show nothing).
|
||||
/// A file's size is read from its header, once while it stays as it is;
|
||||
/// a vector picture has none of its own: its stated width and height,
|
||||
/// else 1 by 1.
|
||||
/// not be shown: a file that is missing, does not decode, or is too large
|
||||
/// to decode (a front end drops those, as it would show nothing). So a
|
||||
/// picture that has a size shows: a raster picture is decoded to tell
|
||||
/// (its first frame, as a front end would show it), an SVG document must
|
||||
/// parse. A file or a downloaded picture is checked once while it stays
|
||||
/// as it is; a vector picture has no size of its own: its stated width
|
||||
/// and height, else 1 by 1.
|
||||
pub fn size(&self) -> Size {
|
||||
match self {
|
||||
Self::None => Size::default(),
|
||||
Self::File { path, stamp } => file_size(path, *stamp),
|
||||
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
|
||||
Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() },
|
||||
Self::Svg(bytes) => svg_size(bytes),
|
||||
Self::Memory { bytes, .. } => bytes_size(bytes),
|
||||
Self::Memory { key, bytes } => memory_size(key, bytes),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,24 +163,38 @@ impl ImageSource {
|
||||
const MAX_DECODED_BYTES: u64 = 128 << 20;
|
||||
|
||||
fn checked(width: u32, height: u32) -> Size {
|
||||
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
|
||||
let bytes = u128::from(width) * u128::from(height) * 4;
|
||||
if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) {
|
||||
Size::default()
|
||||
} else {
|
||||
Size { width, height }
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of a picture file's bytes, told by content.
|
||||
/// What a picture file's bytes show as, told by content: a raster picture is
|
||||
/// decoded (its first frame; the size comes from the header, the decoding
|
||||
/// tells whether the rest of the file is a picture too), an SVG document
|
||||
/// must parse. Anything else, or anything that does not decode, shows
|
||||
/// nothing.
|
||||
fn bytes_size(bytes: &[u8]) -> Size {
|
||||
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
||||
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
|
||||
else {
|
||||
let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else {
|
||||
return Size::default();
|
||||
};
|
||||
if reader.format().is_none() {
|
||||
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
|
||||
}
|
||||
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
|
||||
// What a front end allows itself: 16 bits a channel take twice the bytes.
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
|
||||
reader.limits(limits);
|
||||
let Ok(decoder) = reader.into_decoder() else { return Size::default() };
|
||||
let (width, height) = image::ImageDecoder::dimensions(&decoder);
|
||||
let size = checked(width, height);
|
||||
if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() {
|
||||
return Size::default();
|
||||
}
|
||||
size
|
||||
}
|
||||
|
||||
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
|
||||
@@ -164,34 +203,25 @@ fn number(value: &str) -> Option<u32> {
|
||||
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
|
||||
}
|
||||
|
||||
/// The value of `name="…"` in the root tag of an SVG.
|
||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut rest = tag;
|
||||
while let Some(at) = rest.find(name) {
|
||||
let before = rest[..at].chars().next_back();
|
||||
let after = &rest[at + name.len()..];
|
||||
let after = after.trim_start();
|
||||
if before.is_none_or(char::is_whitespace)
|
||||
&& let Some(value) = after.strip_prefix('=')
|
||||
{
|
||||
let value = value.trim_start();
|
||||
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
|
||||
return value[1..].split(quote).next();
|
||||
}
|
||||
rest = &rest[at + name.len()..];
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The size of an SVG document: none unless it is XML (as the vector
|
||||
/// renderers read it, a doctype allowed) whose root is an `svg` element.
|
||||
fn svg_size(bytes: &[u8]) -> Size {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
|
||||
let tag = &text[start..];
|
||||
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
|
||||
const NAMESPACE: &str = "http://www.w3.org/2000/svg";
|
||||
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
||||
let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() };
|
||||
let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
|
||||
let Ok(document) = roxmltree::Document::parse_with_options(text, options) else {
|
||||
return Size::default();
|
||||
};
|
||||
let root = document.root_element();
|
||||
let name = root.tag_name();
|
||||
if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) {
|
||||
return Size::default();
|
||||
}
|
||||
let stated =
|
||||
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
|
||||
root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number));
|
||||
let boxed = || {
|
||||
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
|
||||
let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
|
||||
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
|
||||
number(w).zip(number(h))
|
||||
};
|
||||
@@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size {
|
||||
checked(width, height)
|
||||
}
|
||||
|
||||
/// What a probe of a file found, and what the file was then.
|
||||
type Probe = (Stamp, Size);
|
||||
/// What identifies the bytes a probe looked at.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Seen {
|
||||
/// A file as it was (length and time).
|
||||
File(Stamp),
|
||||
/// A picture in memory: its length and a hash of its bytes.
|
||||
Bytes(usize, u64),
|
||||
}
|
||||
|
||||
/// Probed files, so a picture shown in many rows is read once; entries are
|
||||
/// checked against the file's length and time before use.
|
||||
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
|
||||
/// Where a probed picture is.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum Probed {
|
||||
File(PathBuf),
|
||||
Memory(Arc<str>),
|
||||
}
|
||||
|
||||
/// Probed pictures with what they were then, so a picture shown in many
|
||||
/// rows is decoded once; an entry is checked against the picture's length
|
||||
/// and time (or bytes) before use.
|
||||
static PROBES: Mutex<Option<HashMap<Probed, (Seen, Size)>>> = Mutex::new(None);
|
||||
|
||||
/// Probes kept at most; the picture cache is far smaller than this.
|
||||
const MAX_PROBES: usize = 4096;
|
||||
|
||||
/// The size of the picture at `at`, from the cache when it is still the
|
||||
/// same, else from `probe` (run without the lock: it decodes).
|
||||
fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size {
|
||||
{
|
||||
let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at))
|
||||
&& *was == seen
|
||||
{
|
||||
return *size;
|
||||
}
|
||||
}
|
||||
let size = probe();
|
||||
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let probes = guard.get_or_insert_with(HashMap::new);
|
||||
if probes.len() >= MAX_PROBES {
|
||||
probes.clear();
|
||||
}
|
||||
probes.insert(at, (seen, size));
|
||||
size
|
||||
}
|
||||
|
||||
fn file_size(path: &Path, stamp: Stamp) -> Size {
|
||||
if stamp == Stamp::default() {
|
||||
return Size::default();
|
||||
}
|
||||
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let probes = guard.get_or_insert_with(HashMap::new);
|
||||
if let Some((was, size)) = probes.get(path)
|
||||
&& *was == stamp
|
||||
{
|
||||
return *size;
|
||||
}
|
||||
// The file is read with the lock held; probes are short and rare.
|
||||
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
|
||||
if probes.len() >= MAX_PROBES {
|
||||
probes.clear();
|
||||
}
|
||||
probes.insert(path.to_owned(), (stamp, size));
|
||||
size
|
||||
probed(Probed::File(path.to_owned()), Seen::File(stamp), || {
|
||||
std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes))
|
||||
})
|
||||
}
|
||||
|
||||
fn memory_size(key: &Arc<str>, bytes: &[u8]) -> Size {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(bytes);
|
||||
probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || {
|
||||
bytes_size(bytes)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -239,7 +301,15 @@ mod tests {
|
||||
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
|
||||
encoder.set_color(::png::ColorType::Rgba);
|
||||
encoder.set_depth(::png::BitDepth::Eight);
|
||||
let pixels = vec![200; width as usize * height as usize * 4];
|
||||
// Pixels that do not compress to nothing, so cutting the file short
|
||||
// cuts into the picture.
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let pixels: Vec<u8> = (0..width as usize * height as usize * 4)
|
||||
.map(|_| {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(seed >> 24) as u8
|
||||
})
|
||||
.collect();
|
||||
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
|
||||
bytes
|
||||
}
|
||||
@@ -257,8 +327,13 @@ mod tests {
|
||||
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
|
||||
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
|
||||
assert!(!pixels.is_empty());
|
||||
// The wrong length is no picture.
|
||||
// The wrong length is no picture, and no pixels either.
|
||||
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
|
||||
assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty());
|
||||
assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none());
|
||||
assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none());
|
||||
let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") };
|
||||
assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24));
|
||||
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
|
||||
}
|
||||
|
||||
@@ -284,6 +359,48 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_decode_shows_nothing() {
|
||||
let dir = temp("corrupt");
|
||||
let whole = png(32, 32);
|
||||
// The header is fine, the picture is cut short (a download that
|
||||
// stopped, a cache file written halfway).
|
||||
let cut = dir.join("cut");
|
||||
std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap();
|
||||
assert!(ImageSource::file(&cut).is_empty());
|
||||
// The header is fine, the data is not: flipped bytes in the image
|
||||
// data, from the middle of the file to its end.
|
||||
let mut flipped = whole.clone();
|
||||
let from = flipped.len() / 2;
|
||||
for byte in &mut flipped[from..] {
|
||||
*byte = !*byte;
|
||||
}
|
||||
let garbled = dir.join("garbled");
|
||||
std::fs::write(&garbled, &flipped).unwrap();
|
||||
assert!(ImageSource::file(&garbled).is_empty());
|
||||
// The whole file shows, and the answer is kept while it stays so.
|
||||
let good = dir.join("good");
|
||||
std::fs::write(&good, &whole).unwrap();
|
||||
assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 });
|
||||
// A file that is made whole shows (another stamp: another answer).
|
||||
std::fs::write(&cut, &whole).unwrap();
|
||||
assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 });
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_downloaded_picture_is_checked_too() {
|
||||
let whole = png(16, 16);
|
||||
let memory =
|
||||
|key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() };
|
||||
assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 });
|
||||
assert!(memory("cut", &whole[..whole.len() / 2]).is_empty());
|
||||
// The same key with other bytes is another picture.
|
||||
assert!(memory("same", &whole[..whole.len() / 2]).is_empty());
|
||||
assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 });
|
||||
assert!(memory("none", b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_pictures() {
|
||||
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
|
||||
@@ -296,6 +413,24 @@ mod tests {
|
||||
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
|
||||
.is_empty()
|
||||
);
|
||||
// Not an SVG document: cut off, a sibling of the root, other roots,
|
||||
// not text.
|
||||
assert!(size("<svg width=\"8\" height=\"8\"").width == 0);
|
||||
assert!(size("<svg width=\"8\" height=\"8\"><g>").width == 0);
|
||||
assert!(size("<svg width=\"8\" height=\"8\"/><svg/>").width == 0);
|
||||
assert!(size("<html width=\"8\" height=\"8\"/>").width == 0);
|
||||
assert!(size("<svg xmlns='urn:other' width='8' height='8'/>").width == 0);
|
||||
assert_eq!(
|
||||
size("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='9'/>").height,
|
||||
9
|
||||
);
|
||||
assert!(
|
||||
ImageSource::Svg(b"<svg width='8' height='8'>\xff</svg>".as_slice().into()).is_empty()
|
||||
);
|
||||
// A doctype, as editors write it.
|
||||
let doctype = "<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \
|
||||
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"5\" height=\"6\"/>";
|
||||
assert_eq!(size(doctype), Size { width: 5, height: 6 });
|
||||
// An SVG file with a byte order mark and a prolog, and in memory.
|
||||
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
|
||||
let dir = temp("svg");
|
||||
|
||||
@@ -3,17 +3,26 @@
|
||||
//! Neither Slint nor GPUI is a dependency; each front end converts these
|
||||
//! types (docs/ui.md, "Two crates").
|
||||
|
||||
// Every public item is documented, the 559 fields of the two mirror modules
|
||||
// (`bridge`, `studio_bridge`) included.
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod avatar;
|
||||
pub mod bbcode;
|
||||
pub mod bridge;
|
||||
pub mod chat;
|
||||
pub mod color;
|
||||
pub mod dev;
|
||||
pub mod emoji;
|
||||
pub mod events;
|
||||
pub mod home;
|
||||
pub mod host;
|
||||
pub mod image;
|
||||
pub mod list;
|
||||
pub mod previews;
|
||||
pub mod servers;
|
||||
pub mod settings;
|
||||
pub mod settings_page;
|
||||
pub mod settings_pages;
|
||||
pub mod social;
|
||||
pub mod state;
|
||||
@@ -23,4 +32,4 @@ pub mod studio_bridge;
|
||||
pub mod tree;
|
||||
|
||||
pub use color::Rgb;
|
||||
pub use image::{ImageRef, ImageSource, Size};
|
||||
pub use image::{ImageRef, ImageSource, Pixels, Size};
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or
|
||||
//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into
|
||||
//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`,
|
||||
//! voice connections only) and the chat shows it as a picture card, and a
|
||||
//! click opens it larger. A picture on the web a message shows (`[img]`)
|
||||
//! comes the way banners do, into the engine's cache (`Command::FetchPicture`,
|
||||
//! up to the same size, only with `cache.fetch_images`), and until it is
|
||||
//! there the message shows its address.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
|
||||
use voelin_model::{ChatTarget, FileRef};
|
||||
|
||||
use crate::host::Cx;
|
||||
use crate::image::{ImageRef, ImageSource};
|
||||
use crate::state::{AppState, Preview, SessionView};
|
||||
|
||||
/// Whether a file name is a picture the chat shows inline.
|
||||
pub fn is_previewable(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
|
||||
}
|
||||
|
||||
/// The key of a link: where the file is.
|
||||
pub fn link_key(file: &FileRef) -> String {
|
||||
format!(
|
||||
"{}/{}{}{}",
|
||||
file.server_uid.as_deref().unwrap_or(""),
|
||||
file.channel,
|
||||
file.path,
|
||||
file.name
|
||||
)
|
||||
}
|
||||
|
||||
/// The picture of a link, if it is there and shows.
|
||||
pub fn image_of<L>(view: &SessionView<L>, file: &FileRef) -> Option<ImageRef> {
|
||||
let key = link_key(file);
|
||||
match view.extra.previews.get(&key)? {
|
||||
Preview::Ready(bytes) => {
|
||||
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
|
||||
(!image.is_empty()).then_some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Download the pictures linked in the current chat of `session` that are
|
||||
/// not there yet.
|
||||
pub fn fetch_previews<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
|
||||
if cx.host.demo_ui() {
|
||||
return;
|
||||
}
|
||||
let limit = cx.host.preview_limit();
|
||||
if limit == 0 {
|
||||
return;
|
||||
}
|
||||
fetch_web_pictures(state, cx, session, limit);
|
||||
let Some(view) = state.sessions.get_mut(&session) else { return };
|
||||
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
|
||||
return;
|
||||
}
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return };
|
||||
// Channel chats only: a link names its channel's file browser.
|
||||
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
|
||||
return;
|
||||
}
|
||||
let wanted: Vec<FileRef> = tab
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.take(200)
|
||||
.flat_map(|m| m.message.message.file_refs())
|
||||
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
|
||||
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
|
||||
.collect();
|
||||
for file in wanted {
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
|
||||
cx.send(Command::DownloadChatFile {
|
||||
session: session as u64,
|
||||
transfer,
|
||||
file,
|
||||
password: None,
|
||||
to: DownloadTo::Memory,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the engine for the pictures on the web (`[img]`) of the current chat
|
||||
/// of `session` that it has not reported; it fetches each once.
|
||||
fn fetch_web_pictures<L>(state: &AppState<L>, cx: &mut Cx<'_>, session: i64, limit: u64) {
|
||||
if !cx.host.fetch_images() {
|
||||
return;
|
||||
}
|
||||
let Some(view) = state.sessions.get(&session) else { return };
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return };
|
||||
// The server chat starts with the server's messages.
|
||||
let server = match tab.target {
|
||||
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let wanted: Vec<String> = tab
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.take(200)
|
||||
.map(|m| m.message.message.text.as_str())
|
||||
.chain(server.into_iter().map(|(text, _)| text))
|
||||
.flat_map(crate::chat::web_pictures)
|
||||
.filter(|url| !view.pictures.contains_key(url))
|
||||
.collect();
|
||||
for url in wanted {
|
||||
cx.send(Command::FetchPicture { session: session as u64, url, max_bytes: limit });
|
||||
}
|
||||
}
|
||||
|
||||
/// A transfer of a picture: `true` if it was one.
|
||||
pub fn preview_progress<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
session: i64,
|
||||
transfer: u64,
|
||||
progress: &TransferState,
|
||||
) -> bool {
|
||||
let limit = cx.host.preview_limit();
|
||||
let current = state.current == Some(session);
|
||||
let Some(view) = state.sessions.get_mut(&session) else { return false };
|
||||
let Some(key) = view
|
||||
.extra
|
||||
.previews
|
||||
.iter()
|
||||
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
|
||||
.map(|(k, _)| k.clone())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match progress {
|
||||
TransferState::Started { size, .. } if *size > limit => {
|
||||
view.extra.previews.insert(key, Preview::Failed);
|
||||
cx.send_real(Command::CancelTransfer { session: session as u64, transfer });
|
||||
}
|
||||
TransferState::Done { data: Some(data), .. } => {
|
||||
view.extra.previews.insert(key, Preview::Ready(data.clone()));
|
||||
if current {
|
||||
cx.update.refresh.chat = true;
|
||||
}
|
||||
}
|
||||
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
|
||||
view.extra.previews.insert(key, Preview::Failed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn previewable_names() {
|
||||
assert!(is_previewable("Banner.PNG"));
|
||||
assert!(is_previewable("a.webp"));
|
||||
assert!(!is_previewable("notes.svg"));
|
||||
assert!(!is_previewable("route.pdf"));
|
||||
let file =
|
||||
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
|
||||
assert_eq!(link_key(&file), "/2/a.png");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,992 @@
|
||||
//! Servers: what the rail, the server card and the channel tree show, which
|
||||
//! server is shown and how it is observed, the gateway found for it, and
|
||||
//! joining a channel. The functions change the [`AppState`] and say in the
|
||||
//! [`Cx`]'s update what to draw and send; the store, the secrets, the identity
|
||||
//! and the sockets are the front end's.
|
||||
|
||||
use voelin_core::ts::identity::LaunchImport;
|
||||
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_model::{ChannelId, ChatTarget};
|
||||
use voelin_store::{Bookmark, QueryConfig};
|
||||
|
||||
use super::{JoinStep, item, join_password, tints};
|
||||
use crate::bridge::{BookmarkForm, MemberItem, ServerItem, TreeItem};
|
||||
use crate::chat::logic::{open_chat, prefetch_counts, save_reads, track_reading};
|
||||
use crate::host::{Cx, Persist};
|
||||
use crate::image::ImageRef;
|
||||
use crate::state::{AppState, Lines, SessionView};
|
||||
|
||||
/// The name of the identity the app creates when it has none.
|
||||
pub const CREATED_IDENTITY: &str = "Default";
|
||||
|
||||
/// What to tell the user about the identities imported from the official
|
||||
/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything.
|
||||
pub fn imported_status(report: &LaunchImport) -> Option<String> {
|
||||
let n = report.added.len();
|
||||
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
|
||||
let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() };
|
||||
Some(match &report.default {
|
||||
Some(f) if report.replaced => format!(
|
||||
"You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}",
|
||||
f.nickname
|
||||
),
|
||||
Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname),
|
||||
None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
|
||||
None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"),
|
||||
None => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The bookmark the form describes, over `old` (what the form does not show,
|
||||
/// like the identity, the default channel or the client version, stays; a
|
||||
/// new server has none of it). Only the address is needed: the name is the
|
||||
/// address until the server tells its own, the nickname `default_nickname`,
|
||||
/// the gateway is looked up in DNS. A new address drops the gateway and the
|
||||
/// query login found or set for the old one.
|
||||
pub fn bookmark_from_form(
|
||||
old: Option<&Bookmark>,
|
||||
form: &BookmarkForm,
|
||||
default_nickname: impl FnOnce() -> String,
|
||||
) -> Bookmark {
|
||||
let mut bookmark = old.cloned().unwrap_or_default();
|
||||
bookmark.id = form.id as i64;
|
||||
bookmark.address = form.address.trim().to_string();
|
||||
if old.is_some_and(|old| old.address != bookmark.address) {
|
||||
bookmark.cached_server_icon = None;
|
||||
bookmark.gateway_url = None;
|
||||
bookmark.gateway_urls.clear();
|
||||
bookmark.query = None;
|
||||
}
|
||||
bookmark.name = match form.name.trim() {
|
||||
"" => bookmark.address.clone(),
|
||||
name => name.to_string(),
|
||||
};
|
||||
bookmark.nickname = match form.nickname.trim() {
|
||||
"" => default_nickname(),
|
||||
nickname => nickname.to_string(),
|
||||
};
|
||||
bookmark
|
||||
}
|
||||
|
||||
/// Whether observing goes on as it is when discovery changed the gateways
|
||||
/// kept from `previous` to `found`: the same ones (an older version kept
|
||||
/// only the one in use), or logged in through `in_use`, still published.
|
||||
/// What was found is kept for the next start, without a new login now.
|
||||
pub fn observing_stays(
|
||||
previous: &[String],
|
||||
found: &[String],
|
||||
in_use: Option<&str>,
|
||||
observe: ObserveState,
|
||||
) -> bool {
|
||||
found == previous
|
||||
|| (observe == ObserveState::Observing
|
||||
&& in_use.is_some_and(|url| found.iter().any(|u| u == url)))
|
||||
}
|
||||
|
||||
/// The options of a voice connection to `bookmark`, into `channel` (a path,
|
||||
/// or `/<id>`, with its password) if given, with a privilege key if given;
|
||||
/// the reason when the bookmark's client version is not one. The identity,
|
||||
/// the server's password and the stream peer are the front end's to add.
|
||||
pub fn voice_options(
|
||||
bookmark: &Bookmark,
|
||||
channel: Option<String>,
|
||||
channel_password: Option<String>,
|
||||
token: Option<String>,
|
||||
) -> Result<VoiceOptions, String> {
|
||||
let mut options = VoiceOptions::new(&bookmark.address, &bookmark.nickname);
|
||||
if let Some(spec) = &bookmark.client_version {
|
||||
// The engine resolves the spec when it connects; asking now tells the
|
||||
// user at once.
|
||||
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
|
||||
return Err(format!("Invalid client compatibility version: {error}"));
|
||||
}
|
||||
options.client_version = Some(spec.clone());
|
||||
}
|
||||
options.channel = channel;
|
||||
options.channel_password = channel_password;
|
||||
options.token = token;
|
||||
options.audio = true;
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
// Which server is shown, and how it is observed.
|
||||
|
||||
/// Show a server (the front end then observes it).
|
||||
pub fn select_server<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
|
||||
state.current = Some(id);
|
||||
prefetch_counts(state, cx);
|
||||
track_reading(state, cx);
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
|
||||
}
|
||||
|
||||
/// A server was removed from the list (the store has the rest now): its
|
||||
/// session goes, and the first server is shown.
|
||||
pub fn forget_server<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
id: i64,
|
||||
bookmarks: Vec<Bookmark>,
|
||||
) {
|
||||
save_reads(state, cx, id);
|
||||
state.sessions.remove(&id);
|
||||
state.gateways_looked_up.remove(&id);
|
||||
state.bookmarks = bookmarks;
|
||||
state.current = state.bookmarks.first().map(|b| b.id);
|
||||
prefetch_counts(state, cx);
|
||||
track_reading(state, cx);
|
||||
let r = &mut cx.update.refresh;
|
||||
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
|
||||
}
|
||||
|
||||
/// What observing a server invisibly comes to ([`observe_plan`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ObservePlan {
|
||||
/// Nothing to do: it is observed already, or there is no server.
|
||||
Nothing,
|
||||
/// The gateway is still being connected to: the engine tries it again
|
||||
/// now.
|
||||
Retry(Vec<String>),
|
||||
/// Observe through these gateways (best first), and look the gateway up
|
||||
/// again; the status line says so.
|
||||
Gateway(Vec<String>),
|
||||
/// Observe through the server's own query login; the status line says so.
|
||||
Query(QueryConfig),
|
||||
/// There is neither: the gateway is looked up, and observing starts
|
||||
/// when it is found.
|
||||
Discover,
|
||||
}
|
||||
|
||||
/// How to observe server `id` invisibly, unless it is already: through its
|
||||
/// gateway, else its own query login. Without either the gateway is looked
|
||||
/// up first, and observing starts when it is found. Asked while still
|
||||
/// connecting, the engine tries the gateway again sooner.
|
||||
pub fn observe_plan<L>(state: &AppState<L>, cx: &Cx<'_>, id: i64) -> ObservePlan {
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else { return ObservePlan::Nothing };
|
||||
if cx.host.demo_ui() {
|
||||
return ObservePlan::Nothing;
|
||||
}
|
||||
let observing = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
|
||||
let urls = b.gateways();
|
||||
match observing {
|
||||
ObserveState::Observing => return ObservePlan::Nothing,
|
||||
// The engine decides: the same gateways are not started over, at most
|
||||
// tried again now.
|
||||
ObserveState::Connecting => {
|
||||
return if urls.is_empty() { ObservePlan::Nothing } else { ObservePlan::Retry(urls) };
|
||||
}
|
||||
ObserveState::Off => {}
|
||||
}
|
||||
if !urls.is_empty() {
|
||||
ObservePlan::Gateway(urls)
|
||||
} else if let Some(q) = &b.query {
|
||||
ObservePlan::Query(q.clone())
|
||||
} else {
|
||||
ObservePlan::Discover
|
||||
}
|
||||
}
|
||||
|
||||
/// The address of server `id` to look the gateway up for, once a run (not
|
||||
/// for the sample sessions).
|
||||
pub fn discover_wanted<L>(state: &mut AppState<L>, cx: &Cx<'_>, id: i64) -> Option<String> {
|
||||
if cx.host.demo_ui() || !state.gateways_looked_up.insert(id) {
|
||||
return None;
|
||||
}
|
||||
state.bookmarks.iter().find(|b| b.id == id).map(|b| b.address.clone())
|
||||
}
|
||||
|
||||
/// What finding the gateways of a server comes to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GatewayFound {
|
||||
/// Nothing changed, or the server is another one now.
|
||||
Same,
|
||||
/// Kept, and observing goes on as it is; `observe` when the server on
|
||||
/// screen is not observed yet.
|
||||
Kept {
|
||||
/// Observe the server now.
|
||||
observe: bool,
|
||||
},
|
||||
/// Kept, and the old ones are left: observing was through them. The
|
||||
/// server on screen is observed through the new ones.
|
||||
Changed {
|
||||
/// The gateways observed through before (the engine stops them).
|
||||
stop: bool,
|
||||
/// Observe the server now.
|
||||
observe: bool,
|
||||
/// Every URL the server publishes, best first, for the log.
|
||||
urls: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Gateways were found for the server at `address` (best first); they are
|
||||
/// kept unless the server changed meanwhile. Users never hear of them
|
||||
/// (logged only).
|
||||
pub fn gateway_found<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
id: i64,
|
||||
address: &str,
|
||||
urls: Vec<String>,
|
||||
) -> GatewayFound {
|
||||
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
|
||||
return GatewayFound::Same;
|
||||
};
|
||||
let previous = b.gateways();
|
||||
let in_use = b.gateway_url.clone();
|
||||
if !b.set_gateways(urls) {
|
||||
return GatewayFound::Same;
|
||||
}
|
||||
cx.persist(Persist::Bookmark { id, what: "gateway found" });
|
||||
let found = b.gateways();
|
||||
let observe = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
|
||||
let kept = observing_stays(&previous, &found, in_use.as_deref(), observe);
|
||||
cx.update.refresh.toolbar = true;
|
||||
let current = state.current == Some(id);
|
||||
if kept {
|
||||
return GatewayFound::Kept { observe: current && observe == ObserveState::Off };
|
||||
}
|
||||
// Observed through the old ones: through these now.
|
||||
let stop = !previous.is_empty();
|
||||
if stop && let Some(view) = state.sessions.get_mut(&id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
}
|
||||
GatewayFound::Changed { stop, observe: current, urls: found }
|
||||
}
|
||||
|
||||
// Joining a channel.
|
||||
|
||||
/// Join a channel of a session (a double-click in the tree, joining a
|
||||
/// friend): move there with voice, or the password to connect into it with
|
||||
/// when there is no voice on that server. A locked channel asks for its
|
||||
/// password first, unless it was given this connection.
|
||||
pub fn join_channel<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
) -> Option<Option<String>> {
|
||||
let view = state.sessions.get(&session)?;
|
||||
let info = view.presence.channels.get(&channel)?;
|
||||
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
|
||||
match join_password(info, remembered) {
|
||||
JoinStep::Send(password) => enter_channel(state, cx, session, channel, password),
|
||||
JoinStep::Ask => {
|
||||
crate::events::ask_password(state, cx, session, channel, false);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The password dialog's Join: the same, with that password.
|
||||
pub fn join_with_password<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
password: String,
|
||||
) -> Option<(i64, ChannelId, Option<String>)> {
|
||||
let (session, channel) = state.join_target.take()?;
|
||||
if password.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(view) = state.sessions.get_mut(&session) {
|
||||
view.channel_passwords.insert(channel, password.clone());
|
||||
}
|
||||
enter_channel(state, cx, session, channel, Some(password)).map(|p| (session, channel, p))
|
||||
}
|
||||
|
||||
/// Move into a channel; without voice on its server the front end connects
|
||||
/// into it, with the password returned.
|
||||
pub fn enter_channel<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
) -> Option<Option<String>> {
|
||||
let view = state.sessions.get_mut(&session)?;
|
||||
if view.state.voice != VoiceState::Disconnected {
|
||||
// Chosen while connecting: no longer the one to join after.
|
||||
view.join_after_connect = None;
|
||||
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
|
||||
return None;
|
||||
}
|
||||
Some(password)
|
||||
}
|
||||
|
||||
/// Voice is being connected into `channel` of session `session`: once
|
||||
/// connected, it is joined again if the server put us elsewhere.
|
||||
pub fn join_after_connect<L>(state: &mut AppState<L>, session: i64, channel: ChannelId) {
|
||||
if let Some(view) = state.sessions.get_mut(&session) {
|
||||
view.join_after_connect = Some(channel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold or unfold a channel of the current session.
|
||||
pub fn toggle_collapse<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, channel: ChannelId) {
|
||||
if let Some(id) = state.current {
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
if !view.collapsed.remove(&channel) {
|
||||
view.collapsed.insert(channel);
|
||||
}
|
||||
}
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
|
||||
/// The members panel's search.
|
||||
pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String) {
|
||||
if state.member_filter != text {
|
||||
state.member_filter = text;
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the card of a client of the server shown over the members panel
|
||||
/// (`None` closes it).
|
||||
pub fn open_member<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, client: Option<u16>) {
|
||||
let Some(view) = state.current.and_then(|id| state.sessions.get_mut(&id)) else { return };
|
||||
if view.member_card != client {
|
||||
view.member_card = client;
|
||||
cx.update.refresh.member_card = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice channel view was opened or closed: its chat is our channel's,
|
||||
/// and its people lead the members panel.
|
||||
pub fn show_voice_view<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) {
|
||||
state.voice_view = on;
|
||||
let channel =
|
||||
state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| v.state.own_channel);
|
||||
if on && let Some(channel) = channel {
|
||||
open_chat(state, cx, ChatTarget::Channel(channel), true);
|
||||
}
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
|
||||
/// A link to the voice channel we are in, for the Invite button (which
|
||||
/// copies it, and the copy's toast names the channel); the reason without
|
||||
/// one.
|
||||
pub fn invite_link<L>(state: &mut AppState<L>) -> Result<String, &'static str> {
|
||||
let address = state
|
||||
.current
|
||||
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
|
||||
.map(|b| b.address.clone());
|
||||
let path = state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| {
|
||||
let cid = v.state.own_channel?;
|
||||
let own = v.presence.channels.get(&cid)?;
|
||||
// The link names the channels as the server has them; the toast as
|
||||
// the tree shows them.
|
||||
Some((
|
||||
crate::tree::channel_path(&v.presence, cid),
|
||||
crate::tree::channel_title(own).0.to_owned(),
|
||||
))
|
||||
});
|
||||
let (Some(address), Some((path, title))) = (address, path) else {
|
||||
return Err("Join a voice channel to invite others to it");
|
||||
};
|
||||
let path: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
let link = super::invite_link(&address, &path);
|
||||
state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
|
||||
Ok(link)
|
||||
}
|
||||
|
||||
// What is shown.
|
||||
|
||||
/// The rail: servers with their state, unread count (without private chats)
|
||||
/// and streams. `icon` gives a server's icon (what its session fetched, else
|
||||
/// what was cached).
|
||||
pub fn rail<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> Vec<ServerItem> {
|
||||
state
|
||||
.bookmarks
|
||||
.iter()
|
||||
.zip(tints(&state.bookmarks))
|
||||
.map(|(b, tint)| {
|
||||
let view = state.sessions.get(&b.id);
|
||||
let session = view.map(|v| v.state.clone()).unwrap_or_default();
|
||||
let unread = view.map_or(0, SessionView::channel_unread);
|
||||
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
|
||||
let detail = view
|
||||
.filter(|v| !v.presence.channels.is_empty())
|
||||
.map(|v| crate::tree::stats(&v.presence))
|
||||
.unwrap_or_default();
|
||||
let product = view.map(|v| v.extra.product.clone()).unwrap_or_default();
|
||||
item(b, &session, unread, live, detail, product, icon(b), tint)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A server's colour, as the rail shows it; none for a server that is not
|
||||
/// in the list (a chat that outlived its bookmark).
|
||||
pub fn server_tint<L>(state: &AppState<L>, id: i64) -> Option<crate::color::Rgb> {
|
||||
let position = state.bookmarks.iter().position(|b| b.id == id)?;
|
||||
Some(tints(&state.bookmarks)[position])
|
||||
}
|
||||
|
||||
/// The colour of a chat's avatar in a list: the server's own colour, as the
|
||||
/// rail shows it, for the chat of a server (`kind` 0 of a
|
||||
/// [`ConversationItem`](crate::bridge::ConversationItem)) that is still in
|
||||
/// the list; for every other chat, and for a server chat that outlived its
|
||||
/// bookmark, the colour of the `title`, never black.
|
||||
pub fn conversation_tint<L>(
|
||||
state: &AppState<L>,
|
||||
kind: i32,
|
||||
session: Option<i64>,
|
||||
title: &str,
|
||||
) -> crate::color::Rgb {
|
||||
match (kind, session) {
|
||||
(0, Some(session)) => server_tint(state, session),
|
||||
_ => None,
|
||||
}
|
||||
.unwrap_or_else(|| crate::avatar::tint(title))
|
||||
}
|
||||
|
||||
/// The server card, the voice controls and who we are.
|
||||
pub struct ToolbarView {
|
||||
/// The server's icon.
|
||||
pub server_icon: ImageRef,
|
||||
/// Its name.
|
||||
pub server_title: String,
|
||||
/// "9 online · 7 channels", once its presence is known.
|
||||
pub server_stats: String,
|
||||
/// Our nickname there.
|
||||
pub nickname: String,
|
||||
/// Our avatar.
|
||||
pub own_avatar: ImageRef,
|
||||
/// The server's banner.
|
||||
pub server_banner: ImageRef,
|
||||
/// How it is drawn.
|
||||
pub server_banner_mode: i32,
|
||||
/// The channel we are in.
|
||||
pub own_channel: String,
|
||||
/// Its topic.
|
||||
pub own_channel_topic: String,
|
||||
/// Its banner.
|
||||
pub own_channel_banner: ImageRef,
|
||||
/// How it is drawn.
|
||||
pub own_channel_banner_mode: i32,
|
||||
/// Its client limit, -1 without one.
|
||||
pub own_channel_limit: i32,
|
||||
/// Voice is connected.
|
||||
pub voice_connected: bool,
|
||||
/// Voice is connecting.
|
||||
pub voice_connecting: bool,
|
||||
/// The server is observed.
|
||||
pub observing: bool,
|
||||
/// Our microphone is muted.
|
||||
pub input_muted: bool,
|
||||
/// Our sound is muted.
|
||||
pub output_muted: bool,
|
||||
/// Voice is transmitted.
|
||||
pub transmitting: bool,
|
||||
/// Where the presence comes from, for people to read.
|
||||
pub presence_source: &'static str,
|
||||
}
|
||||
|
||||
/// The server card for the current server; `icon` is its icon.
|
||||
pub fn toolbar<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> ToolbarView {
|
||||
let bookmark = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id));
|
||||
let view = state.current.and_then(|id| state.sessions.get(&id));
|
||||
let session = view.map(|v| v.state.clone()).unwrap_or_default();
|
||||
let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty())
|
||||
&& (session.voice == VoiceState::Connected || session.observe == ObserveState::Observing);
|
||||
let own = view.zip(session.own_client).and_then(|(v, c)| v.avatar(c));
|
||||
let banner =
|
||||
|url: Option<&str>| view.map(|v| crate::tree::banner(&v.pictures, url)).unwrap_or_default();
|
||||
let details = view.map(|v| &v.presence.server);
|
||||
let own_channel =
|
||||
view.and_then(|v| session.own_channel.and_then(|c| v.presence.channels.get(&c)));
|
||||
ToolbarView {
|
||||
server_icon: bookmark.map(&icon).unwrap_or_default(),
|
||||
server_title: bookmark.map_or("No server selected".into(), |b| b.name.clone()),
|
||||
server_stats: view
|
||||
.filter(|_| has_presence)
|
||||
.map(|v| crate::tree::stats(&v.presence))
|
||||
.unwrap_or_default(),
|
||||
nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default(),
|
||||
own_avatar: crate::avatar::image(own),
|
||||
server_banner: banner(details.map(|d| d.banner_gfx_url.as_str())),
|
||||
server_banner_mode: details.map_or(0, |d| crate::tree::banner_mode(d.banner_mode)),
|
||||
own_channel: own_channel
|
||||
.map(|c| crate::tree::channel_title(c).0.to_owned())
|
||||
.unwrap_or_default(),
|
||||
own_channel_topic: own_channel.and_then(|c| c.topic.clone()).unwrap_or_default(),
|
||||
own_channel_banner: banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())),
|
||||
own_channel_banner_mode: own_channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)),
|
||||
own_channel_limit: own_channel
|
||||
.and_then(|c| c.max_clients)
|
||||
.filter(|m| *m >= 0)
|
||||
.unwrap_or(-1),
|
||||
voice_connected: session.voice == VoiceState::Connected,
|
||||
voice_connecting: session.voice == VoiceState::Connecting,
|
||||
observing: session.observe != ObserveState::Off,
|
||||
input_muted: session.input_muted,
|
||||
output_muted: session.output_muted,
|
||||
transmitting: session.transmitting,
|
||||
presence_source: match session.presence_source {
|
||||
Some(Source::Voice) => "live (voice)",
|
||||
Some(Source::Gateway) => "invisible (gateway)",
|
||||
Some(Source::Query) => "invisible (query)",
|
||||
None => "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The channel tree and the members.
|
||||
pub struct TreeView {
|
||||
/// The channels and clients, as the tree lists them.
|
||||
pub rows: Vec<TreeItem>,
|
||||
/// The members of our channel (while voice is connected).
|
||||
pub members: Vec<MemberItem>,
|
||||
/// Everyone on the server, filtered by the panel's search.
|
||||
pub server_members: Vec<MemberItem>,
|
||||
/// How many are on the server (without query clients).
|
||||
pub member_total: i32,
|
||||
}
|
||||
|
||||
/// The channel tree, the members of our channel and everyone on the server;
|
||||
/// none when no server is shown. `popped_out`: the stream plays in a window
|
||||
/// of its own.
|
||||
pub fn tree_view<L>(state: &AppState<L>, popped_out: bool) -> Option<TreeView> {
|
||||
let view = state.current.and_then(|id| state.sessions.get(&id))?;
|
||||
let input = crate::tree::TreeInput {
|
||||
presence: &view.presence,
|
||||
collapsed: &view.collapsed,
|
||||
talking: &view.talking,
|
||||
playback: &state.playback,
|
||||
own_channel: view.state.own_channel,
|
||||
own_client: view.state.own_client,
|
||||
filter: "",
|
||||
avatars: &view.avatars,
|
||||
icons: &view.icons,
|
||||
pictures: &view.pictures,
|
||||
groups: &view.server_groups,
|
||||
channel_groups: &view.channel_groups,
|
||||
};
|
||||
let rows = crate::tree::rows(&input);
|
||||
let connected = view.state.voice == VoiceState::Connected;
|
||||
let members = if connected { crate::tree::members(&input) } else { Vec::new() };
|
||||
// The people in our channel first while their view is shown (not while
|
||||
// the stream plays in a window of its own).
|
||||
let watching = state.watch.as_ref().is_some_and(|w| w.shown) && !popped_out;
|
||||
let voice_first = connected && (state.voice_view || watching);
|
||||
let everyone = crate::tree::server_members(&input, voice_first);
|
||||
let filter = state.member_filter.trim().to_lowercase();
|
||||
let server_members =
|
||||
if filter.is_empty() { everyone } else { crate::tree::matching(everyone, &filter) };
|
||||
Some(TreeView {
|
||||
rows,
|
||||
members,
|
||||
server_members,
|
||||
member_total: view.presence.clients.values().filter(|c| !c.is_query).count() as i32,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_core::SessionState;
|
||||
use voelin_model::ChannelInfo;
|
||||
|
||||
use super::*;
|
||||
use crate::host::testing::{Fake, State, presence, session, state};
|
||||
|
||||
fn bookmark(id: i64, name: &str, address: &str) -> Bookmark {
|
||||
Bookmark { id, name: name.into(), address: address.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
|
||||
use crate::events::apply_server_icon;
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("voelin-server-icon-edited-{}.svg", std::process::id()));
|
||||
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
|
||||
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
|
||||
let mut view = SessionView::<()>::default();
|
||||
view.icons.insert(1234, path.clone());
|
||||
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
|
||||
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
|
||||
|
||||
bookmark = bookmark_from_form(
|
||||
Some(&bookmark),
|
||||
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|
||||
|| "Me".into(),
|
||||
);
|
||||
// Connecting does not retag received imagery. A failed B connection
|
||||
// must not make A's image appear under B's name.
|
||||
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
|
||||
view.state.voice = state;
|
||||
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
|
||||
}
|
||||
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
|
||||
assert_eq!(view.server_icon, 1234);
|
||||
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
|
||||
assert!(bookmark.server_icon_id().is_none());
|
||||
|
||||
// Equal icon IDs on the next server still need new provenance.
|
||||
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
|
||||
assert_eq!(bookmark.server_icon_id(), Some(1234));
|
||||
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
|
||||
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
|
||||
assert_eq!(bookmark.server_icon_id(), Some(1234));
|
||||
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
|
||||
assert!(bookmark.server_icon_id().is_none());
|
||||
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_address_alone_makes_a_server() {
|
||||
let form =
|
||||
BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() };
|
||||
let b = bookmark_from_form(None, &form, || "Nick".into());
|
||||
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
|
||||
assert_eq!(b.nickname, "Nick");
|
||||
assert_eq!(
|
||||
(b.gateway_url, b.query, b.identity, b.default_channel),
|
||||
(None, None, None, None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_keeps_what_the_form_does_not_show() {
|
||||
let old = Bookmark {
|
||||
id: 7,
|
||||
name: "Old".into(),
|
||||
address: "old.example.test".into(),
|
||||
nickname: "Me".into(),
|
||||
identity: Some(2),
|
||||
default_channel: Some("Lobby/Sub".into()),
|
||||
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
|
||||
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
|
||||
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
|
||||
client_version: Some("linux".into()),
|
||||
cached_server_icon: Some(voelin_store::CachedServerIcon {
|
||||
address: "old.example.test".into(),
|
||||
id: 1234,
|
||||
}),
|
||||
};
|
||||
// Same address: the gateway found and the query login stay.
|
||||
let same = BookmarkForm {
|
||||
id: 7,
|
||||
name: "Mine".into(),
|
||||
address: "old.example.test".into(),
|
||||
nickname: "Other".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given"));
|
||||
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
|
||||
assert_eq!(b.gateway_url, old.gateway_url);
|
||||
assert_eq!(b.query, old.query);
|
||||
assert_eq!(b.cached_server_icon, old.cached_server_icon);
|
||||
// Another address: looked up again, for the new server.
|
||||
let form = BookmarkForm { address: "new.example.test:9988".into(), ..same };
|
||||
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
|
||||
assert_eq!(b.address, "new.example.test:9988");
|
||||
assert!(b.cached_server_icon.is_none());
|
||||
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
|
||||
assert_eq!(b.client_version.as_deref(), Some("linux"));
|
||||
assert_eq!((b.gateway_url, b.query), (None, None));
|
||||
assert!(b.gateway_urls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gateway_found_again_is_not_logged_in_again() {
|
||||
let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1");
|
||||
let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::<Vec<_>>();
|
||||
let stays = |previous: &[&str], found: &[&str], observe| {
|
||||
observing_stays(&urls(previous), &urls(found), Some(plain), observe)
|
||||
};
|
||||
// The same ones (an older version kept only the one in use).
|
||||
assert!(stays(&[plain], &[plain], ObserveState::Connecting));
|
||||
assert!(stays(&[plain], &[plain], ObserveState::Observing));
|
||||
// Logged in through one still published.
|
||||
assert!(stays(&[plain], &[tls, plain], ObserveState::Observing));
|
||||
// Not logged in yet: through the new ones.
|
||||
assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting));
|
||||
// The one in use is no longer published.
|
||||
assert!(!stays(&[plain], &[tls], ObserveState::Observing));
|
||||
assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off));
|
||||
}
|
||||
/// How a server is observed: through its gateway, its query login, or
|
||||
/// after the gateway was looked up; not twice, not for sample servers.
|
||||
#[test]
|
||||
fn a_server_is_observed_through_what_it_has() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let cx = Cx::new(&host);
|
||||
assert_eq!(observe_plan(&st, &cx, 9), ObservePlan::Nothing, "no such server");
|
||||
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Discover);
|
||||
st.bookmarks[0].query = Some(QueryConfig::default());
|
||||
assert!(matches!(observe_plan(&st, &cx, 1), ObservePlan::Query(_)));
|
||||
st.bookmarks[0].gateway_urls = vec!["wss://gw/v1".into()];
|
||||
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Gateway(vec!["wss://gw/v1".into()]));
|
||||
let view = st.sessions.entry(1).or_default();
|
||||
view.state.observe = ObserveState::Connecting;
|
||||
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Retry(vec!["wss://gw/v1".into()]));
|
||||
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
|
||||
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Nothing);
|
||||
let demo = Fake { demo: true, ..Default::default() };
|
||||
assert_eq!(observe_plan(&st, &Cx::new(&demo), 1), ObservePlan::Nothing);
|
||||
// The gateway is looked up once a run.
|
||||
assert_eq!(discover_wanted(&mut st, &cx, 1).as_deref(), Some("ts.example"));
|
||||
assert_eq!(discover_wanted(&mut st, &cx, 1), None);
|
||||
}
|
||||
|
||||
/// What finding the gateways does to a server.
|
||||
#[test]
|
||||
fn found_gateways_are_kept_and_observed_through() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let found = |st: &mut State, urls: &[&str], address: &str| {
|
||||
let mut cx = Cx::new(&host);
|
||||
let result = gateway_found(
|
||||
st,
|
||||
&mut cx,
|
||||
1,
|
||||
address,
|
||||
urls.iter().map(|s| s.to_string()).collect(),
|
||||
);
|
||||
(result, cx.update.persist.len(), cx.update.refresh.toolbar)
|
||||
};
|
||||
// Another address now: nothing.
|
||||
assert_eq!(found(&mut st, &["wss://gw/v1"], "other.example").0, GatewayFound::Same);
|
||||
// First found, the server is shown and not observed: observe.
|
||||
let (result, kept, toolbar) = found(&mut st, &["wss://gw/v1"], "ts.example");
|
||||
assert_eq!(
|
||||
result,
|
||||
GatewayFound::Changed { stop: false, observe: true, urls: vec!["wss://gw/v1".into()] }
|
||||
);
|
||||
assert!(kept == 1 && toolbar);
|
||||
// The same again: nothing changed.
|
||||
assert_eq!(found(&mut st, &["wss://gw/v1"], "ts.example").0, GatewayFound::Same);
|
||||
// Observing through the old: a different gateway list leaves them.
|
||||
st.sessions.entry(1).or_default().state.observe = ObserveState::Observing;
|
||||
let (result, ..) = found(&mut st, &["wss://new/v1"], "ts.example");
|
||||
assert_eq!(
|
||||
result,
|
||||
GatewayFound::Changed { stop: true, observe: true, urls: vec!["wss://new/v1".into()] }
|
||||
);
|
||||
assert_eq!(st.sessions[&1].state.observe, ObserveState::Off);
|
||||
// One that still lists the one in use keeps observing.
|
||||
st.bookmarks[0].gateway_url = Some("wss://new/v1".into());
|
||||
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
|
||||
let (result, ..) = found(&mut st, &["wss://new/v1", "wss://more/v1"], "ts.example");
|
||||
assert_eq!(result, GatewayFound::Kept { observe: false });
|
||||
}
|
||||
|
||||
/// Joining a channel: a free one at once (or connecting into it), a locked
|
||||
/// one asks, the password dialog's Join goes on.
|
||||
#[test]
|
||||
fn joining_a_channel_moves_asks_or_connects() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let mut locked = ChannelInfo { id: 3, name: "Vault".into(), ..Default::default() };
|
||||
locked.has_password = true;
|
||||
let mut p = (*presence()).clone();
|
||||
p.channels.insert(3, locked);
|
||||
st.sessions.entry(1).or_default().presence = std::sync::Arc::new(p);
|
||||
// Connected: moving.
|
||||
st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2));
|
||||
let mut cx = Cx::new(&host);
|
||||
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), None);
|
||||
assert!(matches!(
|
||||
cx.update.commands.as_slice(),
|
||||
[Command::MoveToChannel { session: 1, channel: 1, password: None }]
|
||||
));
|
||||
// A locked one asks.
|
||||
let mut cx = Cx::new(&host);
|
||||
assert_eq!(join_channel(&mut st, &mut cx, 1, 3), None);
|
||||
assert_eq!(cx.update.password.as_ref().map(|p| p.name.as_str()), Some("Vault"));
|
||||
assert_eq!(st.join_target, Some((1, 3)));
|
||||
let mut cx = Cx::new(&host);
|
||||
assert_eq!(join_with_password(&mut st, &mut cx, "".into()), None);
|
||||
st.join_target = Some((1, 3));
|
||||
assert_eq!(join_with_password(&mut st, &mut cx, "pw".into()), None);
|
||||
assert_eq!(st.sessions[&1].channel_passwords.get(&3).map(String::as_str), Some("pw"));
|
||||
assert!(matches!(
|
||||
cx.update.commands.as_slice(),
|
||||
[Command::MoveToChannel { channel: 3, password: Some(p), .. }] if p == "pw"
|
||||
));
|
||||
// Not connected: the front end connects into it.
|
||||
st.sessions.get_mut(&1).unwrap().state = SessionState::default();
|
||||
let mut cx = Cx::new(&host);
|
||||
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), Some(None));
|
||||
join_after_connect(&mut st, 1, 1);
|
||||
assert_eq!(st.sessions[&1].join_after_connect, Some(1));
|
||||
assert!(cx.update.commands.is_empty());
|
||||
}
|
||||
|
||||
/// The server card, the rail and the tree for the server shown.
|
||||
#[test]
|
||||
fn the_rail_the_card_and_the_tree() {
|
||||
let mut st = state();
|
||||
let no_icon = |_: &Bookmark| ImageRef::default();
|
||||
// Nothing connected yet.
|
||||
let rail_rows = rail(&st, no_icon);
|
||||
assert_eq!(rail_rows.len(), 1);
|
||||
assert_eq!((&*rail_rows[0].status, &*rail_rows[0].detail), ("offline", "ts.example"));
|
||||
let card = toolbar(&st, no_icon);
|
||||
assert_eq!((card.server_title.as_str(), card.nickname.as_str()), ("ts.example", "Me"));
|
||||
assert!(!card.voice_connected && card.presence_source.is_empty());
|
||||
assert!(tree_view(&st, false).is_none(), "no session yet");
|
||||
// Connected into Games.
|
||||
let host = Fake::default();
|
||||
for event in [
|
||||
voelin_core::Event::Presence { session: 1, presence: presence() },
|
||||
voelin_core::Event::State {
|
||||
session: 1,
|
||||
state: session(VoiceState::Connected, Some(2)),
|
||||
},
|
||||
] {
|
||||
crate::events::apply(&mut st, &host, event);
|
||||
}
|
||||
let rail_rows = rail(&st, no_icon);
|
||||
assert_eq!(
|
||||
(&*rail_rows[0].status, &*rail_rows[0].detail),
|
||||
("connected", "2 online · 2 channels")
|
||||
);
|
||||
assert_eq!(server_tint(&st, 1), Some(tints(&st.bookmarks)[0]));
|
||||
assert_eq!(server_tint(&st, 9), None);
|
||||
let card = toolbar(&st, no_icon);
|
||||
assert!(card.voice_connected && card.own_channel == "Games");
|
||||
assert_eq!(card.presence_source, "live (voice)");
|
||||
assert_eq!(card.own_channel_limit, -1);
|
||||
let tree = tree_view(&st, false).unwrap();
|
||||
assert_eq!(tree.rows.len(), 4, "two channels and their clients");
|
||||
assert_eq!(tree.members.len(), 2);
|
||||
assert_eq!(tree.member_total, 2);
|
||||
// The members' search filters the server's people only.
|
||||
let mut cx = Cx::new(&host);
|
||||
search_members(&mut st, &mut cx, "ali".into());
|
||||
assert!(cx.update.refresh.tree);
|
||||
let tree = tree_view(&st, false).unwrap();
|
||||
assert_eq!(
|
||||
tree.server_members
|
||||
.iter()
|
||||
.filter(|m| !m.group.is_empty() && &*m.name == "Alice")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(tree.server_members.iter().all(|m| &*m.name != "Me"));
|
||||
// Folding a channel; the tree is drawn again.
|
||||
let mut cx = Cx::new(&host);
|
||||
toggle_collapse(&mut st, &mut cx, 1);
|
||||
assert!(st.sessions[&1].collapsed.contains(&1) && cx.update.refresh.tree);
|
||||
toggle_collapse(&mut st, &mut cx, 1);
|
||||
assert!(st.sessions[&1].collapsed.is_empty());
|
||||
}
|
||||
|
||||
/// The card of a client opens over the members panel of the server shown
|
||||
/// and closes again; the card is drawn again only when it changed.
|
||||
#[test]
|
||||
fn the_member_card_opens_and_closes() {
|
||||
let (mut st, host) = (state(), Fake::default());
|
||||
st.current = Some(1);
|
||||
st.sessions.insert(1, SessionView::default());
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert_eq!(st.sessions[&1].member_card, Some(11));
|
||||
assert!(cx.update.refresh.member_card);
|
||||
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert!(!cx.update.refresh.member_card, "the same card: nothing to draw");
|
||||
open_member(&mut st, &mut cx, None);
|
||||
assert_eq!(st.sessions[&1].member_card, None);
|
||||
assert!(cx.update.refresh.member_card);
|
||||
|
||||
// No server on screen: no card.
|
||||
st.current = None;
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert!(cx.update.refresh.is_empty());
|
||||
}
|
||||
|
||||
/// A chat takes its server's colour only while it is a server chat of a
|
||||
/// server in the list: a chat whose server is gone, and a chat that is a
|
||||
/// channel's or a person's, take the colour of their own title. Black
|
||||
/// is what a missing colour would be (`Rgb::default()`).
|
||||
#[test]
|
||||
fn a_chat_takes_its_servers_colour_or_that_of_its_title() {
|
||||
let st = state();
|
||||
let server = tints(&st.bookmarks)[0];
|
||||
let titled = |title: &str| crate::avatar::tint(title);
|
||||
// Titles whose own colour is not the server's, so that the chat
|
||||
// below can tell the two apart.
|
||||
assert_ne!(titled("Old Server"), server);
|
||||
assert_ne!(titled("Alice"), server);
|
||||
assert_ne!(titled("Alice"), crate::color::Rgb::default());
|
||||
// The server's chat, the server in the list: its colour, not the
|
||||
// title's.
|
||||
assert_eq!(conversation_tint(&st, 0, Some(1), "Old Server"), server);
|
||||
// The server is gone from the list: the title's colour.
|
||||
assert_eq!(conversation_tint(&st, 0, Some(9), "Old Server"), titled("Old Server"));
|
||||
// Not a server chat of a known server: the title's colour, whether
|
||||
// the server is in the list or not, or not known at all.
|
||||
assert_eq!(conversation_tint(&st, 1, Some(1), "Alice"), titled("Alice"));
|
||||
assert_eq!(conversation_tint(&st, 2, Some(1), "Alice"), titled("Alice"));
|
||||
assert_eq!(conversation_tint(&st, 2, Some(9), "Alice"), titled("Alice"));
|
||||
assert_eq!(conversation_tint(&st, 0, None, "Alice"), titled("Alice"));
|
||||
}
|
||||
|
||||
/// The Invite button's link and note; the voice view's chat.
|
||||
#[test]
|
||||
fn invite_and_voice_view() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
assert_eq!(invite_link(&mut st), Err("Join a voice channel to invite others to it"));
|
||||
for event in [
|
||||
voelin_core::Event::Presence { session: 1, presence: presence() },
|
||||
voelin_core::Event::State {
|
||||
session: 1,
|
||||
state: session(VoiceState::Connected, Some(2)),
|
||||
},
|
||||
] {
|
||||
crate::events::apply(&mut st, &host, event);
|
||||
}
|
||||
let link = invite_link(&mut st).unwrap();
|
||||
assert!(link.contains("ts.example") && link.contains("Games"), "{link}");
|
||||
assert_eq!(st.copy_note.as_deref(), Some(&*format!("Copied an invite to Games: {link}")));
|
||||
let mut cx = Cx::new(&host);
|
||||
show_voice_view(&mut st, &mut cx, true);
|
||||
assert!(st.voice_view && cx.update.refresh.tree && cx.update.refresh.chat);
|
||||
}
|
||||
|
||||
/// A server leaves the list; the first one that is left is shown.
|
||||
#[test]
|
||||
fn forgetting_a_server_shows_the_first_left() {
|
||||
let mut st = state();
|
||||
st.bookmarks.push(bookmark(2, "Other", "other.example"));
|
||||
let host = Fake::default();
|
||||
st.sessions.entry(1).or_default();
|
||||
st.gateways_looked_up.insert(1);
|
||||
let mut cx = Cx::new(&host);
|
||||
forget_server(&mut st, &mut cx, 1, vec![bookmark(2, "Other", "other.example")]);
|
||||
assert_eq!(st.current, Some(2));
|
||||
assert!(st.sessions.is_empty() && st.gateways_looked_up.is_empty());
|
||||
let r = cx.update.refresh;
|
||||
assert!(r.servers && r.toolbar && r.tree && r.chat && r.streams);
|
||||
let mut cx = Cx::new(&host);
|
||||
select_server(&mut st, &mut cx, 2);
|
||||
assert_eq!(st.current, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_voice_options_follow_the_bookmark() {
|
||||
let mut b = bookmark(1, "G", "ts.example");
|
||||
b.nickname = "Me".into();
|
||||
let options =
|
||||
voice_options(&b, Some("/5".into()), Some("pw".into()), Some("key".into())).unwrap();
|
||||
assert_eq!(options.channel.as_deref(), Some("/5"));
|
||||
assert_eq!(options.channel_password.as_deref(), Some("pw"));
|
||||
assert_eq!(options.token.as_deref(), Some("key"));
|
||||
assert!(options.audio);
|
||||
// A bookmark without a version spec leaves the engine's default.
|
||||
assert_eq!(options.client_version, None);
|
||||
// A spec that resolves goes on as the spec: the engine resolves it
|
||||
// when it connects.
|
||||
b.client_version = Some("default".into());
|
||||
let options = voice_options(&b, None, None, None).unwrap();
|
||||
assert_eq!(options.client_version.as_deref(), Some("default"));
|
||||
b.client_version = Some("no such version".into());
|
||||
let error = voice_options(&b, None, None, None).err().unwrap();
|
||||
assert!(error.starts_with("Invalid client compatibility version"), "{error}");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
//! The server rail, the server dialog, and joining a channel.
|
||||
//! The server rail, the server dialog, and joining a channel; [`logic`] has
|
||||
//! which server is shown, how it is observed, and the rail, the server card
|
||||
//! and the channel tree as plain data.
|
||||
|
||||
pub mod logic;
|
||||
pub mod sequence;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -126,6 +131,7 @@ pub fn form(
|
||||
pub struct ConnectTo {
|
||||
/// A channel path, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The channel's password, if the form has one.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key.
|
||||
pub token: Option<String>,
|
||||
@@ -0,0 +1,858 @@
|
||||
//! What both front ends do for a server that is more than a state change: the
|
||||
//! sequences over the store, the secrets and the engine.
|
||||
//!
|
||||
//! [`logic`](super::logic) has the transitions that touch the state alone;
|
||||
//! these also read and write the client's store and its secrets (a
|
||||
//! bookmark and its passwords), pick the identity a connection is made with
|
||||
//! and build the engine's commands, and they were written twice, once for
|
||||
//! each front end, before they were one. Each is a transition: it takes the
|
||||
//! state, the transition's [`Cx`] and the [`Backing`], changes the state and
|
||||
//! the store, and says what the front end is to do through the `Cx`
|
||||
//! (commands for the engine, the status line, what to keep, which gateways to
|
||||
//! look up), so that a front end carries it out with its own `perform` and
|
||||
//! tests it as it tests the others: in the GPUI front end the commands of a
|
||||
//! test are the ones its `perform` was handed, and a sample server's are
|
||||
//! dropped there.
|
||||
//!
|
||||
//! What stays with each front end is what needs its toolkit or its runtime:
|
||||
//! the thread hop of a gateway lookup (it runs [`find_gateways`] on the
|
||||
//! engine's runtime and calls [`gateway_found`] when something is found, as
|
||||
//! `Update::discover` asks), the clipboard, the toast, and what it adds to a
|
||||
//! connect (the stream codecs the Slint front end can decode).
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_core::stream::PeerConfig;
|
||||
use voelin_core::{Command, IdentityBlob, ObserveState};
|
||||
use voelin_model::ChannelId;
|
||||
use voelin_store::{Bookmark, QueryTransport, Secrets, Store};
|
||||
|
||||
use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan};
|
||||
use crate::bridge::BookmarkForm;
|
||||
use crate::host::Cx;
|
||||
use crate::state::{AppState, Lines};
|
||||
|
||||
/// What the sequences read and write besides the state: the client's store, its
|
||||
/// secrets and the identity a connection is made with.
|
||||
pub struct Backing<'a> {
|
||||
/// The bookmarks, the identities and the chats' read marks.
|
||||
pub store: &'a Store,
|
||||
/// The servers' passwords.
|
||||
pub secrets: &'a dyn Secrets,
|
||||
/// The identity a connection to a server whose bookmark names `named` is
|
||||
/// made with, as the engine takes it ([`Store::identity_for`]: the named
|
||||
/// one if the store has it, else the default one, else the front end's).
|
||||
pub identity: &'a dyn Fn(Option<i64>) -> IdentityBlob,
|
||||
}
|
||||
|
||||
/// The nickname a new server gets: the default identity's (one imported from
|
||||
/// TeamSpeak keeps the nickname used there), else the system user's.
|
||||
pub fn default_nickname(store: &Store) -> String {
|
||||
store
|
||||
.default_identity()
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identity| identity.name)
|
||||
.filter(|name| {
|
||||
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
|
||||
.contains(&name.as_str())
|
||||
})
|
||||
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
|
||||
// Servers refuse an empty nickname (Android has no user name).
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.unwrap_or_else(|| "Voelin user".to_owned())
|
||||
}
|
||||
|
||||
/// The server dialog's form for server `id` (-1: a new one), with its
|
||||
/// password from the secrets and its session's state.
|
||||
pub fn bookmark_form<L>(
|
||||
state: &AppState<L>,
|
||||
store: &Store,
|
||||
secrets: &dyn Secrets,
|
||||
id: i64,
|
||||
) -> BookmarkForm {
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else {
|
||||
return BookmarkForm {
|
||||
id: -1,
|
||||
nickname: default_nickname(store).into(),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let password = secrets.get(&b.server_password_key()).ok().flatten();
|
||||
let session = state.sessions.get(&b.id).map(|view| &view.state);
|
||||
super::form(b, session, password.as_deref().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Show a server, and observe it.
|
||||
pub fn select_server<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
) {
|
||||
logic::select_server(state, cx, id);
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
|
||||
/// Connect the server on screen with voice, into its default channel.
|
||||
pub fn connect_voice<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let channel = state
|
||||
.current
|
||||
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
|
||||
.and_then(|b| b.default_channel.clone());
|
||||
connect_voice_to(state, cx, backing, channel, None, None, stream_peer)
|
||||
}
|
||||
|
||||
/// Connect the server on screen with voice, into `channel` (a path, or
|
||||
/// `/<id>`, with its password) if given, with a privilege key if given;
|
||||
/// whether it was asked for. `stream_peer`: what the front end can decode
|
||||
/// of a stream, if it says (the engine's default otherwise).
|
||||
pub fn connect_voice_to<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
channel: Option<String>,
|
||||
channel_password: Option<String>,
|
||||
token: Option<String>,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let Some(b) = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id)).cloned()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if cx.host.demo_ui() {
|
||||
return false;
|
||||
}
|
||||
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
cx.status(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
options.identity = Some((backing.identity)(b.identity));
|
||||
options.server_password = backing.secrets.get(&b.server_password_key()).ok().flatten();
|
||||
if let Some(peer) = stream_peer {
|
||||
options.stream_peer = peer;
|
||||
}
|
||||
cx.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
|
||||
cx.status(format!("Connecting to {}…", b.address));
|
||||
// The admin may have published the gateway since it was added.
|
||||
discover_gateway(state, cx, b.id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Join a channel of a session (a double-click in the tree, joining a friend):
|
||||
/// move there with voice ([`logic::join_channel`]), ask for the password of a
|
||||
/// locked channel first, and without voice on that server connect into it.
|
||||
pub fn join_channel<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) {
|
||||
if let Some(password) = logic::join_channel(state, cx, session, channel) {
|
||||
connect_into(state, cx, backing, session, channel, password, stream_peer);
|
||||
}
|
||||
}
|
||||
|
||||
/// The password dialog's Join ([`logic::join_with_password`]): the same, with
|
||||
/// the password given.
|
||||
pub fn join_with_password<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
password: String,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) {
|
||||
if let Some((session, channel, password)) = logic::join_with_password(state, cx, password) {
|
||||
connect_into(state, cx, backing, session, channel, password, stream_peer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect voice into a channel of a server that has none: the server is
|
||||
/// shown first, and the channel is named by its id (by its name the server
|
||||
/// finds only a top-level channel, and a subchannel's name connects into the
|
||||
/// default channel). Joined again after the connect if the server puts us
|
||||
/// elsewhere ([`logic::join_after_connect`]).
|
||||
fn connect_into<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
session: i64,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) {
|
||||
if state.current != Some(session) {
|
||||
select_server(state, cx, backing, session);
|
||||
}
|
||||
let asked = connect_voice_to(
|
||||
state,
|
||||
cx,
|
||||
backing,
|
||||
Some(format!("/{channel}")),
|
||||
password,
|
||||
None,
|
||||
stream_peer,
|
||||
);
|
||||
if asked {
|
||||
logic::join_after_connect(state, session, channel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask for the gateway of a server to be looked up ([`voelin_core::discover`]),
|
||||
/// once a run ([`logic::discover_wanted`]): every one the server publishes is
|
||||
/// kept, best first, and tried in turn; they take the place of a stored one
|
||||
/// that is no longer published (a gateway that moved, or one typed into an
|
||||
/// older version, which showed the field). Nothing found keeps what is
|
||||
/// stored. The front end looks it up (`Update::discover`).
|
||||
pub fn discover_gateway<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
|
||||
if let Some(address) = logic::discover_wanted(state, cx, id) {
|
||||
cx.update.discover.push((id, address));
|
||||
}
|
||||
}
|
||||
|
||||
/// What looking up the gateways of a server found.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
/// Every URL the server publishes, best first.
|
||||
pub urls: Vec<String>,
|
||||
/// How long the lookup took.
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
|
||||
/// Look the gateways of the server at `address` up in DNS; none when the
|
||||
/// server publishes none (logged). Runs on the engine's runtime; what it
|
||||
/// finds goes to [`gateway_found`] on the front end's own thread.
|
||||
pub async fn find_gateways(address: &str) -> Option<Found> {
|
||||
let started = Instant::now();
|
||||
let urls = voelin_core::discover::gateways(address).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
if urls.is_empty() {
|
||||
info!(server = %address, elapsed_ms, "no gateway published");
|
||||
None
|
||||
} else {
|
||||
Some(Found { urls, elapsed_ms })
|
||||
}
|
||||
}
|
||||
|
||||
/// Gateways were found for the server at `address` (best first); they are kept
|
||||
/// unless the server changed meanwhile ([`logic::gateway_found`]), and the
|
||||
/// server is observed through them if it is the one shown. Users never hear of
|
||||
/// them (logged only).
|
||||
pub fn gateway_found<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
address: &str,
|
||||
urls: Vec<String>,
|
||||
elapsed_ms: u64,
|
||||
) {
|
||||
match logic::gateway_found(state, cx, id, address, urls) {
|
||||
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
|
||||
GatewayFound::Kept { observe: now } => {
|
||||
info!(server = %address, elapsed_ms, kept = true, "gateway found");
|
||||
if now {
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
}
|
||||
GatewayFound::Changed { stop, observe: now, urls } => {
|
||||
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
|
||||
if stop {
|
||||
cx.send(Command::StopObserving { session: id as u64 });
|
||||
}
|
||||
if now {
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe the server invisibly ([`logic::observe_plan`]): through its gateway,
|
||||
/// else its own query login. Without either the gateway is looked up first,
|
||||
/// and observing starts when it is found ([`gateway_found`]).
|
||||
pub fn observe<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, backing: &Backing<'_>, id: i64) {
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
|
||||
let session = b.id as u64;
|
||||
let gateway = |urls| Command::ObserveGateway {
|
||||
session,
|
||||
urls,
|
||||
identity: Box::new((backing.identity)(b.identity)),
|
||||
};
|
||||
match logic::observe_plan(state, cx, id) {
|
||||
ObservePlan::Nothing => return,
|
||||
ObservePlan::Retry(urls) => {
|
||||
debug!(server = %b.address, "still connecting to the gateway: try now");
|
||||
cx.send(gateway(urls));
|
||||
return;
|
||||
}
|
||||
ObservePlan::Gateway(urls) => {
|
||||
info!(server = %b.address, ?urls, "observing through the gateway");
|
||||
cx.send(gateway(urls));
|
||||
// Still the one the server publishes?
|
||||
discover_gateway(state, cx, b.id);
|
||||
}
|
||||
ObservePlan::Query(q) => {
|
||||
let secret = backing.secrets.get(&b.query_password_key()).ok().flatten();
|
||||
let transport = match q.transport {
|
||||
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
|
||||
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
|
||||
QueryTransport::Http => voelin_core::QueryTransport::Http,
|
||||
};
|
||||
let connect = voelin_core::QueryLogin {
|
||||
transport,
|
||||
address: format!("{}:{}", q.host, q.port),
|
||||
user: q.user.clone(),
|
||||
secret,
|
||||
server_port: q.server_port,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
cx.send(Command::ObserveQuery { session, connect: Box::new(connect) });
|
||||
}
|
||||
ObservePlan::Discover => {
|
||||
discover_gateway(state, cx, b.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
cx.status("Observing invisibly…");
|
||||
}
|
||||
|
||||
/// Save the server the form describes in the store and the secrets, and show
|
||||
/// it: its id, none when it could not be saved (the status line says why). A
|
||||
/// new address stops what was observed at the old one.
|
||||
pub fn save_bookmark<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
form: &BookmarkForm,
|
||||
) -> Option<i64> {
|
||||
let old = state.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
|
||||
let mut bookmark =
|
||||
logic::bookmark_from_form(old.as_ref(), form, || default_nickname(backing.store));
|
||||
let result = if bookmark.id < 0 {
|
||||
backing.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
|
||||
} else {
|
||||
backing.store.update_bookmark(&bookmark)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
cx.status(format!("Could not save: {e}"));
|
||||
return None;
|
||||
}
|
||||
let key = bookmark.server_password_key();
|
||||
let result = if form.server_password.is_empty() {
|
||||
backing.secrets.delete(&key)
|
||||
} else {
|
||||
backing.secrets.set(&key, &form.server_password)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
warn!(%e, "could not store secret");
|
||||
}
|
||||
// Another server: what was observed is the old one's, and its gateway is
|
||||
// looked up anew.
|
||||
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
|
||||
if old.query.is_some() {
|
||||
let _ = backing.secrets.delete(&old.query_password_key());
|
||||
}
|
||||
state.gateways_looked_up.remove(&bookmark.id);
|
||||
cx.send(Command::StopObserving { session: bookmark.id as u64 });
|
||||
if let Some(view) = state.sessions.get_mut(&bookmark.id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
}
|
||||
}
|
||||
state.bookmarks = backing.store.bookmarks().unwrap_or_default();
|
||||
select_server(state, cx, backing, bookmark.id);
|
||||
Some(bookmark.id)
|
||||
}
|
||||
|
||||
/// The server dialog's Connect: save the server, then connect it with voice,
|
||||
/// into the channel of the link that filled the form if one did
|
||||
/// ([`super::connect_to`]). Only once saved: connecting what is shown after a
|
||||
/// failed save would connect the server shown before. Whether it was saved.
|
||||
pub fn save_and_connect<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
form: &BookmarkForm,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let saved = save_bookmark(state, cx, backing, form);
|
||||
let to = super::connect_to(
|
||||
form,
|
||||
saved.and_then(|id| state.bookmarks.iter().find(|b: &&Bookmark| b.id == id)),
|
||||
);
|
||||
let Some(to) = to else { return false };
|
||||
connect_voice_to(state, cx, backing, to.channel, to.channel_password, to.token, stream_peer);
|
||||
true
|
||||
}
|
||||
|
||||
/// Remove a server: its session is closed, its passwords and the bookmark go,
|
||||
/// and the first server is shown.
|
||||
pub fn delete_bookmark<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
) {
|
||||
cx.send(Command::CloseSession { session: id as u64 });
|
||||
if let Some(b) = state.bookmarks.iter().find(|b| b.id == id) {
|
||||
let _ = backing.secrets.delete(&b.server_password_key());
|
||||
let _ = backing.secrets.delete(&b.query_password_key());
|
||||
}
|
||||
let _ = backing.store.delete_bookmark(id);
|
||||
let bookmarks = backing.store.bookmarks().unwrap_or_default();
|
||||
logic::forget_server(state, cx, id, bookmarks);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_store::{MemorySecrets, QueryConfig};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::VoiceState;
|
||||
|
||||
use super::*;
|
||||
use crate::host::Update;
|
||||
use crate::host::testing::{Fake, State, presence, session};
|
||||
|
||||
/// A store, secrets and a front end of the tests' own.
|
||||
struct Rig {
|
||||
store: Store,
|
||||
secrets: MemorySecrets,
|
||||
host: Fake,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
store: Store::open_in_memory().unwrap(),
|
||||
secrets: MemorySecrets::default(),
|
||||
host: Fake::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A state with these servers saved, the first on screen.
|
||||
fn state(&self, servers: &[(&str, &str)]) -> State {
|
||||
for (name, address) in servers {
|
||||
let bookmark = Bookmark {
|
||||
name: (*name).into(),
|
||||
address: (*address).into(),
|
||||
nickname: "Nova".into(),
|
||||
..Default::default()
|
||||
};
|
||||
self.store.add_bookmark(&bookmark).unwrap();
|
||||
}
|
||||
let bookmarks = self.store.bookmarks().unwrap();
|
||||
let mut state = State::new(
|
||||
bookmarks.clone(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
);
|
||||
state.current = bookmarks.first().map(|b| b.id);
|
||||
state
|
||||
}
|
||||
|
||||
/// Run a sequence, and what it asks of the front end.
|
||||
fn run<R>(
|
||||
&self,
|
||||
state: &mut State,
|
||||
f: impl FnOnce(&mut State, &mut Cx<'_>, &Backing<'_>) -> R,
|
||||
) -> (R, Update) {
|
||||
let identity = |named: Option<i64>| {
|
||||
IdentityBlob::teamspeak(format!("identity-{}", named.unwrap_or(-1)), 8, "{}")
|
||||
};
|
||||
let backing =
|
||||
Backing { store: &self.store, secrets: &self.secrets, identity: &identity };
|
||||
let mut cx = Cx::new(&self.host);
|
||||
let result = f(state, &mut cx, &backing);
|
||||
(result, cx.update)
|
||||
}
|
||||
}
|
||||
|
||||
fn form(address: &str) -> BookmarkForm {
|
||||
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_with_no_identity_to_name_it_gets_the_users_name_or_a_fallback() {
|
||||
let nickname = default_nickname(&Store::open_in_memory().unwrap());
|
||||
assert!(!nickname.trim().is_empty(), "servers refuse an empty nickname");
|
||||
assert!(nickname != CREATED_IDENTITY && nickname != "imported");
|
||||
}
|
||||
|
||||
/// A connect names the server on screen, its nickname and channel, the
|
||||
/// identity it is made with and the password the secrets keep; it says so
|
||||
/// in the status line and asks for the gateway to be looked up, once.
|
||||
#[test]
|
||||
fn a_connect_asks_the_engine_with_what_the_store_and_the_secrets_know() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
rig.secrets.set(&state.bookmarks[0].server_password_key(), "hunter2").unwrap();
|
||||
|
||||
let (asked, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
connect_voice_to(state, cx, backing, Some("Lobby".into()), None, None, None)
|
||||
});
|
||||
assert!(asked);
|
||||
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
|
||||
panic!("{:?}", update.commands.len())
|
||||
};
|
||||
assert_eq!(*session, id as u64);
|
||||
assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova"));
|
||||
assert_eq!(options.channel.as_deref(), Some("Lobby"));
|
||||
assert_eq!(options.server_password.as_deref(), Some("hunter2"));
|
||||
assert_eq!(options.identity.as_ref().map(|i| i.uid.as_str()), Some("identity--1"));
|
||||
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
|
||||
// The second connect of a run does not look it up again.
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert_eq!(update.commands.len(), 1);
|
||||
assert!(update.discover.is_empty());
|
||||
}
|
||||
|
||||
/// The sample servers connect nothing, and a client version that is none
|
||||
/// is refused in words.
|
||||
#[test]
|
||||
fn a_connect_that_cannot_be_made_asks_nothing() {
|
||||
let mut rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
rig.host.demo = true;
|
||||
let (asked, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked && update.commands.is_empty() && update.status.is_none());
|
||||
|
||||
rig.host.demo = false;
|
||||
state.bookmarks[0].client_version = Some("nonsense@0".into());
|
||||
let (asked, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked && update.commands.is_empty());
|
||||
assert!(update.status.is_some_and(|s| s.starts_with("Invalid client compatibility")));
|
||||
|
||||
state.current = None;
|
||||
let (asked, _) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked, "no server on screen");
|
||||
}
|
||||
|
||||
/// A state whose first server has a session with `voice` and the channels
|
||||
/// of `host::testing::presence`: Lobby (1), Games (2, where we are).
|
||||
fn joined(rig: &Rig, voice: VoiceState, locked: Option<ChannelId>) -> (State, i64) {
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
let mut presence = (*presence()).clone();
|
||||
if let Some(channel) = locked {
|
||||
presence.channels.get_mut(&channel).unwrap().has_password = true;
|
||||
}
|
||||
let view = state.sessions.entry(id).or_default();
|
||||
view.presence = Arc::new(presence);
|
||||
view.state = session(voice, Some(2));
|
||||
(state, id)
|
||||
}
|
||||
|
||||
/// A double-click in the tree with voice up asks the engine to move there,
|
||||
/// and connects nothing.
|
||||
#[test]
|
||||
fn joining_a_channel_with_voice_moves_there() {
|
||||
let rig = Rig::new();
|
||||
let (mut state, id) = joined(&rig, VoiceState::Connected, None);
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
|
||||
let [Command::MoveToChannel { session, channel, password }] = &update.commands[..] else {
|
||||
panic!("{:?}", update.commands)
|
||||
};
|
||||
assert_eq!((*session, *channel, password.as_deref()), (id as u64, 1, None));
|
||||
assert!(update.password.is_none());
|
||||
}
|
||||
|
||||
/// With no voice on the server the join connects into the channel, named
|
||||
/// by its id, and remembers to join it again if the server puts us
|
||||
/// elsewhere; a server that is not the one shown is shown first.
|
||||
#[test]
|
||||
fn joining_a_channel_without_voice_connects_into_it() {
|
||||
let rig = Rig::new();
|
||||
let (mut state, id) = joined(&rig, VoiceState::Disconnected, None);
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
|
||||
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
|
||||
panic!("{:?}", update.commands)
|
||||
};
|
||||
assert_eq!((*session, options.channel.as_deref()), (id as u64, Some("/1")));
|
||||
assert_eq!(state.sessions[&id].join_after_connect, Some(1));
|
||||
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
|
||||
|
||||
// Another server is shown, then connected into the channel.
|
||||
let other = rig.store.add_bookmark(&Bookmark {
|
||||
name: "Lounge".into(),
|
||||
address: "lounge.example".into(),
|
||||
nickname: "Nova".into(),
|
||||
..Default::default()
|
||||
});
|
||||
state.bookmarks = rig.store.bookmarks().unwrap();
|
||||
let other = other.unwrap();
|
||||
let view = state.sessions.entry(other).or_default();
|
||||
view.presence = Arc::new((*presence()).clone());
|
||||
let (_, update) = rig
|
||||
.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, other, 2, None));
|
||||
assert_eq!(state.current, Some(other));
|
||||
assert!(
|
||||
update.commands.iter().any(|c| matches!(c, Command::ConnectVoice { session, options }
|
||||
if *session == other as u64 && options.channel.as_deref() == Some("/2"))),
|
||||
"{:?}",
|
||||
update.commands
|
||||
);
|
||||
}
|
||||
|
||||
/// A locked channel asks for its password first (nothing is sent), the
|
||||
/// dialog's Join sends it with the move, and the same channel does not ask
|
||||
/// again this connection.
|
||||
#[test]
|
||||
fn a_locked_channel_asks_for_its_password_and_joins_with_it() {
|
||||
let rig = Rig::new();
|
||||
let (mut state, id) = joined(&rig, VoiceState::Connected, Some(1));
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
|
||||
assert!(update.commands.is_empty(), "{:?}", update.commands);
|
||||
let prompt = update.password.expect("the dialog opens");
|
||||
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
|
||||
assert_eq!(state.join_target, Some((id, 1)));
|
||||
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
join_with_password(state, cx, backing, "secret".into(), None)
|
||||
});
|
||||
let [Command::MoveToChannel { channel, password, .. }] = &update.commands[..] else {
|
||||
panic!("{:?}", update.commands)
|
||||
};
|
||||
assert_eq!((*channel, password.as_deref()), (1, Some("secret")));
|
||||
assert_eq!(state.join_target, None);
|
||||
|
||||
// Remembered for this connection: no dialog the second time.
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None));
|
||||
assert!(update.password.is_none());
|
||||
assert!(
|
||||
matches!(&update.commands[..], [Command::MoveToChannel { password, .. }]
|
||||
if password.as_deref() == Some("secret")),
|
||||
"{:?}",
|
||||
update.commands
|
||||
);
|
||||
// An empty password joins nothing.
|
||||
state.join_target = Some((id, 1));
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
join_with_password(state, cx, backing, String::new(), None)
|
||||
});
|
||||
assert!(update.commands.is_empty());
|
||||
}
|
||||
|
||||
/// A new server is in the store with its password in the secrets, is the
|
||||
/// one on screen, and has its gateway looked up (it has none to observe
|
||||
/// through yet).
|
||||
#[test]
|
||||
fn saving_a_new_server_keeps_it_and_its_password_and_shows_it() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[]);
|
||||
let form = BookmarkForm { server_password: "hunter2".into(), ..form(" ts.example ") };
|
||||
let (saved, update) =
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &form));
|
||||
let id = saved.expect("saved");
|
||||
let stored = rig.store.bookmarks().unwrap();
|
||||
assert_eq!((stored.len(), stored[0].id), (1, id));
|
||||
assert_eq!(
|
||||
(stored[0].address.as_str(), stored[0].name.as_str()),
|
||||
("ts.example", "ts.example")
|
||||
);
|
||||
assert!(!stored[0].nickname.is_empty(), "the default nickname");
|
||||
assert_eq!(
|
||||
rig.secrets.get(&stored[0].server_password_key()).unwrap().as_deref(),
|
||||
Some("hunter2")
|
||||
);
|
||||
assert_eq!(state.current, Some(id));
|
||||
assert_eq!(state.bookmarks, stored);
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
assert!(update.commands.is_empty());
|
||||
|
||||
// An empty password in the form removes it.
|
||||
let edit = BookmarkForm { id: id as i32, ..form_of(&stored[0], "") };
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &edit));
|
||||
assert_eq!(rig.secrets.get(&stored[0].server_password_key()).unwrap(), None);
|
||||
}
|
||||
|
||||
fn form_of(bookmark: &Bookmark, password: &str) -> BookmarkForm {
|
||||
crate::servers::form(bookmark, None, password)
|
||||
}
|
||||
|
||||
/// Another address is another server: what was observed at the old one
|
||||
/// stops, its query password goes, and the gateway is looked up anew.
|
||||
#[test]
|
||||
fn a_new_address_stops_what_was_observed_at_the_old_one() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let old = state.bookmarks[0].clone();
|
||||
let id = old.id;
|
||||
state.gateways_looked_up.insert(id);
|
||||
rig.secrets.set(&old.query_password_key(), "query-secret").unwrap();
|
||||
state.bookmarks[0].query = Some(QueryConfig::default());
|
||||
rig.store.update_bookmark(&state.bookmarks[0]).unwrap();
|
||||
state.sessions.entry(id).or_default().state.observe = ObserveState::Observing;
|
||||
|
||||
let moved = BookmarkForm { address: "ts.elsewhere".into(), ..form_of(&old, "") };
|
||||
let (saved, update) =
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &moved));
|
||||
assert_eq!(saved, Some(id));
|
||||
assert!(
|
||||
matches!(&update.commands[..], [Command::StopObserving { session }] if *session == id as u64)
|
||||
);
|
||||
assert_eq!(rig.secrets.get(&old.query_password_key()).unwrap(), None);
|
||||
assert_eq!(state.sessions[&id].state.observe, ObserveState::Off);
|
||||
assert_eq!(update.discover, [(id, "ts.elsewhere".to_owned())]);
|
||||
assert_eq!(state.bookmarks[0].address, "ts.elsewhere");
|
||||
}
|
||||
|
||||
/// The form's Connect connects only what was saved.
|
||||
#[test]
|
||||
fn save_and_connect_connects_the_server_it_saved() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[]);
|
||||
let linked =
|
||||
BookmarkForm { channel: "Games".into(), token: "key".into(), ..form("ts.example") };
|
||||
let (done, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
save_and_connect(state, cx, backing, &linked, None)
|
||||
});
|
||||
assert!(done);
|
||||
let [Command::ConnectVoice { options, .. }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(
|
||||
(options.channel.as_deref(), options.token.as_deref()),
|
||||
(Some("Games"), Some("key"))
|
||||
);
|
||||
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
|
||||
}
|
||||
|
||||
/// A server is removed with its session, its passwords and its row, and
|
||||
/// the first of the others is shown.
|
||||
#[test]
|
||||
fn deleting_a_server_closes_its_session_and_forgets_its_secrets() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
|
||||
let [first, second] = [state.bookmarks[0].clone(), state.bookmarks[1].clone()];
|
||||
rig.secrets.set(&first.server_password_key(), "hunter2").unwrap();
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| delete_bookmark(state, cx, backing, first.id));
|
||||
assert!(
|
||||
matches!(&update.commands[..], [Command::CloseSession { session }] if *session == first.id as u64)
|
||||
);
|
||||
assert_eq!(rig.secrets.get(&first.server_password_key()).unwrap(), None);
|
||||
assert_eq!(
|
||||
rig.store.bookmarks().unwrap().iter().map(|b| b.id).collect::<Vec<_>>(),
|
||||
[second.id]
|
||||
);
|
||||
assert_eq!((state.current, state.bookmarks.len()), (Some(second.id), 1));
|
||||
}
|
||||
|
||||
/// Showing a server observes it: through its gateways if it has some (and
|
||||
/// looks the gateway up again, in case it moved), else through its query
|
||||
/// login with the password the secrets keep, else it looks the gateway up
|
||||
/// and observes when it is found.
|
||||
#[test]
|
||||
fn showing_a_server_observes_it_the_way_it_can_be() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
assert!(
|
||||
update.commands.is_empty() && update.status.is_none(),
|
||||
"nothing to observe through yet"
|
||||
);
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
|
||||
state.bookmarks[0].query = Some(QueryConfig {
|
||||
host: "query.example".into(),
|
||||
port: 10022,
|
||||
user: "serveradmin".into(),
|
||||
..Default::default()
|
||||
});
|
||||
rig.secrets.set(&state.bookmarks[0].query_password_key(), "q").unwrap();
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
let [Command::ObserveQuery { session, connect }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(*session, id as u64);
|
||||
assert_eq!(connect.address, "query.example:10022");
|
||||
assert_eq!((connect.user.as_str(), connect.secret.as_deref()), ("serveradmin", Some("q")));
|
||||
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
|
||||
|
||||
state.bookmarks[0].set_gateways(vec!["ws://gw.example/".into()]);
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
let [Command::ObserveGateway { urls, identity, .. }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(urls, &["ws://gw.example/".to_owned()]);
|
||||
assert_eq!(identity.uid, format!("identity-{}", -1));
|
||||
assert!(update.discover.is_empty(), "looked up once");
|
||||
}
|
||||
|
||||
/// What a lookup found is kept for the next start, and the server on
|
||||
/// screen is observed through it.
|
||||
#[test]
|
||||
fn a_found_gateway_is_kept_and_the_server_on_screen_is_observed_through_it() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
state.gateways_looked_up.insert(id);
|
||||
let urls = vec!["ws://gw.example/".to_owned()];
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
gateway_found(state, cx, backing, id, "ts.example", urls.clone(), 12)
|
||||
});
|
||||
assert_eq!(state.bookmarks[0].gateways(), urls);
|
||||
assert!(
|
||||
update
|
||||
.persist
|
||||
.iter()
|
||||
.any(|p| matches!(p, crate::host::Persist::Bookmark { id: i, .. } if *i == id))
|
||||
);
|
||||
assert!(matches!(&update.commands[..], [Command::ObserveGateway { .. }]));
|
||||
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
|
||||
|
||||
// For a server that changed meanwhile, nothing.
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
gateway_found(state, cx, backing, id, "another.example", urls.clone(), 12)
|
||||
});
|
||||
assert!(update.commands.is_empty() && update.persist.is_empty());
|
||||
}
|
||||
|
||||
/// The dialog's form: a new server gets the default nickname, a saved one
|
||||
/// its own with the password from the secrets.
|
||||
#[test]
|
||||
fn the_form_of_a_server_has_its_password_and_a_new_one_a_nickname() {
|
||||
let rig = Rig::new();
|
||||
let state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let saved = &state.bookmarks[0];
|
||||
rig.secrets.set(&saved.server_password_key(), "hunter2").unwrap();
|
||||
let form = bookmark_form(&state, &rig.store, &rig.secrets, saved.id);
|
||||
assert_eq!(
|
||||
(form.address.as_ref(), form.server_password.as_ref()),
|
||||
("ts.example", "hunter2")
|
||||
);
|
||||
assert_eq!(form.nickname.as_ref(), "Nova");
|
||||
let new = bookmark_form(&state, &rig.store, &rig.secrets, -1);
|
||||
assert_eq!((new.id, new.nickname.as_ref()), (-1, default_nickname(&rig.store).as_str()));
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,14 @@
|
||||
//! the settings page.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::warn;
|
||||
use voelin_audio::process::NoiseLevel;
|
||||
use voelin_core::settings::{Key, Kind};
|
||||
use voelin_core::settings::{Key, Kind, Settings};
|
||||
use voelin_core::{AudioSettings, TransmitMode};
|
||||
use voelin_model::ChannelId;
|
||||
|
||||
use crate::bridge::AudioForm;
|
||||
|
||||
@@ -31,8 +34,10 @@ pub static CLIENT_PLAYBACK: Key<ClientPlaybackMap> = Key::new(
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ThemeChoice {
|
||||
/// The dark palette.
|
||||
#[default]
|
||||
Dark,
|
||||
/// The light palette.
|
||||
Light,
|
||||
/// The system's light or dark scheme.
|
||||
System,
|
||||
@@ -111,6 +116,113 @@ pub static UI_VOICE_COMPACT: Key<bool> = Key::new(
|
||||
|| false,
|
||||
);
|
||||
|
||||
/// Where the main window was and how large, as the last run left it: size and
|
||||
/// position in logical pixels, and whether it was maximized (then the size is
|
||||
/// the one it returns to). The position is left out where the platform does
|
||||
/// not tell it (Wayland). A front end keeps it in [`UI_WINDOW`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct WindowState {
|
||||
/// Width in logical pixels.
|
||||
pub width: u32,
|
||||
/// Height in logical pixels.
|
||||
pub height: u32,
|
||||
/// Distance of the window's left edge from the screen's, when known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub x: Option<i32>,
|
||||
/// Distance of the window's top edge from the screen's, when known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub y: Option<i32>,
|
||||
/// The window was maximized.
|
||||
#[serde(default)]
|
||||
pub maximized: bool,
|
||||
}
|
||||
|
||||
impl WindowState {
|
||||
/// The smallest size a window can have been left at.
|
||||
pub const MIN_SIZE: (u32, u32) = (320, 240);
|
||||
/// The largest size and the farthest position taken as real: a value
|
||||
/// beyond it is a damaged setting, not a screen.
|
||||
pub const LIMIT: u32 = 16_384;
|
||||
|
||||
/// Whether the values can be a window: a size within [`Self::MIN_SIZE`]
|
||||
/// and [`Self::LIMIT`], a position within it either way, and a position
|
||||
/// that is given whole or not at all.
|
||||
pub fn is_sane(&self) -> bool {
|
||||
let limit = i64::from(Self::LIMIT);
|
||||
(Self::MIN_SIZE.0..=Self::LIMIT).contains(&self.width)
|
||||
&& (Self::MIN_SIZE.1..=Self::LIMIT).contains(&self.height)
|
||||
&& self.x.is_some() == self.y.is_some()
|
||||
&& [self.x, self.y].into_iter().flatten().all(|at| i64::from(at).abs() <= limit)
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_window(state: &Option<WindowState>) -> Result<(), String> {
|
||||
match state {
|
||||
Some(state) if !state.is_sane() => Err("a window of 320x240 to 16384x16384".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.window`: the main window's size and position as the last run left them
|
||||
/// (none until a run has). The GPUI front end writes it; the Slint one does
|
||||
/// not read it.
|
||||
pub static UI_WINDOW: Key<Option<WindowState>> = Key::new(
|
||||
"ui.window",
|
||||
Kind::Json,
|
||||
"The main window's size and position as the last run left them (none: not stored yet).",
|
||||
|| None,
|
||||
)
|
||||
.validated(valid_window);
|
||||
|
||||
/// What the channel tree remembers of one server: the channels folded shut and
|
||||
/// the channel last selected (a click on its row).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TreeState {
|
||||
/// The channels folded shut, in ascending order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub collapsed: Vec<ChannelId>,
|
||||
/// The channel last selected, if one was.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub selected: Option<ChannelId>,
|
||||
}
|
||||
|
||||
impl TreeState {
|
||||
/// Nothing is remembered.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.collapsed.is_empty() && self.selected.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the channel tree remembers, by the id of the server's bookmark
|
||||
/// (as text: a JSON object's keys are).
|
||||
pub type TreeStates = BTreeMap<String, TreeState>;
|
||||
|
||||
/// The most channels one server may have folded in [`UI_TREE`]: a server has
|
||||
/// far fewer channels, so more is a damaged setting.
|
||||
const TREE_STATE_LIMIT: usize = 10_000;
|
||||
|
||||
fn valid_tree(states: &TreeStates) -> Result<(), String> {
|
||||
if states.keys().any(|id| id.parse::<i64>().is_err()) {
|
||||
return Err("keyed by the id of a server".into());
|
||||
}
|
||||
if states.values().any(|state| state.collapsed.len() > TREE_STATE_LIMIT) {
|
||||
return Err(format!("at most {TREE_STATE_LIMIT} folded channels of a server"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `ui.tree`: which channels each server's tree has folded shut, and which
|
||||
/// channel was selected, by the id of the server's bookmark. The GPUI front
|
||||
/// end writes it; the Slint one does not read it (its tree forgets both
|
||||
/// when the app ends).
|
||||
pub static UI_TREE: Key<TreeStates> = Key::new(
|
||||
"ui.tree",
|
||||
Kind::Json,
|
||||
"The channels each server's tree has folded and the channel selected, by server.",
|
||||
TreeStates::new,
|
||||
)
|
||||
.validated(valid_tree);
|
||||
|
||||
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
|
||||
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
|
||||
[
|
||||
@@ -128,8 +240,11 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NotifyLevel {
|
||||
/// Nothing.
|
||||
Off,
|
||||
/// The bell in the app.
|
||||
App,
|
||||
/// The bell and a desktop notification.
|
||||
#[default]
|
||||
Desktop,
|
||||
}
|
||||
@@ -257,6 +372,53 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings service on the client database in `dir` (`client.db`), the way
|
||||
/// both front ends open it: the keys they read registered ([`UI`],
|
||||
/// [`CLIENT_PLAYBACK`], [`appearance_keys`] and [`page_keys`]; `register` adds
|
||||
/// the keys of one front end only, before anything is read), then a config file
|
||||
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists), the
|
||||
/// `VOELIN_SETTING_*` variables and `overrides` (`--set key=value`) below the
|
||||
/// stored values. Without the database the settings live in memory. What
|
||||
/// cannot be applied is logged, not fatal.
|
||||
pub fn open_settings(
|
||||
dir: &Path,
|
||||
overrides: &[String],
|
||||
register: impl FnOnce(&Settings),
|
||||
) -> Settings {
|
||||
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
|
||||
warn!(%e, "settings are not stored this time");
|
||||
Settings::in_memory()
|
||||
});
|
||||
register_keys(&prefs);
|
||||
register(&prefs);
|
||||
let config = std::env::var_os("VOELIN_CONFIG")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
|
||||
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
|
||||
Some(Ok(errors)) => errors,
|
||||
Some(Err(e)) => vec![e],
|
||||
None => Vec::new(),
|
||||
};
|
||||
errors.extend(prefs.apply_env(std::env::vars()));
|
||||
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
|
||||
for e in errors {
|
||||
warn!(%e, "setting ignored");
|
||||
}
|
||||
prefs
|
||||
}
|
||||
|
||||
/// Make the keys both front ends read known to `prefs`.
|
||||
pub fn register_keys(prefs: &Settings) {
|
||||
prefs.register(&UI);
|
||||
prefs.register(&CLIENT_PLAYBACK);
|
||||
for key in appearance_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
for key in page_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
|
||||
/// offers, in the order of its lists (`dialogs.slint`); any other value can
|
||||
/// be typed in.
|
||||
@@ -294,6 +456,7 @@ pub struct UiSettings {
|
||||
pub openh264: bool,
|
||||
/// The ScreenCast portal's token for the last shared screen.
|
||||
pub portal_restore_token: Option<String>,
|
||||
/// The last choices in the share dialog.
|
||||
pub share: ShareDefaults,
|
||||
/// Write crash reports to disk (opt-in; never uploaded).
|
||||
pub crash_reports: bool,
|
||||
@@ -321,8 +484,11 @@ impl Default for UiSettings {
|
||||
/// path, its names from the top as the server has them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LastVoice {
|
||||
/// The id of the server's bookmark.
|
||||
pub bookmark: i64,
|
||||
/// The address the bookmark had then.
|
||||
pub address: String,
|
||||
/// The channel's names from the top.
|
||||
pub channel: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -333,9 +499,13 @@ pub struct LastVoice {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ShareDefaults {
|
||||
/// The frame rate's position in the old list ([`LEGACY_FPS_CHOICES`]).
|
||||
pub fps_index: usize,
|
||||
/// The bitrate's position in the old list ([`LEGACY_BITRATE_CHOICES`]).
|
||||
pub bitrate_index: usize,
|
||||
/// Share the sound too.
|
||||
pub audio: bool,
|
||||
/// Accept the viewers that ask to watch without asking us.
|
||||
pub auto_accept: bool,
|
||||
}
|
||||
|
||||
@@ -350,6 +520,7 @@ impl Default for ShareDefaults {
|
||||
pub struct ClientPlayback {
|
||||
/// Linear, 1 = unchanged.
|
||||
pub volume: f32,
|
||||
/// Not played at all.
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
@@ -372,6 +543,7 @@ pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
|
||||
/// Audio devices as listed in the settings: the system default first.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DeviceChoices {
|
||||
/// What the list shows, by index.
|
||||
pub names: Vec<String>,
|
||||
/// Device ids by index; `None` for the system default.
|
||||
pub ids: Vec<Option<String>>,
|
||||
@@ -589,6 +761,74 @@ mod tests {
|
||||
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
|
||||
}
|
||||
|
||||
/// The settings both front ends open: the shared keys, the config file's
|
||||
/// values, then `--set` over it, a front end's own key only when it
|
||||
/// registers it, and a database in the directory given.
|
||||
#[test]
|
||||
fn the_settings_open_with_the_shared_keys_a_config_file_and_overrides() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("voelin-ui-vm-settings-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("config.toml"),
|
||||
"\"ui.theme\" = \"light\"\n\"ui.members_width\" = 300\n",
|
||||
)
|
||||
.unwrap();
|
||||
let overrides = ["ui.font_scale=1.5".to_owned(), "ui.members_width=320".to_owned()];
|
||||
let prefs = open_settings(&dir, &overrides, |prefs| prefs.register(&UI_WINDOW));
|
||||
assert_eq!(prefs.get(&UI_THEME), ThemeChoice::Light, "from the config file");
|
||||
assert_eq!(prefs.get(&UI_FONT_SCALE), 1.5, "from --set");
|
||||
assert_eq!(prefs.get(&UI_MEMBERS_WIDTH), 320, "--set over the file");
|
||||
assert_eq!(prefs.get(&UI_WINDOW), None);
|
||||
let names = |prefs: &Settings| prefs.keys().iter().map(|k| k.name()).collect::<Vec<_>>();
|
||||
for shared in
|
||||
["ui", "client_playback", "ui.theme", "notify.mentions", "ui.image_preview_kb"]
|
||||
{
|
||||
assert!(names(&prefs).contains(&shared), "{shared}");
|
||||
}
|
||||
assert!(names(&prefs).contains(&"ui.window"), "the front end's own key");
|
||||
prefs.set(&UI_FONT_SCALE, 1.25).unwrap();
|
||||
prefs.flush().unwrap();
|
||||
drop(prefs);
|
||||
assert!(dir.join("client.db").is_file(), "the database is in the directory given");
|
||||
|
||||
let plain = open_settings(&dir, &[], |_| {});
|
||||
assert!(!names(&plain).contains(&"ui.window"), "not registered by this front end");
|
||||
assert_eq!(plain.get(&UI_FONT_SCALE), 1.25, "what was stored wins over nothing");
|
||||
drop(plain);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// The tree's memory is a JSON object by server, round-trips through the
|
||||
/// service, and a damaged value is refused.
|
||||
#[test]
|
||||
fn tree_key() {
|
||||
let settings = voelin_core::settings::Settings::in_memory();
|
||||
settings.register(&UI_TREE);
|
||||
assert!(settings.get(&UI_TREE).is_empty(), "nothing remembered at first");
|
||||
let states = TreeStates::from([
|
||||
("3".to_owned(), TreeState { collapsed: vec![4, 9], selected: Some(2) }),
|
||||
("5".to_owned(), TreeState { collapsed: Vec::new(), selected: Some(1) }),
|
||||
]);
|
||||
settings.set(&UI_TREE, states.clone()).unwrap();
|
||||
assert_eq!(settings.get(&UI_TREE), states);
|
||||
assert_eq!(
|
||||
settings.get_json("ui.tree"),
|
||||
Some(
|
||||
serde_json::json!({"3": {"collapsed": [4, 9], "selected": 2}, "5": {"selected": 1}})
|
||||
)
|
||||
);
|
||||
// What an older build wrote without a field still loads.
|
||||
settings.set_json("ui.tree", serde_json::json!({"7": {}})).unwrap();
|
||||
assert!(settings.get(&UI_TREE)["7"].is_empty());
|
||||
for damaged in
|
||||
[serde_json::json!({"nope": {}}), serde_json::json!({"1": {"selected": "x"}})]
|
||||
{
|
||||
assert!(settings.set_json("ui.tree", damaged).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_compact_key() {
|
||||
let settings = voelin_core::settings::Settings::in_memory();
|
||||
@@ -601,6 +841,47 @@ mod tests {
|
||||
assert!(settings.set_json("ui.voice_compact", "small".into()).is_err());
|
||||
}
|
||||
|
||||
/// The window's state is stored as the setting `ui.window`, comes back as it
|
||||
/// went, and a damaged value is refused in words.
|
||||
#[test]
|
||||
fn window_state_roundtrip() {
|
||||
let state =
|
||||
WindowState { width: 1440, height: 960, x: Some(-20), y: Some(35), maximized: true };
|
||||
let settings = voelin_core::settings::Settings::in_memory();
|
||||
assert_eq!(settings.get(&UI_WINDOW), None, "none until a run left one");
|
||||
settings.set(&UI_WINDOW, Some(state)).unwrap();
|
||||
assert_eq!(settings.get(&UI_WINDOW), Some(state));
|
||||
assert_eq!(
|
||||
settings.get_json("ui.window"),
|
||||
Some(
|
||||
serde_json::json!({"width": 1440, "height": 960, "x": -20, "y": 35, "maximized": true})
|
||||
)
|
||||
);
|
||||
// A platform that does not tell the position leaves it out.
|
||||
let no_position = WindowState { x: None, y: None, maximized: false, ..state };
|
||||
let json = serde_json::to_value(no_position).unwrap();
|
||||
assert_eq!(json, serde_json::json!({"width": 1440, "height": 960, "maximized": false}));
|
||||
assert_eq!(serde_json::from_value::<WindowState>(json).unwrap(), no_position);
|
||||
let older: WindowState = serde_json::from_str(r#"{"width":800,"height":600}"#).unwrap();
|
||||
assert_eq!(
|
||||
older,
|
||||
WindowState { width: 800, height: 600, x: None, y: None, maximized: false }
|
||||
);
|
||||
for damaged in [
|
||||
WindowState { width: 0, ..state },
|
||||
WindowState { height: 100_000, ..state },
|
||||
WindowState { x: Some(1_000_000), ..state },
|
||||
WindowState { y: None, ..state },
|
||||
] {
|
||||
assert!(!damaged.is_sane(), "{damaged:?}");
|
||||
assert!(settings.set(&UI_WINDOW, Some(damaged)).is_err(), "{damaged:?}");
|
||||
}
|
||||
assert!(settings.set_json("ui.window", "big".into()).is_err());
|
||||
assert_eq!(settings.get(&UI_WINDOW), Some(state), "a refused value changes nothing");
|
||||
settings.set(&UI_WINDOW, None).unwrap();
|
||||
assert_eq!(settings.get(&UI_WINDOW), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_settings_defaults() {
|
||||
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
//! The audio settings page and the local volume of clients: the device
|
||||
//! lists and the form, what a change of the form sends to the engine, the
|
||||
//! microphone test, the push-to-talk and H.264 switches, the crash notice
|
||||
//! and the volume dialog. The functions change the
|
||||
//! [`AppState`] and say in the [`Cx`]'s update what
|
||||
//! to send and keep; the devices, the hotkey, the store and the window are
|
||||
//! the front end's.
|
||||
|
||||
use voelin_core::Command;
|
||||
|
||||
use crate::bridge::{AudioForm, ClientAudio};
|
||||
use crate::host::{Cx, Persist};
|
||||
use crate::settings::{ClientPlayback, DeviceChoices, apply_audio_form, audio_form};
|
||||
use crate::state::AppState;
|
||||
|
||||
/// What the settings page shows when it opens ([`open_settings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SettingsView {
|
||||
/// The input devices' names, the system default first.
|
||||
pub input_devices: Vec<String>,
|
||||
/// The output devices' names, the system default first.
|
||||
pub output_devices: Vec<String>,
|
||||
/// The form of the audio settings.
|
||||
pub audio: AudioForm,
|
||||
/// The push-to-talk key works in every window.
|
||||
pub global_ptt: bool,
|
||||
/// The push-to-talk key.
|
||||
pub ptt_key: String,
|
||||
/// H.264 through the downloaded OpenH264 is on.
|
||||
pub h264_enabled: bool,
|
||||
}
|
||||
|
||||
/// An audio device the system lists: its id, its name and whether it is the
|
||||
/// system's default of its direction.
|
||||
pub type Device = (String, String, bool);
|
||||
|
||||
/// The settings page opens: the devices the system lists become the choices
|
||||
/// (a device that is stored but not there stays in the list), and the form
|
||||
/// and the switches are those of the state.
|
||||
pub fn open_settings<L>(
|
||||
state: &mut AppState<L>,
|
||||
inputs: &[Device],
|
||||
outputs: &[Device],
|
||||
) -> SettingsView {
|
||||
state.inputs = DeviceChoices::new(inputs, state.audio.input_device.as_deref());
|
||||
state.outputs = DeviceChoices::new(outputs, state.audio.output_device.as_deref());
|
||||
SettingsView {
|
||||
input_devices: state.inputs.names.clone(),
|
||||
output_devices: state.outputs.names.clone(),
|
||||
audio: audio_form(&state.audio, &state.inputs, &state.outputs),
|
||||
global_ptt: state.settings.global_ptt,
|
||||
ptt_key: state.settings.ptt_key.clone(),
|
||||
h264_enabled: state.settings.openh264,
|
||||
}
|
||||
}
|
||||
|
||||
/// The form changed: the engine gets the new audio settings, and they are
|
||||
/// kept later ([`save_audio`]), if the form changed anything.
|
||||
pub fn audio_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &AudioForm) {
|
||||
let audio = apply_audio_form(form, &state.audio, &state.inputs, &state.outputs);
|
||||
if audio == state.audio {
|
||||
return;
|
||||
}
|
||||
state.audio = audio;
|
||||
state.audio_dirty = true;
|
||||
cx.send(Command::SetAudioSettings(Box::new(state.audio.clone())));
|
||||
}
|
||||
|
||||
/// Keep the audio settings, if they changed since they were kept.
|
||||
pub fn save_audio<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
|
||||
if state.audio_dirty {
|
||||
state.audio_dirty = false;
|
||||
cx.persist(Persist::Audio);
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings page closes: the microphone test stops and the audio
|
||||
/// settings are kept. Whether the test was on.
|
||||
pub fn close_settings<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) -> bool {
|
||||
let was_on = set_mic_test(state, cx, false);
|
||||
save_audio(state, cx);
|
||||
was_on
|
||||
}
|
||||
|
||||
/// Start or stop the microphone test: whether that changed anything.
|
||||
pub fn set_mic_test<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) -> bool {
|
||||
if state.mic_test == on {
|
||||
return false;
|
||||
}
|
||||
state.mic_test = on;
|
||||
cx.send(Command::TestMicrophone { on });
|
||||
true
|
||||
}
|
||||
|
||||
/// The push-to-talk switch and key: kept, and the key to register as a
|
||||
/// hotkey of the whole desktop, none to unregister it. A blank key leaves
|
||||
/// the one that was set.
|
||||
pub fn apply_ptt<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
enabled: bool,
|
||||
key: &str,
|
||||
) -> Option<String> {
|
||||
let key = key.trim().to_owned();
|
||||
state.settings.global_ptt = enabled;
|
||||
if !key.is_empty() {
|
||||
state.settings.ptt_key = key.clone();
|
||||
}
|
||||
cx.persist(Persist::Settings);
|
||||
(enabled && !key.is_empty()).then_some(key)
|
||||
}
|
||||
|
||||
/// The H.264 switch: kept; the front end tells the encoder.
|
||||
pub fn set_h264<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
|
||||
state.settings.openh264 = enabled;
|
||||
cx.persist(Persist::Settings);
|
||||
}
|
||||
|
||||
/// What the H.264 rows show ([`h264_view`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct H264View {
|
||||
/// The library is loaded.
|
||||
pub loaded: bool,
|
||||
/// It is being downloaded.
|
||||
pub busy: bool,
|
||||
/// What the front end's codec says.
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
/// The H.264 rows for the codec's state: `loaded`, and its `status` text
|
||||
/// ("Downloading …" while it is being fetched).
|
||||
pub fn h264_view(loaded: bool, status: String) -> H264View {
|
||||
H264View { loaded, busy: status.starts_with("Downloading"), status }
|
||||
}
|
||||
|
||||
/// The crash reports switch: kept (the front end also tells the crash
|
||||
/// handler and the settings service).
|
||||
pub fn set_crash_reports<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
|
||||
state.settings.crash_reports = enabled;
|
||||
// Also in the blob, for older versions.
|
||||
cx.persist(Persist::Settings);
|
||||
}
|
||||
|
||||
/// The notice while crash reports are on disk: `summaries` are the first
|
||||
/// lines of their panic messages, oldest first. Empty without reports.
|
||||
pub fn crash_notice(summaries: &[String]) -> String {
|
||||
let Some(newest) = summaries.last() else { return String::new() };
|
||||
let saved = match summaries.len() {
|
||||
1 => "1 crash report is saved".to_owned(),
|
||||
n => format!("{n} crash reports are saved"),
|
||||
};
|
||||
format!("The app crashed earlier ({newest}). {saved} on this device.")
|
||||
}
|
||||
|
||||
// Local volume and mute of clients.
|
||||
|
||||
/// Fill the volume dialog for `client` of the current session; none when
|
||||
/// there is no such client.
|
||||
pub fn open_client<L>(state: &mut AppState<L>, client: u16) -> Option<ClientAudio> {
|
||||
let id = state.current?;
|
||||
let info = state.sessions.get(&id)?.presence.clients.get(&client)?.clone();
|
||||
let playback =
|
||||
info.uid.as_ref().and_then(|uid| state.playback.get(uid)).copied().unwrap_or_default();
|
||||
state.playback_dialog = Some((id, client, info.uid.clone()));
|
||||
Some(ClientAudio {
|
||||
id: i32::from(client),
|
||||
name: info.nickname.into(),
|
||||
volume: playback.volume * 100.0,
|
||||
muted: playback.muted,
|
||||
streaming: info.streaming == Some(true),
|
||||
})
|
||||
}
|
||||
|
||||
/// The volume dialog changed: the engine plays the client so, and the
|
||||
/// choice is kept by the client's unique id (a client without one only for
|
||||
/// this connection), the default as no choice. The tree shows who is muted.
|
||||
pub fn client_playback_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &ClientAudio) {
|
||||
let Some((session, client, uid)) = state.playback_dialog.clone() else { return };
|
||||
let playback =
|
||||
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
|
||||
let session = session as u64;
|
||||
cx.send(Command::SetClientVolume { session, client, volume: playback.volume });
|
||||
cx.send(Command::SetClientMuted { session, client, muted: playback.muted });
|
||||
if let Some(uid) = uid {
|
||||
if playback.is_default() {
|
||||
state.playback.remove(&uid);
|
||||
} else {
|
||||
state.playback.insert(uid, playback);
|
||||
}
|
||||
cx.persist(Persist::Playback);
|
||||
}
|
||||
cx.update.refresh.tree = true;
|
||||
}
|
||||
|
||||
/// The first client of the current session that is not us nor a query
|
||||
/// client (`VOELIN_OPEN=client`): its id, when we are in the session.
|
||||
pub fn first_client<L>(state: &AppState<L>) -> Option<u16> {
|
||||
let view = state.current.and_then(|id| state.sessions.get(&id))?;
|
||||
let own = view.state.own_client?;
|
||||
view.presence.clients.values().filter(|c| c.id != own && !c.is_query).map(|c| c.id).min()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_core::VoiceState;
|
||||
|
||||
use super::*;
|
||||
use crate::host::testing::{Fake, State, presence, session, state};
|
||||
|
||||
fn device(id: &str, name: &str, default: bool) -> Device {
|
||||
(id.into(), name.into(), default)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_opens_with_the_devices_and_a_stored_one_stays() {
|
||||
let mut st = state();
|
||||
st.audio.input_device = Some("gone".into());
|
||||
st.settings.global_ptt = true;
|
||||
st.settings.ptt_key = "F9".into();
|
||||
let inputs = [device("a", "Built-in", true), device("b", "Headset", false)];
|
||||
let outputs = [device("a", "Built-in", false), device("b", "Headset", true)];
|
||||
let view = open_settings(&mut st, &inputs, &outputs);
|
||||
// The system default first, named after the one that is the default.
|
||||
assert_eq!(
|
||||
view.input_devices,
|
||||
["System default (Built-in)", "Built-in", "Headset", "gone (not connected)"]
|
||||
);
|
||||
// Outputs have the other as the default, and no stored device.
|
||||
assert_eq!(view.output_devices, ["System default (Headset)", "Built-in", "Headset"]);
|
||||
assert_eq!(view.audio.input_index, 3, "the stored device is selected");
|
||||
assert_eq!(view.audio.output_index, 0, "no stored output: the default");
|
||||
assert!(view.global_ptt && view.ptt_key == "F9" && !view.h264_enabled);
|
||||
assert_eq!(st.inputs.names, view.input_devices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_of_the_form_goes_to_the_engine_once_and_is_kept_later() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
open_settings(&mut st, &[], &[]);
|
||||
let mut form = audio_form(&st.audio, &st.inputs, &st.outputs);
|
||||
// Nothing changed: nothing sent.
|
||||
let mut cx = Cx::new(&host);
|
||||
audio_changed(&mut st, &mut cx, &form);
|
||||
assert!(cx.update.commands.is_empty() && !st.audio_dirty);
|
||||
form.output_volume = 50.0;
|
||||
audio_changed(&mut st, &mut cx, &form);
|
||||
assert!(matches!(
|
||||
cx.update.commands.as_slice(),
|
||||
[Command::SetAudioSettings(audio)] if audio.output_volume == 0.5
|
||||
));
|
||||
assert!(st.audio_dirty);
|
||||
// The same form again changes nothing.
|
||||
audio_changed(&mut st, &mut cx, &form);
|
||||
assert_eq!(cx.update.commands.len(), 1);
|
||||
// Kept once, when the page closes or the clock ticks.
|
||||
save_audio(&mut st, &mut cx);
|
||||
save_audio(&mut st, &mut cx);
|
||||
assert_eq!(cx.update.persist, [Persist::Audio]);
|
||||
assert!(!st.audio_dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_microphone_test_stops_with_the_page() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let mut cx = Cx::new(&host);
|
||||
assert!(!close_settings(&mut st, &mut cx), "it was not on");
|
||||
assert!(cx.update.commands.is_empty());
|
||||
assert!(set_mic_test(&mut st, &mut cx, true));
|
||||
assert!(!set_mic_test(&mut st, &mut cx, true), "already on");
|
||||
st.audio_dirty = true;
|
||||
assert!(close_settings(&mut st, &mut cx), "it was on");
|
||||
assert!(!st.mic_test);
|
||||
assert!(matches!(
|
||||
cx.update.commands.as_slice(),
|
||||
[Command::TestMicrophone { on: true }, Command::TestMicrophone { on: false }]
|
||||
));
|
||||
assert_eq!(cx.update.persist, [Persist::Audio]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_push_to_talk_key_is_registered_when_it_is_on_and_set() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let mut cx = Cx::new(&host);
|
||||
assert_eq!(apply_ptt(&mut st, &mut cx, true, " F9 ").as_deref(), Some("F9"));
|
||||
assert!(st.settings.global_ptt);
|
||||
assert_eq!(st.settings.ptt_key, "F9");
|
||||
// Off: unregistered, the key stays for later.
|
||||
assert_eq!(apply_ptt(&mut st, &mut cx, false, "F10"), None);
|
||||
assert_eq!(st.settings.ptt_key, "F10");
|
||||
// A blank key leaves the one that was set, and registers nothing.
|
||||
assert_eq!(apply_ptt(&mut st, &mut cx, true, " "), None);
|
||||
assert_eq!(st.settings.ptt_key, "F10");
|
||||
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings, Persist::Settings]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switches_are_kept() {
|
||||
let mut st = state();
|
||||
let host = Fake::default();
|
||||
let mut cx = Cx::new(&host);
|
||||
set_h264(&mut st, &mut cx, true);
|
||||
set_crash_reports(&mut st, &mut cx, true);
|
||||
assert!(st.settings.openh264 && st.settings.crash_reports);
|
||||
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings]);
|
||||
assert_eq!(
|
||||
h264_view(false, "Downloading OpenH264… 40%".into()),
|
||||
H264View { loaded: false, busy: true, status: "Downloading OpenH264… 40%".into() }
|
||||
);
|
||||
assert!(!h264_view(true, "Loaded".into()).busy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_crash_notice_counts_the_reports() {
|
||||
assert_eq!(crash_notice(&[]), "");
|
||||
assert_eq!(
|
||||
crash_notice(&["index out of bounds".into()]),
|
||||
"The app crashed earlier (index out of bounds). 1 crash report is saved on this device."
|
||||
);
|
||||
assert_eq!(
|
||||
crash_notice(&["old".into(), "new".into()]),
|
||||
"The app crashed earlier (new). 2 crash reports are saved on this device."
|
||||
);
|
||||
}
|
||||
|
||||
/// Connected, with Alice (11) in Games next to us (10), a query client
|
||||
/// (12) and Zed (9, a lower id).
|
||||
fn with_clients() -> State {
|
||||
let mut st = state();
|
||||
let mut p = (*presence()).clone();
|
||||
p.clients.get_mut(&11).unwrap().streaming = Some(true);
|
||||
for (id, name, query) in [(12, "serveradmin", true), (9, "Zed", false)] {
|
||||
p.clients.insert(
|
||||
id,
|
||||
voelin_model::ClientInfo {
|
||||
id,
|
||||
channel: 2,
|
||||
nickname: name.into(),
|
||||
is_query: query,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let view = st.sessions.entry(1).or_default();
|
||||
view.presence = std::sync::Arc::new(p);
|
||||
view.state = session(VoiceState::Connected, Some(2));
|
||||
st
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_volume_dialog_fills_from_what_was_kept() {
|
||||
let mut st = with_clients();
|
||||
assert_eq!(open_client(&mut st, 99), None, "no such client");
|
||||
let form = open_client(&mut st, 11).unwrap();
|
||||
assert_eq!((form.id, &*form.name, form.volume, form.muted), (11, "Alice", 100.0, false));
|
||||
assert!(form.streaming);
|
||||
assert_eq!(st.playback_dialog, Some((1, 11, Some("alice=".into()))));
|
||||
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
|
||||
let form = open_client(&mut st, 11).unwrap();
|
||||
assert_eq!((form.volume, form.muted), (50.0, true));
|
||||
st.current = None;
|
||||
assert_eq!(open_client(&mut st, 11), None, "no server shown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_is_played_as_the_dialog_says_and_the_default_is_forgotten() {
|
||||
let mut st = with_clients();
|
||||
let host = Fake::default();
|
||||
let mut cx = Cx::new(&host);
|
||||
// No dialog open: nothing.
|
||||
client_playback_changed(&mut st, &mut cx, &ClientAudio::default());
|
||||
assert!(cx.update.commands.is_empty());
|
||||
let mut form = open_client(&mut st, 11).unwrap();
|
||||
form.volume = 900.0;
|
||||
form.muted = true;
|
||||
client_playback_changed(&mut st, &mut cx, &form);
|
||||
// Clamped to four times, sent, kept by unique id, the tree shows it.
|
||||
assert!(matches!(
|
||||
cx.update.commands.as_slice(),
|
||||
[
|
||||
Command::SetClientVolume { session: 1, client: 11, volume: 4.0 },
|
||||
Command::SetClientMuted { session: 1, client: 11, muted: true },
|
||||
]
|
||||
));
|
||||
assert_eq!(st.playback["alice="], ClientPlayback { volume: 4.0, muted: true });
|
||||
assert_eq!(cx.update.persist, [Persist::Playback]);
|
||||
assert!(cx.update.refresh.tree);
|
||||
// Back to the default: no entry.
|
||||
form.volume = 100.0;
|
||||
form.muted = false;
|
||||
client_playback_changed(&mut st, &mut cx, &form);
|
||||
assert!(st.playback.is_empty());
|
||||
// A client without a unique id is played so only for now.
|
||||
st.playback_dialog = Some((1, 9, None));
|
||||
let before = cx.update.persist.len();
|
||||
client_playback_changed(&mut st, &mut cx, &form);
|
||||
assert!(st.playback.is_empty());
|
||||
assert_eq!(cx.update.persist.len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_client_is_the_lowest_id_that_is_not_us() {
|
||||
let mut st = with_clients();
|
||||
assert_eq!(first_client(&st), Some(9), "not us (10), not the query client");
|
||||
st.sessions.get_mut(&1).unwrap().state.own_client = None;
|
||||
assert_eq!(first_client(&st), None, "not in the session");
|
||||
st.current = None;
|
||||
assert_eq!(first_client(&st), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! The settings page of the audio devices and the voice controls, the push
|
||||
//! to talk key, the H.264 switch, the crash reports and the volume of a
|
||||
//! client. [`logic`] has what the page shows and what its controls change;
|
||||
//! the engine, the store, the hotkey and the window are the front end's.
|
||||
|
||||
pub mod logic;
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user