diff --git a/CHANGELOG.md b/CHANGELOG.md index b6f28d6..b81dcd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,12 @@ All notable changes will be documented here. The format follows [Keep a Changelo - `FAD-0205` XDG desktop-entry snapshots now refresh after debounced filesystem changes, advance a monotonic identity revision, and re-resolve active sessions once through the serialized mixer coordinator. - `FAD-0206` Ordinary `fadrioctl apps` output no longer exposes process IDs; raw process and node details live in the explicit advanced inspector. - `REL-00003` Visible XDG launchers now take precedence over hidden helpers when both have strong executable evidence; common `-bin` runtime names can match their launcher executable. +- `FAD-0503` Active mixer rows sort deterministically and stay in place during pointer/keyboard volume gestures; backend echoes cannot overwrite an active drag. +- `FAD-0503` Volume and mute commands run off the UI thread with bounded pending state, visible failure feedback, and queued-command discard on disconnect. Connected-empty and reconnecting states have distinct messages. + +### Fixed + +- `BUG-00003` Incremental PipeWire property updates no longer erase application identity and disable an active mixer slider. ## [0.2.0-alpha.2] - 2026-09-13 diff --git a/ROADMAP.md b/ROADMAP.md index 889161e..8413e22 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -181,10 +181,19 @@ Canonical ticket format: - [x] `FAD-0501` `P0` Connect immutable mixer snapshots and commands to the Avalonia view models. - [ ] `FAD-0502` `P1` Build accessible output and logical-application rows with mixed-volume state. -- [ ] `FAD-0503` `P1` Add stable sorting, interaction freeze, empty, unavailable, and reconnect states. +- [x] `FAD-0503` `P1` Add stable sorting, interaction freeze, empty, unavailable, and reconnect states. + - Scope: Deterministic active-row ordering and pointer/keyboard interaction freeze; connected-empty versus unavailable states and reconnect-safe commands. Persistent pinned/inactive rows remain FAD-0303. + - Acceptance: Rows are reused, structural changes wait until gesture end, removed targets disable immediately, queued commands are discarded on disconnect, and rendered controls recover after an isolated daemon restart. + - Evidence: `docs/development/qualifying-ui-interactions.md`; full host-font startup remains separately tracked by BUG-00004, and REL-00006 is still open. - [ ] `FAD-0504` `P1` Implement tray popup, single-instance activation, and clean shutdown. - [ ] `FAD-0505` `P0` Establish localization resources, keyboard navigation, screen-reader labels, and scaling tests. - [ ] `REL-00006` `P0` Qualify the mixer on GNOME/KDE Wayland and X11 at supported scale factors. +- [x] `BUG-00003` `P0` Preserve application metadata across incremental PipeWire node updates. + - Scope: Merge supplied node-info properties without erasing omitted identity fields; honor explicit replacements and removals. + - Acceptance: Native delta fixtures retain application identity and process evidence, and a rendered slider drag keeps controlling the same logical application. +- [ ] `BUG-00004` `P0` Diagnose Avalonia startup stalls with the full host font configuration. + - Scope: Trace font initialization on the affected desktop without changing the user's font installation or silently forcing a restricted font set. + - Acceptance: The normal launch reaches the mixer with the default host Fontconfig configuration, with reproducible startup evidence. ## 0.6 — MIDI controllers @@ -239,5 +248,5 @@ Canonical ticket format: - Next `FAD-08xx`: `FAD-0806` - Next `FAD-09xx`: `FAD-0905` - Next `FAD-10xx`: `FAD-1005` -- Next `BUG`: `BUG-00003` +- Next `BUG`: `BUG-00005` - Next `REL`: `REL-00012` diff --git a/docs/development/qualifying-ui-interactions.md b/docs/development/qualifying-ui-interactions.md new file mode 100644 index 0000000..2068f0b --- /dev/null +++ b/docs/development/qualifying-ui-interactions.md @@ -0,0 +1,44 @@ +# FAD-0503 interaction qualification + +Recorded on 2026-09-27. This is an interaction slice, not completion of the production UI or `REL-00006` desktop matrix. + +## Implemented behavior + +Active logical applications sort audible-first, then by display name and canonical identity. Existing row objects are reused. While a volume pointer or keyboard gesture is active, collection insertions, removals and moves wait until the gesture ends. Missing targets disable immediately; their queued commands are discarded. Backend volume echoes do not move the thumb during a gesture. Persistent pinned/remembered inactive rows and their grace period belong to `FAD-0303` and are not implemented here. + +Volume and mute each have at most one in-flight command and one latest pending value per row. Native round trips run off the Avalonia thread. The native lifecycle gate prevents command/dispose overlap from accessing a destroyed context. Failed commands show a generic row message and restore observed state; disconnect clears pending intent rather than replaying it after reconnect. + +`BUG-00003` was found through the rendered drag: the first volume change caused a partial node-info property update to erase application identity, disabling the row. The bridge now preserves omitted metadata and honors supplied replacements/removals. A private native fixture covers delta, replacement, removal and PID parsing behavior. + +## Local evidence + +- `FADRIO_RUN_PIPEWIRE_INTEGRATION=1 ./scripts/test.sh`: managed tests, two native tests and isolated stream/restart integration passed. +- `dotnet test tests/Fadrio.UI.Tests --no-restore`: 16 interaction/presentation tests passed, including property notifications, sorting, row reuse, freeze, disappearance, command coalescing, disconnect discard and failure rollback. +- `dotnet format Fadrio.slnx --verify-no-changes --no-restore`, roadmap audit and whitespace check passed. +- Local ASAN/UBSAN build: both native tests and the isolated PipeWire command/churn/restart harness passed with fatal sanitizer errors enabled and mixed-runtime leak detection disabled. These are local results, not remote CI qualification. +- Actual Avalonia window on GNOME Wayland through XWayland, 360 x 680, isolated silent playback: drag reached 37%, Home plus ten Right keys reached 10%, and the mute button muted the stream. Stopping the private PipeWire daemon during another active drag caused no crash; the same controls worked again after restarting the daemon and creating a fresh stream. +- The rendered unavailable and connected-empty states were inspected, as was the recovered row. No ordinary host audio was modified. + +![Recovered fixture at 10 percent, muted](../screenshots/fad-0503-recovered-fixture.png) + +![Connected with no playback applications](../screenshots/fad-0503-connected-empty.png) + +![Audio unavailable and reconnecting](../screenshots/fad-0503-reconnecting.png) + +## Reproduce the rendered check + +After a normal local build, close other Fadrio windows and run: + +```bash +./scripts/test-ui-interactions.sh +``` + +This optional developer harness requires an X11/XWayland display, DejaVu fonts, X11/XTest libraries, `xwininfo`, `xprop`, `ffmpeg`, PipeWire tools, Python and .NET. It injects mouse/keyboard events into the exact Fadrio window whose process ownership it verifies. Do not interact with the desktop while it runs. It restores the prior pointer/focus and terminates only its owned processes. Its private runtime/data/cache directory is retained with logs and screenshots; the path is printed at exit. It is not part of headless CI or the supported-desktop matrix. + +The fixture intentionally sets a process-local minimal Fontconfig configuration. It does not change host fonts or ship a restricted-font workaround in the app. + +## Open qualification limits + +- `BUG-00004`: normal launch with this host's full Fontconfig configuration stalled before `App.Initialize`, consuming a CPU core. The startup trace showed font/cache enumeration. A restricted process-local DejaVu configuration allowed the window to open; a software-rendering attempt did not resolve normal startup. This isolates a useful investigation path, not a proven upstream cause or a production fix. Default host-font startup is unqualified. +- The checks above are XWayland, not native Wayland, KDE, screen-reader, fractional-scaling, packaged installation or long-running qualification. Those gates remain open. +- Output control, icons, persistence of pinned/inactive rows, tray integration and localization are still later roadmap work. No new release is justified by this slice alone. diff --git a/docs/development/testing.md b/docs/development/testing.md index 8b89658..e26faf3 100644 --- a/docs/development/testing.md +++ b/docs/development/testing.md @@ -15,3 +15,4 @@ The opt-in isolated PipeWire test is enabled with `FADRIO_RUN_PIPEWIRE_INTEGRATI Browser qualification evidence and its reproducible checklist are documented in [qualifying-browser.md](qualifying-browser.md). PipeWire restart and command-recovery evidence is documented in [qualifying-reconnect.md](qualifying-reconnect.md). Native ownership and sanitizer coverage is documented in [native-sanitizers.md](native-sanitizers.md). +Rendered mixer gesture/reconnect evidence and the opt-in desktop test are documented in [qualifying-ui-interactions.md](qualifying-ui-interactions.md). That check uses process-local fixture fonts; it does not qualify the separately tracked full-host-font startup issue. diff --git a/docs/screenshots/fad-0503-connected-empty.png b/docs/screenshots/fad-0503-connected-empty.png new file mode 100644 index 0000000..9d3dc6a Binary files /dev/null and b/docs/screenshots/fad-0503-connected-empty.png differ diff --git a/docs/screenshots/fad-0503-reconnecting.png b/docs/screenshots/fad-0503-reconnecting.png new file mode 100644 index 0000000..2b0db3f Binary files /dev/null and b/docs/screenshots/fad-0503-reconnecting.png differ diff --git a/docs/screenshots/fad-0503-recovered-fixture.png b/docs/screenshots/fad-0503-recovered-fixture.png new file mode 100644 index 0000000..7f4cf34 Binary files /dev/null and b/docs/screenshots/fad-0503-recovered-fixture.png differ diff --git a/scripts/test-ui-interactions.sh b/scripts/test-ui-interactions.sh new file mode 100755 index 0000000..ea43c2f --- /dev/null +++ b/scripts/test-ui-interactions.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +set -euo pipefail +repository_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repository_root" +for command in xwininfo xprop ffmpeg pipewire pw-cat dotnet rg python3; do + command -v "$command" >/dev/null 2>&1 || { echo "Missing $command" >&2; exit 77; } +done +[[ -n "${DISPLAY:-}" ]] || { echo 'An X11/XWayland display is required.' >&2; exit 77; } +if xwininfo -root -tree | rg '"Fadrio"' >/dev/null; then + echo 'Close the existing Fadrio test window before running.' >&2 + exit 1 +fi +fadrio_fixture_dir=$(mktemp -d -t fadrio-gesture-XXXXXX) +fadrio_fixture_pipewire_pid="" +fadrio_fixture_stream_pid="" +fadrio_fixture_ui_pid="" +cleanup() { + for fadrio_fixture_pid in "$fadrio_fixture_ui_pid" "$fadrio_fixture_stream_pid" "$fadrio_fixture_pipewire_pid"; do + if [[ -n "$fadrio_fixture_pid" ]]; then kill "$fadrio_fixture_pid" 2>/dev/null || true; fi + done + wait 2>/dev/null || true + printf 'fixture_dir=%s\n' "$fadrio_fixture_dir" +} +trap cleanup EXIT INT TERM +export XDG_RUNTIME_DIR="$fadrio_fixture_dir" +export PIPEWIRE_RUNTIME_DIR="$fadrio_fixture_dir" +export PIPEWIRE_REMOTE=pipewire-0 +export XDG_DATA_HOME="$fadrio_fixture_dir/share" +export XDG_CACHE_HOME="$fadrio_fixture_dir/cache" +export FONTCONFIG_FILE="$repository_root/tests/fixtures/fonts/ui-test-fontconfig.conf" +export LD_LIBRARY_PATH="$PWD/build/native" +pipewire -c "$PWD/tests/fixtures/pipewire/fadrio-test.conf" >"$fadrio_fixture_dir/pipewire.log" 2>&1 & +fadrio_fixture_pipewire_pid=$! +for _ in {1..100}; do + [[ -S "$fadrio_fixture_dir/pipewire-0" ]] && break + sleep .05 +done +[[ -S "$fadrio_fixture_dir/pipewire-0" ]] +pw-cat --playback --target 0 --rate 48000 --channels 2 --format s16 \ + -P '{ application.name = "Fadrio Fixture" application.id = "dev.fglabs.Fadrio.UiFixture" }' \ + - "$fadrio_fixture_dir/stream.log" 2>&1 & +fadrio_fixture_stream_pid=$! +env -u WAYLAND_DISPLAY dotnet "$PWD/src/Fadrio.UI/bin/Debug/net10.0/fadrio.dll" >"$fadrio_fixture_dir/ui.log" 2>&1 & +fadrio_fixture_ui_pid=$! +fadrio_fixture_window="" +for _ in {1..100}; do + fadrio_fixture_window=$(xwininfo -root -tree | awk '/"Fadrio"/ && !/mutter/ {if (!found) print $1; found=1}') + [[ -n "$fadrio_fixture_window" ]] && break + sleep .1 +done +[[ -n "$fadrio_fixture_window" ]] +xprop -id "$fadrio_fixture_window" _NET_WM_PID | rg -F "= $fadrio_fixture_ui_pid" >/dev/null +sleep 1 +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/before.png" +python3 "$repository_root/scripts/ui-interaction-probe.py" "$fadrio_fixture_window" "$PWD" +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/mixer.png" +kill -0 "$fadrio_fixture_ui_pid" +python3 "$repository_root/scripts/ui-interaction-probe.py" "$fadrio_fixture_window" "$PWD" "$fadrio_fixture_pipewire_pid" +wait "$fadrio_fixture_pipewire_pid" 2>/dev/null || true +fadrio_fixture_pipewire_pid="" +wait "$fadrio_fixture_stream_pid" 2>/dev/null || true +fadrio_fixture_stream_pid="" +sleep 1 +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/reconnecting.png" +pipewire -c "$PWD/tests/fixtures/pipewire/fadrio-test.conf" >>"$fadrio_fixture_dir/pipewire.log" 2>&1 & +fadrio_fixture_pipewire_pid=$! +for _ in {1..100}; do + [[ -S "$fadrio_fixture_dir/pipewire-0" ]] && break + sleep .05 +done +sleep 3 +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/empty.png" +pw-cat --playback --target 0 --rate 48000 --channels 2 --format s16 \ + -P '{ application.name = "Fadrio Fixture" application.id = "dev.fglabs.Fadrio.UiFixture" }' \ + - >"$fadrio_fixture_dir/stream.log" 2>&1 & +fadrio_fixture_stream_pid=$! +sleep 2 +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/recovered-before.png" +python3 "$repository_root/scripts/ui-interaction-probe.py" "$fadrio_fixture_window" "$PWD" +ffmpeg -hide_banner -loglevel error -f x11grab -window_id "$fadrio_fixture_window" \ + -video_size 360x680 -i "$DISPLAY" -frames:v 1 "$fadrio_fixture_dir/recovered.png" +kill -0 "$fadrio_fixture_ui_pid" diff --git a/scripts/ui-interaction-probe.py b/scripts/ui-interaction-probe.py new file mode 100644 index 0000000..5512350 --- /dev/null +++ b/scripts/ui-interaction-probe.py @@ -0,0 +1,107 @@ +import ctypes as c +import os +import re +import signal +import subprocess +import sys +import time + +window = int(sys.argv[1], 16) +root_path = sys.argv[2] +x = c.CDLL('libX11.so.6') +t = c.CDLL('libXtst.so.6') +x.XOpenDisplay.restype = c.c_void_p +x.XDefaultRootWindow.argtypes = [c.c_void_p] +x.XDefaultRootWindow.restype = c.c_ulong +x.XGetInputFocus.argtypes = [c.c_void_p, c.POINTER(c.c_ulong), c.POINTER(c.c_int)] +x.XSetInputFocus.argtypes = [c.c_void_p, c.c_ulong, c.c_int, c.c_ulong] +x.XRaiseWindow.argtypes = [c.c_void_p, c.c_ulong] +x.XFlush.argtypes = [c.c_void_p] +x.XCloseDisplay.argtypes = [c.c_void_p] +x.XTranslateCoordinates.argtypes = [c.c_void_p, c.c_ulong, c.c_ulong, c.c_int, c.c_int, c.POINTER(c.c_int), c.POINTER(c.c_int), c.POINTER(c.c_ulong)] +x.XStringToKeysym.argtypes = [c.c_char_p] +x.XStringToKeysym.restype = c.c_ulong +x.XKeysymToKeycode.argtypes = [c.c_void_p, c.c_ulong] +x.XKeysymToKeycode.restype = c.c_uint +x.XQueryPointer.argtypes = [c.c_void_p, c.c_ulong, c.POINTER(c.c_ulong), c.POINTER(c.c_ulong), c.POINTER(c.c_int), c.POINTER(c.c_int), c.POINTER(c.c_int), c.POINTER(c.c_int), c.POINTER(c.c_uint)] +t.XTestFakeMotionEvent.argtypes = [c.c_void_p, c.c_int, c.c_int, c.c_int, c.c_ulong] +t.XTestFakeButtonEvent.argtypes = [c.c_void_p, c.c_uint, c.c_int, c.c_ulong] +t.XTestFakeKeyEvent.argtypes = [c.c_void_p, c.c_uint, c.c_int, c.c_ulong] +d = x.XOpenDisplay(None) +assert d, 'No X11 display' +root = x.XDefaultRootWindow(d) +old_focus, revert = c.c_ulong(), c.c_int() +x.XGetInputFocus(d, c.byref(old_focus), c.byref(revert)) +root_ret, child = c.c_ulong(), c.c_ulong() +old_x, old_y, win_x, win_y, mask = c.c_int(), c.c_int(), c.c_int(), c.c_int(), c.c_uint() +x.XQueryPointer(d, root, c.byref(root_ret), c.byref(child), c.byref(old_x), c.byref(old_y), c.byref(win_x), c.byref(win_y), c.byref(mask)) +origin_x, origin_y = c.c_int(), c.c_int() +x.XTranslateCoordinates(d, window, root, 0, 0, c.byref(origin_x), c.byref(origin_y), c.byref(child)) + +def move(px, py): + t.XTestFakeMotionEvent(d, -1, origin_x.value + px, origin_y.value + py, 0) + x.XFlush(d) + time.sleep(.08) + +def button(down): + t.XTestFakeButtonEvent(d, 1, down, 0) + x.XFlush(d) + time.sleep(.08) + +def key(name): + code = x.XKeysymToKeycode(d, x.XStringToKeysym(name.encode())) + t.XTestFakeKeyEvent(d, code, 1, 0) + t.XTestFakeKeyEvent(d, code, 0, 0) + x.XFlush(d) + time.sleep(.08) + +def state(): + output = subprocess.check_output(['dotnet', root_path + '/src/Fadrio.Cli/bin/Debug/net10.0/fadrioctl.dll', 'apps'], text=True) + assert 'Application: Fadrio Fixture' in output, output + return int(re.search(r'Volume: (\d+)%', output)[1]), 'Muted: true' in output + +try: + x.XRaiseWindow(d, window) + x.XSetInputFocus(d, window, 2, 0) + x.XFlush(d) + time.sleep(.5) + x.XTranslateCoordinates(d, window, root, 0, 0, c.byref(origin_x), c.byref(origin_y), c.byref(child)) + if len(sys.argv) > 3: + # The shell passes only its own isolated daemon PID. + move(73, 281) + button(1) + move(100, 281) + os.kill(int(sys.argv[3]), signal.SIGTERM) + time.sleep(1) + move(146, 281) + button(0) + print('Disconnected the isolated daemon during an active drag', flush=True) + sys.exit(0) + assert state()[0] == 100 + move(314, 281) + button(1) + for px in [290, 265, 240, 215, 190, 165, 146]: move(px, 281) + button(0) + volume, muted = state() + assert 35 <= volume <= 45, (volume, muted) + print('Rendered slider drag reached', volume, 'percent', flush=True) + # Reassert focus after the separate CLI probe; the desktop may redirect it. + x.XSetInputFocus(d, window, 2, 0) + x.XFlush(d) + time.sleep(.15) + key('Home') + for _ in range(10): key('Right') + volume, muted = state() + assert volume == 10, (volume, muted) + print('Keyboard Home + ten Right keys reached 10 percent', flush=True) + move(62, 327) + button(1) + button(0) + assert state()[1] + print('Rendered mute button muted the isolated stream', flush=True) +finally: + t.XTestFakeButtonEvent(d, 1, 0, 0) + t.XTestFakeMotionEvent(d, -1, old_x.value, old_y.value, 0) + if old_focus.value > 1: x.XSetInputFocus(d, old_focus.value, revert.value, 0) + x.XFlush(d) + x.XCloseDisplay(d) diff --git a/src/Fadrio.NativeInterop/NativeAudioBackend.cs b/src/Fadrio.NativeInterop/NativeAudioBackend.cs index 1f3d7d6..5d2ba63 100644 --- a/src/Fadrio.NativeInterop/NativeAudioBackend.cs +++ b/src/Fadrio.NativeInterop/NativeAudioBackend.cs @@ -13,6 +13,7 @@ public sealed class NativeAudioBackend : IAudioBackend private IntPtr _context; private bool _started; private bool _disposed; + private readonly object _lifecycleGate = new(); public NativeAudioBackend() { @@ -47,42 +48,54 @@ public ValueTask SetStreamVolumeAsync(uint nodeId, float volume, CancellationTok cancellationToken.ThrowIfCancellationRequested(); ArgumentOutOfRangeException.ThrowIfLessThan(volume, 0f); ArgumentOutOfRangeException.ThrowIfGreaterThan(volume, 1f); - ThrowOnNativeError(NativeMethods.vm_set_stream_volume(_context, nodeId, volume), "set stream volume"); + lock (_lifecycleGate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + ThrowOnNativeError(NativeMethods.vm_set_stream_volume(_context, nodeId, volume), "set stream volume"); + } return ValueTask.CompletedTask; } public ValueTask SetStreamMuteAsync(uint nodeId, bool muted, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - ThrowOnNativeError(NativeMethods.vm_set_stream_mute(_context, nodeId, muted ? (byte)1 : (byte)0), "set stream mute"); + lock (_lifecycleGate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + ThrowOnNativeError(NativeMethods.vm_set_stream_mute(_context, nodeId, muted ? (byte)1 : (byte)0), "set stream mute"); + } return ValueTask.CompletedTask; } public ValueTask DisposeAsync() { - if (!_disposed) + lock (_lifecycleGate) { - _disposed = true; - if (_context != IntPtr.Zero) + if (!_disposed) { - NativeMethods.vm_stop(_context); - NativeMethods.vm_context_destroy(_context); - _context = IntPtr.Zero; + _disposed = true; + if (_context != IntPtr.Zero) + { + NativeMethods.vm_stop(_context); + NativeMethods.vm_context_destroy(_context); + _context = IntPtr.Zero; + } + _events.Writer.TryComplete(); + GC.KeepAlive(_callback); } - _events.Writer.TryComplete(); - GC.KeepAlive(_callback); } return ValueTask.CompletedTask; } private void Start() { - if (_started) + lock (_lifecycleGate) { - return; + ObjectDisposedException.ThrowIf(_disposed, this); + if (_started) return; + ThrowOnNativeError(NativeMethods.vm_start(_context), "connect to PipeWire"); + _started = true; } - ThrowOnNativeError(NativeMethods.vm_start(_context), "connect to PipeWire"); - _started = true; } private void OnNativeEvent(IntPtr nativeEventPointer, IntPtr userData) diff --git a/src/Fadrio.UI/Controls/ApplicationVolumeSlider.cs b/src/Fadrio.UI/Controls/ApplicationVolumeSlider.cs new file mode 100644 index 0000000..06c26af --- /dev/null +++ b/src/Fadrio.UI/Controls/ApplicationVolumeSlider.cs @@ -0,0 +1,75 @@ +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Fadrio.UI.ViewModels; + +namespace Fadrio.UI.Controls; + +// Presentation-only gesture adapter. Audio commands remain in the view model. +public sealed class ApplicationVolumeSlider : Slider +{ + private readonly HashSet _pressedKeys = []; + private ApplicationRowViewModel? _interactionRow; + private bool _pointerActive; + + public ApplicationVolumeSlider() + { + AddHandler(PointerPressedEvent, (_, args) => + { + if (!args.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; + Focus(); + _pointerActive = true; + Begin(); + }, RoutingStrategies.Tunnel, handledEventsToo: true); + AddHandler(PointerReleasedEvent, (_, _) => EndPointer(), RoutingStrategies.Tunnel, handledEventsToo: true); + AddHandler(PointerCaptureLostEvent, (_, _) => EndPointer(), RoutingStrategies.Bubble, handledEventsToo: true); + AddHandler(KeyDownEvent, (_, args) => + { + if (!IsVolumeKey(args.Key)) return; + _pressedKeys.Add(args.Key); + Begin(); + }, RoutingStrategies.Tunnel, handledEventsToo: true); + AddHandler(KeyUpEvent, (_, args) => + { + _pressedKeys.Remove(args.Key); + EndIfIdle(); + }, RoutingStrategies.Tunnel, handledEventsToo: true); + LostFocus += (_, _) => + { + _pressedKeys.Clear(); + EndIfIdle(); + }; + DetachedFromVisualTree += (_, _) => + { + _pointerActive = false; + _pressedKeys.Clear(); + EndIfIdle(); + }; + } + + protected override Type StyleKeyOverride => typeof(Slider); + + private void Begin() + { + if (_interactionRow is not null || !IsEnabled) return; + _interactionRow = DataContext as ApplicationRowViewModel; + _interactionRow?.BeginInteraction(); + } + + private void EndPointer() + { + _pointerActive = false; + EndIfIdle(); + } + + private void EndIfIdle() + { + if (_pointerActive || _pressedKeys.Count > 0) return; + ApplicationRowViewModel? row = _interactionRow; + _interactionRow = null; + row?.EndInteraction(); + } + + private static bool IsVolumeKey(Key key) => key is + Key.Left or Key.Right or Key.Up or Key.Down or Key.Home or Key.End or Key.PageUp or Key.PageDown; +} diff --git a/src/Fadrio.UI/MainWindow.axaml b/src/Fadrio.UI/MainWindow.axaml index 4bf7450..b4513e3 100644 --- a/src/Fadrio.UI/MainWindow.axaml +++ b/src/Fadrio.UI/MainWindow.axaml @@ -1,6 +1,7 @@ -