Compare 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,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==
|
||||
@@ -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
|
||||
@@ -9,9 +9,7 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
### Added
|
||||
|
||||
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
|
||||
window titled Voelin with one line of the app's state in it (the version,
|
||||
the voice connections that are up, the engine events handled, the seconds
|
||||
up), fed by the same engine and the same view models as the Slint app
|
||||
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
|
||||
@@ -26,6 +24,53 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
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.
|
||||
@@ -223,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
|
||||
|
||||
|
||||
@@ -12587,6 +12587,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-platform",
|
||||
"voelin-store",
|
||||
@@ -12596,7 +12597,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.23.1",
|
||||
@@ -12654,8 +12655,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "voelin-model"
|
||||
version = "0.1.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"serde",
|
||||
@@ -12694,7 +12695,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
@@ -12789,6 +12790,7 @@ dependencies = [
|
||||
"roxmltree 0.21.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tracing",
|
||||
"unicode-segmentation",
|
||||
"voelin-audio",
|
||||
"voelin-core",
|
||||
|
||||
@@ -59,15 +59,18 @@ 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 c5bb6b9: the account-bound
|
||||
# KeyStore whose sign-out keeps every device key and the release of a device key,
|
||||
# Phase 2 task 34; the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# 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 = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
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 = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
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,
|
||||
|
||||
@@ -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 c5bb6b9 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),
|
||||
"{:?}",
|
||||
|
||||
@@ -333,7 +333,7 @@ enum Expect {
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c5bb6b9`, 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.
|
||||
///
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -21,18 +21,22 @@ anyhow = "1.0.104"
|
||||
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
|
||||
gpui-kit = { workspace = true }
|
||||
# The engine's runtime and the channel of its events (a tokio receiver needs no
|
||||
# reactor, so GPUI's executor can await it).
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
|
||||
# reactor, so GPUI's executor can await it); `macros` for the hotkey task's
|
||||
# `select!`.
|
||||
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "sync", "time"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
# The TeamSpeak identity a connection is made with (the store hands it out).
|
||||
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 Host trait's types (what the store knows of a chat's read marker).
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
# 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" }
|
||||
|
||||
|
||||
@@ -25,11 +25,17 @@ 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,25 @@
|
||||
//! 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 will give (`ui.theme` in the Slint front end).
|
||||
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
|
||||
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
|
||||
//! 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`]).
|
||||
|
||||
@@ -19,7 +34,7 @@ use crate::theme::Choice;
|
||||
/// A page the window can be opened on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
/// The shell. Today an empty window with the state line.
|
||||
/// The desktop shell.
|
||||
Shell,
|
||||
/// Every theme token, a few components and the icons.
|
||||
Swatch,
|
||||
@@ -30,6 +45,25 @@ pub enum Page {
|
||||
pub struct Switches {
|
||||
/// The page to open on.
|
||||
pub open: Page,
|
||||
/// The voice channel page is asked for (`VOELIN_OPEN=voice`): it shows
|
||||
/// once voice is connected.
|
||||
pub voice: bool,
|
||||
/// With the voice page, the smaller stage, as the switch says (it is not
|
||||
/// stored, as the Slint front end's `voice:compact`).
|
||||
pub voice_compact: bool,
|
||||
/// Show the sample servers instead of the stored ones.
|
||||
pub demo_ui: bool,
|
||||
/// Write the sample servers' pictures to a folder of the temporary
|
||||
/// directory and deliver them: what the binary does with the sample
|
||||
/// servers, and what a test asks for by name (a test that does not leaves
|
||||
/// nothing behind).
|
||||
pub demo_pictures: bool,
|
||||
/// The sample server to show, by its place in the list, when the switch
|
||||
/// names one.
|
||||
pub demo_server: Option<usize>,
|
||||
/// How many times a second a sample person starts or stops talking (with
|
||||
/// the sample servers), when the switch names a rate.
|
||||
pub demo_talk: Option<f32>,
|
||||
/// The theme mode, when the switch names one.
|
||||
pub theme: Option<Choice>,
|
||||
/// The text size factor, when the switch names one.
|
||||
@@ -42,7 +76,19 @@ pub struct Switches {
|
||||
|
||||
impl Default for Switches {
|
||||
fn default() -> Self {
|
||||
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +106,10 @@ impl Switches {
|
||||
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
|
||||
match what {
|
||||
"swatch" => switches.open = Page::Swatch,
|
||||
"voice" => switches.voice = true,
|
||||
"voice:compact" => (switches.voice, switches.voice_compact) = (true, true),
|
||||
other => tracing::warn!(
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)"
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)"
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -84,7 +132,22 @@ impl Switches {
|
||||
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
|
||||
}
|
||||
}
|
||||
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -116,19 +179,32 @@ mod tests {
|
||||
#[test]
|
||||
fn every_switch_is_read() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "swatch"),
|
||||
("VOELIN_OPEN", "swatch,voice:compact"),
|
||||
("VOELIN_DEMO_UI", "1"),
|
||||
("VOELIN_DEMO_SERVER", "2"),
|
||||
("VOELIN_DEMO_TALK", "10"),
|
||||
("VOELIN_DEV_THEME", "light"),
|
||||
("VOELIN_FONT_SCALE", "1.25"),
|
||||
("VOELIN_WINDOW_SIZE", "1440x960"),
|
||||
("VOELIN_METER", "1"),
|
||||
]);
|
||||
assert_eq!(s.open, Page::Swatch);
|
||||
assert!(s.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(&[
|
||||
@@ -136,6 +212,9 @@ mod tests {
|
||||
("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());
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
|
||||
use tokio::runtime::{Handle, Runtime};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_core::{Engine, Event};
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::{Backends, Engine, Event, History};
|
||||
|
||||
/// An engine owned by the caller of [`crate::run`].
|
||||
pub struct HostedEngine {
|
||||
@@ -24,7 +25,25 @@ pub struct HostedEngine {
|
||||
impl HostedEngine {
|
||||
/// A new engine on `runtime`, all of whose events go to the window.
|
||||
pub fn start(runtime: &Runtime) -> Self {
|
||||
let engine = runtime.block_on(async { Engine::start() });
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the
|
||||
//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports
|
||||
//! the key's presses and releases, whichever window has the focus.
|
||||
//!
|
||||
//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`),
|
||||
//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the
|
||||
//! engine's runtime and the front end's own way back to its state, and the
|
||||
//! Slint crate cannot be a dependency (it brings Slint in); both go into one
|
||||
//! place when the Slint front end is retired.
|
||||
//!
|
||||
//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on
|
||||
//! it), not from a foreground task of GPUI: the portal's backend calls
|
||||
//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which
|
||||
//! panics where no tokio runtime is current, and GPUI's executor has none.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
|
||||
|
||||
/// The id of the push-to-talk registration (the portal remembers the user's
|
||||
/// choice by it).
|
||||
const PTT_ID: &str = "push-to-talk";
|
||||
|
||||
/// The handle to the hotkey task.
|
||||
pub struct GlobalPtt {
|
||||
tx: mpsc::UnboundedSender<Option<String>>,
|
||||
}
|
||||
|
||||
impl GlobalPtt {
|
||||
/// Start the task on `runtime`. `status` gets a line that says how the key
|
||||
/// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered),
|
||||
/// `transmit` the key's state; both are called on the runtime, so they hand
|
||||
/// over to GPUI's thread ([`crate::app::Later`]).
|
||||
pub fn start(
|
||||
runtime: &Handle,
|
||||
status: impl Fn(String) + Send + 'static,
|
||||
transmit: impl Fn(bool) + Send + 'static,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
runtime.spawn(run(rx, status, transmit));
|
||||
Self { tx }
|
||||
}
|
||||
|
||||
/// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered,
|
||||
/// or nothing.
|
||||
pub fn set(&self, key: Option<String>) {
|
||||
let _ = self.tx.send(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream of press and release events for one registered hotkey (`None` once
|
||||
/// the desktop removes it).
|
||||
trait EventStream: Send {
|
||||
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send;
|
||||
}
|
||||
|
||||
impl EventStream for HotkeyEvents {
|
||||
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send {
|
||||
HotkeyEvents::recv(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers and unregisters the global push-to-talk hotkey with the platform
|
||||
/// (or a test double).
|
||||
trait Registrar: Send {
|
||||
type Events: EventStream;
|
||||
|
||||
fn register(
|
||||
&mut self,
|
||||
key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> impl Future<Output = Result<(Self::Events, String), String>> + Send;
|
||||
|
||||
fn unregister(&mut self) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
|
||||
/// The real platform hotkey manager, opened lazily on the first registration.
|
||||
struct PlatformRegistrar {
|
||||
manager: Option<HotkeyManager>,
|
||||
}
|
||||
|
||||
impl Registrar for PlatformRegistrar {
|
||||
type Events = HotkeyEvents;
|
||||
|
||||
async fn register(
|
||||
&mut self,
|
||||
key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> Result<(Self::Events, String), String> {
|
||||
if self.manager.is_none() {
|
||||
match HotkeyManager::new().await {
|
||||
Ok(m) => self.manager = Some(m),
|
||||
Err(e) => return Err(format!("Global hotkeys are not available: {e}")),
|
||||
}
|
||||
}
|
||||
let Some(m) = &mut self.manager else {
|
||||
return Err("Global hotkeys are not available.".into());
|
||||
};
|
||||
match m.register(PTT_ID, "Push to talk", hotkey).await {
|
||||
Ok(registered) => {
|
||||
let line = match m.backend() {
|
||||
BackendKind::Portal => format!(
|
||||
"Registered with the desktop: {}",
|
||||
m.trigger_description(PTT_ID).unwrap_or(key)
|
||||
),
|
||||
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
|
||||
BackendKind::WindowsHook => format!("Active: {hotkey}"),
|
||||
};
|
||||
Ok((registered, line))
|
||||
}
|
||||
Err(e) => Err(format!("Could not register {key}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn unregister(&mut self) {
|
||||
if let Some(m) = &mut self.manager {
|
||||
let _ = m.unregister(PTT_ID).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next event of the registration, or never while there is none.
|
||||
async fn next_event<E: EventStream>(events: &mut Option<E>) -> Option<HotkeyEvent> {
|
||||
match events {
|
||||
Some(events) => events.recv().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// The task: a key to register (or none) arrives on `rx`, the registered key's
|
||||
/// events are reported through `transmit`, and `status` says what happened.
|
||||
async fn run(
|
||||
rx: mpsc::UnboundedReceiver<Option<String>>,
|
||||
status: impl Fn(String),
|
||||
transmit: impl Fn(bool),
|
||||
) {
|
||||
run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await;
|
||||
}
|
||||
|
||||
/// The event loop of [`run`], parameterised over `registrar` so the
|
||||
/// fail-closed release paths are tested without a portal or display.
|
||||
async fn run_loop<R: Registrar>(
|
||||
mut rx: mpsc::UnboundedReceiver<Option<String>>,
|
||||
mut registrar: R,
|
||||
status: impl Fn(String),
|
||||
transmit: impl Fn(bool),
|
||||
) {
|
||||
let mut events: Option<R::Events> = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
key = rx.recv() => {
|
||||
let Some(key) = key else {
|
||||
// Fail closed on task exit: drop any hold that was still down.
|
||||
transmit(false);
|
||||
break;
|
||||
};
|
||||
events = None;
|
||||
// Whatever was held no longer counts.
|
||||
transmit(false);
|
||||
registrar.unregister().await;
|
||||
let Some(key) = key else {
|
||||
status("Off.".into());
|
||||
continue;
|
||||
};
|
||||
let hotkey: Hotkey = match key.parse() {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
status(format!("{e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match registrar.register(key, hotkey).await {
|
||||
Ok((registered, line)) => {
|
||||
events = Some(registered);
|
||||
status(line);
|
||||
}
|
||||
Err(line) => status(line),
|
||||
}
|
||||
}
|
||||
event = next_event(&mut events) => match event {
|
||||
Some(HotkeyEvent::Pressed) => transmit(true),
|
||||
Some(HotkeyEvent::Released) => transmit(false),
|
||||
None => {
|
||||
events = None;
|
||||
// Fail closed if the desktop removes the shortcut mid-hold.
|
||||
transmit(false);
|
||||
status("The hotkey was removed by the desktop.".into());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A channel-backed event stream for testing [`run_loop`] without a display.
|
||||
struct FakeEvents(mpsc::UnboundedReceiver<HotkeyEvent>);
|
||||
|
||||
impl EventStream for FakeEvents {
|
||||
async fn recv(&mut self) -> Option<HotkeyEvent> {
|
||||
self.0.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
/// A registrar that hands out a prepared [`FakeEvents`] stream once.
|
||||
struct FakeRegistrar {
|
||||
stream: Option<FakeEvents>,
|
||||
}
|
||||
|
||||
impl Registrar for FakeRegistrar {
|
||||
type Events = FakeEvents;
|
||||
|
||||
async fn register(
|
||||
&mut self,
|
||||
_key: String,
|
||||
hotkey: Hotkey,
|
||||
) -> Result<(Self::Events, String), String> {
|
||||
let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?;
|
||||
Ok((events, format!("Active: {hotkey} (test)")))
|
||||
}
|
||||
|
||||
async fn unregister(&mut self) {}
|
||||
}
|
||||
|
||||
/// Next recorded message from the task, bounded only against a hang.
|
||||
async fn recv_log(rx: &mut mpsc::UnboundedReceiver<String>) -> String {
|
||||
tokio::time::timeout(Duration::from_secs(30), rx.recv())
|
||||
.await
|
||||
.expect("hotkey loop timed out")
|
||||
.expect("log channel closed unexpectedly")
|
||||
}
|
||||
|
||||
/// A key that is not one is said so and registers nothing, and the held
|
||||
/// state is let go first; no display or desktop is needed to say it.
|
||||
#[test]
|
||||
fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
|
||||
let log = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let (said, held) = (log.clone(), log.clone());
|
||||
let ptt = GlobalPtt::start(
|
||||
runtime.handle(),
|
||||
move |line| said.lock().unwrap().push(format!("status: {line}")),
|
||||
move |on| held.lock().unwrap().push(format!("transmit: {on}")),
|
||||
);
|
||||
ptt.set(Some("Ctrl+Hyper+Banana".into()));
|
||||
ptt.set(None);
|
||||
// The task answers in order: the last answer says the end of the list.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
while log.lock().unwrap().len() < 4 {
|
||||
assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap());
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let log = log.lock().unwrap().clone();
|
||||
assert_eq!(log[0], "transmit: false", "{log:?}");
|
||||
assert!(log[1].starts_with("status: "), "the parse error: {log:?}");
|
||||
assert_eq!(log[2], "transmit: false", "{log:?}");
|
||||
assert_eq!(log[3], "status: Off.", "{log:?}");
|
||||
drop(ptt);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
|
||||
/// When the desktop removes the registered hotkey while it is pressed, the
|
||||
/// loop releases transmit before reporting the removal.
|
||||
#[test]
|
||||
fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let (tx_key, rx_key) = mpsc::unbounded_channel();
|
||||
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
|
||||
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
|
||||
let (said, held) = (tx_log.clone(), tx_log);
|
||||
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
|
||||
let task = tokio::spawn(run_loop(
|
||||
rx_key,
|
||||
registrar,
|
||||
move |line| {
|
||||
let _ = said.send(format!("status: {line}"));
|
||||
},
|
||||
move |on| {
|
||||
let _ = held.send(format!("transmit: {on}"));
|
||||
},
|
||||
));
|
||||
|
||||
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
|
||||
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
|
||||
|
||||
tx_evt.send(HotkeyEvent::Pressed).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
|
||||
|
||||
// Desktop removes the shortcut while held.
|
||||
drop(tx_evt);
|
||||
assert_eq!(
|
||||
recv_log(&mut rx_log).await,
|
||||
"transmit: false",
|
||||
"transmit must fail closed before reporting removal"
|
||||
);
|
||||
assert_eq!(
|
||||
recv_log(&mut rx_log).await,
|
||||
"status: The hotkey was removed by the desktop."
|
||||
);
|
||||
|
||||
drop(tx_key);
|
||||
tokio::time::timeout(Duration::from_secs(30), task)
|
||||
.await
|
||||
.expect("task exit timed out")
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
/// When the command channel closes (task exit) while the hotkey is pressed,
|
||||
/// the loop releases transmit before exiting.
|
||||
#[test]
|
||||
fn closing_command_channel_mid_hold_releases_transmit_before_exiting() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let (tx_key, rx_key) = mpsc::unbounded_channel();
|
||||
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
|
||||
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
|
||||
let (said, held) = (tx_log.clone(), tx_log);
|
||||
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
|
||||
let task = tokio::spawn(run_loop(
|
||||
rx_key,
|
||||
registrar,
|
||||
move |line| {
|
||||
let _ = said.send(format!("status: {line}"));
|
||||
},
|
||||
move |on| {
|
||||
let _ = held.send(format!("transmit: {on}"));
|
||||
},
|
||||
));
|
||||
|
||||
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
|
||||
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
|
||||
|
||||
tx_evt.send(HotkeyEvent::Pressed).unwrap();
|
||||
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
|
||||
|
||||
// Keep the event stream open while the handle drops (task exit).
|
||||
drop(tx_key);
|
||||
tokio::time::timeout(Duration::from_secs(30), task)
|
||||
.await
|
||||
.expect("task exit timed out")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
rx_log.try_recv().ok().as_deref(),
|
||||
Some("transmit: false"),
|
||||
"closing rx mid-hold must release transmit before breaking"
|
||||
);
|
||||
drop(tx_evt);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,15 @@
|
||||
|
||||
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;
|
||||
@@ -20,17 +25,27 @@ use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
|
||||
use 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;
|
||||
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::{Choice, VoelinTheme};
|
||||
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.
|
||||
@@ -58,18 +73,50 @@ pub fn init_logging() {
|
||||
.try_init();
|
||||
}
|
||||
|
||||
/// The main window's options: titled with the app's name, grouped by its id,
|
||||
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
|
||||
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
|
||||
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
|
||||
/// 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(voelin_platform::APP_NAME.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
|
||||
app_id: Some(voelin_platform::APP_ID.to_owned()),
|
||||
window_min_size: Some(size(px(640.0), px(480.0))),
|
||||
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
|
||||
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
|
||||
window_bounds: Some(window_bounds(switches, remembered, cx)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -81,6 +128,7 @@ fn open_main_window(
|
||||
cx: &mut App,
|
||||
switches: &Switches,
|
||||
engine: HostedEngine,
|
||||
backend: Backend,
|
||||
counters: Counters,
|
||||
closed_sessions: Rc<Cell<usize>>,
|
||||
) -> Result<()> {
|
||||
@@ -94,10 +142,22 @@ fn open_main_window(
|
||||
}
|
||||
let HostedEngine { engine, events, .. } = engine;
|
||||
let app = cx.new({
|
||||
let counters = counters.clone();
|
||||
move |cx| AppState::new(Some(engine), events, counters, cx)
|
||||
let setup = Setup {
|
||||
engine: Some(engine),
|
||||
events,
|
||||
counters: counters.clone(),
|
||||
backend,
|
||||
switches: switches.clone(),
|
||||
};
|
||||
move |cx| AppState::new(setup, cx)
|
||||
});
|
||||
let options = window_options(switches, 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();
|
||||
@@ -108,7 +168,7 @@ fn open_main_window(
|
||||
window.on_window_should_close(cx, {
|
||||
let app = app.clone();
|
||||
move |_, cx| {
|
||||
closed_sessions.set(app.read(cx).shutdown());
|
||||
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
|
||||
cx.quit();
|
||||
true
|
||||
}
|
||||
@@ -120,6 +180,14 @@ fn open_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();
|
||||
@@ -139,6 +207,13 @@ pub fn run() -> Result<()> {
|
||||
.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({
|
||||
@@ -146,16 +221,14 @@ pub fn run() -> Result<()> {
|
||||
let closed_sessions = closed_sessions.clone();
|
||||
move |cx| {
|
||||
gpui_kit::init(cx);
|
||||
shell::bind_keys(cx);
|
||||
fonts::load(cx);
|
||||
// Until the settings are read here (the shell slice), the mode and
|
||||
// the text size are the development switches' or the defaults.
|
||||
VoelinTheme::init(
|
||||
cx,
|
||||
switches.theme.unwrap_or(Choice::System),
|
||||
cx.window_appearance(),
|
||||
switches.font_scale.unwrap_or(1.0),
|
||||
);
|
||||
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
|
||||
// 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
|
||||
@@ -172,7 +245,7 @@ pub fn run() -> Result<()> {
|
||||
// on the servers until they time out. Any other way to end the app that
|
||||
// the slices add must call `AppState::shutdown` too.
|
||||
if closed_sessions.get() > 0 {
|
||||
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
|
||||
give_the_engine_time(&runtime, CLOSE_GRACE);
|
||||
}
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
match failure.take() {
|
||||
@@ -180,3 +253,21 @@ pub fn run() -> Result<()> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,44 @@ impl Counter {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times each pane of the window was rendered (per second). A pane
|
||||
/// is an entity of its own that the window draws again only when it was
|
||||
/// notified (`Entity::cached`), or when something below it was; the figures
|
||||
/// say which panes a change of the state cost.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Panes {
|
||||
/// The server rail.
|
||||
pub rail: Counter,
|
||||
/// The top bar.
|
||||
pub topbar: Counter,
|
||||
/// The sidebar (the server card, the voice and user cards; the tree is
|
||||
/// inside it).
|
||||
pub sidebar: Counter,
|
||||
/// The channel tree.
|
||||
pub tree: Counter,
|
||||
/// The main area.
|
||||
pub main: Counter,
|
||||
/// The members panel.
|
||||
pub members: Counter,
|
||||
/// The voice channel page.
|
||||
pub voice: Counter,
|
||||
}
|
||||
|
||||
impl Panes {
|
||||
/// The counters with the names the meter reports them under.
|
||||
pub fn named(&self) -> [(&'static str, Counter); 7] {
|
||||
[
|
||||
("rail", self.rail.clone()),
|
||||
("topbar", self.topbar.clone()),
|
||||
("sidebar", self.sidebar.clone()),
|
||||
("tree", self.tree.clone()),
|
||||
("main", self.main.clone()),
|
||||
("members", self.members.clone()),
|
||||
("voice", self.voice.clone()),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's own numbers the meter reports besides the process's.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counters {
|
||||
@@ -50,6 +88,8 @@ pub struct Counters {
|
||||
pub ticks: Counter,
|
||||
/// Windows drawn (frames, per second).
|
||||
pub renders: Counter,
|
||||
/// Renders of each pane of the window (per second).
|
||||
pub panes: Panes,
|
||||
/// Jobs other threads handed to the foreground through
|
||||
/// [`crate::app::Later`] (per second).
|
||||
pub later_jobs: Counter,
|
||||
@@ -194,12 +234,15 @@ pub fn start(counters: Counters) {
|
||||
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
|
||||
return;
|
||||
};
|
||||
let rated = [
|
||||
let rated: Vec<(&str, Counter)> = [
|
||||
("engine_events", counters.engine_events.clone()),
|
||||
("ticks", counters.ticks.clone()),
|
||||
("renders", counters.renders.clone()),
|
||||
("later_jobs", counters.later_jobs.clone()),
|
||||
];
|
||||
]
|
||||
.into_iter()
|
||||
.chain(counters.panes.named())
|
||||
.chain([("later_jobs", counters.later_jobs.clone())])
|
||||
.collect();
|
||||
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
|
||||
loop {
|
||||
@@ -232,6 +275,17 @@ pub fn start(counters: Counters) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_panes_are_counted_by_name() {
|
||||
let panes = Panes::default();
|
||||
panes.members.incr();
|
||||
let named = panes.named();
|
||||
let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect();
|
||||
assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]);
|
||||
let seen: Vec<u64> = named.iter().map(|(_, counter)| counter.get()).collect();
|
||||
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_drop_trailing_numbers() {
|
||||
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ 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,
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -407,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
|
||||
@@ -718,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.
|
||||
|
||||
@@ -791,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();
|
||||
@@ -1887,9 +1892,19 @@ fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row(
|
||||
};
|
||||
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!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
|
||||
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");
|
||||
@@ -1905,6 +1920,37 @@ fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row(
|
||||
}
|
||||
}
|
||||
|
||||
#[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
|
||||
|
||||
@@ -31,6 +31,9 @@ miniz_oxide = "0.8"
|
||||
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" }
|
||||
|
||||
@@ -119,6 +119,56 @@ impl Refresh {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// Every part either of the two names: what a front end that handles a
|
||||
/// batch of events draws once, however many events set a part.
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
let Self {
|
||||
servers,
|
||||
toolbar,
|
||||
tree,
|
||||
chat,
|
||||
streams,
|
||||
viewer,
|
||||
member_card,
|
||||
home,
|
||||
events,
|
||||
gateways,
|
||||
people,
|
||||
conversations,
|
||||
dm,
|
||||
} = other;
|
||||
self.servers |= servers;
|
||||
self.toolbar |= toolbar;
|
||||
self.tree |= tree;
|
||||
self.chat |= chat;
|
||||
self.streams |= streams;
|
||||
self.viewer |= viewer;
|
||||
self.member_card |= member_card;
|
||||
self.home |= home;
|
||||
self.events |= events;
|
||||
self.gateways |= gateways;
|
||||
self.people |= people;
|
||||
self.conversations |= conversations;
|
||||
self.dm |= dm;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refresh_tests {
|
||||
use super::Refresh;
|
||||
|
||||
#[test]
|
||||
fn merging_names_the_parts_of_both() {
|
||||
let mut a = Refresh { tree: true, chat: true, ..Default::default() };
|
||||
a.merge(Refresh { toolbar: true, tree: true, ..Default::default() });
|
||||
assert_eq!(a, Refresh { toolbar: true, tree: true, chat: true, ..Default::default() });
|
||||
let mut none = Refresh::default();
|
||||
none.merge(Refresh::default());
|
||||
assert!(none.is_empty());
|
||||
none.merge(Refresh::ALL);
|
||||
assert_eq!(none, Refresh::ALL);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a transition wants kept.
|
||||
@@ -179,6 +229,12 @@ pub struct Update {
|
||||
/// 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.
|
||||
|
||||
@@ -59,7 +59,7 @@ impl fmt::Debug for ImageSource {
|
||||
|
||||
/// What identifies a file's content without reading it: its length and the
|
||||
/// time it was last written. Both zero for a file that is missing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Stamp {
|
||||
len: u64,
|
||||
modified: Option<SystemTime>,
|
||||
|
||||
@@ -339,6 +339,16 @@ pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String)
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the card of a client of the server shown over the members panel
|
||||
/// (`None` closes it).
|
||||
pub fn open_member<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, client: Option<u16>) {
|
||||
let Some(view) = state.current.and_then(|id| state.sessions.get_mut(&id)) else { return };
|
||||
if view.member_card != client {
|
||||
view.member_card = client;
|
||||
cx.update.refresh.member_card = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice channel view was opened or closed: its chat is our channel's,
|
||||
/// and its people lead the members panel.
|
||||
pub fn show_voice_view<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) {
|
||||
@@ -863,6 +873,32 @@ mod tests {
|
||||
assert!(st.sessions[&1].collapsed.is_empty());
|
||||
}
|
||||
|
||||
/// The card of a client opens over the members panel of the server shown
|
||||
/// and closes again; the card is drawn again only when it changed.
|
||||
#[test]
|
||||
fn the_member_card_opens_and_closes() {
|
||||
let (mut st, host) = (state(), Fake::default());
|
||||
st.current = Some(1);
|
||||
st.sessions.insert(1, SessionView::default());
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert_eq!(st.sessions[&1].member_card, Some(11));
|
||||
assert!(cx.update.refresh.member_card);
|
||||
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert!(!cx.update.refresh.member_card, "the same card: nothing to draw");
|
||||
open_member(&mut st, &mut cx, None);
|
||||
assert_eq!(st.sessions[&1].member_card, None);
|
||||
assert!(cx.update.refresh.member_card);
|
||||
|
||||
// No server on screen: no card.
|
||||
st.current = None;
|
||||
let mut cx = Cx::new(&host);
|
||||
open_member(&mut st, &mut cx, Some(11));
|
||||
assert!(cx.update.refresh.is_empty());
|
||||
}
|
||||
|
||||
/// A chat takes its server's colour only while it is a server chat of a
|
||||
/// server in the list: a chat whose server is gone, and a chat that is a
|
||||
/// channel's or a person's, take the colour of their own title. Black
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! and the channel tree as plain data.
|
||||
|
||||
pub mod logic;
|
||||
pub mod sequence;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -113,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] {
|
||||
[
|
||||
@@ -262,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.
|
||||
@@ -604,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();
|
||||
@@ -616,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();
|
||||
|
||||
@@ -4,16 +4,18 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use voelin_model::channel_title;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges,
|
||||
tree_rows,
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges, tree_rows,
|
||||
};
|
||||
pub use voelin_model::{ChannelId, channel_title};
|
||||
|
||||
use voelin_core::{Contact, Relation};
|
||||
|
||||
use crate::avatar;
|
||||
use crate::bridge::{BadgeItem, MemberItem, TreeItem};
|
||||
use crate::bridge::{BadgeItem, MemberCard, MemberItem, TreeItem};
|
||||
use crate::image::ImageRef;
|
||||
use crate::settings::ClientPlaybackMap;
|
||||
use crate::state::SessionView;
|
||||
|
||||
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
|
||||
pub fn banner_mode(mode: BannerMode) -> i32 {
|
||||
@@ -54,6 +56,47 @@ pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The card over a member row: everything about the client `id` of a session
|
||||
/// and what is known of it locally (the contact, the playback settings).
|
||||
/// None when the presence has no such client (it left).
|
||||
pub fn member_card<L>(
|
||||
view: &SessionView<L>,
|
||||
id: u16,
|
||||
contacts: &HashMap<String, Contact>,
|
||||
playback: &ClientPlaybackMap,
|
||||
) -> Option<MemberCard> {
|
||||
let client = view.presence.clients.get(&id)?;
|
||||
let uid = client.uid.as_ref();
|
||||
let contact = uid.and_then(|u| contacts.get(u));
|
||||
let local = uid.and_then(|u| playback.get(u)).copied().unwrap_or_default();
|
||||
let groups = client
|
||||
.server_groups
|
||||
.iter()
|
||||
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
|
||||
.map(|g| g.name.as_str().into())
|
||||
.collect();
|
||||
Some(MemberCard {
|
||||
open: true,
|
||||
id: i32::from(id),
|
||||
name: client.nickname.as_str().into(),
|
||||
initials: avatar::initials(&client.nickname).into(),
|
||||
tint: avatar::tint(&client.nickname),
|
||||
avatar: avatar::image(view.avatar(id)),
|
||||
status: status_of(client, view.talking.contains(&id)).into(),
|
||||
description: client.description.as_deref().unwrap_or_default().into(),
|
||||
groups,
|
||||
badges: badge_items(&client.badges, &view.pictures),
|
||||
country: client.country.as_deref().unwrap_or_default().into(),
|
||||
talk_power: client.talk_power,
|
||||
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
|
||||
blocked: contact.is_some_and(|c| c.relation == Relation::Blocked),
|
||||
volume: local.volume * 100.0,
|
||||
muted: local.muted,
|
||||
known: uid.is_some(),
|
||||
streaming: client.streaming == Some(true),
|
||||
})
|
||||
}
|
||||
|
||||
/// What the tree shows besides the presence.
|
||||
pub struct TreeInput<'a> {
|
||||
/// The channels and clients of the server.
|
||||
@@ -901,6 +944,61 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The card has what the row has, the groups by name, the badges, the
|
||||
/// contact's relation and the local playback; a client that left has none.
|
||||
#[test]
|
||||
fn the_member_card_is_what_is_known_of_one_client() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::settings::ClientPlayback;
|
||||
|
||||
let mut p = presence();
|
||||
let bob = p.clients.get_mut(&11).unwrap();
|
||||
bob.uid = Some("bob=".into());
|
||||
bob.server_groups = vec![6, 99];
|
||||
bob.description = Some("Raid lead".into());
|
||||
bob.country = Some("DE".into());
|
||||
bob.talk_power = 75;
|
||||
bob.badges = vec!["4b27be5a-b92a-4b30-8b2d-14b59653f427".into()];
|
||||
bob.streaming = Some(true);
|
||||
let mut view = SessionView::<()> {
|
||||
presence: Arc::new(p),
|
||||
server_groups: vec![GroupInfo {
|
||||
id: 6,
|
||||
name: "Moderator".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
view.talking.insert(11);
|
||||
let mut friend = Contact::new("bob=");
|
||||
friend.relation = Relation::Friend;
|
||||
let contacts = HashMap::from([("bob=".to_owned(), friend)]);
|
||||
let playback = ClientPlaybackMap::from([(
|
||||
"bob=".to_owned(),
|
||||
ClientPlayback { volume: 1.5, muted: true },
|
||||
)]);
|
||||
|
||||
let card = member_card(&view, 11, &contacts, &playback).expect("bob is there");
|
||||
assert!(card.open);
|
||||
assert_eq!((card.id, &*card.name, &*card.initials), (11, "bob", "BO"));
|
||||
assert_eq!(card.tint, avatar::tint("bob"));
|
||||
assert_eq!(&*card.status, "Speaking");
|
||||
assert_eq!((&*card.description, &*card.country, card.talk_power), ("Raid lead", "DE", 75));
|
||||
let groups: Vec<&str> = card.groups.iter().map(|g| &**g).collect();
|
||||
assert_eq!(groups, ["Moderator"], "a group the server did not list is left out");
|
||||
assert_eq!(card.badges.len(), 1);
|
||||
assert_eq!(&*card.badges[0].name, "20th Anniversary");
|
||||
assert!(card.friend && !card.blocked && card.known && card.streaming && card.muted);
|
||||
assert_eq!(card.volume, 150.0);
|
||||
|
||||
// Someone nobody knows: not known, nothing local, listening.
|
||||
let alice = member_card(&view, 10, &contacts, &playback).unwrap();
|
||||
assert!(!alice.known && !alice.friend && !alice.muted && alice.volume == 100.0);
|
||||
assert_eq!(&*alice.status, "Listening");
|
||||
assert!(member_card(&view, 99, &contacts, &playback).is_none(), "a client that left");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_paths() {
|
||||
let mut p = presence();
|
||||
|
||||
@@ -37,83 +37,28 @@ use crate::vm;
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
/// The settings service on the client database: the UI's keys registered,
|
||||
/// then a config file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it
|
||||
/// exists), `VOELIN_SETTING_*` variables and `overrides` below the stored
|
||||
/// values. Without the database the settings live in memory.
|
||||
/// The settings service on the client database
|
||||
/// ([`vm::settings::open_settings`], which the GPUI front end opens the same
|
||||
/// way): the UI's keys registered, with the Stream Studio's, then a config
|
||||
/// file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it exists),
|
||||
/// `VOELIN_SETTING_*` variables and `overrides` below the stored values.
|
||||
/// Without the database the settings live in memory.
|
||||
fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
|
||||
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
|
||||
warn!(%e, "settings are not stored this time");
|
||||
Settings::in_memory()
|
||||
});
|
||||
prefs.register(&UI);
|
||||
prefs.register(&CLIENT_PLAYBACK);
|
||||
for key in appearance_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
for key in crate::settings::page_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
|
||||
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
|
||||
}
|
||||
|
||||
/// Secrets in the OS keyring, or in memory when there is none (headless
|
||||
/// Linux without a Secret Service).
|
||||
#[cfg(not(target_os = "android"))]
|
||||
struct FallbackSecrets {
|
||||
keyring: voelin_store::KeyringSecrets,
|
||||
memory: MemorySecrets,
|
||||
vm::settings::open_settings(dir, overrides, |prefs| {
|
||||
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
|
||||
})
|
||||
}
|
||||
|
||||
/// The secrets store when [`RunOptions::secrets`] is not given: the OS
|
||||
/// keyring on desktop, memory elsewhere.
|
||||
/// keyring on desktop (memory behind it where the keyring refuses: a headless
|
||||
/// Linux without a Secret Service), memory elsewhere.
|
||||
fn default_secrets() -> Box<dyn Secrets> {
|
||||
#[cfg(not(target_os = "android"))]
|
||||
return Box::new(FallbackSecrets {
|
||||
keyring: voelin_store::KeyringSecrets::new("voelin"),
|
||||
memory: MemorySecrets::default(),
|
||||
});
|
||||
return Box::new(voelin_store::FallbackSecrets::new("voelin"));
|
||||
#[cfg(target_os = "android")]
|
||||
return Box::new(MemorySecrets::default());
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
impl Secrets for FallbackSecrets {
|
||||
fn get(&self, key: &str) -> voelin_store::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) -> voelin_store::Result<()> {
|
||||
if let Err(error) = self.keyring.set(key, value) {
|
||||
warn!(%error, "keyring unavailable, keeping the secret for this session only");
|
||||
return self.memory.set(key, value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&self, key: &str) -> voelin_store::Result<()> {
|
||||
let _ = self.keyring.delete(key);
|
||||
self.memory.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of a chat as the chat view shows them.
|
||||
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB};
|
||||
use crate::social::Social;
|
||||
use crate::studio::StudioState;
|
||||
use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
|
||||
use crate::vm::servers::sequence::Backing;
|
||||
|
||||
/// What the transitions ask while they run: the window, the store and the
|
||||
/// settings, borrowed from the app besides its state.
|
||||
@@ -87,6 +88,16 @@ impl App {
|
||||
pub(crate) fn with_social<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R,
|
||||
) -> R {
|
||||
self.with_parts(|state, social, host, _| f(state, social, host))
|
||||
}
|
||||
|
||||
/// Run `f` with the state, the social state, the host and the
|
||||
/// [`Backing`] of the server sequences (the store, the secrets and the
|
||||
/// identity, borrowed from the app besides its state).
|
||||
fn with_parts<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>, &Backing<'_>) -> R,
|
||||
) -> R {
|
||||
let host = SlintHost {
|
||||
demo_ui: self.demo_ui,
|
||||
@@ -99,7 +110,11 @@ impl App {
|
||||
prefs: &self.prefs,
|
||||
studio: &self.studio,
|
||||
};
|
||||
f(&mut self.state, &mut self.social, &host)
|
||||
let identity = |named| {
|
||||
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
|
||||
};
|
||||
let backing = Backing { store: &self.store, secrets: &*self.secrets, identity: &identity };
|
||||
f(&mut self.state, &mut self.social, &host, &backing)
|
||||
}
|
||||
|
||||
/// An engine event: what it does to the state is in `voelin-ui-vm`
|
||||
@@ -123,6 +138,22 @@ impl App {
|
||||
result
|
||||
}
|
||||
|
||||
/// Like [`App::transition`], for a sequence that also reads and writes the
|
||||
/// store and the secrets and picks the identity
|
||||
/// (`voelin_ui_vm::servers::sequence`).
|
||||
pub(crate) fn transition_with<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut AppState, &mut Cx<'_>, &Backing<'_>) -> R,
|
||||
) -> R {
|
||||
let (result, update) = self.with_parts(|state, _, host, backing| {
|
||||
let mut cx = Cx::new(host);
|
||||
let result = f(state, &mut cx, backing);
|
||||
(result, cx.update)
|
||||
});
|
||||
self.perform(update);
|
||||
result
|
||||
}
|
||||
|
||||
/// Like [`App::transition`], for a transition that changes the social
|
||||
/// state too.
|
||||
pub(crate) fn social_transition<R>(
|
||||
@@ -148,6 +179,7 @@ impl App {
|
||||
commands,
|
||||
persist,
|
||||
reloaded,
|
||||
discover,
|
||||
input_level,
|
||||
password,
|
||||
notices,
|
||||
@@ -169,6 +201,10 @@ impl App {
|
||||
for command in commands {
|
||||
self.engine.send(command);
|
||||
}
|
||||
// The gateways to look up, on the engine's runtime.
|
||||
for (id, address) in discover {
|
||||
self.look_up_gateway(id, address);
|
||||
}
|
||||
// The capture and the decoder.
|
||||
if let Some(sink) = stream.attach
|
||||
&& let Some(share) = &self.share
|
||||
|
||||
@@ -3,273 +3,116 @@
|
||||
//! the channel tree, and the callbacks' ways into the transitions of
|
||||
//! `voelin_ui_vm::servers::logic`.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_core::{Command, JoinFailure, ObserveState};
|
||||
use voelin_core::JoinFailure;
|
||||
use voelin_core::stream::PeerConfig;
|
||||
use voelin_model::ChannelId;
|
||||
use voelin_store::{Bookmark, QueryTransport};
|
||||
use voelin_store::Bookmark;
|
||||
|
||||
use crate::app::{App, Bridge, later};
|
||||
use crate::bind::convert;
|
||||
use crate::vm;
|
||||
use crate::vm::bridge::BookmarkForm;
|
||||
use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan};
|
||||
use crate::vm::servers::logic;
|
||||
use crate::vm::servers::sequence;
|
||||
|
||||
impl App {
|
||||
/// Connect the server on screen with voice, into its default channel
|
||||
/// ([`sequence::connect_voice`]).
|
||||
pub(crate) fn connect_voice(&mut self) {
|
||||
let channel = self
|
||||
.state
|
||||
.current
|
||||
.and_then(|id| self.bookmark(id))
|
||||
.and_then(|b| b.default_channel.clone());
|
||||
self.connect_voice_to(channel, None, None);
|
||||
let peer = self.stream_peer();
|
||||
self.transition_with(|state, cx, backing| {
|
||||
sequence::connect_voice(state, cx, backing, Some(peer))
|
||||
});
|
||||
}
|
||||
|
||||
/// Connect the current server with voice, into `channel` (a path, or
|
||||
/// `/<id>`, with its password) if given, with a privilege key if given;
|
||||
/// whether it was asked for.
|
||||
/// whether it was asked for ([`sequence::connect_voice_to`]).
|
||||
pub(crate) fn connect_voice_to(
|
||||
&mut self,
|
||||
channel: Option<String>,
|
||||
channel_password: Option<String>,
|
||||
token: Option<String>,
|
||||
) -> bool {
|
||||
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
|
||||
return false;
|
||||
};
|
||||
if self.demo_ui {
|
||||
return false;
|
||||
}
|
||||
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
self.set_status(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
|
||||
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
|
||||
options.stream_peer = self.video.peer_config(options.stream_peer);
|
||||
self.engine
|
||||
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
|
||||
self.set_status(format!("Connecting to {}…", b.address));
|
||||
// The admin may have published the gateway since it was added.
|
||||
self.discover_gateway(b.id);
|
||||
true
|
||||
let peer = self.stream_peer();
|
||||
self.transition_with(|state, cx, backing| {
|
||||
sequence::connect_voice_to(
|
||||
state,
|
||||
cx,
|
||||
backing,
|
||||
channel,
|
||||
channel_password,
|
||||
token,
|
||||
Some(peer),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The nickname a new server gets: the default identity's (one imported
|
||||
/// from TeamSpeak keeps the nickname used there), else the system user's.
|
||||
/// What this front end can decode of a stream, to connect with: the
|
||||
/// codecs of the machine, the configured one first.
|
||||
fn stream_peer(&self) -> PeerConfig {
|
||||
self.video.peer_config(PeerConfig::default())
|
||||
}
|
||||
|
||||
/// The nickname a new server gets ([`sequence::default_nickname`]).
|
||||
pub(crate) fn default_nickname(&self) -> String {
|
||||
self.store
|
||||
.default_identity()
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identity| identity.name)
|
||||
.filter(|name| {
|
||||
![logic::CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
|
||||
.contains(&name.as_str())
|
||||
})
|
||||
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
|
||||
// Servers refuse an empty nickname (Android has no user name).
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.unwrap_or_else(|| "Voelin user".to_owned())
|
||||
sequence::default_nickname(&self.store)
|
||||
}
|
||||
|
||||
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
|
||||
/// run ([`logic::discover_wanted`]): every one the server publishes is
|
||||
/// kept, best first, and tried in turn; they take the place of a stored
|
||||
/// one that is no longer published (a gateway that moved, or one typed
|
||||
/// into an older version, which showed the field). Nothing found keeps
|
||||
/// what is stored.
|
||||
pub(crate) fn discover_gateway(&mut self, id: i64) {
|
||||
let Some(address) = self.transition(|state, cx| logic::discover_wanted(state, cx, id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
/// Look the gateway of a server up on the engine's runtime
|
||||
/// ([`sequence::find_gateways`]), as `Update::discover` asks; what is found
|
||||
/// comes back through [`later`].
|
||||
pub(crate) fn look_up_gateway(&mut self, id: i64, address: String) {
|
||||
self.engine.runtime().spawn(async move {
|
||||
let started = Instant::now();
|
||||
let urls = voelin_core::discover::gateways(&address).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
if urls.is_empty() {
|
||||
info!(server = %address, elapsed_ms, "no gateway published");
|
||||
} else {
|
||||
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
|
||||
if let Some(found) = sequence::find_gateways(&address).await {
|
||||
later(move |app| app.gateway_found(id, &address, found.urls, found.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).
|
||||
/// Gateways were found for the server at `address`
|
||||
/// ([`sequence::gateway_found`]).
|
||||
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
|
||||
let found = self.transition(|state, cx| logic::gateway_found(state, cx, id, address, urls));
|
||||
match found {
|
||||
GatewayFound::Same => {
|
||||
debug!(server = %address, elapsed_ms, "gateway found, as kept");
|
||||
}
|
||||
GatewayFound::Kept { observe } => {
|
||||
info!(server = %address, elapsed_ms, kept = true, "gateway found");
|
||||
if observe {
|
||||
self.observe(id);
|
||||
}
|
||||
}
|
||||
GatewayFound::Changed { stop, observe, urls } => {
|
||||
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
|
||||
if stop {
|
||||
self.engine.send(Command::StopObserving { session: id as u64 });
|
||||
}
|
||||
if observe {
|
||||
self.observe(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.transition_with(|state, cx, backing| {
|
||||
sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
|
||||
});
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
/// Observe the server invisibly ([`sequence::observe`]).
|
||||
pub(crate) fn observe(&mut self, id: i64) {
|
||||
let Some(b) = self.bookmark(id).cloned() else { return };
|
||||
let session = b.id as u64;
|
||||
match self.transition(|state, cx| logic::observe_plan(state, cx, id)) {
|
||||
ObservePlan::Nothing => return,
|
||||
ObservePlan::Retry(urls) => {
|
||||
debug!(server = %b.address, "still connecting to the gateway: try now");
|
||||
self.engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls,
|
||||
identity: Box::new(voelin_core::ts::identity::to_blob(
|
||||
&self.identity_for(Some(b.id)),
|
||||
)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
ObservePlan::Gateway(urls) => {
|
||||
info!(server = %b.address, ?urls, "observing through the gateway");
|
||||
self.engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls,
|
||||
identity: Box::new(voelin_core::ts::identity::to_blob(
|
||||
&self.identity_for(Some(b.id)),
|
||||
)),
|
||||
});
|
||||
// Still the one the server publishes?
|
||||
self.discover_gateway(b.id);
|
||||
}
|
||||
ObservePlan::Query(q) => {
|
||||
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
|
||||
let transport = match q.transport {
|
||||
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
|
||||
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
|
||||
QueryTransport::Http => voelin_core::QueryTransport::Http,
|
||||
};
|
||||
let connect = voelin_core::QueryLogin {
|
||||
transport,
|
||||
address: format!("{}:{}", q.host, q.port),
|
||||
user: q.user.clone(),
|
||||
secret,
|
||||
server_port: q.server_port,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
|
||||
}
|
||||
ObservePlan::Discover => {
|
||||
self.discover_gateway(b.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.set_status("Observing invisibly…");
|
||||
self.transition_with(|state, cx, backing| sequence::observe(state, cx, backing, id));
|
||||
}
|
||||
|
||||
/// Show a server, and observe it.
|
||||
/// Show a server, and observe it ([`sequence::select_server`]).
|
||||
pub(crate) fn select_server(&mut self, id: i64) {
|
||||
self.transition(|state, cx| logic::select_server(state, cx, id));
|
||||
self.observe(id);
|
||||
self.transition_with(|state, cx, backing| sequence::select_server(state, cx, backing, id));
|
||||
}
|
||||
|
||||
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
|
||||
let Some(b) = self.bookmark(id) else {
|
||||
return BookmarkForm {
|
||||
id: -1,
|
||||
nickname: self.default_nickname().into(),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
|
||||
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
|
||||
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
|
||||
sequence::bookmark_form(&self.state, &self.store, &*self.secrets, id)
|
||||
}
|
||||
|
||||
/// Save the server dialog's server, and show it; its id, none when it
|
||||
/// could not be saved (the toast says why).
|
||||
/// could not be saved (the toast says why) ([`sequence::save_bookmark`]).
|
||||
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
|
||||
let old = self.bookmark(form.id as i64).cloned();
|
||||
let mut bookmark =
|
||||
logic::bookmark_from_form(old.as_ref(), form, || self.default_nickname());
|
||||
let result = if bookmark.id < 0 {
|
||||
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
|
||||
} else {
|
||||
self.store.update_bookmark(&bookmark)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
self.set_status(format!("Could not save: {e}"));
|
||||
return None;
|
||||
}
|
||||
let key = bookmark.server_password_key();
|
||||
let result = if form.server_password.is_empty() {
|
||||
self.secrets.delete(&key)
|
||||
} else {
|
||||
self.secrets.set(&key, &form.server_password)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
warn!(%e, "could not store secret");
|
||||
}
|
||||
// Another server: what was observed is the old one's, and its
|
||||
// gateway is looked up anew.
|
||||
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
|
||||
if old.query.is_some() {
|
||||
let _ = self.secrets.delete(&old.query_password_key());
|
||||
}
|
||||
self.state.gateways_looked_up.remove(&bookmark.id);
|
||||
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
|
||||
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
}
|
||||
}
|
||||
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
|
||||
self.select_server(bookmark.id);
|
||||
Some(bookmark.id)
|
||||
self.transition_with(|state, cx, backing| sequence::save_bookmark(state, cx, backing, form))
|
||||
}
|
||||
|
||||
/// The server dialog's Connect: save the server, then connect it with
|
||||
/// voice, into the channel of the link that filled the form if one did
|
||||
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
|
||||
/// shown after a failed save would connect the server shown before.
|
||||
/// Whether it was saved.
|
||||
/// ([`sequence::save_and_connect`]). Whether it was saved.
|
||||
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
|
||||
let saved = self.save_bookmark(form);
|
||||
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
|
||||
return false;
|
||||
};
|
||||
self.connect_voice_to(to.channel, to.channel_password, to.token);
|
||||
true
|
||||
let peer = self.stream_peer();
|
||||
self.transition_with(|state, cx, backing| {
|
||||
sequence::save_and_connect(state, cx, backing, form, Some(peer))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn delete_bookmark(&mut self, id: i64) {
|
||||
self.engine.send(Command::CloseSession { session: id as u64 });
|
||||
if let Some(b) = self.bookmark(id).cloned() {
|
||||
let _ = self.secrets.delete(&b.server_password_key());
|
||||
let _ = self.secrets.delete(&b.query_password_key());
|
||||
}
|
||||
let _ = self.store.delete_bookmark(id);
|
||||
let bookmarks = self.store.bookmarks().unwrap_or_default();
|
||||
self.transition(|state, cx| logic::forget_server(state, cx, id, bookmarks));
|
||||
self.transition_with(|state, cx, backing| {
|
||||
sequence::delete_bookmark(state, cx, backing, id)
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
|
||||
|
||||
@@ -426,23 +426,22 @@ impl App {
|
||||
self.state.own_uids = uids;
|
||||
}
|
||||
|
||||
/// The identity servers see us as on `bookmark` (the one place that
|
||||
/// picks it): the bookmark's own if it names one that exists, else the
|
||||
/// store's default.
|
||||
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
|
||||
let entries = self.store.identities().unwrap_or_default();
|
||||
bookmark
|
||||
.and_then(|b| self.bookmark(b))
|
||||
.and_then(|b| b.identity)
|
||||
.filter(|id| entries.iter().any(|e| e.id == *id))
|
||||
.or_else(|| self.default_identity_id())
|
||||
/// The identity a bookmark names, if it names one.
|
||||
fn named_identity(&self, bookmark: Option<i64>) -> Option<i64> {
|
||||
bookmark.and_then(|b| self.bookmark(b)).and_then(|b| b.identity)
|
||||
}
|
||||
|
||||
/// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]).
|
||||
/// The identity servers see us as on `bookmark`: the bookmark's own if it
|
||||
/// names one that exists, else the store's default (the one place that
|
||||
/// picks it is [`voelin_store::Store::identity_id_for`]).
|
||||
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
|
||||
self.store.identity_id_for(self.named_identity(bookmark))
|
||||
}
|
||||
|
||||
/// The identity a connection to `bookmark` uses
|
||||
/// ([`voelin_store::Store::identity_for`]).
|
||||
pub(crate) fn identity_for(&self, bookmark: Option<i64>) -> tsclientlib::Identity {
|
||||
self.identity_id_for(bookmark)
|
||||
.and_then(|id| self.store.identity(id).ok())
|
||||
.unwrap_or_else(|| self.identity.clone())
|
||||
self.store.identity_for(self.named_identity(bookmark), &self.identity)
|
||||
}
|
||||
|
||||
/// The store's default identity (`Store::default_identity`).
|
||||
|
||||
@@ -90,13 +90,26 @@ WORKDIR /src
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this (Gradle's cargo-ndk inherits the agent and the
|
||||
# variable below).
|
||||
# the first cargo command needs this: 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 (the packages of every
|
||||
# target, so the Android ones too): 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).
|
||||
RUN --mount=type=ssh,required=true \
|
||||
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
cargo fetch --locked
|
||||
# Gradle starts cargo-ndk, which starts cargo: the variable makes every one of
|
||||
# them offline, as `--offline` does for the other Dockerfiles (the Gradle task
|
||||
# is left as it is, because a developer's own build has network and no
|
||||
# `cargo fetch`). The build uses what the step above fetched (the registry in
|
||||
# the cache mount shared with it, the git checkout of VoelinProtocol in its
|
||||
# layer) or fails.
|
||||
ENV CARGO_NET_OFFLINE=true
|
||||
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,id=voelin-target-android,target=/src/target \
|
||||
--mount=type=cache,id=voelin-gradle,target=/root/.gradle \
|
||||
--mount=type=secret,id=keystore,required=false \
|
||||
|
||||
@@ -45,14 +45,23 @@ WORKDIR /src
|
||||
# `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.
|
||||
# the first cargo command needs this: 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. It shares the registry
|
||||
# cache with the build below, which has no ssh mount (so no agent socket and no
|
||||
# key in reach of the code it compiles and runs) and is --offline: it uses what
|
||||
# this step fetched (the registry in the cache mount, the git checkout of
|
||||
# VoelinProtocol in this step's layer) or fails.
|
||||
RUN --mount=type=ssh,required=true \
|
||||
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
cargo fetch --locked
|
||||
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,id=voelin-target-linux,target=/src/target \
|
||||
cargo build --release --locked -p voelin-ui -p voelin-gateway \
|
||||
cargo build --release --locked --offline -p voelin-ui -p voelin-gateway \
|
||||
&& scripts/package.sh linux /out
|
||||
|
||||
FROM scratch AS artifacts
|
||||
|
||||
@@ -98,15 +98,24 @@ WORKDIR /src
|
||||
# `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.
|
||||
# the first cargo command needs this: 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 . .
|
||||
# FFmpeg's LGPL DLLs go into the packages (scripts/fetch-ffmpeg-windows.sh).
|
||||
# Only this step is given the agent, and it only fetches (the packages of every
|
||||
# target, so the Windows ones too): 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: it
|
||||
# uses what this step fetched (the registry in the cache mount shared with it,
|
||||
# the git checkout of VoelinProtocol in this step's layer) or fails.
|
||||
RUN --mount=type=ssh,required=true \
|
||||
--mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
cargo fetch --locked
|
||||
# FFmpeg's LGPL DLLs go into the packages (scripts/fetch-ffmpeg-windows.sh).
|
||||
RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,id=voelin-target-windows,target=/src/target \
|
||||
cargo build --release --locked --target x86_64-pc-windows-gnu -p voelin-ui \
|
||||
cargo build --release --locked --offline --target x86_64-pc-windows-gnu -p voelin-ui \
|
||||
&& scripts/fetch-ffmpeg-windows.sh /tmp/ffmpeg \
|
||||
&& FFMPEG_DLL_DIR=/tmp/ffmpeg WINDOWS_TARGET=x86_64-pc-windows-gnu scripts/package.sh windows /out
|
||||
|
||||
|
||||
@@ -516,7 +516,8 @@ deleted. Keys deleted before `secure_delete` was on stay in the free pages until
|
||||
the database is vacuumed.
|
||||
|
||||
`voelin-identity` comes from the private VoelinProtocol repository as a git
|
||||
dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)).
|
||||
dependency pinned by its release tag, `v0.2.0`
|
||||
([building.md](building.md#depending-on-voelinprotocol)).
|
||||
|
||||
## Streams
|
||||
|
||||
|
||||
@@ -86,7 +86,8 @@ The same with plain Docker, e.g. `docker build --ssh default -f docker/linux.Doc
|
||||
**The builds need an ssh-agent that holds a key able to read the private
|
||||
VoelinProtocol repository** ([below](#depending-on-voelinprotocol)): Cargo
|
||||
fetches it inside the image, through the agent that `--ssh default` hands to the
|
||||
build. The key stays in the agent; it is not copied into the image or the build
|
||||
build, in a `RUN cargo fetch` of its own: the build after it has no agent and is
|
||||
offline. The key stays in the agent; it is not copied into the image or the build
|
||||
cache. `scripts/docker-build.sh` passes `--ssh default` itself and stops with a
|
||||
message when `ssh-add -l` shows no agent or no key (`eval "$(ssh-agent -s)"`,
|
||||
then `ssh-add` your key). The server's host key comes from
|
||||
@@ -161,15 +162,20 @@ dependencies in the workspace `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[workspace.dependencies]
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" }
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
```
|
||||
|
||||
They are pinned by one commit until the protocol tags a release; moving
|
||||
to a newer protocol means changing the `rev` of all three (later a `tag`) and committing
|
||||
They are pinned by the protocol's release tag, all three at the same one
|
||||
(`v0.2.0` is the first tag with the protocol crates; VoelinProtocol's README,
|
||||
"Releases", says how to pin, and its `CHANGELOG.md`, "For consumers", what a
|
||||
move changes). Moving to a newer release means changing the `tag` of all three,
|
||||
making what its "For consumers" list asks of this repository, and committing
|
||||
the resulting `Cargo.lock` together with `THIRD_PARTY_NOTICES.md`, which
|
||||
`scripts/notices.sh` regenerates (the CI notices job fails on a stale one).
|
||||
`scripts/notices.sh` regenerates (the CI notices job fails on a stale one). The
|
||||
lock then has one revision of each crate, and `spikes/gpui/Cargo.toml` pins
|
||||
`voelin-model` at the same tag with a lock of its own.
|
||||
Cargo fetches it over SSH, so the machine needs an SSH key that can read
|
||||
VoelinProtocol (an `ssh-agent` or a `~/.ssh/config` entry for
|
||||
`git.faumaray.com`); if Cargo's built-in git client cannot use your SSH setup,
|
||||
@@ -178,15 +184,19 @@ set `net.git-fetch-with-cli = true` in `~/.cargo/config.toml`.
|
||||
compiler (gcc or clang) and cmake.
|
||||
`deny.toml` allows this one git source.
|
||||
|
||||
**CI and the Docker builds read it with a read-only SSH deploy key.** The key
|
||||
is registered on VoelinProtocol and stored as the repository secret
|
||||
`VOELIN_PROTOCOL_DEPLOY_KEY`; the Gitea workflows write it to `~/.ssh` (CI) or
|
||||
load it into an ssh-agent (release builds), the server's host key comes from the
|
||||
committed `.gitea/known_hosts`, and Cargo is told to fetch with the system git
|
||||
(`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because its built-in git client ignores
|
||||
`~/.ssh/config`. The Docker builds use the same key through
|
||||
`docker build --ssh default` (see above). What was set up, how to re-check the
|
||||
host key's fingerprint and what each failure means:
|
||||
**CI and the Docker builds read it with a read-only SSH deploy key, and only to
|
||||
fetch.** The key is registered on VoelinProtocol and stored as the repository
|
||||
secret `VOELIN_PROTOCOL_DEPLOY_KEY`. The CI job writes it to a directory of its
|
||||
own (nothing in `~/.ssh`), runs `cargo fetch --locked` with it as the one
|
||||
`ssh -i` of that step, deletes it, and runs every later cargo command
|
||||
`--offline`; the release builds load it into an ssh-agent, and each Dockerfile
|
||||
gives the agent to a `RUN cargo fetch` only, the `cargo build --offline` after it
|
||||
has none. The server's host key comes from the committed `.gitea/known_hosts`, and
|
||||
Cargo is told to fetch with the system git (`CARGO_NET_GIT_FETCH_WITH_CLI=true`)
|
||||
because its built-in git client cannot use a key file. The Docker builds use the
|
||||
same key through `docker build --ssh default` (see above). What was set up, the
|
||||
order of the steps, why a runner that may print the key does not get it, how to
|
||||
re-check the host key's fingerprint and what each failure means:
|
||||
[ci.md](ci.md#voelinprotocol-access). A runner of your own gets the same setup
|
||||
from the workflows; the alternative to a deploy key is an access token (rewrite
|
||||
the SSH URL to HTTPS with
|
||||
@@ -219,4 +229,5 @@ voelin-model = { path = "../VoelinProtocol/crates/voelin-model" }
|
||||
- With the patch active Cargo rewrites `Cargo.lock` (the patched crates lose
|
||||
their git `source`). Do not commit that: run `git checkout Cargo.lock` before
|
||||
committing, or remove the file and run `cargo update -p voelin-identity -p voelin-proto -p voelin-model`
|
||||
after changing the `rev` (for all three crates). CI builds with `--locked` and has no patch.
|
||||
after changing the `tag` (for all three crates; `cargo update -p` can move unrelated
|
||||
lock edges, so review the lock diff or edit the lock by hand). CI builds with `--locked` and has no patch.
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
GitHub Actions runs `.github/workflows/ci.yml`, including Linux checks,
|
||||
Windows and Android Clippy, and TeamSpeak integration smoke tests. Automatic
|
||||
runs are off: CI, the dependency audit and fuzzing run only by hand
|
||||
(Actions → the workflow → Run workflow; the same on Gitea). Only the package
|
||||
runs are off there: CI, the dependency audit and fuzzing run only by hand
|
||||
(Actions → the workflow → Run workflow). On Gitea, CI also runs on pushes to
|
||||
`main` and on pull requests ([Gitea Actions](#gitea-actions)). Only the package
|
||||
builds run by themselves, on `v*` tags, and they run none of these checks.
|
||||
Both GitHub and Gitea provide release packaging; see [release.md](release.md)
|
||||
and [building.md](building.md).
|
||||
@@ -22,10 +23,18 @@ runtime performance has not been benchmarked for this change.
|
||||
|
||||
## Gitea Actions
|
||||
|
||||
`.gitea/workflows/ci.yml` runs a single Linux job when dispatched by hand
|
||||
(automatic runs on pushes and pull requests are off).
|
||||
`.gitea/workflows/ci.yml` runs a single Linux job on pushes to `main`, on pull
|
||||
requests (not when only `docs/` or Markdown files change, apart from
|
||||
`THIRD_PARTY_NOTICES.md`) and when dispatched by hand.
|
||||
|
||||
The job runs:
|
||||
Before any check the job fetches every dependency with the read-only deploy key
|
||||
with which Cargo reads the private VoelinProtocol repository, and deletes the key
|
||||
again; the checks run `--offline`, in a job that holds no key
|
||||
([VoelinProtocol access](#voelinprotocol-access)). The repository secret
|
||||
`VOELIN_PROTOCOL_DEPLOY_KEY` is needed for it, and the job refuses a runner that
|
||||
may print it and a fork's pull request.
|
||||
|
||||
The checks are:
|
||||
|
||||
- formatting and warnings-as-errors Clippy for our crates;
|
||||
- workspace Clippy (vendored warnings are reported, compilation errors fail);
|
||||
@@ -61,10 +70,13 @@ the separate `release.yml` workflow below.
|
||||
distribution servers, crates.io and dependency/license sources used by
|
||||
cargo-about. The
|
||||
workspace also depends on the **private** VoelinProtocol repository
|
||||
(`voelin-identity`, over SSH), so the job needs read access to it and the
|
||||
server's SSH port. The workflows set that up themselves from a repository
|
||||
secret: [VoelinProtocol access](#voelinprotocol-access). A runner needs
|
||||
nothing for it beyond the network access and the image tools above.
|
||||
(`voelin-identity`, `voelin-proto` and `voelin-model` at its release tag,
|
||||
over SSH), so the job needs read access to it and the server's SSH port.
|
||||
The workflows set that up themselves from a repository secret:
|
||||
[VoelinProtocol access](#voelinprotocol-access). A runner needs nothing for
|
||||
it beyond the network access and the image tools above, **and a version that
|
||||
masks multi-line secrets in the job log** (3.1.0 or newer): the workflows do
|
||||
not give the key to an older runner and fail the job instead.
|
||||
4. Provision enough RAM, swap and free disk for a full Slint workspace build
|
||||
plus cargo-deny/cargo-about compilation. These are large builds; monitor
|
||||
the first run and size the runner accordingly. The workflow limits Cargo
|
||||
@@ -90,8 +102,10 @@ the separate `release.yml` workflow below.
|
||||
The workflow shares the repository's local system-dependencies action with
|
||||
GitHub CI and bootstraps rustup if absent, then installs the toolchain and
|
||||
components pinned in `rust-toolchain.toml` (1.95: a channel change there is all
|
||||
the runner needs). Checkout uses a fully qualified GitHub action URL rather
|
||||
than depending on the instance's action-source configuration.
|
||||
the runner needs); these are steps of `ci.yml`, and the composite action
|
||||
`.gitea/actions/checks` holds the checks that run after the fetch. Checkout uses
|
||||
a fully qualified GitHub action URL rather than depending on the instance's
|
||||
action-source configuration.
|
||||
|
||||
No GitHub cache/artifact service or reusable-workflow support is required.
|
||||
The job does not need a Docker socket mounted inside its container; the
|
||||
@@ -194,61 +208,150 @@ known and left alone.
|
||||
|
||||
### VoelinProtocol access
|
||||
|
||||
The workspace depends on `voelin-identity` from the **private** repository
|
||||
`Voelin/VoelinProtocol`, as a git dependency over SSH
|
||||
([building.md](building.md#depending-on-voelinprotocol)). Cargo resolves the
|
||||
whole workspace before it builds anything, so *every* cargo command needs
|
||||
that access: all of CI, all three package images and the gateway image (whose
|
||||
crate does not use `voelin-identity` itself). Without it the first cargo
|
||||
command fails with `unknown SSH host key` (runs 1037 and 1050 did).
|
||||
The workspace depends on `voelin-identity`, `voelin-proto` and `voelin-model`
|
||||
from the **private** repository `Voelin/VoelinProtocol`, as git dependencies over
|
||||
SSH, pinned by its release tag `v0.2.0`
|
||||
([building.md](building.md#depending-on-voelinprotocol)). The tag is read over
|
||||
the same SSH access as the commit it replaced (Cargo fetches it through the
|
||||
system `git`, like any ref). Cargo resolves the whole workspace before it builds
|
||||
anything, so *every* cargo command needs that access until the sources are on
|
||||
disk: all of CI, all three package images and the gateway image (whose crate does
|
||||
not use `voelin-identity` itself). Without it the first cargo command fails with
|
||||
`unknown SSH host key` (runs 1037 and 1050 did). The workflows therefore fetch
|
||||
first, with the key, and build afterwards without it.
|
||||
|
||||
What is set up:
|
||||
|
||||
- **The deploy key.** A read-only SSH deploy key is registered on
|
||||
`Voelin/VoelinProtocol` (Settings → Deploy Keys, write access off). It has
|
||||
no other use and no access to any other repository. Its private half is the
|
||||
repository secret **`VOELIN_PROTOCOL_DEPLOY_KEY`** of `Voelin/VoelinClient`
|
||||
(Settings → Actions → Secrets): the whole OpenSSH private key file, BEGIN
|
||||
and END lines included, without a passphrase. To rotate it, make a new pair
|
||||
(`ssh-keygen -t ed25519 -N '' -C voelin-client-ci -f key`), register
|
||||
`key.pub` on VoelinProtocol, replace the secret with the contents of
|
||||
`key`, run CI, then delete the old deploy key and `key`.
|
||||
- **CI** (`ci.yml`). The workflow hands the secret to the checks action as its
|
||||
input `protocol-deploy-key` (a repository secret is not visible inside a
|
||||
composite action). The action's first step fails at once, naming the secret,
|
||||
if the input is empty or is not a private key. Otherwise it writes the key to
|
||||
`~/.ssh/voelin_protocol` (mode 0600, `~/.ssh` 0700), appends the host key
|
||||
line to `~/.ssh/known_hosts`, writes a `Host git.faumaray.com` block to
|
||||
`~/.ssh/config` (`User gitea`, that `IdentityFile`, `IdentitiesOnly yes`,
|
||||
`StrictHostKeyChecking yes`) and exports `CARGO_NET_GIT_FETCH_WITH_CLI=true`
|
||||
and `GIT_SSH_COMMAND` for the rest of the job (`ci.yml` sets the first one
|
||||
in its own `env` as well). It prints only the key's
|
||||
public fingerprint; the key is never echoed. After the system packages a
|
||||
second step runs `git ls-remote` on VoelinProtocol, so a wrong key or host
|
||||
key fails there, with the reason, and not inside a cargo command. The key
|
||||
lives in the job container and goes with it.
|
||||
- **Release** (`release.yml`). A step after checkout starts an `ssh-agent` on
|
||||
the release host, loads the key into it from stdin (it is never written to
|
||||
disk) and exports `SSH_AUTH_SOCK`; the agent forgets the key after nine
|
||||
hours, and a last step, which also runs after a failure, stops it. The
|
||||
builds pass the agent on with `docker build --ssh default`
|
||||
(`scripts/docker-build.sh` does it for the three packages; the gateway image
|
||||
step does it itself).
|
||||
- **The images.** Each cargo `RUN` of `docker/*.Dockerfile` and
|
||||
`crates/voelin-gateway/Dockerfile` has `--mount=type=ssh,required=true`, so
|
||||
the key exists only inside that step, through the agent socket, and never
|
||||
reaches a layer, a build argument or the cache; a build without `--ssh`
|
||||
stops there with `unset ssh forward key default`. The build stage copies
|
||||
`.gitea/known_hosts` to `/etc/ssh/ssh_known_hosts` and sets the same
|
||||
`CARGO_NET_GIT_FETCH_WITH_CLI=true`; the toolchain stages install `git` and
|
||||
`openssh-client`.
|
||||
`Voelin/VoelinProtocol` (Settings → Deploy Keys, write access off; deploy key
|
||||
**id 7**, "VoelinClient CI (read-only)", made on 2026-10-28,
|
||||
`SHA256:TWpZx3NgSMKTBkNLfp0C+Q1/DPD0E44Gy+GiHwK/zpI`). It has no other use and no
|
||||
access to any other repository. It replaced this repository's first deploy key
|
||||
(the secret of 2026-10-24), which a job log had shown in clear
|
||||
([The key and the runners](#the-key-and-the-runners)); that key is deleted, and so
|
||||
are the runs that printed it. The private half is the repository secret
|
||||
**`VOELIN_PROTOCOL_DEPLOY_KEY`** of `Voelin/VoelinClient` (Settings → Actions →
|
||||
Secrets): the whole OpenSSH private key file, BEGIN and END lines included,
|
||||
without a passphrase. The key step prints the public fingerprint on every run,
|
||||
to compare with the Deploy Keys page of VoelinProtocol. To rotate it, make a
|
||||
new pair (`ssh-keygen -t ed25519 -N '' -C voelin-client-ci -f key`), register
|
||||
`key.pub` on VoelinProtocol, replace the secret with the contents of `key`, run
|
||||
CI and look at the fingerprint the key step prints, then delete the old deploy
|
||||
key and `key`. If the old key may have been seen, delete the runs that could
|
||||
have shown it and count the lines in the logs that remain
|
||||
([Looking at a run](#looking-at-a-run)).
|
||||
- **CI** (`ci.yml`). In order; the key exists only between steps 3 and 4:
|
||||
1. **Check that this job may hold the VoelinProtocol deploy key.** It reads
|
||||
`GITEA_ACTIONS_RUNNER_VERSION`; a plain `X.Y.Z` (an optional leading `v`) of
|
||||
`MIN_MASKING_RUNNER_VERSION` (3.1.0) or more passes the runner part. A lower
|
||||
version, no version, or anything else (`3.1.0-rc1`) fails it. For a pull
|
||||
request it also asks whether the PR's head is in this repository (below). If
|
||||
both hold it writes `VOELIN_KEY_ALLOWED=yes` to `GITHUB_ENV`; otherwise it
|
||||
prints each reason as an error and **fails the job**: 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. Run it again to be given
|
||||
another runner.
|
||||
2. The system packages (the `system-deps` action, apt) and the pinned Rust
|
||||
toolchain. No key yet.
|
||||
3. **Install the VoelinProtocol deploy key.** The secret is the `env:` of this
|
||||
one step, through `${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}`,
|
||||
and the step has `if: env.VOELIN_KEY_ALLOWED == 'yes'`: both ask for the
|
||||
positive flag, so a runner that is not trusted, or one whose expression
|
||||
context does not hold what an earlier step wrote to `GITHUB_ENV`, leaves the
|
||||
step not started and the variable empty. The script never prints the key and
|
||||
has no `set -x`. It writes the key to `id` (mode 0600) in a directory of the
|
||||
job's own, `mktemp -d "$RUNNER_TEMP/voelin-protocol-key.XXXXXX"` (mode 0700;
|
||||
the name goes to `GITHUB_ENV` first so that the cleanup finds it even if this
|
||||
step is killed), checks it with `ssh-keygen -y` and prints the fingerprint. From
|
||||
the `mktemp` on, the step removes the directory itself on every way out but
|
||||
the last line (an `EXIT` trap: a key that is not a key, a full disk, a
|
||||
termination). It writes nothing to `~/.ssh`: no key file, no `known_hosts`,
|
||||
no config block.
|
||||
4. **Fetch the dependencies with the deploy key.** The only step that uses the
|
||||
key, and the only one that sets `GIT_SSH_COMMAND` (not in `GITHUB_ENV`, so no
|
||||
other step has it):
|
||||
`ssh -F /dev/null -i <dir>/id -o IdentitiesOnly=yes -o IdentityAgent=none -o UserKnownHostsFile=<workspace>/.gitea/known_hosts -o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes -o BatchMode=yes -o ConnectTimeout=30`.
|
||||
`-F /dev/null` leaves out every ssh config file, the identity is that file and
|
||||
nothing from an agent, and the host key accepted is the committed line and no
|
||||
other (a changed or unknown host key fails rather than asks). The paths are
|
||||
absolute because Cargo runs git in its own directory, not in the checkout.
|
||||
The step runs `git ls-remote` on VoelinProtocol first, so a wrong key or host
|
||||
key fails there, with the reason, and not inside Cargo; then
|
||||
`cargo fetch --locked`, which downloads every package of `Cargo.lock` (all
|
||||
targets, because cargo-deny and cargo-about read the whole graph) and runs **no
|
||||
build script, procedural macro or test**; then it deletes the directory (on
|
||||
every way out of the step, a failed fetch included) and checks that it is
|
||||
gone.
|
||||
5. **Delete the deploy key**, `if: always()`: removes the directory if it is
|
||||
still there (the key step failed after creating it, the job was cancelled) and
|
||||
says so, or says that none is left. It runs right after the fetch, so the
|
||||
checks never start with a key in the job.
|
||||
6. **The checks** (`.gitea/actions/checks`): formatting, Clippy, the build, the
|
||||
tests under Xvfb, cargo-deny, the notices check and the release tooling tests.
|
||||
The action has **no input and no secret**: the secret is never handed to the
|
||||
steps that run the repository's build scripts and tests. Every cargo command
|
||||
in it is `--offline` (with `--locked`), and the steps that start cargo through
|
||||
a script or plugin (`scripts/own-crates.sh`, `cargo fmt`, `cargo deny`,
|
||||
`scripts/notices.sh`) have `CARGO_NET_OFFLINE=true`. cargo-deny's own
|
||||
`--offline` is not used: it would also stop it fetching the RustSec database
|
||||
(from github.com, no key), which the check needs; the variable keeps its
|
||||
`cargo metadata` offline and leaves the fetch alone. The only cargo commands
|
||||
that go online are the two `cargo install` of cargo-deny and cargo-about, which
|
||||
read no manifest of this workspace. A dependency added later that Cargo could
|
||||
not get from `cargo fetch` fails these steps with an offline error instead of
|
||||
waiting for an ssh key that is not there.
|
||||
- **A fork's pull request.** A pull request gets the key only when its head branch
|
||||
is in this repository. The job-level `env` of `ci.yml` asks
|
||||
`github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository`:
|
||||
Gitea's event payload names, in `pull_request.head.repo.full_name`, the repository
|
||||
that holds the branch to be merged. That is `Voelin/VoelinClient` for a branch
|
||||
pushed here and the fork's own name (`someone/VoelinClient`) for a fork; any other
|
||||
event has no pull request, and the first operand is true. An absent or different
|
||||
name reads `no`, and step 1 treats everything but `yes` as no (the same
|
||||
fail-closed direction as the runner version). Step 1 also asks the question
|
||||
again in its script, from the name itself: for a `pull_request` event (and for any
|
||||
event that carries a head repository) it requires `PR_HEAD_REPO`, the same payload
|
||||
field, to be non-empty and equal to `GITHUB_REPOSITORY`, so a mistake in the
|
||||
expression or in the script alone does not hand the key to a fork's code. A fork's
|
||||
pull request therefore fails at step 1 with the reason and the head repository's
|
||||
name, without a key, as it failed before (at the empty secret). Gitea gives such a
|
||||
run no secrets in any case; the check also keeps a same-looking head from being
|
||||
trusted by accident. It does not make a same-repository branch safe: code of a
|
||||
branch pushed here runs the build scripts and tests with no key (it is gone by
|
||||
then), but a branch that changes the workflow itself is a change of the workflow
|
||||
([below](#what-this-does-not-do)).
|
||||
- **Release** (`release.yml`). A step after the checkout checks the runner as
|
||||
step 1 above does (a release has no pull request). The step that starts an
|
||||
`ssh-agent` on the release host has the same flag guard, loads the key into the
|
||||
agent from stdin (it is never written to disk) and exports `SSH_AUTH_SOCK`; the
|
||||
agent forgets the key after nine hours. The builds pass the agent on with
|
||||
`docker build --ssh default` (`scripts/docker-build.sh` does it for the three
|
||||
packages, the Android one twice, as the debug APK and as the signed release APK;
|
||||
the gateway image step does it itself). A step directly after the last build,
|
||||
`if: always()`, stops the agent and empties `SSH_AUTH_SOCK`, so the artifact
|
||||
upload and the release draft have neither the key nor the socket.
|
||||
- **The images.** In `docker/linux.Dockerfile`, `docker/windows.Dockerfile`,
|
||||
`docker/android.Dockerfile` and `crates/voelin-gateway/Dockerfile` only a
|
||||
`RUN cargo fetch --locked` has `--mount=type=ssh,required=true`; the build after
|
||||
it has no ssh mount and is offline: `cargo build --release --locked --offline`
|
||||
in three of them, `CARGO_NET_OFFLINE=true` in the Android one, whose Gradle task
|
||||
starts cargo-ndk and cargo (the task itself is left as it is, because a
|
||||
developer's own build has network and no `cargo fetch`). The key exists inside
|
||||
the fetch only, through the agent socket, and never reaches a layer, a build
|
||||
argument or the cache; the code that the build compiles and runs (build scripts,
|
||||
procedural macros, Gradle) has no agent socket in reach. A build without `--ssh`
|
||||
stops at the fetch with `unset ssh forward key default`. The build stage copies
|
||||
`.gitea/known_hosts` to `/etc/ssh/ssh_known_hosts` and sets
|
||||
`CARGO_NET_GIT_FETCH_WITH_CLI=true`; the images install `git` and `openssh-client`
|
||||
in their build stage. The fetched git checkout of VoelinProtocol stays in the
|
||||
layer of the fetch step, the registry in the cache mount that the build step
|
||||
shares (the three package images; the gateway image has no cache mount, its
|
||||
registry stays in the layer too).
|
||||
- **Cargo uses the system git** (`CARGO_NET_GIT_FETCH_WITH_CLI=true`) because
|
||||
Cargo's built-in git client does not read `~/.ssh/config` (so it cannot use
|
||||
an `IdentityFile`), authenticates with an ssh-agent and checks the host
|
||||
against `~/.ssh/known_hosts` and its own `net.ssh.known-hosts` setting. The
|
||||
system git runs `ssh`, which reads the config above (and
|
||||
`/etc/ssh/ssh_known_hosts` in the images), so the same files serve a plain
|
||||
`git` call, Cargo and the access check.
|
||||
Cargo's built-in git client does not run `ssh -i` (so it cannot use a key file),
|
||||
authenticates with an ssh-agent and checks the host against `~/.ssh/known_hosts`
|
||||
and its own `net.ssh.known-hosts` setting. The system git runs the command in
|
||||
`GIT_SSH_COMMAND`, so the same command serves the access check and Cargo.
|
||||
- **The host key** is committed in [`.gitea/known_hosts`](../.gitea/known_hosts),
|
||||
never fetched while a job runs. Gitea's built-in SSH server (`SSH-2.0-Go`)
|
||||
offers an RSA host key only (`ssh-keyscan -t ed25519 git.faumaray.com`
|
||||
@@ -265,21 +368,135 @@ What is set up:
|
||||
new `ssh-keyscan -t rsa` line and the date in `.gitea/known_hosts` and the
|
||||
fingerprint here, and commit all of it in one change. Until then a changed key
|
||||
makes every job stop with `Host key verification failed`, which is the point.
|
||||
VoelinGateWay, VoelinProtocol and VoelinServer keep the same line.
|
||||
|
||||
Pull requests from forks get no secrets: their CI run stops at the first step
|
||||
with the message about the empty deploy key. Anyone who can change a workflow of
|
||||
this repository, or run code in one of its jobs, can read the key; it can only
|
||||
read VoelinProtocol, and it is replaced as above. That is one more reason to
|
||||
keep the CI runner isolated, as said above.
|
||||
#### The key and the runners
|
||||
|
||||
Gitea has more than one runner with the same labels (`ubuntu-latest`,
|
||||
`voelin-release`, `ubuntu-24.04`, `ubuntu-22.04`, `echoion-release-serial`), so
|
||||
`runs-on` cannot choose between them, and they do not log alike. A runner prints
|
||||
the `env:` of a step in the job log when the step starts. "Perfrormance Runner"
|
||||
(act_runner, reports `v3.1.0`, the one that is online) masks a multi-line secret
|
||||
line by line (`***`). The runner **gitea-runner-docker v0.6.1 (id 1, offline on
|
||||
2026-10-28) printed the whole private key in clear**, on one line with the line
|
||||
ends shown as `\n`, in the logs of runs of this repository, of VoelinGateWay and of
|
||||
VoelinServer on 2026-10-27. On 2026-10-28 every deploy key was rotated and the
|
||||
runs that printed one were deleted.
|
||||
|
||||
What follows from it, in the workflows:
|
||||
|
||||
- **The key is not given to such a runner.** Step 1 of the job (and the check in
|
||||
`release.yml`) writes the flag only for a runner whose reported version is
|
||||
`MIN_MASKING_RUNNER_VERSION` (3.1.0, the oldest one seen masking) or more; for any
|
||||
other the job fails there, before any step names the secret, and the key step is
|
||||
not started. This is a gate on the version number and no test of masking: a
|
||||
runner that reports 3.1.0 or more is trusted by its number, and a version
|
||||
that a runner does not report is not trusted. It was **rehearsed** with a
|
||||
stand-in for the runner (the step script with the reported version set to
|
||||
`v0.6.1`, to nothing, to `3.0.9`, to `v3.1.0-rc1`, to `3.1` and to a word: the job
|
||||
fails with the reason and no flag is written; `v3.1.0`, `3.1.0`, `v3.1.1`,
|
||||
`v10.0.0` pass) and **has not been seen on gitea-runner-docker itself**, because
|
||||
it is offline, and what that runner reports in `GITEA_ACTIONS_RUNNER_VERSION` is
|
||||
not known. To let the gate admit an older runner, lower
|
||||
`MIN_MASKING_RUNNER_VERSION` (in `ci.yml` and in `release.yml`) only after a
|
||||
canary secret of several lines has been shown masked in the log of that runner.
|
||||
- **The cause is the runner**, and the fix that covers every secret of every
|
||||
repository is there: upgrade gitea-runner-docker to a version that masks
|
||||
multi-line secrets, retire it, or register it with labels no workflow asks for.
|
||||
- The log of a run that did hold the key shows the step headers with `***` for
|
||||
each line of the secret; nothing else prints it.
|
||||
|
||||
#### What has been seen, and what has not
|
||||
|
||||
Seen on a real runner ("Perfrormance Runner", reports `v3.1.0`), by dispatching
|
||||
`ci.yml` on the branch that introduced this order of steps:
|
||||
|
||||
- **Run 1226, the full path, green** (36 minutes). The check passes ("Runner …
|
||||
reports version v3.1.0, which masks secrets in the log"; "Event
|
||||
workflow_dispatch: no pull request"); the key step's header shows
|
||||
`PROTOCOL_DEPLOY_KEY: ***` and one `***` for each further line of the key, and
|
||||
prints `Deploy key installed: 256 SHA256:TWpZx3NgSMKTBkNLfp0C+Q1/DPD0E44Gy+GiHwK/zpI`
|
||||
(deploy key id 7); the fetch step reads VoelinProtocol, runs `cargo fetch --locked`
|
||||
(some eighteen seconds) and prints "The deploy key is removed from the job."; the
|
||||
cleanup step prints "No deploy key is left in the job."; the checks run
|
||||
`--offline`; the only `Updating crates.io index` after the fetch are the two
|
||||
`cargo install` steps. The log of the job has no line with `PRIVATE KEY`.
|
||||
- **Run 1225, the gate refusing, red by design.** A temporary commit raised
|
||||
`MIN_MASKING_RUNNER_VERSION` to `99.0.0` (reverted by the next commit): the check
|
||||
failed the job with "… the runner (Perfrormance Runner) reports version 'v3.1.0',
|
||||
and only a runner of version 99.0.0 or newer …"; the system packages, the
|
||||
toolchain, the key step, the fetch and the checks were not started and left no
|
||||
line in the log (so the secret was named nowhere), the cleanup step ran and said
|
||||
that no key is left, and the log has no `PRIVATE KEY` line and no mention of the
|
||||
secret.
|
||||
- Run 1224, of the same workflow as run 1226, was cancelled four minutes in, as
|
||||
1225 was started on the same branch (a run started on a branch cancels the one
|
||||
still running there, so dispatch the next only when the last has ended): the
|
||||
key step, the fetch and the cleanup had run as in 1226 and the offline Clippy had
|
||||
started. It shows nothing more.
|
||||
|
||||
Rehearsed with stand-ins, not seen on a runner: the runner check of `ci.yml` and of
|
||||
`release.yml` for the reported versions above, and the pull request rule of
|
||||
`ci.yml` (head repository empty, another one, equal to the repository, with the
|
||||
expression's answer yes, no or missing: only equal and named passes); the key step
|
||||
with a text that is no key, with an empty one and with a failing `GITHUB_ENV` (the
|
||||
`EXIT` trap removes the directory) and with a key whose lines end in CR (it stays for
|
||||
the fetch); the fetch step with a key that VoelinProtocol does not know (`Permission
|
||||
denied (publickey)` from the server whose host key `.gitea/known_hosts` holds, the
|
||||
directory removed by the step's trap); the cleanup step with and without a
|
||||
directory; the ssh-agent step of `release.yml` with a key (the fingerprint, the
|
||||
variables) and its stop step (the agent is gone, the variables are emptied).
|
||||
|
||||
Not seen: a job on gitea-runner-docker (offline; the gate is rehearsed with a
|
||||
stand-in for the runner, above); a `pull_request` run, so neither the same-repository
|
||||
head (`yes`) nor a fork's (`no`) has been read from a real event payload (the field
|
||||
is the one that Gitea's API gives as `head.repo.full_name` of a pull request, which
|
||||
reads `Voelin/VoelinClient` for a branch of this repository, and an absent field
|
||||
fails closed); `release.yml` on a runner; the four Dockerfiles built (they pass
|
||||
`docker build --check` with no warning, and the `cargo fetch` then `cargo build
|
||||
--offline` split is that of VoelinGateWay's `docker/linux.Dockerfile`, which was
|
||||
built with `docker build --ssh default`; the Android Gradle task with
|
||||
`CARGO_NET_OFFLINE` has not been run). The first release or image build is the
|
||||
check.
|
||||
|
||||
#### Looking at a run
|
||||
|
||||
The fingerprint of the key step, and the proof that no log holds a private key
|
||||
(the job ids are in `GET .../actions/runs/<run id>/jobs`):
|
||||
|
||||
```sh
|
||||
curl -s -H "Authorization: token $TOKEN" "https://git.faumaray.com/api/v1/repos/Voelin/VoelinClient/actions/jobs/<job id>/logs" | grep -c 'PRIVATE KEY' # 0
|
||||
```
|
||||
|
||||
#### What this does not do
|
||||
|
||||
- Anyone who can change a workflow of this repository, or run code in one of its
|
||||
jobs, can read the key: a branch pushed here that prints it in the key step, or
|
||||
that lowers `MIN_MASKING_RUNNER_VERSION`, or that adds a step. The key can only
|
||||
read VoelinProtocol and is replaced as above; keep the CI runner isolated, as said
|
||||
above. What the hardening does is keep the *code* of a change (build scripts,
|
||||
procedural macros, tests, tools installed by cargo) away from the key while the
|
||||
workflow is the reviewed one.
|
||||
- `cargo fetch` reads the checkout's `Cargo.toml` and `Cargo.lock` files,
|
||||
`rust-toolchain.toml` and a `.cargo/config.toml` if there is one (there is none
|
||||
at the root today), and runs the toolchain's `rustc -vV`. A branch that adds a
|
||||
Cargo configuration with a `build.rustc` or `build.rustc-wrapper` program would
|
||||
run it while the key exists. That is a change of the build configuration, to be
|
||||
reviewed as one.
|
||||
- The job token that `actions/checkout` leaves in the checkout's git configuration
|
||||
is not touched by this.
|
||||
|
||||
If a run fails here:
|
||||
|
||||
| Message | Cause |
|
||||
|---|---|
|
||||
| `The VoelinProtocol deploy key is empty` | the secret is missing, empty or not visible (a fork's pull request) |
|
||||
| `The VoelinProtocol deploy key is not given to this job: the runner (…) reports version …` | the job landed on a runner that is not known to mask the key in the log (gitea-runner-docker v0.6.1, or one that reports no version): run it again |
|
||||
| `… the pull request's head repository is '…'` | a fork's pull request, or an event that did not name the head: push the branch to this repository |
|
||||
| `The VoelinProtocol deploy key is empty` | the secret is missing or empty |
|
||||
| `… is not an unencrypted OpenSSH or PEM private key` | the secret holds something else, or a key with a passphrase |
|
||||
| `Permission denied (publickey)` in "Check read access to VoelinProtocol" | the key is valid but is not a deploy key of VoelinProtocol: compare the fingerprint "Deploy key installed" printed with the one in VoelinProtocol's deploy key settings |
|
||||
| `Permission denied (publickey)` in "Fetch the dependencies with the deploy key" | the key is valid but is not a deploy key of VoelinProtocol: compare the fingerprint "Deploy key installed" printed with the one in VoelinProtocol's deploy key settings |
|
||||
| `Host key verification failed` | `.gitea/known_hosts` does not match the server: check as above before changing anything |
|
||||
| an offline error ("no matching package", "can't update … in offline mode") in a check step | a dependency changed after the fetch, or `cargo fetch --locked` did not get something the checks need: fix the fetch step, do not give the checks a key |
|
||||
| `unset ssh forward key default` | a Docker build ran without `--ssh default`: a plain `docker build` (`scripts/docker-build.sh` passes it itself and stops earlier when the agent has no key) |
|
||||
|
||||
### Gitea release runner
|
||||
@@ -297,9 +514,13 @@ voelin-release:host
|
||||
|
||||
Provision Bash, Git, the OpenSSH client (`ssh-agent` and `ssh-add`), Node.js
|
||||
20+, Python 3.11+, curl, tar, gzip and rootful Docker 23+ with BuildKit. Use
|
||||
**act_runner 0.2.7 or newer** (prefer the latest maintained release), or
|
||||
gitea-runner 2+. Older act_runner does not provide
|
||||
`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. Register the
|
||||
**a runner that reports 3.1.0 or newer** (the key gate refuses older ones;
|
||||
0.2.7 is only the artifact action's minimum; prefer the latest maintained
|
||||
release), or gitea-runner 2+. Older act_runner does not provide
|
||||
`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. The workflow also
|
||||
gives the deploy key only to a runner that reports version 3.1.0 or newer in
|
||||
`GITEA_ACTIONS_RUNNER_VERSION` ([VoelinProtocol access](#voelinprotocol-access)),
|
||||
so on a lower one the release stops at its first check. Register the
|
||||
runner against `https://git.faumaray.ru`, reachable from both the host and
|
||||
build containers. Gitea 1.25.4 provides the required artifact-v4 API.
|
||||
The shared checks install native build dependencies
|
||||
|
||||
@@ -23,8 +23,9 @@ cases the foundation's review ran again on a quiet machine. The same day the
|
||||
foundation of step 3 landed on `phase5/gpui-foundation` (items 1 to 4 and 6
|
||||
of "What step 3's first slice must contain": Rust 1.95, ashpd on `async-io`,
|
||||
the `voelin-gpui` crate with its root entity, the theme with Inter and Lucide,
|
||||
the cost meter; item 5, the shell, is next): what exists, how to run it and
|
||||
the slices that follow are in [docs/ui.md](../ui.md), "The GPUI front end".
|
||||
the cost meter; item 5, the shell, followed the same day, below): what exists,
|
||||
how to run it and the slices that follow are in [docs/ui.md](../ui.md), "The
|
||||
GPUI front end".
|
||||
The foundation was reviewed and gated the same day (a Sonnet review, then the
|
||||
Opus gate: no blocker and no major, six minors), and the minors are closed in
|
||||
the commits after it: the meter's `/proc` test waits for a CPU tick instead of
|
||||
@@ -32,7 +33,50 @@ burning 60 ms, zbus runs on `async-io` alone in every binary (with a test for
|
||||
the order of ashpd's callers), the lock figures and the Lucide 1.43 credit are
|
||||
corrected, the slice list points at "Open choices for step 3", and the parity
|
||||
test sees a second brush or string. The risks the review and the gate left to
|
||||
the slices that meet them are in docs/ui.md, "For the next slices".
|
||||
the slices that meet them are in docs/ui.md, "For the next slices". Item 5, the
|
||||
desktop shell, is slice 1 of the step's list and landed on `phase5/gpui-shell`
|
||||
(2026-10-27): the store at start (the client's database, the settings with the
|
||||
UI's keys, the secrets, the default identity), the server rail, the sidebar,
|
||||
the top bar and the main area as entities that tell the window when what they
|
||||
show changed (the window then draws every part: gpui-pre 0.3.10 renders every
|
||||
uncached child view on every frame), the eleven callbacks of `bind/servers.rs`
|
||||
as actions through `voelin-ui-vm`'s logic and the engine's commands, the
|
||||
window's size and position kept in `ui.window`, the engine-event task in steps
|
||||
and a tick that draws nothing. What it shows, what it costs idle and what it
|
||||
leaves to the slices after it are in docs/ui.md, "The desktop shell"; the next
|
||||
slice is the channel tree and the members. The shell was reviewed and gated the
|
||||
same day (an Opus gate: no blocker and no major, six minors), and the minors are
|
||||
closed on `phase5/gpui-shell-minors`: the records that said the parts draw only
|
||||
when what they show changed are corrected (a part tells the window, and the
|
||||
window draws every part, as gpui-pre 0.3.10 renders every uncached child view on
|
||||
every frame), a window left maximized is maximized again on X11, the pictures
|
||||
are 1440 by 960, the connect test sends no DNS query, the sequences both front
|
||||
ends ran are shared in `voelin-ui-vm`, and the `ui.window` row is in the
|
||||
settings table; the gate's four risks of the shell are in docs/ui.md, "For the
|
||||
next slices". Slice 2, the channel tree and the members panel, landed on
|
||||
`phase5/gpui-tree` (2026-10-28): `Update.refresh` as per-area signals and the
|
||||
shell's panes cached (the design the shell's review left for it), the pictures
|
||||
the engine writes again shown and the old copies dropped, the tree over a
|
||||
virtual list that applies the row operations of `voelin-ui-vm`'s `list::diff`,
|
||||
the members panel, the member card and the password prompt, with the folds and
|
||||
the selection kept per server; what a change costs, figure by figure, is in
|
||||
docs/ui.md, "The channel tree and the members". The slice was reviewed the same
|
||||
day (one major and five minors) and the commits after it close them: a channel's
|
||||
banner is drawn under the surface veil of the Slint tree's `BannerPicture`, an
|
||||
avatar under 28 pixels shows one letter, the password prompt ignores an empty
|
||||
field and closes on Escape, and the `ui.tree` row of the settings table, the
|
||||
list of the Bridge's properties and callbacks that the two panes use and some
|
||||
long lines are corrected in docs/ui.md. Slice 3, the voice page and the call bar,
|
||||
landed on `phase5/gpui-voice` (2026-10-28): the page as a cached pane of its own
|
||||
that takes the main area (its people from the tree model's one build, so a talker
|
||||
is still one build for three lists), the call bar and the smaller stage kept in
|
||||
`ui.voice_compact`, the sidebar's server card with its banner, the voice card's
|
||||
transmit modes and the volume of a person following the settings, the release
|
||||
guard of Hold to talk (voice that drops, a window that loses the focus) and the
|
||||
global push-to-talk key started on the engine's runtime; it was seen against both
|
||||
development servers with a second client that talks. What it costs and what it
|
||||
leaves is in docs/ui.md, "The voice page and the call bar". The next slice is the
|
||||
chat, the composer and emoji.
|
||||
|
||||
| Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict |
|
||||
|---|---|---|---|
|
||||
@@ -637,8 +681,12 @@ set; the meter as `VOELIN_METER=1`. The crate is named `voelin-gpui` (binary
|
||||
`voelin-gpui`), the choices below stayed as the report leaves them except
|
||||
those named in docs/ui.md ("The GPUI front end"): the theme's second layer is
|
||||
written as a `ThemeColor` mapping (a table there), and the client's Lucide set
|
||||
is served under gpui-component's `icons/` paths. Item 5, the shell, is the
|
||||
next task.
|
||||
is served under gpui-component's `icons/` paths. Item 5, the shell, is done on
|
||||
`phase5/gpui-shell` (the status paragraph above, docs/ui.md "The desktop
|
||||
shell"): the screenshots are made the `docs/ui.md` way
|
||||
(`scripts/gpui-shot.sh` under `headless.sh`), the form that adds a server is the
|
||||
shell's own until the dialogs slice, and the open choices that remain (video,
|
||||
emoji, links) are untouched by it.
|
||||
|
||||
### The risks of plan section 6, against what was seen
|
||||
|
||||
|
||||
@@ -35,6 +35,16 @@ HTTPS and never uses GitHub's release API. On this instance the server URL
|
||||
is `https://git.faumaray.ru`. No registry credentials are needed: the gateway
|
||||
image is attached as `tsgw-image.tar.gz`, not pushed to an OCI registry.
|
||||
|
||||
The builds also read the private VoelinProtocol repository
|
||||
(`voelin-identity`, `voelin-proto`, `voelin-model`): the repository secret
|
||||
`VOELIN_PROTOCOL_DEPLOY_KEY`, the read-only deploy key of that repository, is
|
||||
loaded into an ssh-agent for the Docker builds, given to the `cargo fetch` of each
|
||||
Dockerfile only, and the agent is stopped right after the last build
|
||||
([ci.md](ci.md#voelinprotocol-access)). The workflow gives the key only to a
|
||||
runner of version 3.1.0 or newer (an older one may print it in the job log) and
|
||||
stops at that check otherwise; without the secret it stops at its ssh-agent step,
|
||||
naming the secret.
|
||||
|
||||
Retries update only a matching **draft**, replacing same-named assets.
|
||||
Published releases are not changed; a failed upload leaves a partial draft
|
||||
for retry. Do not publish or modify a draft while the workflow runs. Gitea
|
||||
|
||||
@@ -4,7 +4,7 @@ Status: design (2026-10-20); slices 1, 2 and 3 are implemented (section 13
|
||||
says how slice 1 differs from this text, sections 14 and 15 what its reviews
|
||||
changed, section 16 what slice 2 built, found and corrected, section 17 what
|
||||
slice 3 moved, changed and ran, 17.7 the round after its review, which
|
||||
brought the branch onto main `ad20979`, and 17.8 the round after the gate of the
|
||||
brought the branch onto main `ad20979`, 17.9 the move of the pin to the tag v0.2.0, and 17.8 the round after the gate of the
|
||||
merge; 17.6 has the complete edge list for the second half); section 10 has
|
||||
the slices.
|
||||
|
||||
@@ -19,7 +19,7 @@ here; section 11 lists what it has to do.
|
||||
Read for this design: `crates/voelin-core/src/link.rs`, `ts_link.rs`,
|
||||
`voice.rs`, `book.rs`, `stream.rs`, `files.rs`, `session.rs` (its use of the
|
||||
link), `tests/link_fake.rs`, `voelin-audio/src/packet.rs`; and in
|
||||
VoelinProtocol (main at the pin of that round; moved to `c5bb6b9` by task 34)
|
||||
VoelinProtocol (main at the pin of that round; moved by task 34, and since then to the tag `v0.2.0`, 17.9)
|
||||
`crates/voelin-proto/src/link.rs`,
|
||||
`media.rs` with `media/`, `test_util/` (FakeHost, FakeSession,
|
||||
FakeConnector, FakeAccountAgent, the conformance suite),
|
||||
@@ -1218,8 +1218,8 @@ second that works.
|
||||
### 16.2 The conformance suite
|
||||
|
||||
**Through the registry.** `the_conformance_suite_passes_on_a_session_of_the_registry`
|
||||
runs the 17 cases of the protocol's suite (still 17, in the same order, at
|
||||
`c5bb6b9`) against the `FakeSession` that
|
||||
runs the 17 cases of the protocol's suite (still 17, in the same order, at the
|
||||
pin of task 34 and at the tag `v0.2.0`) against the `FakeSession` that
|
||||
`Backends::connect(params, LocalCtx::standalone())` hands over: 17 of 17
|
||||
pass, none is skipped. The registry adds nothing to a plain connector's
|
||||
session (`host_uid` is the connector's, there is no stream port), so the
|
||||
@@ -1737,8 +1737,9 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run.
|
||||
|
||||
- **The key store follows task 34 (`phase4/keystore-task34`).** Open question 10
|
||||
of the accounts design (answered by the owner on 2026-10-24) made
|
||||
`KeyStore::sign_out` keep every device key, and VoelinProtocol `main`
|
||||
(`c5bb6b9`) has it. `SqliteKeyStore` runs that trait method, so the follow-up
|
||||
`KeyStore::sign_out` keep every device key, and VoelinProtocol `main` at
|
||||
the pin of that task (and every release from the tag `v0.2.0`) has it.
|
||||
`SqliteKeyStore` runs that trait method, so the follow-up
|
||||
that Phase 2 task 34 leaves to this repository ("Note for VoelinClient") is
|
||||
the pin of the three protocol crates, the tests that asserted the deletion
|
||||
of a key made for the account (now kept, unbound, byte for byte; only
|
||||
@@ -1759,7 +1760,8 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run.
|
||||
trait's provided `sign_out` lists the key twice in `SignOut.unbound` (once in
|
||||
its loop over the identities bound to the account, once in the `Auto` branch),
|
||||
which the tests of this repository do not mind (they use `contains`) and which
|
||||
is a follow-up for the protocol repository.
|
||||
is a follow-up for the protocol repository. (Closed in VoelinProtocol
|
||||
`v0.2.0`: a key is listed once. 17.9 has the tests that now count it.)
|
||||
- **The same leak in `voelin-store`, closed in `phase4/keystore-task34`.**
|
||||
`Store::identity` and `Store::identities` read the stored JSON of a
|
||||
TeamSpeak identity with `?`, so an `Error::Json` whose text is the
|
||||
@@ -1835,7 +1837,7 @@ changes). `Cargo.lock`, `Cargo.toml`, `README.md`, `docs/ui.md`,
|
||||
conflict: the lock resolves with `--locked`, and its difference to `main`'s is
|
||||
the branch's alone (the edges of `voelin-core` to `voelin-identity` and
|
||||
`voelin-proto`, the revision of the three protocol crates that the branch
|
||||
pinned (since moved to `c5bb6b9` by task 34), and
|
||||
pinned (since moved by task 34, and then to the tag `v0.2.0`, 17.9), and
|
||||
`voelin-model` as a git package). `CHANGELOG.md` is `main`'s entry
|
||||
(`voelin-ui-vm`); the branch adds none (17.1), and still needs none: nothing
|
||||
of this round is visible to a user.
|
||||
@@ -1960,3 +1962,80 @@ targets included.
|
||||
| `RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p voelin-core --locked` | 1.94 and nightly: clean. |
|
||||
| `Cargo.lock`, `THIRD_PARTY_NOTICES.md` | Unchanged: `git diff c60acf9 -- Cargo.lock Cargo.toml` is empty, so there was nothing to regenerate. |
|
||||
| `scripts/it-smoke.sh ts3 ts6`, on `c60acf9` (before) and at the head (after) | The stack of `VoelinGateWay/dev/docker-compose.yml` as a compose project of its own (`voelin-seam-followups`), the state directory under the scratch directory. On a fresh stack each (`down -v`, `up -d` before each): both pass every per-server scenario of ts3 and ts6 (connect and tree, server and channel chat, voice tone, invisible presence, relay, gateway, history, pins and reactions, the engine's voice features, the TeamSpeak 6 streams), the TeamSpeak session module stage (12 passed, 2 ignored; 16.38 s before, 16.73 s after) and fail in the same place, the engine stage at `ts6_banners` (`live.rs:396`, 5 passed, 1 failed), the failure 17.5 and 17.7 record. Two more runs on the first stack, which was no longer fresh (before, then after), gave the same: the outputs have 100 lines each and differ only in ids, counters, tone ratios and the number of tests filtered out of the module stage (236 before, 240 after: this round's four unit tests). The very first run, on `c60acf9` on the first stack, stopped earlier, at the first gateway request of the admin identity of ts3 (`config_set` not answered, observe stayed `Connecting`); it did not repeat on the fresh stack at `c60acf9`, nor in any later run, and was not chased. |
|
||||
|
||||
### 17.9 The pin moves to the tag `v0.2.0` (`phase4/protocol-pin-v0.2.0`)
|
||||
|
||||
VoelinProtocol released `v0.2.0` on 2026-10-27 (the tag points at `a45c154`;
|
||||
its `README.md`, "Releases", says how a consumer pins, and its `CHANGELOG.md`,
|
||||
"For consumers", what a consumer at the pin of task 34 meets). This round, on
|
||||
`phase4/protocol-pin-v0.2.0` from `0d32ac2`, moves the three entries of
|
||||
`[workspace.dependencies]` (`voelin-identity`, `voelin-proto`, `voelin-model`)
|
||||
from that rev to `tag = "v0.2.0"`, and the `voelin-model` of `spikes/gpui` with
|
||||
them. The `mao-*` agents were not registered in the session, so a
|
||||
general-purpose agent played `mao-implementer`, attempt 1. No history was
|
||||
rewritten.
|
||||
|
||||
| Commit | What |
|
||||
|---|---|
|
||||
| `dccedf2` | `spikes/gpui/Cargo.lock` loses three dependency edges (tokio's `signal-hook-registry` and `tracing`, zbus's `tokio`) and nothing else. It was stale on `main` since `ed49c28` (`voelin-platform`: notify-rust's `z` instead of `z-with-tokio`, which updated the root lock and not this one): `cargo build --locked` in `spikes/gpui` failed there with "cannot update the lock file", before the pin was touched. Separate from the pin so that the pin's own diff to the lock is the three packages. |
|
||||
| `6938dbe` | The pin. Both `Cargo.toml` files, both locks, the two tests of the sign-out, and the two strings that named the old rev. |
|
||||
| the commit of this section | The CHANGELOG line, `docs/building.md`, `docs/ci.md`, `docs/architecture.md`, and the four sentences of this file that named the old rev (the rev is not written in the tree any more; it is in the history of `Cargo.toml`). |
|
||||
|
||||
**The lock.** `cargo update -p voelin-identity -p voelin-proto -p voelin-model`
|
||||
also moved ten edges of the lock that have nothing to do with the protocol
|
||||
(`windows-sys` 0.61.2 to 0.52.0, 0.48.0 and 0.45.0 in seven crates, `itertools`
|
||||
0.14.0 to 0.11.0, `base64` 0.23.1 to 0.22.1, `getrandom` 0.4.3 to 0.3.4; the
|
||||
message of `6938dbe` says eleven, ten is right). The manifests of the three
|
||||
crates are the same at both revisions but for `voelin-model`'s version (0.1.0
|
||||
to 0.2.0), so the lock was edited by hand instead: the `source` of the three
|
||||
packages and that one version, in each of the two locks, and
|
||||
`cargo metadata --locked` accepts both. Each lock has one revision of each
|
||||
crate, and `cargo tree -d` lists no `voelin-*` package twice, in either
|
||||
workspace. The lock's set of third-party packages is the same (only the three
|
||||
protocol packages changed, and `voelin-model`'s version), and
|
||||
`THIRD_PARTY_NOTICES.md` lists third-party packages, so
|
||||
`scripts/notices.sh --check` is clean without a regeneration.
|
||||
|
||||
**What "For consumers" meant here.**
|
||||
|
||||
- `KeyStore::sign_out` lists a device key once. The client never had a test
|
||||
that failed on the double listing: `a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row`
|
||||
(the row of the device key carries a device-only binding, the one case in
|
||||
which the trait listed the key twice, see 17.6) asked `contains`. It counts
|
||||
now: one entry in `unbound` and none in `removed`. A new test,
|
||||
`a_device_key_that_carries_a_binding_is_listed_once_as_deleted_when_it_is_forgotten`,
|
||||
does the same for `Forget` (one entry in `removed`, none in `unbound`; the
|
||||
key used to be in both lists). Both fail with the pin at the old rev (checked
|
||||
by putting `Cargo.toml` and `Cargo.lock` of `main` back for the run: the
|
||||
first sees the key twice in `unbound`, the second once in each list) and pass
|
||||
at the tag. The other sign-out tests passed unchanged.
|
||||
- `Debug` of `Hello`, `Welcome`, `Server`, `Channel`, `Member` and the other
|
||||
messages that `voelin_proto::redact::REDACTED` lists prints `<redacted>` for
|
||||
their secrets. No code or test of the client formats one of those messages
|
||||
with `{:?}` and looks at the text: the only `Debug` text a test inspects is
|
||||
that of the engine's events in
|
||||
`a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`, which
|
||||
looks for pieces of a TeamSpeak key. Nothing to adapt; the full test run
|
||||
below is the evidence.
|
||||
- Every crate is at 0.2.0, `voelin-model` from 0.1.0: visible in the lock only.
|
||||
The conformance suite still has 17 cases (`fake_tests.rs` and `live_tests.rs`
|
||||
name the tag where they named the rev).
|
||||
- The rest of the list is additive and in crates the client does not use.
|
||||
|
||||
**What did not change.** The deploy key, `.gitea/known_hosts`, the CI step that
|
||||
runs `git ls-remote` on the repository, and `deny.toml` (`allow-git` is the
|
||||
URL): Cargo fetches the tag over the same SSH access as it fetched the commit
|
||||
(`git ls-remote` shows the tag as an annotated one, `v0.2.0^{}` being
|
||||
`a45c154`).
|
||||
|
||||
**What ran.** The toolchain of `rust-toolchain.toml` (1.95.0, from the pinned
|
||||
fenix of `spikes/gpui/shell.sh`), on a machine at a load average of about 40.
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `cargo fmt $(scripts/own-crates.sh) -- --check` | clean |
|
||||
| `cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings` | clean |
|
||||
| `cargo test --workspace --locked --no-fail-fast`, under Xvfb with `VOELIN_X11_TEST_DISPLAY` | 1,293 passed, 0 failed, 21 ignored. `voelin-store`: 31 unit tests, `identity_text` 4, `keystore` 57 (56 and the new one); `voelin-core`: 273 and 2 ignored, `session_fake` 20 and 2 ignored, `session_backends` 2; the registry's conformance suite passes 17 of 17 |
|
||||
| `cargo deny --locked --workspace check` (cargo-deny 0.20.2) | advisories, bans, licenses and sources ok; the two warnings, yanked `crypto-bigint` and `clipboard-win`, are of packages this change does not touch |
|
||||
| `scripts/notices.sh --check` | clean, no regeneration |
|
||||
| `spikes/gpui`: `cargo build --locked` and `cargo clippy --locked --all-targets -- -D warnings` (`shell.sh`, 1.95) | both clean |
|
||||
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 157 KiB |
|
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 183 KiB |
|
After Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 95 KiB |
@@ -10,7 +10,9 @@
|
||||
# The workspace depends on the private VoelinProtocol repository, which the
|
||||
# build fetches over SSH with your ssh-agent (`docker build --ssh default`):
|
||||
# the agent must hold a key that can read it (docs/building.md, "Depending on
|
||||
# VoelinProtocol"). The key stays in the agent, never in the image.
|
||||
# VoelinProtocol"). The key stays in the agent, never in the image, and only the
|
||||
# Dockerfile's `cargo fetch` step is given the agent: the build after it is
|
||||
# offline.
|
||||
#
|
||||
# Behind an HTTPS proxy, HTTPS_PROXY/HTTP_PROXY/NO_PROXY are passed on to the
|
||||
# build; a proxy on this machine's loopback is reached with host networking.
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
# GPUI_SHOT_HEADLESS=1 spikes/gpui/shell.sh spikes/gpui/headless.sh -- \
|
||||
# scripts/gpui-shot.sh docs/ui/gpui-swatch-dark.png swatch 1440x960
|
||||
#
|
||||
# Needs xdotool, xwd (x11-apps) and ImageMagick.
|
||||
# Needs xdotool, xwd (x11-apps) and ImageMagick. The screen must be larger
|
||||
# than the window (headless.sh's is 3840x2160; xvfb-run gets twice the window):
|
||||
# on one as large as the window the window manager fits the window and its
|
||||
# frame into the screen, and the picture is smaller than the size asked for.
|
||||
#
|
||||
# Wayland is taken out of the environment (GPUI prefers it, so the window
|
||||
# would open on the desktop), and so are the desktop's session bus and its
|
||||
@@ -25,7 +28,8 @@
|
||||
#
|
||||
# VOELIN_BIN: the binary (default target/release/voelin-gpui, else
|
||||
# target/debug); DELAY: seconds the window is shown before the picture
|
||||
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of
|
||||
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE, VOELIN_DEMO_UI (the sample
|
||||
# servers: a picture of the shell with one on screen) and the other switches of
|
||||
# `src/dev.rs` are passed on as set.
|
||||
set -eu
|
||||
out=${1:?usage: gpui-shot.sh <out.png> [<VOELIN_OPEN> [<width>x<height>]]}
|
||||
@@ -70,7 +74,8 @@ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS
|
||||
"$bin" >"$work/app.log" 2>&1 &
|
||||
pid=$!
|
||||
i=0
|
||||
until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do
|
||||
# The title is the app's name, and ` - <server>` once a server is on screen.
|
||||
until win=$(xdotool search --name '^Voelin( - |$)' 2>/dev/null | head -1) && [ -n "$win" ]; do
|
||||
i=$((i + 1))
|
||||
kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
|
||||
[ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
|
||||
|
||||
@@ -8959,10 +8959,8 @@ dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -9725,7 +9723,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.23.1",
|
||||
@@ -9768,8 +9766,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "voelin-model"
|
||||
version = "0.1.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"serde",
|
||||
@@ -9804,7 +9802,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?tag=v0.2.0#a45c1541b76dcccd23137a357a1e78dfccddc833"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
@@ -11304,7 +11302,6 @@ dependencies = [
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_repr",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uds_windows",
|
||||
"uuid",
|
||||
|
||||
@@ -28,8 +28,8 @@ voelin-core = { path = "../../crates/voelin-core", default-features = false, fea
|
||||
voelin-media = { path = "../../crates/voelin-media", default-features = false, features = ["vpx", "openh264", "ffmpeg", "av1", "x11"] }
|
||||
voelin-platform = { path = "../../crates/voelin-platform", default-features = false, features = ["x11"] }
|
||||
voelin-ui-vm = { path = "../../crates/voelin-ui-vm" }
|
||||
# The revision the root workspace pins (chat messages for voelin-ui-vm).
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# The tag the root workspace pins (chat messages for voelin-ui-vm).
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
|
||||
# Logs of GPUI (the adapter it picked) and of the client's crates.
|
||||
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
|
||||
log = "0.4"
|
||||
|
||||