diff --git a/I38.md b/I38.md index 8307545..6db2deb 100644 --- a/I38.md +++ b/I38.md @@ -247,8 +247,7 @@ configuration, saved stream settings and supported server settings. Per-channel volumes can be linked or adjusted separately. Measure level reports a numeric peak on demand. Details contains selectable device and application information. -See [Sound Manager features and testing](docs/sound-manager.md) for advanced -controls and server-specific limitations. For an existing installation, copy +For an existing installation, copy the updated scripts with `./i38.sh -u`, regenerate the configuration and run `i3-msg reload` to add its binding. @@ -430,6 +429,8 @@ Enter Ratpoison Mode with `@RATPOISONKEY@`, then press `Control` + `Alt` + `d`. The **Shortcut name** edit box contains a suggested name. For a web link, I38 looks up the page title, using the hostname if the title is unavailable. Edit the name if desired, then press **Create Shortcut** to confirm. Nothing is written until you confirm, and a late page title never replaces your edits. Use **Run program in a terminal** for command-line programs. Folders open in your selected file manager; files and web links use their default applications. Application shortcuts preserve the original launcher settings and require that original launcher to remain available. Repeated names receive numbered filenames. Deleting a created shortcut removes only the shortcut. +Windows `.exe` programs run with Wine, which must be installed, using the program's folder as the working directory. The creator suggests the Wine prefix (bottle) that contains the program, or your existing `~/.wine` prefix. Review or change the suggested **Wine prefix (bottle) folder**; if none is found, enter or browse for the existing prefix before creating the shortcut. + ### Desktop navigation I38 uses minimal window decorations. Windows do not use the usual title bars with minimize and maximize buttons. Instead, windows fill their available space automatically, and most interactions are performed through keyboard shortcuts. diff --git a/README.md b/README.md index e149a21..e0edd1b 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ # I38 -Accessibility setup script for the i3 window manager. +Accessibility setup script for the i3 window manager. I38 generates an i3 configuration designed for blind and low vision users, along with a set of accessible tools for everyday desktop tasks. -## i38.sh Released under the terms of the GPL License Version 3: https://www.gnu.org/licenses/ + This is a Stormux project: https://stormux.org +Complete usage instructions and keybindings are in the I38 guide, which opens in your web browser on first login and with Mod+Shift+F1 (Alt or Super, depending on your settings). This README covers installation, configuration, and an overview for contributors. + ## Why the name? @@ -31,214 +33,128 @@ Required for the setup script and generated I38 configuration: Optional features use these packages when installed: -- acpi: [optional] for battery status. It will still work even without this package, but uses it if it is installed. Required for the battery monitor with sound alerts. -- bc: For the information panel. -- dex: [optional] Alternative method for auto starting applications. -- libnotify: For sending notifications -- magic-wormhole: [optional] for file sharing with magic-wormhole GUI -- notification-daemon: To handle notifications -- networkmanager: [optional] for the Network panel, including libnm's GObject introspection data. -- pamixer: for the mute-unmute script -- python-pulsectl: [optional] for I38 Sound Manager. Requires GTK3 and a running PulseAudio server or PipeWire with pipewire-pulse. PulseAudio client tools (`pactl` 16 or newer) enable advanced controls. -- pcmanfm: [optional] Graphical file manager. -- playerctl: music controls -- python-pillow: For OCR -- python-pytesseract: For OCR -- python-pyudev: [optional] for USB connection and removal alerts. -- remind: [optional] For reminder notifications, Requires notify-daemon and notify-send for automatic reminders. -- scrot: For OCR -- sox: for sounds. -- speech-dispatcher: [optional] provides `spd-say` for spoken USB alerts and other I38 announcements. -- tesseract: For OCR -- xprintidle: [optional] For screen lock autolock on X11/i3 -- i38lock: [optional] Secure accessible screen locker. On Stormux, install it from the repository. It requires Cthulhu or Orca 50 or newer for screen reader feedback. -- tesseract-data-eng: For OCR -- udiskie: [optional] for automatically mounting removable storage -- x11bell: [optional] Bell support if you do not have a PC speaker. Available from https://github.com/jovanlanik/x11bell -- xbacklight: [optional] for screen brightness adjustment -- xclip: Clipboard support -- xfce4-notifyd: For sending notifications. Replaces notification-daemon -- xorg-setxkbmap: [optional] for multiple keyboard layouts -- xzoom: [optional] lightweight X11 magnifier bound by I38 when installed +- acpi: For battery status. Battery status works without it, but the battery monitor with sound alerts requires it. +- bc: For the system information panel. +- dex: Alternative method for auto starting applications. +- i38lock: Secure accessible screen locker, packaged in the Stormux repository and available at https://git.stormux.org/storm/i38lock. It requires Cthulhu or Orca 50 or newer for screen reader feedback. +- libnotify: For sending notifications. +- magic-wormhole: For file sharing with the Magic Wormhole panel. +- networkmanager: For the network panel. Requires NetworkManager/libnm 1.30 or newer and its `NM-1.0` GObject introspection data. +- notification-daemon or xfce4-notifyd: To display notifications. xfce4-notifyd is used when both are installed. +- pamixer: For the mute and unmute script. +- pcmanfm: Graphical file manager. +- playerctl: For music controls. +- python-pillow, python-pytesseract, scrot, tesseract, and tesseract-data-eng: For OCR. +- python-pulsectl: For I38 Sound Manager. Requires GTK3 and a running PulseAudio server, or PipeWire with pipewire-pulse. PulseAudio client tools (`pactl` 16 or newer) enable advanced controls. +- python-pyudev: For USB connection and removal alerts. +- remind: For reminder notifications. Automatic reminders also require a notification daemon and notify-send. +- sox: For sounds. +- speech-dispatcher: Provides `spd-say` for I38's spoken announcements, such as USB alerts, OCR, and configuration reloads. +- udiskie: For automatically mounting removable storage. +- x11bell: Bell support if you do not have a PC speaker. Available from https://github.com/jovanlanik/x11bell +- xbacklight: For screen brightness adjustment. +- xclip: For clipboard support. +- xorg-setxkbmap: For multiple keyboard layouts. +- xprintidle: For screen lock autolock. +- xzoom: Lightweight magnifier, bound by I38 when installed. ### AI Assistant (Optional) -- python-requests: For Ollama integration -- claude: [optional] Claude Code CLI for Claude AI integration. Install from https://claude.ai/code -- ollama: [optional] Local AI models. Install from https://ollama.ai + +- claude: Claude Code CLI for Claude AI integration. Install from https://claude.ai/code +- ollama: Local AI models. Install from https://ollama.ai +- python-requests: For Ollama integration. ### Voice Mode (Optional) -- python-speechrecognition: For voice input recognition -- python-pyaudio: For audio recording -- pocketsphinx: [optional] For offline speech recognition fallback -- flac: [optional] For better audio encoding in speech recognition -I38 will try to detect your browser, file manager, and text editor and present you with a list of options to bind to their launch keys. It will also create bindings for pidgin and mumble if they are installed. Additionally, you can now add custom applications with your own keybindings during the setup process. To use the bindings, press your ratpoison mode key which is set when you run the i38.sh script. Next, press the binding for the application you want; w for web browser, e for text editor, f for file manager, m for mumble, etc. To learn all the bindings, find and read the mode ratpoison section of ~/.config/i3/config or use the help binding key, alt or super depending on your settings with Shift+F1. +- python-speechrecognition: For voice input recognition. +- python-pyaudio: For audio recording. +- pocketsphinx: Offline speech recognition fallback. +- flac: Better audio encoding for speech recognition. -Ratpoison mode is now enabled by default for better accessibility and ease of use. +### Dependency Helpers -During setup, the screen reader picker includes Cthulhu, Orca, and None. If no supported screen reader is installed, I38 assumes None and skips screen-reader startup. Setup also asks for the generated i3 window-title font size, defaulting to 12. I38 applies a larger mouse cursor size at startup when xrdb is available. If xzoom is installed when the i3 config is generated, I38 binds it as a lightweight magnifier. I38 also includes a keybinding to move the mouse pointer to the center of the focused window. - -During setup, I38 can configure one screen lock method. The legacy I38 PIN lock is a privacy screen only. I38Lock is a true PAM-backed screen locker, available at https://git.stormux.org/storm/i38lock and packaged in the Stormux repository. I38 offers I38Lock only when `i38lock` is installed and the screen-reader setup can support it: Cthulhu, or Orca 50 or newer. I38 does not enable the PIN lock and I38Lock at the same time. - -## I38 Sound Manager - -Run `python3 scripts/sound_manager.py`, or use `v` in Panel Mode after -regenerating the I38 configuration. The single Python 3.6-compatible script -provides native GTK3 controls for playback, recording, devices, profiles, -channel volumes, routing and saved stream settings. Its backend supports -PulseAudio and PipeWire through pipewire-pulse. - -See [Sound Manager features and testing](docs/sound-manager.md) for advanced -controls, server limitations, keyboard use and the live accessibility checks -that remain necessary before claiming full accessibility. - -## Screen reader announcements - -I38 leaves workspace-switch and window-workspace-move speech to Cthulhu when -its native session-bus service is running on the current X display. Detection -runs for each announcement, so switching to Orca or stopping Cthulhu restores -I38's speech immediately. Installation or saved screen-reader preferences alone -do not suppress speech; an unavailable bus or unreadable process also leaves -I38 speech enabled. - -Workspace and mode sounds remain enabled as configured. I38's mode feedback is -sound only; Cthulhu supplies its own mode speech. Battery, USB, OCR, brightness, -keyboard-layout, and other I38-specific announcements continue as before. -Keep Cthulhu's Reading choices “Announce i3 workspaces” and “Announce i3 window -workspace moves” enabled for its replacement speech. Turning those choices off -leaves those events silent while Cthulhu is active. - -For an existing installation, run `./i38.sh -u` to copy the updated workspace -script and shared helper. Regenerate the I38 configuration and run -`i3-msg reload` to update window-move bindings too; copying scripts alone does -not change those bindings. Custom bindings which invoke `spd-say` directly need -to use `scripts/announce_i3.py` for overlapping i3 speech. - -Run `python3 -B -m unittest discover -s tests -v` for automated checks. After -reviewing the diff and updating the installation, use Control+F1/F2 to switch -workspaces and Control+Shift+F1/F2 to move an expendable window. With Cthulhu, -expect its native speech once per real change and the usual I38 sounds. Switch -to Orca and repeat: expect I38 workspace and move speech. Switch back without -regenerating and confirm duplicate speech stops. Enter/leave Ratpoison, Panel, -Personal (if configured), and Bypass modes; check existing mode sounds and -Cthulhu's native mode speech. Also check battery status, OCR, and USB alerts if -enabled. Automated checks do not prove audible output or physical key behavior. - -## Network Panel (Optional) - -Press Control+Alt+Tab, then Shift+N to open the accessible wired/Wi-Fi panel. -It requires NetworkManager/libnm 1.30 or newer and its `NM-1.0` introspection -data, plus I38's existing Python/PyGObject/GTK 3 dependencies. On Stormux, -connection management requires membership in `network` in the current session -and an appropriate polkit policy. The GUI never elevates or requests an -administrator password. If permissions or its process-specific protection -against authentication prompts are unavailable, it remains usable for viewing -connection information. No group membership or policy is changed by the panel. - -Try the source directly before updating your installation: +Distro-specific dependency helpers live in `extra/`. On Arch Linux, run: ```bash -python3 -B scripts/network.py +extra/arch-linux.sh ``` -Use the arrows to select a connection; Tab to Connect, Disconnect, Refresh, -Details, or Close. Selection alone does not connect or disconnect. Type a -case-insensitive name prefix to filter. Escape clears the filter, then closes -the window. Nearby access points with the same SSID and security are combined -per adapter, while distinct saved profiles remain selectable. Existing rows -retain their order and selection when scans change. Signal strength is available -in Details; fluctuations do not rewrite the focused row. +The helper checks I38's required packages, asks which missing provider applications to install, adds lightweight optional feature packages, then installs the selected package list at the end. Optional packages that need manual choice, such as Tesseract language data, are skipped. -New personal Wi-Fi networks use an accessible GTK password dialog. Remember -password saves through NetworkManager with the system-wide profile, under its -access controls. Without remembering, a new profile is saved without its -password and with autoconnect disabled. Existing profiles can request another -password, including after a wrong-password failure. Saving a replacement -requires modification permission; otherwise it is used only for that attempt. -I38 stores no passwords itself. Enterprise/hidden-network setup, VPN setup, and -advanced IP/DNS editing are not included. Closing the window leaves established -connections running. See the Network Connections section of the I38 guide. -For the installed binding, review the diff and regenerate your I38 configuration, -then reload i3. `./i38.sh -u` copies scripts but does not add Shift+N to existing -bindings. Regeneration uses your saved preferences; review them first. +## Usage -Automated checks (no host connections are changed): +- With no arguments, create the i3 configuration. +- -d: Generate the default I38 configuration without prompting. +- -D: Generate the default I38 configuration plus ~/.xinitrc and ~/.xprofile without prompting. +- -h: Help screen. +- -u: Copy over the latest version of scripts. +- -x: Generate ~/.xinitrc and ~/.xprofile. +- -X: Generate ~/.xprofile only. -```bash -dbus-run-session -- env I38_PRIVATE_NETWORK_TEST=1 python3 -B -m unittest discover -s tests -p test_network.py -v -xvfb-run -a dbus-run-session -- env -u AT_SPI_BUS_ADDRESS I38_PRIVATE_NETWORK_GUI_TEST=1 python3 -B tests/native_network_gui.py -v +### Setup + +I38 detects your browser, file manager, and text editor and lets you choose which to bind to their launch keys. It also creates bindings for pidgin and mumble if they are installed, and you can add custom applications with your own keybindings. + +The screen reader choices are Cthulhu, Orca, and None. If no supported screen reader is installed, I38 assumes None and skips screen reader startup. Setup also asks about the window title font size, the screen lock method, USB alerts, and other optional features. + +Setup can save your answers to `I38_preferences.conf` in the current directory. Later runs load the saved preferences and only ask about missing or invalid values. Edit the file to change preferences, or delete it to reconfigure from scratch. + +Default configuration mode (`-d` and `-D`) uses I38Lock when it is installed and supported. In that case I38 locks on startup and autolocks after 5 minutes when `xprintidle` is available. + +### Updating + +`./i38.sh -u` copies the latest scripts into your installation. It does not change your i3 configuration, so new keybindings and startup entries are not added. To get those, regenerate the configuration by running `./i38.sh` again, then reload i3 with `i3-msg reload`, or enter Ratpoison Mode and press Control+semicolon. + + +## Modes + +I38 is an adaptation of the old Strychnine project which was based on the Ratpoison window manager. Ratpoison is a screen-like window manager, and the important concept from that, which applies to I38, is adding keyboard shortcuts without conflicting application shortcuts. This is done with an "escape key". + +When creating I38, I really wanted to port that functionality over, because it is very powerful and allows for lots and lots of shortcuts while minimizing collisions between shortcuts. So, for example, if you have chosen brave as your web browser, and selected alt+escape as your ratpoison mode key, you can quickly launch brave by pressing alt+escape followed by the letter w. + +- Ratpoison Mode: Entered with the key chosen during setup. Launches applications and I38 tools. +- Panel Mode: Entered with Control+Alt+Tab. Holds items a traditional desktop keeps in its panel, such as notes, weather, network, sound, battery, and power options. +- Bypass Mode: Mod+Shift+BackSpace passes all keys directly to the focused application, for applications that need many keyboard shortcuts of their own. Press Mod+Shift+BackSpace again to return to the default mode. +- Personal Mode: An optional mode for your own keybindings, described below. + +In Ratpoison, Panel, and Personal Mode, F1 lists that mode's keybindings, and Escape or Control+g leaves the mode. + +### Personal Mode + +Personal Mode is a user-defined mode where you can add your own keybindings without worrying about them being overwritten when you update I38. When you run `i38.sh`, you are prompted to choose a personal mode key, or you can skip it. + +Edit `~/.config/i3/customizations` to add your own shortcuts. This file is never overwritten by I38. Inside the `mode "personal" { ... }` block, add i3 `bindsym` commands and end each one with `, mode "default"` so the mode exits after the action. + +Example: + +```i3 +mode "personal" { + bindsym f exec firefox, mode "default" + bindsym Shift+f exec firefox --private-window, mode "default" + bindsym Escape mode "default" + bindsym Control+g mode "default" +} ``` -For a native check against the running NetworkManager and polkit services, add -`I38_NETWORK_LIVE_READONLY_TEST=1` to the second command's environment. It reads -connection information, registers the panel's temporary agents, and checks that -a polkit challenge for this process is declined when the local policy offers -one. It does not activate, disconnect, scan, or modify connections or policy. +With this example, pressing your personal mode key followed by `f` opens Firefox. `Shift+f` opens a private window. -Before submission, review and test the changes as required by this project's -AI-assisted contributions policy. For live testing with Cthulhu and Orca: +If a custom binding speaks with `spd-say` while also changing workspaces or moving windows, call `~/.config/i3/scripts/announce_i3.py` instead so its speech does not overlap with screen reader announcements. -1. Open the source panel. Check initial selection, complete row announcements, - prefix search, Tab/Shift+Tab, status review, Details, and Escape. Check Braille - if available. Refresh must preserve focus and selection without repeated - signal-strength announcements. -2. Join a test Wi-Fi network. Check password masking, Show password, Remember - password, cancellation, an incorrect password, a correct retry, and reopening - the panel. Verify remembered credentials reconnect and an unremembered new - profile requires its password again. No administrator dialog should appear. -3. Check an existing wired connection and Wi-Fi, including both active together, - disconnect/reconnect, Wi-Fi disabled/enabled, and hardware wireless blocking - if available. Confirm normal networking still works after the panel closes. -4. If a restricted test account is available, check that missing `network` - membership or denied authorization leaves information readable and changes - disabled. A policy change while a password dialog is open must be rechecked. -5. After configuration regeneration, check Panel Mode Shift+N, existing lowercase - `n` for Notes, F1 help, and the other panel bindings. Opening the network panel - twice should focus its existing window. -Private GTK and D-Bus checks do not establish audible speech, Braille, physical -key behavior, or successful live connection/password persistence. +## Features -## USB Connection Alerts (Optional) +All scripts live in `scripts/` and are installed to `~/.config/i3/scripts/`. The I38 guide describes how to use each feature. -Setup offers USB connection sounds and spoken device names separately from window -event sounds. Default configuration mode enables USB alerts. Install -`python-pyudev`, plus SoX for sounds and Speech Dispatcher (`spd-say`) for speech. -If either output command is absent, the available output still works. +- Screen reader support: Starts Cthulhu or Orca, with keys to restart or toggle it, and Braille through XBrlAPI. When Cthulhu is running, I38 leaves workspace switch and window move announcements to Cthulhu; otherwise I38 speaks them itself (`announce_workspace.sh`, `announce_i3.py`). +- Sounds: Window, workspace, and mode sounds (`sound.py`), plus optional USB connection and removal alerts that speak the device name (`usb_notifications.py`). +- Launching: Accessible application menu (`menu.py`), run dialog (`run_dialog.py`), and the I38 Desktop dialog (`desktop.py`) with a desktop shortcut creator that supports files, folders, applications, web links, and Windows programs through Wine (`shortcut_creator.py`, `shortcuts.py`). +- Panels: Network (`network.py`, `network_backend.py`), experimental Sound Manager (`sound_manager.py`), notes (`notes.py`), passwords using `pass` (`passmanager.py`), reminders (`reminder.sh`), weather, system information, battery, power options, and Magic Wormhole file transfer (`wormhole.py`). +- Productivity: Clipboard history (`i38-clipboard.py`), bookmarks (`bookmarks.sh`), window list (`window_list.sh`), and an AI assistant using Claude Code or Ollama, with optional voice input (`ai.py`). +- Accessibility tools: OCR of the screen (`ocr.py`), brightness control and screen curtain (`screen_controller.sh`), xzoom magnifier, larger mouse cursor, and a key to move the pointer to the focused window (`find_mouse.sh`). +- Screen lock: I38Lock, a PAM-backed locker, or the legacy PIN lock, which is a privacy screen only and not a secure lock (`screenlock.sh`, `screenlock_autolock.sh`). +- Background services: i3 lockup watchdog (`i3_watchdog.sh`), I38 update check (`i38-update-check.sh`), battery alerts (`battery_alert.sh`), and Steam game focus (`steam_games.py`). -Connections play a 0.65-second rising, pulsing triangle tone; removals play the -same sound reversed. Alerts use the device's product and manufacturer names, -with `USB device connected` or `USB device disconnected` when no product name is -available. Names are cached so unplugged devices can still be identified. -Wireless receivers may expose only their receiver name, not the names of paired -keyboards or mice. These alerts describe USB attachment, not successful mounting -or readiness for use. - -The listener observes udev events without changing rules, claiming devices, or -mounting storage. It filters out USB interface events, silently records devices -already attached at startup, and allows one listener per X display. It survives -i3 restarts and exits when i3 logs out. Speech uses `spd-say -P important -w` -without globally cancelling other speech. - -After updating, regenerate the I38 configuration and enable the USB option; -`./i38.sh -u` alone copies scripts without adding the startup entry. Saved -preferences use `usbNotifications=0` to enable alerts and `usbNotifications=1` -to disable them. To try the source listener before regeneration, run -`python3 scripts/usb_notifications.py` in a terminal within your i3 session, -then press Control+C when finished. Stop that foreground trial before testing -the installed listener. - -Run the focused checks with -`python3 -B -m unittest discover -s tests -p 'test_usb_notifications.py' -v`. -For human review, connect and remove a named USB device, an unnamed device if -available, and a multifunction device: expect one alert per USB device, including -the cached name on removal. Devices behind a hub each generate their own alert. -Restart i3 and check that subsequent hotplug events are announced once and that -devices already attached do not produce startup alerts. Confirm normal keyboard, -mouse, storage mounting, existing window/mode sounds, and other speech still -work. Check the USB setup option both enabled and disabled. Automated checks do -not establish audible sound or spoken output. ## GTK Application Sound Themes (Optional) @@ -273,50 +189,6 @@ You can apply the same configuration to GTK2 apps. Create or edit ~/.gtkrc-2.0 gtk-sound-theme-name=name gtk-modules=canberra-gtk-module -## Usage: - -- With no arguments, create the i3 configuration. -- -d: Generate the default I38 configuration without prompting. -- -D: Generate the default I38 configuration plus ~/.xinitrc and ~/.xprofile without prompting. -- -h: Help screen. -- -u: Copy over the latest version of scripts. -- -x: Generate ~/.xinitrc and ~/.xprofile. -- -X: Generate ~/.xprofile only. - -Default configuration mode uses I38Lock when it is installed and supported by the screen-reader setup. In that case I38 locks on startup and autolocks after 5 minutes when `xprintidle` is available. - -## Desktop Dialog - -Press the configured desktop shortcut, Mod+Control+D (Super+Control+D or Alt+Control+D, depending on your setup), to open the I38 Desktop dialog. Use Up and Down to move through items, hold Shift with Up or Down to select multiple items, and press Control+Space to clear the selection. Type to filter items whose names start with the typed text, ignoring case, and press Enter to open the focused item. Escape clears an active search and returns to the list; press it again to close the dialog. Use Tab and Shift+Tab to reach the search field and buttons. Press Shift+F10 for the context menu; this also opens with the right-click button without clearing selected items. Press Delete to permanently remove selected desktop files or folders after confirmation. Deleting a folder also deletes everything inside it. Shortcut entries are kept. - -Quick-launch shortcut entries come from `~/.config/i3/desktop_shortcuts`. They are not deleted from disk by the desktop dialog. - -### Creating desktop shortcuts - -Enter Ratpoison Mode, then press Control+Alt+D to open **I38 Create Desktop Shortcut**. Choose **Add from Clipboard**, **Browse for File**, **Browse for Folder**, or **Search for Application**. You can also type an absolute path such as `/usr/bin/firefox`, a home-relative path such as `~/Documents`, a program name on PATH, or a complete HTTP/HTTPS URL in the Target field, then press Enter. Copy one item at a time; copying a file in a file manager and copying its path as text both work. Copied files are left in place, including files marked for cutting. - -Review the suggested shortcut name, edit it if desired, then choose **Create Shortcut**. Web links use the page title when available, with the site hostname as a fallback. The title lookup runs in the background with a size limit and short network timeouts, without browser cookies or JavaScript. It never replaces a name you have edited. Files open in their default application, folders open in I38's selected file manager, and executable programs run directly. For command-line programs, select **Run program in a terminal**. Target accepts a program or path, rather than a shell command with arguments. - -Application search lists registered visible applications, including user and system application launchers, with case-insensitive name-prefix filtering like the desktop dialog. Type to search and press Down to move into the list; press Enter to select an application. The shortcut launches the original `.desktop` entry, preserving its terminal, working-directory, D-Bus, and launch options. Keep that original entry available. You can also browse to or paste a `.desktop` file directly. - -Windows `.exe` programs run with Wine, using the program's folder as the working directory. The creator looks for an enclosing Wine prefix (bottle), including through symbolic links, then checks the existing `~/.wine` prefix. It recognizes prefixes by their `drive_c`, `dosdevices`, and `system.reg` entries. Review or change the suggested **Wine prefix (bottle) folder**; if none is found, enter or browse for the existing prefix before creating the shortcut. Wine must be installed. Existing shortcuts are not updated automatically; recreate a shortcut made before this support was added. - -Shortcuts are ordinary `.desktop` files in the XDG desktop directory (normally `~/Desktop`). Existing items are never overwritten; repeated names get numbered filenames. Tab and Shift+Tab move between controls, and Escape closes the dialog. Deleting a created shortcut through I38 Desktop removes only the shortcut file. - -After updating an existing installation, regenerate your I38 configuration to add the new Ratpoison binding; `./i38.sh -u` copies scripts but does not add bindings. Review your configuration preferences before regeneration. Then reload i3 with `i3-msg reload`, or enter Ratpoison Mode and press Control+semicolon, to activate the new binding in the running session. - -## Dependency Helpers - -Distro-specific dependency helpers live in `extra/`. On Arch Linux, run: - -```bash -extra/arch-linux.sh -``` - -The helper checks I38's required packages, asks which missing provider -applications to install, adds lightweight optional feature packages, then -installs the selected package list at the end. Optional packages that need -manual choice, such as Tesseract language data, are skipped. ## Development @@ -326,18 +198,29 @@ Enable the tracked pre-commit hooks once after cloning: git config --local core.hooksPath .githooks ``` -The pre-commit hook rejects staged Python cache files. The I38 script installer -also excludes and removes Python cache artifacts when copying `scripts/`. +The pre-commit hook rejects staged Python cache files. The I38 script installer also excludes and removes Python cache artifacts when copying `scripts/`. -Shortcut regression tests use Python's unittest, PyGObject, and `desktop-file-validate` (desktop-file-utils). Run `python3 -B -m unittest discover -s tests -v`. These check Wine prefix detection, desktop-entry argument handling and working directory using a recording Wine substitute, and existing target types. For native GTK Wine-prefix field and validation checks, also install Xvfb, then run: +The user guide is `I38.md`. Setup converts it to HTML with placeholders such as `@MODKEY@` replaced by your chosen keys. When a change adds or changes a feature or keybinding, update the guide. + +### Tests + +Run the unit tests with: ```bash -xvfb-run -a dbus-run-session -- env -u AT_SPI_BUS_ADDRESS I38_PRIVATE_GUI_TEST=1 PYTHONDONTWRITEBYTECODE=1 python3 tests/native_shortcut_gui.py -v +python3 -B -m unittest discover -s tests -v ``` -The GUI test uses a separate display and session bus. It does not prove live speech or Braille. After reviewing the diff and regenerating your configuration, test the new Ratpoison binding, clipboard and browse sources, application search, edited names, and opening each shortcut type through I38 Desktop. Confirm that normal desktop prefix search and existing launchers still work, that repeated names preserve previous shortcuts, and that deleting a generated shortcut leaves its original target intact. +The network tests that use a private D-Bus session, and the GUI checks, need extra setup. Each runs on a private display and session bus and never changes host connections or uses the desktop's audio server. The GUI checks need Xvfb; the sound check also needs PipeWire, WirePlumber, and PulseAudio client tools. -For Wine, create a shortcut to an `.exe` inside a non-default prefix and confirm that the suggested prefix is correct and the program opens with its settings and resources. Try an `.exe` outside any prefix: review the `~/.wine` suggestion when that prefix exists, or select the bottle manually when it does not. Test an explicit override, cancel the bottle chooser, and verify that an invalid folder prevents creation. Check that switching to a native program or document hides the Wine controls and preserves its normal launch behavior. +```bash +dbus-run-session -- env I38_PRIVATE_NETWORK_TEST=1 python3 -B -m unittest discover -s tests -p test_network.py -v +xvfb-run -a dbus-run-session -- env -u AT_SPI_BUS_ADDRESS I38_PRIVATE_NETWORK_GUI_TEST=1 python3 -B tests/native_network_gui.py -v +I38_PRIVATE_SOUND_TEST=1 dbus-run-session -- xvfb-run -a python3 -B tests/native_sound_manager.py +``` + +Adding `I38_NETWORK_LIVE_READONLY_TEST=1` to the network GUI check's environment also reads from the running NetworkManager and polkit services, without activating, disconnecting, scanning, or modifying anything. + +Automated checks do not prove audible output, speech, Braille, or physical key behavior. Test changes live with Cthulhu and Orca. The desktop shortcut creator has no automated checks. ### AI-assisted contributions @@ -377,107 +260,3 @@ Stormux projects may accept patches through email using `git send-email`. If you 6. Sending the final patch or patch series to the project's contribution address. Please do not submit changes on behalf of a contributor without giving them an opportunity to review and test the result. - - -## Ratpoison Mode - -I38 is an adaptation of the old Strychnine project which was based on the Ratpoison window manager. Ratpoison is a screen-like window manager, and the important concept from that, which applies to I38, is adding keyboard shortcuts without conflicting application shortcuts. This is done with an "escape key". - -When creating I38, I really wanted to port that functionality over, because it is very powerful and allows for lots and lots of shortcuts while minimizing collisions between shortcuts. So, for example, if you have chosen brave as your web browser, and selected alt+escape as your ratpoison mode key, you can quickly launch brave by pressing alt+escape followed by the letter w. - - -## AI Assistant - -I38 includes an integrated AI assistant accessible through ratpoison mode with the 'a' key. The AI assistant provides accessibility-focused AI interaction with support for multiple providers: - -### Features - -- **Multiple AI Providers**: Support for Claude Code and Ollama -- **Voice Input & Output**: Hands-free voice interaction with speech recognition and synthesis -- **Wake Word Detection**: Continuous listening mode with customizable wake phrases -- **Contextual Questions**: Ask questions about the currently focused window -- **File Analysis**: Share files with the AI for analysis -- **Image Description**: Take screenshots and get AI descriptions for accessibility -- **Selected Text Analysis**: Analyze selected text or screen content using OCR -- **Action Confirmation**: Optional confirmation dialogs for AI-suggested actions -- **Keyboard Shortcuts**: F4 for voice input, F5 for continuous listening toggle -- **Accessibility First**: Full screen reader compatibility with keyboard navigation - -### Usage - -1. Press your ratpoison mode key (e.g., Alt+Escape) -2. Press 'a' to launch the AI assistant -3. Use Tab to navigate between the Interaction and Settings tabs -4. In the Interaction tab: - - Enter your question in the text area - - Use "Ask AI Question" for general queries - - Use "Ask About Focused Window" to include window context - - Use "Request AI Action" for step-by-step instructions - - Use "Browse" to select files for analysis - - Use "Describe Screenshot" for visual content - - Use "Analyze Selected Text/Screen Content" to analyze selected text or perform OCR - -5. Voice Mode (if enabled): - - Press F4 or click "🎤 Voice Question" to speak your question - - Toggle continuous listening with F5 or "👂 Continuous Listen" - - Say your wake phrase (default: "hey assistant") when continuous listening is active - - Responses are automatically spoken if voice output is enabled - -### Configuration - -The AI assistant stores its configuration in `~/.config/stormux/I38/ai.conf` using XDG directory standards. Settings include: - -- AI provider selection (Claude Code or Ollama) -- Ollama model selection, host configuration, and request timeout -- Action confirmation preferences -- Voice input/output settings -- Wake word customization -- Voice recognition timeout settings - -### Providers - -**Claude Code**: Requires the Claude Code CLI to be installed and authenticated. Supports text, code, and image analysis. - -**Ollama**: Requires Ollama service to be running locally. Automatically discovers available models and supports text analysis. - - -## Personal Mode - -Personal Mode is a user-defined mode where you can add your own keybindings without worrying about them being overwritten when you update I38. - -### Setup - -When you run `i38.sh`, you are prompted to choose a personal mode key (or you can skip it). If you selected one, pressing that key enters Personal Mode. - -### Adding Custom Bindings - -Edit `~/.config/i3/customizations` to add your own shortcuts. This file is never overwritten by I38. Inside the `mode "personal" { ... }` block, add i3 `bindsym` commands and end each one with `, mode "default"` so the mode exits after the action. - -Example: - -```i3 -mode "personal" { - bindsym f exec firefox, mode "default" - bindsym Shift+f exec firefox --private-window, mode "default" - bindsym Escape mode "default" - bindsym Control+g mode "default" -} -``` - -With this example, pressing your personal mode key followed by `f` opens Firefox. `Shift+f` opens a private window. - -### Default Bindings - -- `F1` — Show personal mode keybindings -- `Escape` or `Control+g` — Exit Personal Mode - -## Panel Mode - -Very similar to ratpoison, accessed with Alt+Control+Tab. It contains items that would normally be found in a traditional desktop's panel. For example, it has a simple note app, system information, weather, bluetooth and power options, and remind. - - -## I38 Help - -To get help for I38, you can press the top level keybinding alt+shift+F1. It is also available by pressing the ratpoison mode key followed by question mark. A limitation of yad, which is used to display the help text means that the cursor starts at the bottom of the text. Please press control+home to jump to the top. You can navigate with the arrow keys, and use control+f to find text within the document. - -The help text is a modified version of the configuration file itself that is intended to be easier to read. I have tried to add in comments that should also serve to make things more clear. diff --git a/tests/atspi_sound_manager.py b/tests/atspi_sound_manager.py new file mode 100644 index 0000000..11a0cdc --- /dev/null +++ b/tests/atspi_sound_manager.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""External accessibility client for the private Sound Manager test session.""" + +import os +from pathlib import Path +import subprocess +import sys +import time + +import pulsectl +import pyatspi + +if os.environ.get("I38_PRIVATE_SOUND_TEST") != "1" or not os.environ.get("PULSE_SERVER", "").startswith("unix:/tmp/i38-audio-"): + raise SystemExit("This probe requires native_sound_manager.py's private server.") + + +def wait_for(predicate): + deadline = time.monotonic() + 12 + while time.monotonic() < deadline: + result = predicate() + if result: + return result + time.sleep(0.05) + raise AssertionError("The expected accessible UI did not appear") + + +def showing(obj): + return obj.getState().contains(pyatspi.STATE_SHOWING) + + +def assert_tab_traversal(frame, count=8): + def focused(): + return [(obj.getRoleName(), obj.name) for obj in pyatspi.findAllDescendants( + frame, lambda obj: obj.getState().contains(pyatspi.STATE_FOCUSED))] + sequence = [focused()] + for key in ["Tab"] * count + ["shift+Tab"] * count: + before = focused() + subprocess.check_call(["xdotool", "key", "--clearmodifiers", key]) + deadline = time.monotonic() + 1 + while time.monotonic() < deadline and focused() == before: + time.sleep(0.02) + after = focused() + sequence.append(after) + assert after and after != before, "Focus did not move after {}: {}".format(key, sequence) + + +def main(): + script = Path(__file__).resolve().parents[1] / "scripts/sound_manager.py" + process = subprocess.Popen([sys.executable, "-B", str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + desktop = pyatspi.Registry.getDesktop(0) + app = wait_for(lambda: next((obj for obj in desktop if obj.get_process_id() == process.pid), None)) + frame = wait_for(lambda: pyatspi.findDescendant(app, lambda obj: obj.name == "I38 Sound Manager")) + tabs = pyatspi.findAllDescendants(frame, lambda obj: obj.getRole() == pyatspi.ROLE_PAGE_TAB) + assert [tab.name for tab in tabs] == ["Playback", "Recording", "Output devices", "Input devices", + "Configuration", "Saved streams", "Server settings"] + xid = subprocess.check_output(["xdotool", "search", "--name", "^I38 Sound Manager$"], + universal_newlines=True).splitlines()[0] + subprocess.check_call(["xdotool", "windowfocus", "--sync", xid]) + assert_tab_traversal(frame) + subprocess.check_call(["xdotool", "key", "--clearmodifiers", "ctrl+Page_Down", "ctrl+Page_Down"]) + wait_for(lambda: tabs[2].getState().contains(pyatspi.STATE_SELECTED)) + volume = wait_for(lambda: pyatspi.findDescendant(frame, lambda obj: + obj.getRole() == pyatspi.ROLE_SPIN_BUTTON and showing(obj) and obj.name == "Volume (percent)")) + volume.queryValue().currentValue = 40 + applyButton = pyatspi.findDescendant(frame, lambda obj: obj.name == "Apply volume" and showing(obj)) + assert applyButton is not None + assert applyButton.queryAction().doAction(0) + try: + status = wait_for(lambda: pyatspi.findDescendant(frame, lambda obj: + obj.name == "Status" and "Volume applied" in obj.queryText().getText(0, -1))) + except AssertionError: + for obj in pyatspi.findAllDescendants(frame, lambda obj: obj.name.startswith("Status")): + print("Accessible status:", obj.getRoleName(), repr(obj.name), repr(obj.queryText().getText(0, -1)), file=sys.stderr) + raise + assert status.getState().contains(pyatspi.STATE_FOCUSED) + with pulsectl.Pulse("I38 private AT-SPI verification") as pulse: + result = pulse.get_sink_by_name("example-output") + assert abs(max(result.volume.values) - 0.4) < 0.0001 + # Real X11 keys through the private display exercise notebook shortcuts. + subprocess.check_call(["xdotool", "key", "--clearmodifiers", "Tab", "shift+Tab", "ctrl+Page_Down"]) + wait_for(lambda: tabs[3].getState().contains(pyatspi.STATE_SELECTED)) + subprocess.check_call(["xdotool", "key", "--clearmodifiers", "ctrl+Page_Up"]) + wait_for(lambda: tabs[2].getState().contains(pyatspi.STATE_SELECTED)) + print("External AT-SPI labels, seven tabs, volume editing, Apply/result focus and X11 tab navigation passed.") + finally: + process.terminate() + output, errors = process.communicate(timeout=5) + if process.returncode not in (0, -15) or sys.exc_info()[0]: + print(errors.decode("utf-8", "replace"), file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/tests/native_network_gui.py b/tests/native_network_gui.py new file mode 100644 index 0000000..4d89cc8 --- /dev/null +++ b/tests/native_network_gui.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Run under private Xvfb/D-Bus; no host networking operations or reader changes.""" + +import os +from pathlib import Path +import sys +import time +import unittest +from unittest import mock + +if os.environ.get("I38_PRIVATE_NETWORK_GUI_TEST") != "1": + raise SystemExit("Run this test with I38_PRIVATE_NETWORK_GUI_TEST=1 on a private display and bus.") + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import network +from network_backend import NetworkRow +from gi.repository import Atk, Gdk, Gio, GLib, Gtk, NM + +testApp = None + + +def get_test_app(): + global testApp + if testApp is None: + testApp = Gtk.Application(application_id="org.stormux.I38.NetworkTest", flags=Gio.ApplicationFlags.NON_UNIQUE) + testApp.register(None) + return testApp + + +def drain_events(): + context = GLib.MainContext.default() + while context.pending(): + context.iteration(False) + + +class GuiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = get_test_app() + + def setUp(self): + self.backend = mock.Mock() + self.backend.client.wireless_get_enabled.return_value = True + self.backend.client.wireless_hardware_get_enabled.return_value = True + self.backend.client.get_nm_running.return_value = True + self.backend.client.get_connectivity.return_value = NM.ConnectivityState.FULL + self.backend.permission_problem.return_value = "" + self.backend.authorize.return_value = True + self.backend.agentReady = True + self.backend.busy = False + self.backend.secretRequest = None + self.device = mock.Mock() + self.device.get_iface.return_value = "wlan0" + self.device.get_ip4_config.return_value = None + self.device.get_ip6_config.return_value = None + self.profile = mock.Mock() + self.profile.get_uuid.return_value = "00000000-0000-4000-8000-000000000001" + self.first = NetworkRow(("wifi", "example"), "Example Network", "Wi-Fi", "Connected", "70%", + "WPA Personal", self.device, self.profile, None, mock.Mock()) + self.second = self.first._replace(key=("wifi", "another"), name="Another Network", state="Disconnected", active=None) + self.backend.rows.return_value = [self.second, self.first] + self.window = network.NetworkWindow(self.app, lambda *args: self.backend) + drain_events() + + def tearDown(self): + self.window.destroy() + drain_events() + + def test_active_selection_complete_accessible_row_and_explicit_actions(self): + self.assertEqual(self.window.selected_row().key, self.first.key) + accessible = self.window.tree.get_accessible() + self.assertEqual(accessible.get_name(), "Network connections") + cell = accessible.ref_at(1, 0) + self.assertIn("Example Network", cell.get_name()) + self.assertIn("Connected", cell.get_name()) + self.assertNotIn("signal", cell.get_name()) + self.assertIn("signal 70%", self.window.row_text(self.first, includeSignal=True)) + self.assertFalse(self.window.connectButton.get_sensitive()) + self.assertTrue(self.window.disconnectButton.get_sensitive()) + self.window.tree.set_cursor(Gtk.TreePath.new_from_indices([0])) + self.backend.connect_row.assert_not_called() + self.backend.disconnect_row.assert_not_called() + self.assertTrue(self.window.connectButton.get_sensitive()) + + def test_scan_preserves_selection_focus_and_order(self): + self.window.tree.set_cursor(Gtk.TreePath.new_from_indices([0])) + self.window.search.grab_focus() + drain_events() + self.backend.rows.return_value = [self.first._replace(signal="30%"), self.second._replace(signal="90%")] + self.window.refresh() + self.assertEqual(self.window.selected_row().key, self.second.key) + self.assertEqual(self.window.get_focus(), self.window.search) + self.assertEqual([row[2] for row in self.window.store], ["Another Network", "Example Network"]) + + def test_prefix_search_and_escape(self): + self.window.search.set_text("EX") + self.window.on_search(self.window.search) + self.assertEqual(len(self.window.filtered), 1) + self.assertEqual(self.window.selected_row().key, self.first.key) + self.window.search.set_text("Network") + self.window.on_search(self.window.search) + self.assertEqual(len(self.window.filtered), 0) + self.assertFalse(self.window.connectButton.get_sensitive()) + self.assertTrue(self.window.on_key(self.window, mock.Mock(keyval=Gdk.KEY_Escape))) + self.assertEqual(self.window.search.get_text(), "") + + def test_all_restricted_controls_disabled_but_details_available(self): + self.backend.permission_problem.return_value = "Managing connections requires membership in the network group." + self.window.refresh() + self.assertFalse(self.window.connectButton.get_sensitive()) + self.assertFalse(self.window.disconnectButton.get_sensitive()) + self.assertFalse(self.window.refreshButton.get_sensitive()) + self.assertFalse(self.window.wireless.get_sensitive()) + self.assertTrue(self.window.detailsButton.get_sensitive()) + self.assertIn("network group", self.window.permissionText.get_text()) + + def test_password_labels_masking_validation_and_cancellation(self): + callback = mock.Mock() + self.window.request_password("Example Network", "wpa-psk", True, callback) + dialog = self.window.passwordDialog + self.assertFalse(dialog.entry.get_visibility()) + self.assertEqual(dialog.get_focus(), dialog.entry) + self.assertFalse(dialog.connectButton.get_sensitive()) + relations = dialog.entry.get_accessible().ref_relation_set() + self.assertIsNotNone(relations.get_relation_by_type(Atk.RelationType.LABELLED_BY)) + dialog.entry.set_text("ExamplePassword") + self.assertTrue(dialog.connectButton.get_sensitive()) + dialog.response(Gtk.ResponseType.CANCEL) + callback.assert_called_once_with(None, True) + self.assertIsNone(self.window.passwordDialog) + + def test_password_success_and_no_permission_to_remember(self): + callback = mock.Mock() + self.window.request_password("Example Network", "sae", False, callback) + dialog = self.window.passwordDialog + self.assertFalse(dialog.remember.get_sensitive()) + self.assertFalse(dialog.remember.get_active()) + dialog.entry.set_text("ExamplePassword") + dialog.response(Gtk.ResponseType.OK) + callback.assert_called_once_with("ExamplePassword", False) + + def test_details_tab_exits_text_and_status_result_is_native_dialog(self): + self.window.on_details(None) + dialog = next(w for w in Gtk.Window.list_toplevels() if w.get_title() == "Connection details") + scroll = dialog.get_content_area().get_children()[0] + self.assertFalse(scroll.get_child().get_accepts_tab()) + dialog.response(Gtk.ResponseType.CLOSE) + self.window.lastBusy = True + self.window.on_status("Connected to Example Network.") + self.assertIsInstance(self.window.resultDialog, Gtk.MessageDialog) + self.assertEqual(self.window.statusEntry.get_text(), "Connected to Example Network.") + + +@unittest.skipUnless(os.environ.get("I38_NETWORK_LIVE_READONLY_TEST") == "1", "optional read-only system-service check") +class LiveBackendTests(unittest.TestCase): + def wait_for(self, condition): + deadline = time.monotonic() + 12 + while not condition() and time.monotonic() < deadline: + drain_events() + time.sleep(0.005) + self.assertTrue(condition(), "System-service check timed out") + + def test_real_profiles_native_refresh_and_process_prompt_guard(self): + app = get_test_app() + window = network.NetworkWindow(app) + backend = window.backend + try: + self.wait_for(lambda: backend.client and backend.guard and backend.guard.ready and backend.agentReady) + # Repeated refreshes exercise profile lifetime and signal disconnection. + window.refresh() + window.refresh() + replies = [] + + def checked(bus, result, data): + replies.append(bus.call_finish(result).unpack()[0]) + + def check_authorization(flags): + backend.bus.call(backend.guard.owner, "/org/freedesktop/PolicyKit1/Authority", + "org.freedesktop.PolicyKit1.Authority", "CheckAuthorization", + GLib.Variant("((sa{sv})sa{ss}us)", (backend.guard.subject, "org.freedesktop.policykit.exec", {}, flags, "")), + None, Gio.DBusCallFlags.NONE, 5000, None, checked, None) + + check_authorization(0) + self.wait_for(lambda: bool(replies)) + if replies[0][1]: + replies.clear() + check_authorization(1) + self.wait_for(lambda: bool(replies)) + self.assertFalse(replies[0][0]) + self.assertIn("no password dialog", window.statusEntry.get_text()) + else: + # Custom policies may already allow or deny this action without a challenge. + self.assertIsInstance(replies[0][0], bool) + finally: + window.destroy() + drain_events() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/native_sound_manager.py b/tests/native_sound_manager.py new file mode 100644 index 0000000..d6ca499 --- /dev/null +++ b/tests/native_sound_manager.py @@ -0,0 +1,507 @@ +#!/usr/bin/env python3 +"""Private GTK/virtual-audio checks. Never uses the desktop's audio server. + +Run: I38_PRIVATE_SOUND_TEST=1 dbus-run-session -- xvfb-run -a \ + python3 -B tests/native_sound_manager.py +Requires PipeWire, WirePlumber, PulseAudio client tools, GTK3 and pulsectl. +WirePlumber runs its policy-only profile, without hardware monitors. +""" + +import copy +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import unittest +import queue +from unittest import mock + +if os.environ.get("I38_PRIVATE_SOUND_TEST") != "1": + raise SystemExit("Run on a private display and bus with I38_PRIVATE_SOUND_TEST=1; see the module docstring.") + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import sound_manager as sound +from test_sound_manager import make_backend, make_object + +applicationClass, windowClass = sound.build_application() +from gi.repository import Atk, Gdk, Gio, GLib, Gtk + + +def drain_events(): + context = GLib.MainContext.default() + deadline = time.monotonic() + 1 + while context.pending() and time.monotonic() < deadline: + context.iteration(False) + + +def snapshot(): + backend, obj, row = make_backend() + obj2 = copy.deepcopy(obj) + obj2.index = 2 + obj2.name = "example-output-two" + obj2.description = "Example output two" + backend.pulse.server_info.return_value = mock.Mock( + server_name="Example server", default_sink_name=obj.name, default_source_name="") + backend.pulse.sink_list.return_value = [obj, obj2] + for kind in ("sink_input", "source_output", "source", "card"): + getattr(backend.pulse, kind + "_list").return_value = [] + backend.read_snapshot() + return backend.onSnapshot.call_args[0][0] + + +class GuiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = Gtk.Application(application_id="org.stormux.I38.SoundTest", flags=Gio.ApplicationFlags.NON_UNIQUE) + cls.app.register(None) + + def setUp(self): + self.backend = mock.Mock() + self.window = windowClass(self.app, lambda *args: self.backend) + self.data = snapshot() + self.window.on_snapshot(self.data) + self.window.notebook.set_current_page(2) + self.window.present() + self.page = self.window.pages["sink"] + drain_events() + + def tearDown(self): + self.window.destroy() + drain_events() + + def test_native_roles_labels_and_no_writes_on_selection(self): + self.assertEqual(self.window.get_title(), "I38 Sound Manager") + self.assertEqual(self.page.tree.get_accessible().get_name(), "Output devices") + self.assertEqual(self.page.master.get_accessible().get_role(), Atk.Role.SPIN_BUTTON) + relations = self.page.master.get_accessible().ref_relation_set() + self.assertTrue(relations.contains(Atk.RelationType.LABELLED_BY)) + self.assertIn("Example output", self.page.tree.get_accessible().ref_at(0, 0).get_name()) + self.page.tree.set_cursor(Gtk.TreePath.new_from_indices([1])) + self.backend.request.assert_not_called() + + def test_refresh_preserves_focus_widgets_and_pending_edits(self): + control = self.page.master + control.grab_focus() + control.set_value(75) + self.page.mute.set_active(True) + newData = copy.deepcopy(self.data) + newData["rows"][("sink", 1)]["volumes"] = [0.1, 0.2] + self.window.on_snapshot(newData) + drain_events() + self.assertIs(self.page.master, control) + self.assertTrue(self.page.master.is_focus()) + self.assertEqual(self.page.master.get_value(), 75) + self.assertTrue(self.page.mute.get_active()) + self.assertEqual(self.page.drafts, {"volume", "mute"}) + + def test_refresh_syncs_clean_values_without_audio_writes(self): + self.data["rows"][("sink", 1)]["volumes"] = [0.2, 0.8] + self.data["rows"][("sink", 1)]["mute"] = True + self.window.on_snapshot(self.data) + self.assertEqual(self.page.master.get_value(), 80) + self.assertEqual(self.page.volumeSpins[0].get_value(), 20) + self.assertTrue(self.page.mute.get_active()) + self.backend.request.assert_not_called() + + def test_unrelated_hotplug_preserves_device_volume_draft_and_focus(self): + control = self.page.master + control.grab_focus() + control.set_value(55) + data = copy.deepcopy(self.data) + row = copy.deepcopy(data["rows"][("sink", 2)]) + row.update(key=("sink", 3), index=3, name="example-output-three", title="Example output three") + data["rows"][row["key"]] = row + self.window.on_snapshot(data) + self.assertIs(self.page.master, control) + self.assertEqual(control.get_value(), 55) + self.assertTrue(control.is_focus()) + + def test_server_settings_refresh_preserves_pending_choice(self): + message = sound.SERVER_SETTINGS[0][0] + self.data["settings"] = {message: False} + self.window.on_snapshot(self.data) + control = self.window.settingControls[message] + self.data["settings"][message] = True + self.window.on_snapshot(self.data) + self.assertTrue(control.get_active()) + control.set_active(False) + self.window.on_snapshot(self.data) + self.assertFalse(control.get_active()) + self.window.apply_settings(None) + self.assertEqual(self.backend.request.call_args[0][2], (message, False)) + + def test_mute_completion_preserves_separate_volume_edits(self): + self.page.master.set_value(70) + self.page.mute.set_active(True) + self.page.submit("mute", True) + self.backend.request.call_args[0][3](True, "Muted.") + self.assertIn("volume", self.page.drafts) + self.assertNotIn("mute", self.page.drafts) + + def test_async_completion_cannot_erase_newer_edits(self): + self.page.master.set_value(70) + self.page.submit("volume", [0.35, 0.7]) + done = self.backend.request.call_args[0][3] + self.page.master.set_value(80) + done(True, "Volume applied.") + self.assertIn("volume", self.page.drafts) + self.assertEqual(self.page.master.get_value(), 80) + + def test_disconnection_removes_controls_and_rejects_stale_selection(self): + self.page.master.grab_focus() + self.window.on_snapshot(None) + self.assertIsNone(self.page.selected()) + self.assertEqual(len(self.page.volumeSpins), 0) + self.assertFalse(self.window.settingsBox.get_sensitive()) + self.page.submit("mute", True) + self.backend.request.assert_not_called() + + def test_details_text_view_does_not_capture_tab(self): + def inspect(dialog): + scroll = dialog.get_content_area().get_children()[0] + view = scroll.get_child() + self.assertIsInstance(view, Gtk.TextView) + self.assertFalse(view.get_accepts_tab()) + self.assertEqual(view.get_accessible().get_name(), "Sound details") + return Gtk.ResponseType.CLOSE + with mock.patch.object(Gtk.Dialog, "run", inspect): + self.page.on_details(None) + + def test_rename_keeps_original_identity_during_hotplug(self): + original = dict(self.page.selected()) + def change_selection(dialog): + self.page.tree.set_cursor(Gtk.TreePath.new_from_indices([1])) + return Gtk.ResponseType.OK + with mock.patch.object(Gtk.Dialog, "run", change_selection): + self.page.on_rename(None) + self.assertEqual(self.backend.request.call_args[0][0]["key"], original["key"]) + + def test_empty_tab_can_be_searched_without_losing_keyboard_navigation(self): + page = self.window.pages["sink_input"] + self.window.notebook.set_current_page(0) + page.search.set_text("Example") + self.assertIsNone(page.selected()) + event = Gdk.Event.new(Gdk.EventType.KEY_PRESS) + event.state = Gdk.ModifierType(0) + event.keyval = Gdk.KEY_Escape + self.assertTrue(self.window.on_key(self.window, event)) + self.assertEqual(page.search.get_text(), "") + self.assertFalse(self.window.closed) + + def test_tab_shortcuts_work_from_status_outside_the_notebook(self): + self.window.status.grab_focus() + self.window.notebook.set_current_page(2) + event = Gdk.Event.new(Gdk.EventType.KEY_PRESS) + event.state = Gdk.ModifierType.CONTROL_MASK + event.keyval = Gdk.KEY_Page_Down + self.assertTrue(self.window.on_key(self.window, event)) + self.assertEqual(self.window.notebook.get_current_page(), 3) + self.assertTrue(self.window.pages["source"].tree.is_focus()) + + +class PrivateAudioSession: + def __enter__(self): + self.directory = tempfile.TemporaryDirectory(prefix="i38-audio-") + self.path = Path(self.directory.name) + (self.path / "pulse").mkdir() + self.processes = [] + self.logs = [] + self.oldEnvironment = dict(os.environ) + os.environ.update(XDG_RUNTIME_DIR=str(self.path), PIPEWIRE_RUNTIME_DIR=str(self.path), + PIPEWIRE_REMOTE="pipewire-0", PULSE_SERVER="unix:" + str(self.path / "pulse/native"), + XDG_CONFIG_HOME=str(self.path / "config"), XDG_STATE_HOME=str(self.path / "state"), + PIPEWIRE_CONFIG_DIR="/usr/share/pipewire", WIREPLUMBER_CONFIG_DIR="/usr/share/wireplumber") + config = self.path / "private.conf" + config.write_text(''' +context.properties = { core.daemon = true core.name = pipewire-0 } +context.spa-libs = { + support.* = support/libspa-support + audio.convert.* = audioconvert/libspa-audioconvert +} +context.modules = [ + { name = libpipewire-module-protocol-native } + { name = libpipewire-module-metadata } + { name = libpipewire-module-spa-node-factory } + { name = libpipewire-module-client-node } + { name = libpipewire-module-adapter } + { name = libpipewire-module-link-factory } + { name = libpipewire-module-access } + { name = libpipewire-module-protocol-pulse } +] +context.objects = [ + { factory = spa-node-factory args = { + factory.name = support.node.driver node.name = Dummy-Driver + node.group = pipewire.dummy priority.driver = 20000 + } } +] +pulse.properties = { server.address = [ "unix:PRIVATE_SOCKET" ] } +pulse.cmd = [ + { cmd = load-module args = module-device-manager } + { cmd = load-module args = module-device-restore } + { cmd = load-module args = module-stream-restore } +] +'''.replace("PRIVATE_SOCKET", str(self.path / "pulse/native"))) + try: + self.start(["pipewire", "-c", str(config)], "pipewire") + self.wait_for(lambda: (self.path / "pipewire-0").exists()) + # Installed WirePlumber has a profile for policy alone: no ALSA, + # Bluetooth, MIDI or camera monitors can acquire physical devices. + self.start(["wireplumber", "--profile=policy"], "wireplumber") + self.wait_for(lambda: (self.path / "pulse/native").exists()) + sound.pactl("load-module", "module-null-sink", "sink_name=example-output", "channels=2") + sound.pactl("load-module", "module-null-sink", "sink_name=example-output-two", "channels=2") + self.wait_for(self.devices_ready) + except Exception: + self.__exit__(*sys.exc_info()) + raise + return self + + def devices_ready(self): + with sound.pulsectl.Pulse("I38 private readiness") as pulse: + return len(pulse.sink_list()) == 2 + + def start(self, command, name): + log = open(str(self.path / (name + ".log")), "w+") + self.logs.append(log) + process = subprocess.Popen(command, stdout=log, stderr=log) + self.processes.append(process) + return process + + def wait_for(self, predicate): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if any(p.poll() is not None for p in self.processes): + raise RuntimeError("A private audio daemon stopped.") + try: + if predicate(): + return + except (RuntimeError, sound.pulsectl.PulseError): + pass + time.sleep(0.05) + raise RuntimeError("Private audio setup timed out.") + + def __exit__(self, errorType, error, traceback): + for process in reversed(self.processes): + process.terminate() + try: + process.wait(timeout=4) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + if error: + for log in self.logs: + log.seek(0) + print(log.read()[-4000:], file=sys.stderr) + for log in self.logs: + log.close() + os.environ.clear() + os.environ.update(self.oldEnvironment) + self.directory.cleanup() + + +class AudioTests(unittest.TestCase): + def setUp(self): + self.backend, obj, row = make_backend() + self.backend.pulse = sound.pulsectl.Pulse("I38 private sound tests") + self.backend.extensions = sound.NativeExtensions(self.backend.pulse) + self.backend.renameSupported = self.backend.extensions.can_rename() + self.backend.restoreSupported = bool(self.backend.pulse.stream_restore_test()) + self.backend.hasPactl = True + self.backend.read_snapshot() + self.row = next(row for row in self.backend.rows.values() + if row["kind"] == "sink" and row["name"] == "example-output") + + def tearDown(self): + self.backend.pulse.close() + + def test_only_virtual_devices_are_visible(self): + self.assertEqual({obj.name for obj in self.backend.pulse.sink_list()}, + {"example-output", "example-output-two"}) + self.assertTrue(all(obj.monitor_of_sink != sound.INVALID_INDEX for obj in self.backend.pulse.source_list())) + + def test_worker_connection_and_shutdown(self): + snapshots = queue.Queue() + backend = sound.SoundBackend(snapshots.put, lambda text: None, + lambda callback, *args: callback(*args)) + try: + data = snapshots.get(timeout=5) + self.assertIsNotNone(data) + self.assertIn("PipeWire", data["server"]) + finally: + backend.close() + backend.thread.join(timeout=5) + self.assertFalse(backend.thread.is_alive()) + + def test_external_atspi_volume_workflow_and_keyboard_tabs(self): + probe = Path(__file__).with_name("atspi_sound_manager.py") + process = subprocess.Popen([sys.executable, "-B", str(probe)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 35 + while process.poll() is None and time.monotonic() < deadline: + drain_events() + time.sleep(0.02) + if process.poll() is None: + process.kill() + output, errors = process.communicate(timeout=5) + self.assertEqual(process.returncode, 0, (output + errors).decode("utf-8", "replace")) + finally: + if process.poll() is None: + process.terminate() + process.communicate(timeout=5) + + def test_channel_volume_mute_and_default_round_trip(self): + self.backend.execute(self.row, "volume", [0.25, 0.75]) + self.backend.execute(self.row, "mute", True) + self.backend.execute(self.row, "default", None) + obj = self.backend.pulse.get_sink_by_name("example-output") + self.assertAlmostEqual(obj.volume.values[0], 0.25, places=4) + self.assertAlmostEqual(obj.volume.values[1], 0.75, places=4) + self.assertTrue(obj.mute) + self.assertEqual(self.backend.pulse.server_info().default_sink_name, obj.name) + self.backend.execute(self.row, "mute", False) + + def test_unsupported_device_rename_is_reported_and_disabled(self): + # PipeWire 1.6.11's module-device-manager is a placeholder, with no + # PulseAudio device-manager extension. A loaded module proves nothing. + self.assertFalse(self.backend.renameSupported) + self.assertFalse(self.row["canRename"]) + with self.assertRaisesRegex(RuntimeError, "unavailable"): + self.backend.execute(self.row, "rename", "Example renamed output") + + def test_saved_stream_settings_preserve_channels(self): + pulse = self.backend.pulse + saved = sound.pulsectl.PulseExtStreamRestoreInfo("sink-input-by-media-role:event", + volume=[0.2, 0.6], channel_list=["front-left", "front-right"], device="example-output-two") + pulse.stream_restore_write(saved, mode="replace", apply_immediately=True) + self.backend.read_snapshot() + row = self.backend.rows[("restore", saved.name)] + self.backend.execute(row, "mute", True) + self.backend.execute(row, "volume", [0.3, 0.7]) + result = next(obj for obj in pulse.stream_restore_list() if obj.name == saved.name) + self.assertTrue(result.mute) + self.assertEqual(result.device, "example-output-two") + self.assertAlmostEqual(result.volume.values[0], 0.3, places=4) + self.assertAlmostEqual(result.volume.values[1], 0.7, places=4) + + def test_peak_sampling_does_not_leave_monitor_streams(self): + before = len(self.backend.pulse.source_output_list()) + result = self.backend.execute(self.row, "peak", None) + self.assertIn("Peak:", result) + self.assertIn("silence", result) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline and len(self.backend.pulse.source_output_list()) != before: + time.sleep(0.05) + self.assertEqual(len(self.backend.pulse.source_output_list()), before, + [(obj.name, obj.proplist) for obj in self.backend.pulse.source_output_list()]) + + def test_peak_sampling_detects_nonzero_virtual_audio(self): + process = subprocess.Popen(["pacat", "--playback", "--raw", "--channels=2", "--rate=48000", + "--format=s16le", "--device=example-output", "--client-name=I38 private signal"], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + stop = threading.Event() + def feed_signal(): + try: + while not stop.is_set(): + process.stdin.write(b"\0\x20" * 960) + process.stdin.flush() + except (OSError, ValueError): + pass + feeder = threading.Thread(target=feed_signal, daemon=True) + feeder.start() + try: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not self.backend.pulse.sink_input_list(): + time.sleep(0.05) + result = self.backend.execute(self.row, "peak", None) + self.assertNotIn("silence", result) + self.assertGreater(float(result.split()[1]), 0) + finally: + stop.set() + process.terminate() + feeder.join(timeout=3) + process.communicate(timeout=3) + + def test_playback_routing_and_native_termination(self): + process = subprocess.Popen(["pacat", "--playback", "--raw", "--channels=2", "--rate=48000", + "--device=example-output", "--client-name=I38 private playback", "--stream-name=Example playback"], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + process.stdin.write(b"\0" * 4096) + process.stdin.flush() + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + self.backend.read_snapshot() + rows = [row for row in self.backend.rows.values() if row["kind"] == "sink_input" + and row["name"] == "Example playback"] + if rows: + break + time.sleep(0.05) + self.assertTrue(rows, "Private playback stream did not appear") + row = rows[0] + self.backend.execute(row, "route", "example-output-two") + stream = self.backend.pulse.sink_input_info(row["index"]) + self.assertEqual(stream.sink, self.backend.pulse.get_sink_by_name("example-output-two").index) + self.backend.execute(row, "kill", None) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + if not any(obj.index == row["index"] for obj in self.backend.pulse.sink_input_list()): + break + time.sleep(0.05) + self.assertFalse(any(obj.index == row["index"] for obj in self.backend.pulse.sink_input_list())) + finally: + process.terminate() + process.communicate(timeout=3) + + def test_recording_routing_and_native_termination(self): + process = subprocess.Popen(["parec", "--raw", "--device=example-output.monitor", + "--client-name=I38 private recording", "--stream-name=Example recording"], + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + rows = [] + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + self.backend.read_snapshot() + rows = [row for row in self.backend.rows.values() if row["kind"] == "source_output" + and row["name"] == "Example recording"] + if rows: + break + time.sleep(0.05) + self.assertTrue(rows, "Private recording stream did not appear") + row = rows[0] + self.backend.execute(row, "route", "example-output-two.monitor") + stream = self.backend.pulse.source_output_info(row["index"]) + self.assertEqual(stream.source, self.backend.pulse.get_source_by_name("example-output-two.monitor").index) + self.backend.execute(row, "kill", None) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + if not any(obj.index == row["index"] for obj in self.backend.pulse.source_output_list()): + break + time.sleep(0.05) + self.assertFalse(any(obj.index == row["index"] for obj in self.backend.pulse.source_output_list())) + finally: + process.terminate() + process.communicate(timeout=3) + + +def main(): + missing = [name for name in ("pipewire", "wireplumber", "pactl", "pacat", "parec", "xdotool") if not shutil.which(name)] + if missing: + raise SystemExit("Missing private-test tools: " + ", ".join(missing)) + suite = unittest.TestSuite() + if len(sys.argv) > 1: + suite.addTests(unittest.defaultTestLoader.loadTestsFromNames(sys.argv[1:], sys.modules[__name__])) + else: + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(GuiTests)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(AudioTests)) + with PrivateAudioSession(): + result = unittest.TextTestRunner(verbosity=2).run(suite) + return 0 if result.wasSuccessful() else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_i3_announcements.py b/tests/test_i3_announcements.py new file mode 100644 index 0000000..2f0a59a --- /dev/null +++ b/tests/test_i3_announcements.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Exercise real D-Bus discovery with private services and recorded output.""" + +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +from gi.repository import Gio, GLib + + +rootPath = Path(__file__).resolve().parents[1] +helperPath = rootPath / 'scripts' / 'announce_i3.py' +spec = importlib.util.spec_from_file_location('announce_i3', str(helperPath)) +announcements = importlib.util.module_from_spec(spec) +spec.loader.exec_module(announcements) +readerName = 'org.stormux.Cthulhu1.Service' + + +class DetectionTests(unittest.TestCase): + def test_no_display_keeps_speech_without_querying_bus(self): + with mock.patch.dict(os.environ, {'DISPLAY': ''}): + with mock.patch.object(Gio, 'bus_get_sync') as connect: + self.assertFalse(announcements.cthulhu_is_active()) + connect.assert_not_called() + + def test_unreadable_process_keeps_speech(self): + connection = mock.Mock() + connection.call_sync.side_effect = [GLib.Variant('(s)', (':1.23',)), + GLib.Variant('(u)', (123,))] + with mock.patch.dict(os.environ, {'DISPLAY': ':123'}): + with mock.patch.object(Gio, 'bus_get_sync', return_value=connection): + with mock.patch.object(Path, 'stat', side_effect=PermissionError): + self.assertFalse(announcements.cthulhu_is_active()) + + def test_wrong_user_keeps_speech(self): + connection = mock.Mock() + connection.call_sync.side_effect = [GLib.Variant('(s)', (':1.23',)), + GLib.Variant('(u)', (123,))] + with mock.patch.dict(os.environ, {'DISPLAY': ':123'}): + with mock.patch.object(Gio, 'bus_get_sync', return_value=connection): + with mock.patch.object(Path, 'stat', + return_value=mock.Mock(st_uid=os.getuid() + 1)): + self.assertFalse(announcements.cthulhu_is_active()) + + +class PrivateBusTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory(prefix='i38-announcements-') + self.addCleanup(self.directory.cleanup) + self.tempPath = Path(self.directory.name) + self.recordPath = self.tempPath / 'commands.jsonl' + self.environment = dict(os.environ, I38_TEST_RECORD=str(self.recordPath), + I38_TEST_WORKSPACE='2') + self.environment['PATH'] = str(self.tempPath) + os.pathsep + os.environ['PATH'] + for command in ('spd-say', 'play', 'i3-msg'): + stubPath = self.tempPath / command + stubPath.write_text( + '#!{python}\n' + 'import json, os, sys\n' + 'from pathlib import Path\n' + 'command = Path(sys.argv[0]).name\n' + 'if command == "i3-msg":\n' + ' print(json.dumps([{{"focused": True, "name": ' + 'os.environ["I38_TEST_WORKSPACE"]}}]))\n' + 'else:\n' + ' with open(os.environ["I38_TEST_RECORD"], "a") as record:\n' + ' record.write(json.dumps([command] + sys.argv[1:]) + "\\n")\n' + .format(python=sys.executable)) + stubPath.chmod(0o755) + self.connection = Gio.bus_get_sync(Gio.BusType.SESSION, None) + + def bus_call(self, method, name): + return self.connection.call_sync( + 'org.freedesktop.DBus', '/org/freedesktop/DBus', + 'org.freedesktop.DBus', method, GLib.Variant('(s)', (name,)), + None, Gio.DBusCallFlags.NONE, 500, None).unpack()[0] + + def own_name(self, name): + reply = self.connection.call_sync( + 'org.freedesktop.DBus', '/org/freedesktop/DBus', + 'org.freedesktop.DBus', 'RequestName', GLib.Variant('(su)', (name, 4)), + None, Gio.DBusCallFlags.NONE, 500, None).unpack()[0] + self.assertEqual(reply, 1) + self.addCleanup(self.bus_call, 'ReleaseName', name) + + def run_announcement(self, message='moved to workspace 2'): + subprocess.run([sys.executable, '-B', str(helperPath), message], + env=self.environment, check=True, timeout=5) + + def commands(self): + if not self.recordPath.exists(): + return [] + return [json.loads(line) for line in self.recordPath.read_text().splitlines()] + + def test_orca_and_no_reader_keep_speech(self): + self.run_announcement() + self.own_name('org.gnome.Orca.Service') + message = '--rate=100 $(echo example); quoted "workspace"' + self.run_announcement(message) + self.assertEqual(self.commands(), [ + ['spd-say', '-P', 'important', '-Cw', '--', 'moved to workspace 2'], + ['spd-say', '-P', 'important', '-Cw', '--', message]]) + + def test_reader_switch_is_detected_each_time(self): + self.own_name(readerName) + self.run_announcement() + self.assertEqual(self.commands(), []) + self.bus_call('ReleaseName', readerName) + self.run_announcement() + self.assertEqual(len(self.commands()), 1) + self.own_name(readerName) + self.run_announcement() + self.assertEqual(len(self.commands()), 1) + + def test_other_display_and_screen_keep_speech(self): + self.own_name(readerName) + self.environment['DISPLAY'] = ':987655' + self.run_announcement() + self.assertEqual(len(self.commands()), 1) + self.environment['DISPLAY'] = ':987654.1' + self.run_announcement() + self.assertEqual(len(self.commands()), 2) + self.environment['DISPLAY'] = ':987654.0' + self.run_announcement() + self.assertEqual(len(self.commands()), 2) + + def test_unavailable_bus_keeps_speech(self): + self.environment['DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=' + str(self.tempPath / 'absent') + self.run_announcement() + self.assertEqual(len(self.commands()), 1) + + def test_workspace_sounds_survive_speech_suppression(self): + self.own_name(readerName) + workspaceScript = rootPath / 'scripts' / 'announce_workspace.sh' + for workspace in ('2', '11', 'Named workspace'): + with self.subTest(workspace=workspace): + self.environment['I38_TEST_WORKSPACE'] = workspace + subprocess.run(['bash', str(workspaceScript)], env=self.environment, + check=True, timeout=5, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.assertEqual([command[0] for command in self.commands()], ['play'] * 3) + + def test_orca_workspace_and_panel_keep_sounds_and_speech(self): + self.own_name('org.gnome.Orca.Service') + workspaceScript = rootPath / 'scripts' / 'announce_workspace.sh' + for workspace, message in (('2', 'Workspace 2'), ('11', 'I38 panel'), + ('Named workspace', 'Workspace Named workspace')): + with self.subTest(workspace=workspace): + self.environment['I38_TEST_WORKSPACE'] = workspace + subprocess.run(['bash', str(workspaceScript)], env=self.environment, + check=True, timeout=5, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + speech = [command for command in self.commands() if command[0] == 'spd-say'] + self.assertEqual(speech[-1][-1], message) + self.assertEqual(sum(command[0] == 'play' for command in self.commands()), 3) + + +class PrivateBusIntegrationTests(unittest.TestCase): + def test_private_bus_and_script_output(self): + environment = dict(os.environ, DISPLAY=':987654', PYTHONDONTWRITEBYTECODE='1') + subprocess.run(['dbus-run-session', '--', sys.executable, '-B', + str(Path(__file__).resolve()), '--private-bus'], + env=environment, check=True, timeout=30) + + +def load_tests(loader, tests, pattern): + return unittest.TestSuite([ + loader.loadTestsFromTestCase(DetectionTests), + loader.loadTestsFromTestCase(PrivateBusIntegrationTests)]) + + +if __name__ == '__main__': + if '--private-bus' in sys.argv: + suite = unittest.defaultTestLoader.loadTestsFromTestCase(PrivateBusTests) + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not result.wasSuccessful()) + unittest.main() diff --git a/tests/test_network.py b/tests/test_network.py new file mode 100644 index 0000000..d216d04 --- /dev/null +++ b/tests/test_network.py @@ -0,0 +1,335 @@ +"""Focused networking tests; never change the host's connections or policy.""" + +import os +from pathlib import Path +import sys +import time +import unittest +from unittest import mock + +import gi +gi.require_version("NM", "1.0") +from gi.repository import Gio, GLib, NM + + +scriptsPath = Path(__file__).resolve().parents[1] / "scripts" +sys.path.insert(0, str(scriptsPath)) +import network_backend as network + + +class FakeAp: + def __init__(self, name=b"Example Network", flags=0, wpa=0, rsn=0, strength=70, path="/ap/1"): + self.name = name + self.flags = flags + self.wpa = wpa + self.rsn = rsn + self.strength = strength + self.path = path + + def get_ssid(self): + return GLib.Bytes.new(self.name) + + def get_flags(self): + return self.flags + + def get_wpa_flags(self): + return self.wpa + + def get_rsn_flags(self): + return self.rsn + + def get_strength(self): + return self.strength + + def get_path(self): + return self.path + + def connection_valid(self, connection): + return bytes(connection.get_setting_wireless().get_ssid().get_data()) == self.name + + +def wifi_row(ap=None): + ap = ap or FakeAp(rsn=network.ApSecurityFlags.KEY_MGMT_PSK) + device = mock.Mock() + device.get_path.return_value = "/devices/wifi1" + device.get_iface.return_value = "wlan0" + return network.NetworkRow(("device", "network"), "Example Network", "Wi-Fi", "Disconnected", + "70%", "WPA Personal", device, None, ap, None) + + +def make_backend(): + with mock.patch.object(NM.Client, "new_async"), mock.patch.object(network, "network_group_member", return_value=True): + backend = network.NetworkBackend(mock.Mock(), mock.Mock(), mock.Mock()) + backend.client = mock.Mock() + backend.client.get_nm_running.return_value = True + backend.client.get_permissions_state.return_value = NM.Ternary.TRUE + backend.client.get_permission_result.return_value = NM.ClientPermissionResult.YES + backend.guard = mock.Mock(ready=True, error="") + backend.agentReady = True + backend.bus = mock.Mock() + return backend + + +class PermissionTests(unittest.TestCase): + def test_session_groups_include_primary_and_supplementary(self): + with mock.patch.object(network.grp, "getgrnam", return_value=mock.Mock(gr_gid=42)), \ + mock.patch.object(network.os, "getgroups", return_value=[42]), \ + mock.patch.object(network.os, "getgid", return_value=7): + self.assertTrue(network.network_group_member()) + with mock.patch.object(network.grp, "getgrnam", return_value=mock.Mock(gr_gid=42)), \ + mock.patch.object(network.os, "getgroups", return_value=[]), \ + mock.patch.object(network.os, "getgid", return_value=42): + self.assertTrue(network.network_group_member()) + with mock.patch.object(network.grp, "getgrnam", side_effect=KeyError): + self.assertFalse(network.network_group_member()) + + def test_no_mutations_without_group_guard_or_current_permissions(self): + for condition in ("group", "guard", "pending", "auth", "no", "unknown"): + with self.subTest(condition=condition): + backend = make_backend() + if condition == "group": + backend.member = False + elif condition == "guard": + backend.guard.ready = False + elif condition == "pending": + backend.client.get_permissions_state.return_value = NM.Ternary.DEFAULT + else: + backend.client.get_permission_result.return_value = { + "auth": NM.ClientPermissionResult.AUTH, "no": NM.ClientPermissionResult.NO, + "unknown": NM.ClientPermissionResult.UNKNOWN}[condition] + row = wifi_row()._replace(active=mock.Mock()) + backend.connect_row(row, "ExamplePassword", True) + backend.disconnect_row(row) + backend.set_wireless(False) + backend.scan() + backend.client.add_and_activate_connection_async.assert_not_called() + backend.client.activate_connection_async.assert_not_called() + backend.client.deactivate_connection_async.assert_not_called() + backend.bus.call.assert_not_called() + self.assertTrue(backend.status.called) + + def test_rechecks_permissions_after_password_dialog(self): + backend = make_backend() + self.assertTrue(backend.authorize([network.NETWORK_CONTROL, network.MODIFY_SYSTEM])) + backend.client.get_permission_result.return_value = NM.ClientPermissionResult.AUTH + backend.connect_row(wifi_row(), "ExamplePassword", True) + backend.client.add_and_activate_connection_async.assert_not_called() + + def test_saved_profile_does_not_require_modification_permission(self): + backend = make_backend() + backend.client.get_permission_result.side_effect = lambda permission: ( + NM.ClientPermissionResult.YES if permission == network.NETWORK_CONTROL else NM.ClientPermissionResult.NO) + profile = mock.Mock() + profile.get_uuid.return_value = "00000000-0000-4000-8000-000000000001" + backend.connect_row(wifi_row()._replace(profile=profile)) + backend.client.activate_connection_async.assert_called_once() + self.assertTrue(backend.busy) + + +class ProfileTests(unittest.TestCase): + def test_scan_deduplicates_access_points_and_preserves_saved_profiles(self): + backend = make_backend() + backend.watch = mock.Mock() + device = wifi_row().device + device.get_device_type.return_value = NM.DeviceType.WIFI + device.get_managed.return_value = True + device.connection_valid.return_value = True + weak = FakeAp(strength=30, rsn=network.ApSecurityFlags.KEY_MGMT_PSK) + strong = FakeAp(strength=90, path="/ap/2", rsn=network.ApSecurityFlags.KEY_MGMT_PSK) + firstProfile = network.new_wifi_connection(wifi_row(weak), "ExamplePassword", True) + secondProfile = network.new_wifi_connection(wifi_row(weak), "ExamplePassword", True) + active = mock.Mock() + active.get_connection.return_value = firstProfile + active.get_state.return_value = NM.ActiveConnectionState.ACTIVATED + device.get_active_connection.return_value = active + device.get_active_access_point.return_value = weak + device.get_access_points.return_value = [weak, strong] + backend.client.get_devices.return_value = [device] + backend.client.get_connections.return_value = [firstProfile, secondProfile] + rows = backend.rows() + self.assertEqual(len(rows), 2) + self.assertEqual({row.profile.get_uuid() for row in rows}, {firstProfile.get_uuid(), secondProfile.get_uuid()}) + self.assertEqual(sum(row.state == "Connected" for row in rows), 1) + self.assertTrue(all(row.ap == weak for row in rows)) + device.filter_connections.assert_not_called() + + def test_personal_security_and_no_enterprise_downgrade(self): + flags = network.ApSecurityFlags + cases = [(0, 0, ""), (int(network.ApFlags.PRIVACY), 0, None), + (0, flags.KEY_MGMT_PSK, "wpa-psk"), (0, flags.KEY_MGMT_SAE, "sae"), + (0, flags.KEY_MGMT_OWE, "owe"), + (0, flags.KEY_MGMT_802_1X | flags.KEY_MGMT_PSK, None)] + for apFlags, securityFlags, expected in cases: + self.assertEqual(network.security_type(FakeAp(flags=apFlags, rsn=securityFlags))[1], expected) + + def test_saved_password_belongs_to_networkmanager(self): + connection = network.new_wifi_connection(wifi_row(), "ExamplePassword", True) + connection.verify() + security = connection.get_setting_wireless_security() + self.assertEqual(security.get_psk_flags(), NM.SettingSecretFlags.NONE) + self.assertEqual(security.get_key_mgmt(), "wpa-psk") + self.assertEqual(connection.get_setting_connection().get_num_permissions(), 0) + self.assertTrue(connection.get_setting_connection().get_autoconnect()) + + def test_unremembered_password_not_persistent_or_autoconnected(self): + connection = network.new_wifi_connection(wifi_row(), "ExamplePassword", False) + connection.verify() + self.assertEqual(connection.get_setting_wireless_security().get_psk_flags(), NM.SettingSecretFlags.NOT_SAVED) + self.assertFalse(connection.get_setting_connection().get_autoconnect()) + + def test_ssid_bytes_and_special_characters_are_preserved(self): + ssid = b"Example:'\\: Wi-Fi \xff" + row = wifi_row(FakeAp(name=ssid)) + connection = network.new_wifi_connection(row, "", True) + self.assertEqual(bytes(connection.get_setting_wireless().get_ssid().get_data()), ssid) + self.assertIsNone(connection.get_setting_wireless_security()) + + def test_invalid_passwords_and_unsupported_security_rejected(self): + for password in ("", "short", "g" * 64): + with self.assertRaises(ValueError): + network.new_wifi_connection(wifi_row(), password, True) + self.assertTrue(network.valid_password("a" * 64, "wpa-psk")) + with self.assertRaises(ValueError): + network.new_wifi_connection(wifi_row(FakeAp(rsn=network.ApSecurityFlags.KEY_MGMT_802_1X)), "ExamplePassword", True) + + def test_activation_acknowledgement_is_not_connection_success(self): + backend = make_backend() + active = mock.Mock() + active.get_state.return_value = NM.ActiveConnectionState.ACTIVATING + backend.client.activate_connection_finish.return_value = active + backend.pending = {"active": None, "name": "Example Network"} + backend.busy = True + backend.on_activated(backend.client, object(), False) + self.assertTrue(backend.busy) + backend.status.assert_not_called() + active.get_state.return_value = NM.ActiveConnectionState.ACTIVATED + backend.check_activation(active) + self.assertFalse(backend.busy) + backend.status.assert_called_with("Connected to Example Network.") + + def test_secret_agent_rejects_unrelated_and_noninteractive_requests(self): + backend = make_backend() + backend.client.get_dbus_name_owner.return_value = ":1.20" + backend.pending = {"uuid": "00000000-0000-4000-8000-000000000001"} + for sender, requestedUuid, flags in ((":1.21", backend.pending["uuid"], 1), + (":1.20", "00000000-0000-4000-8000-000000000002", 1), + (":1.20", backend.pending["uuid"], 0)): + invocation = mock.Mock() + settings = {"connection": {"uuid": GLib.Variant("s", requestedUuid)}, + network.SECURITY_SETTING: {"key-mgmt": GLib.Variant("s", "wpa-psk")}} + backend.handle_secret(None, sender, network.SECRET_PATH, network.SECRET_INTERFACE, "GetSecrets", + GLib.Variant("(a{sa{sv}}osasu)", (settings, "/profile/1", network.SECURITY_SETTING, [], flags)), invocation) + invocation.return_dbus_error.assert_called_once() + backend.password.assert_not_called() + + def test_cancelled_password_returns_error_and_releases_request(self): + backend = make_backend() + invocation = mock.Mock() + backend.secretRequest = ("/profile/1", invocation) + backend.cancel_secret() + invocation.return_dbus_error.assert_called_once() + self.assertIsNone(backend.secretRequest) + + +AUTHORITY_XML = """ + + + +""" + + +@unittest.skipUnless(os.environ.get("I38_PRIVATE_NETWORK_TEST") == "1", "run with a private session bus") +class PromptGuardTests(unittest.TestCase): + def setUp(self): + address = os.environ["DBUS_SESSION_BUS_ADDRESS"] + flags = Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION + self.service = Gio.DBusConnection.new_for_address_sync(address, flags, None, None) + self.client = Gio.DBusConnection.new_for_address_sync(address, flags, None, None) + self.calls = [] + self.service.register_object(network.POLKIT_PATH, Gio.DBusNodeInfo.new_for_xml(AUTHORITY_XML).interfaces[0], + self.authority_call, None, None) + self.service.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", + GLib.Variant("(su)", (network.POLKIT_NAME, 0)), None, Gio.DBusCallFlags.NONE, 2000, None) + self.status = mock.Mock() + self.guard = network.PromptGuard(self.client, mock.Mock(), self.status) + self.wait_for(lambda: self.guard.ready) + + def authority_call(self, bus, sender, path, interface, method, parameters, invocation): + self.calls.append((method, parameters.unpack())) + invocation.return_value(GLib.Variant("()", ())) + + def wait_for(self, condition): + context = GLib.MainContext.default() + deadline = time.monotonic() + 4 + while not condition() and time.monotonic() < deadline: + while context.pending(): + context.iteration(False) + time.sleep(0.002) + self.assertTrue(condition(), "D-Bus operation timed out") + + def tearDown(self): + self.guard.close() + self.wait_for(lambda: any(call[0] == "UnregisterAuthenticationAgent" for call in self.calls)) + self.client.close_sync(None) + self.service.close_sync(None) + + def test_registration_is_only_for_this_process_and_late_challenge_is_declined(self): + method, args = self.calls[0] + subject = args[0] + self.assertEqual(subject[0], "unix-process") + self.assertEqual(subject[1]["pid"], os.getpid()) + self.assertEqual(subject[1]["uid"], os.getuid()) + self.assertGreater(subject[1]["start-time"], 0) + replies = [] + + def replied(bus, result, data): + try: + bus.call_finish(result) + replies.append("unexpected success") + except GLib.Error as error: + replies.append(Gio.DBusError.get_remote_error(error)) + + self.service.call(self.client.get_unique_name(), network.AUTH_PATH, + network.POLKIT_NAME + ".AuthenticationAgent", "BeginAuthentication", + GLib.Variant("(sssa{ss}sa(sa{sv}))", ("org.example.network", "Authenticate", "", {}, "cookie", [])), + None, Gio.DBusCallFlags.NONE, 2000, None, replied, None) + self.wait_for(lambda: bool(replies)) + self.assertEqual(replies, [network.POLKIT_NAME + ".Error.Cancelled"]) + self.assertIn("no password dialog", self.status.call_args[0][0]) + + def test_wifi_password_request_and_reply_use_real_dbus(self): + backend = make_backend() + backend.client.get_dbus_name_owner.return_value = self.service.get_unique_name() + profile = network.new_wifi_connection(wifi_row(), "ExamplePassword", True) + backend.client.get_connection_by_uuid.return_value = profile + backend.pending = {"uuid": profile.get_uuid(), "name": "Example Network"} + requests = [] + + def password(name, keyMgmt, canRemember, answered): + requests.append((name, keyMgmt, canRemember)) + answered("ReplacementPassword", False) + + backend.password = password + objectId = self.client.register_object(network.SECRET_PATH, + Gio.DBusNodeInfo.new_for_xml(network.SECRET_XML).interfaces[0], backend.handle_secret, None, None) + replies = [] + + def replied(bus, result, data): + replies.append(bus.call_finish(result).unpack()[0]) + + settings = {"connection": {"uuid": GLib.Variant("s", profile.get_uuid())}, + network.SECURITY_SETTING: {"key-mgmt": GLib.Variant("s", "wpa-psk")}} + self.service.call(self.client.get_unique_name(), network.SECRET_PATH, network.SECRET_INTERFACE, "GetSecrets", + GLib.Variant("(a{sa{sv}}osasu)", (settings, "/profile/1", network.SECURITY_SETTING, [], 1)), + None, Gio.DBusCallFlags.NONE, 2000, None, replied, None) + try: + self.wait_for(lambda: bool(replies)) + self.assertEqual(requests, [("Example Network", "wpa-psk", True)]) + self.assertEqual(replies[0][network.SECURITY_SETTING]["psk"], "ReplacementPassword") + self.assertIsNone(backend.secretRequest) + finally: + self.client.unregister_object(objectId) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sound_manager.py b/tests/test_sound_manager.py new file mode 100644 index 0000000..cc69a9d --- /dev/null +++ b/tests/test_sound_manager.py @@ -0,0 +1,209 @@ +"""Focused Sound Manager regressions; no connection to the host audio server.""" + +import copy +from pathlib import Path +import queue +import sys +from types import SimpleNamespace +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import sound_manager as sound + + +def make_object(kind="sink", index=1): + obj = SimpleNamespace(name="example-output", index=index, mute=False, + proplist={}, description="Example output", client=2, owner_module=3, + volume=SimpleNamespace(values=[0.3, 0.6]), channel_list=["front-left", "front-right"], + state="running", port_list=[], port_active=None, card=sound.INVALID_INDEX, + monitor_source_name="example-output.monitor", monitor_of_sink=sound.INVALID_INDEX, + corked=False, sink=1, source=1, device=None) + if kind == "restore": + obj.name = "sink-input-by-media-role:event" + return obj + + +def make_backend(): + backend = sound.SoundBackend.__new__(sound.SoundBackend) + backend.pulse = mock.Mock() + backend.extensions = mock.Mock() + backend.generation = 1 + backend.settings = {} + backend.rows = {} + backend.restoreSupported = False + backend.renameSupported = True + backend.commands = queue.Queue() + backend.dispatch = lambda callback, *args: callback(*args) + backend.onSnapshot = mock.Mock() + backend.onStatus = mock.Mock() + obj = make_object() + backend.pulse.sink_info.return_value = obj + row = dict(kind="sink", key=("sink", 1), name=obj.name, index=1, + generation=1, identity=sound.identity(obj), title="Example output") + return backend, obj, row + + +class VolumeTests(unittest.TestCase): + def test_unlinked_master_preserves_stereo_balance(self): + self.assertEqual(sound.scale_channels([0.25, 0.5], 80, False), [0.4, 0.8]) + + def test_linked_and_silent_channels_can_be_raised(self): + self.assertEqual(sound.scale_channels([0.25, 0.5], 80, True), [0.8, 0.8]) + self.assertEqual(sound.scale_channels([0, 0], 40, False), [0.4, 0.4]) + + def test_bad_numeric_volume_is_rejected(self): + for value in (float("nan"), float("inf"), -1): + with self.assertRaises(ValueError): + sound.scale_channels([0.5], value, False) + + def test_pulse_volume_uses_cubic_decibels(self): + self.assertIn("-18.06 dB", sound.volume_text(0.5)) + self.assertIn("silence", sound.volume_text(0)) + + +class BackendTests(unittest.TestCase): + def test_reused_index_and_old_connection_cannot_receive_edits(self): + backend, obj, row = make_backend() + obj.name = "replacement-output" + with self.assertRaises(RuntimeError): + backend.execute(row, "mute", True) + backend.pulse.mute.assert_not_called() + obj.name = row["name"] + row["generation"] = 0 + with self.assertRaises(RuntimeError): + backend.execute(row, "volume", [0.4, 0.4]) + backend.pulse.volume_set.assert_not_called() + + def test_channel_layout_changes_and_invalid_volume_are_rejected(self): + backend, obj, row = make_backend() + for values in ([0.5], [], [float("nan"), 0.5], [1.6, 1.6], [-0.1, 0.5]): + with self.assertRaises(ValueError): + backend.execute(row, "volume", values) + backend.pulse.volume_set.assert_not_called() + + @unittest.skipIf(sound.pulsectl is None, "pulsectl is unavailable") + def test_exact_per_channel_values_are_written(self): + backend, obj, row = make_backend() + backend.execute(row, "volume", [0.4, 0.7]) + target, volume = backend.pulse.volume_set.call_args[0] + self.assertIs(target, obj) + self.assertEqual(volume.values, [0.4, 0.7]) + + def test_saved_mute_preserves_route_and_other_saved_records(self): + backend, obj, row = make_backend() + obj = make_object("restore") + obj.device = "example-output" + backend.pulse.stream_restore_list.return_value = [obj] + row.update(kind="restore", identity=sound.identity(obj), name=obj.name) + backend.execute(row, "mute", True) + backend.pulse.stream_restore_write.assert_called_once_with(obj, mode="replace", apply_immediately=True) + self.assertTrue(obj.mute) + self.assertEqual(obj.device, "example-output") + + def test_routing_resolves_the_current_device_by_name(self): + backend, obj, row = make_backend() + row["kind"] = "sink_input" + backend.pulse.sink_input_info.return_value = obj + backend.pulse.get_sink_by_name.return_value = SimpleNamespace(index=42) + backend.execute(row, "route", "example-output-two") + backend.pulse.get_sink_by_name.assert_called_once_with("example-output-two") + backend.pulse.sink_input_move.assert_called_once_with(1, 42) + + def test_offset_cannot_follow_a_changed_port(self): + backend, obj, row = make_backend() + row.update(card="example-card", port="headphones") + obj.port_active = SimpleNamespace(name="speaker") + with mock.patch.object(sound, "pactl") as command: + with self.assertRaises(RuntimeError): + backend.execute(row, "offset", 50) + command.assert_not_called() + + def test_reading_advanced_controls_never_mutates_audio(self): + backend, obj, row = make_backend() + backend.hasPactl = True + row["kind"] = "card" + with mock.patch.object(sound, "optional_message", side_effect=[ + [{"name": "sbc", "description": "SBC"}], "sbc", False]) as message: + result = backend.read_advanced(row, obj) + self.assertEqual(result["codecs"], [("sbc", "SBC")]) + self.assertEqual([call[0][1] for call in message.call_args_list], + ["list-codecs", "get-codec", "get-profile-sticky"]) + + def test_server_setting_requires_confirmation(self): + backend, obj, row = make_backend() + backend.settings["example-setting"] = False + with mock.patch.object(sound, "pactl"), mock.patch.object(sound, "optional_message", return_value=False): + with self.assertRaises(RuntimeError): + backend.execute(None, "setting", ("example-setting", True)) + self.assertFalse(backend.settings["example-setting"]) + + def test_server_setting_from_an_old_connection_is_rejected(self): + backend, obj, row = make_backend() + with mock.patch.object(sound, "pactl") as command: + with self.assertRaises(RuntimeError): + backend.execute({"generation": 0}, "setting", ("example-setting", True)) + command.assert_not_called() + + def test_no_selected_route_cannot_silently_use_the_default(self): + backend, obj, row = make_backend() + with self.assertRaises(ValueError): + backend.execute(row, "route", None) + backend.pulse.get_sink_by_name.assert_not_called() + + def test_saved_stream_can_resume_following_the_default(self): + backend, obj, row = make_backend() + obj = make_object("restore") + obj.device = "example-output" + backend.pulse.stream_restore_list.return_value = [obj] + row.update(kind="restore", identity=sound.identity(obj), name=obj.name) + backend.execute(row, "route", sound.FOLLOW_DEFAULT) + self.assertIsNone(obj.device) + backend.pulse.stream_restore_write.assert_called_once_with(obj, mode="replace", apply_immediately=True) + + def test_disconnection_rejects_queued_actions_without_replay(self): + backend, obj, row = make_backend() + done = mock.Mock() + backend.commands.put((row, "mute", True, done)) + backend.reject_pending() + self.assertFalse(done.call_args[0][0]) + self.assertTrue(backend.commands.empty()) + backend.pulse.mute.assert_not_called() + + def test_cli_arguments_are_literal_and_bounded(self): + name = "example; $(do-not-run)" + with mock.patch.object(sound.subprocess, "run", return_value=SimpleNamespace( + returncode=0, stdout="true\n", stderr="")) as run: + self.assertEqual(sound.pactl("send-message", name, "get-codec"), "true") + self.assertEqual(run.call_args[0][0], ["pactl", "send-message", name, "get-codec"]) + self.assertEqual(run.call_args[1]["timeout"], 4) + self.assertNotIn("shell", run.call_args[1]) + + def test_snapshot_contains_defaults_channels_monitors_and_routes(self): + backend, obj, row = make_backend() + backend.pulse.server_info.return_value = SimpleNamespace( + server_name="Example server", default_sink_name=obj.name, default_source_name="example-input") + source = make_object("source", 2) + source.name = "example-input" + monitor = copy.deepcopy(source) + monitor.index = 3 + monitor.name = "example-output.monitor" + monitor.monitor_of_sink = 1 + stream = make_object("sink_input", 5) + stream.name = "Example playback" + backend.pulse.sink_list.return_value = [obj] + backend.pulse.source_list.return_value = [source, monitor] + backend.pulse.sink_input_list.return_value = [stream] + backend.pulse.source_output_list.return_value = [] + backend.pulse.card_list.return_value = [] + backend.read_snapshot() + snapshot = backend.onSnapshot.call_args[0][0] + self.assertTrue(snapshot["rows"][("sink", 1)]["default"]) + self.assertEqual(snapshot["rows"][("sink", 1)]["channels"], ["front-left", "front-right"]) + self.assertTrue(snapshot["rows"][("source", 3)]["monitor"]) + self.assertEqual(snapshot["rows"][("sink_input", 5)]["route"], obj.name) + self.assertEqual(snapshot["rows"][("sink", 1)]["state"], "Running") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_usb_notifications.py b/tests/test_usb_notifications.py new file mode 100644 index 0000000..995a941 --- /dev/null +++ b/tests/test_usb_notifications.py @@ -0,0 +1,241 @@ +import array +import importlib.util +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest import mock +import wave + + +scriptPath = Path(__file__).resolve().parents[1] / 'scripts/usb_notifications.py' +spec = importlib.util.spec_from_file_location('usb_notifications', str(scriptPath)) +usb = importlib.util.module_from_spec(spec) +spec.loader.exec_module(usb) + + +class VanishedAttributes: + def get(self, name): + raise OSError('Device has been removed') + + +class Device: + def __init__(self, path='/usb1/1-1', action='add', properties=None, + attributes=None, deviceType='usb_device', subsystem='usb'): + self.device_path = path + self.action = action + self.properties = properties or {} + self.attributes = attributes if attributes is not None else {} + self.device_type = deviceType + self.subsystem = subsystem + + +class UsbDevicesTests(unittest.TestCase): + def test_product_and_manufacturer_name(self): + device = Device(attributes={'manufacturer': b'Example Devices', + 'product': b'Mechanical Keyboard'}) + self.assertEqual(usb.device_name(device), + 'Example Devices Mechanical Keyboard') + + def test_database_name_and_udev_name(self): + device = Device(properties={'ID_MODEL_FROM_DATABASE': 'Bolt Receiver', + 'ID_MODEL': 'USB_Receiver', + 'ID_VENDOR': 'Example_Devices'}) + self.assertEqual(usb.device_name(device), 'Example Devices Bolt Receiver') + device.properties.pop('ID_MODEL_FROM_DATABASE') + self.assertEqual(usb.device_name(device), 'Example Devices USB Receiver') + + def test_clean_names_and_no_duplicate_vendor(self): + device = Device(attributes={'manufacturer': b'Example', + 'product': b'EXAMPLE\x00Keyboard\n\tPro'}) + self.assertEqual(usb.device_name(device), 'EXAMPLE Keyboard Pro') + + def test_startup_is_silent_and_removal_uses_cached_name(self): + device = Device(attributes={'manufacturer': b'Example', + 'product': b'Keyboard'}) + devices = usb.UsbDevices([device]) + self.assertIsNone(devices.handle_event(device)) + removed = Device(action='remove', attributes=VanishedAttributes()) + self.assertEqual(devices.handle_event(removed), + ('remove', 'Example Keyboard disconnected')) + + def test_connect_then_sparse_disconnect_and_reconnect(self): + devices = usb.UsbDevices([]) + device = Device(attributes={'product': b'Keyboard'}) + self.assertEqual(devices.handle_event(device), + ('add', 'Keyboard connected')) + removed = Device(action='remove', attributes=VanishedAttributes()) + self.assertEqual(devices.handle_event(removed), + ('remove', 'Keyboard disconnected')) + self.assertEqual(devices.handle_event(device), + ('add', 'Keyboard connected')) + + def test_unidentified_devices_get_generic_announcements(self): + devices = usb.UsbDevices([]) + self.assertEqual(devices.handle_event(Device()), + ('add', 'USB device connected')) + self.assertEqual(devices.handle_event(Device(action='remove')), + ('remove', 'USB device disconnected')) + self.assertEqual(usb.device_name(Device( + attributes={'manufacturer': b'Example'})), 'USB device') + + def test_uncached_removal_uses_event_properties_or_generic_name(self): + devices = usb.UsbDevices([]) + device = Device(action='remove', attributes=VanishedAttributes(), + properties={'ID_MODEL': 'USB_Sound_Card'}) + self.assertEqual(devices.handle_event(device), + ('remove', 'USB Sound Card disconnected')) + self.assertEqual(devices.handle_event(Device( + path='/usb1/1-2', action='remove', attributes=VanishedAttributes())), + ('remove', 'USB device disconnected')) + + def test_interfaces_other_subsystems_and_duplicate_events_are_silent(self): + devices = usb.UsbDevices([]) + self.assertIsNone(devices.handle_event(Device(deviceType='usb_interface'))) + self.assertIsNone(devices.handle_event(Device(subsystem='input'))) + self.assertIsNotNone(devices.handle_event(Device())) + self.assertIsNone(devices.handle_event(Device())) + self.assertIsNotNone(devices.handle_event(Device(action='remove'))) + self.assertIsNone(devices.handle_event(Device(action='remove'))) + self.assertIsNone(devices.handle_event(Device(action='bind'))) + + def test_same_model_on_different_ports_is_not_deduplicated(self): + devices = usb.UsbDevices([]) + for path in ('/usb1/1-1', '/usb1/1-2'): + self.assertEqual(devices.handle_event(Device( + path=path, attributes={'product': b'Keyboard'})), + ('add', 'Keyboard connected')) + for path in ('/usb1/1-2', '/usb1/1-1'): + self.assertEqual(devices.handle_event(Device(path=path, action='remove')), + ('remove', 'Keyboard disconnected')) + + def test_change_improves_cached_name_without_announcing(self): + devices = usb.UsbDevices([Device()]) + self.assertIsNone(devices.handle_event(Device( + action='change', properties={'ID_MODEL': 'Keyboard'}))) + self.assertIsNone(devices.handle_event(Device(action='change'))) + self.assertEqual(devices.handle_event(Device(action='remove')), + ('remove', 'Keyboard disconnected')) + + +class AnnouncerTests(unittest.TestCase): + def make_announcer(self, play=True, speech=True): + commands = {'play': '/example/play' if play else None, + 'spd-say': '/example/spd-say' if speech else None} + with mock.patch.object(usb.shutil, 'which', side_effect=commands.get): + return usb.Announcer(threading.Event()) + + def record_commands(self, announcer, expectedCount): + commands = [] + + def record(command, timeout): + commands.append(command) + if len(commands) == expectedCount: + announcer.stopEvent.set() + + with mock.patch.object(announcer, 'run_command', side_effect=record): + announcer.run() + return commands + + def test_sound_then_speech_and_exact_reverse_without_global_cancel(self): + announcer = self.make_announcer() + # Device text must remain a single argument, even if it resembles code. + name = '--rate=100 $(touch unexpected) Keyboard' + announcer.enqueue(('add', name + ' connected')) + announcer.enqueue(('remove', name + ' disconnected')) + commands = self.record_commands(announcer, 4) + expectedSound = ['-q', '-r', '44100', '-c', '1', '-n', 'synth', '0.65', + 'triangle', '360:1190', 'tremolo', '14', '85', 'fade', + 'h', '0.01', '0.65', '0.1', 'gain', '-14'] + self.assertEqual(commands[0], ['/example/play'] + expectedSound) + self.assertEqual(commands[2], commands[0] + ['reverse']) + for index, suffix in ((1, ' connected'), (3, ' disconnected')): + self.assertEqual(commands[index], ['/example/spd-say', '-P', + 'important', '-w', '--', name + suffix]) + + def test_missing_output_does_not_disable_other_output(self): + for play, speech in ((True, False), (False, True)): + with self.subTest(play=play, speech=speech): + announcer = self.make_announcer(play, speech) + announcer.enqueue(('add', 'USB device connected')) + commands = self.record_commands(announcer, 1) + self.assertEqual(commands[0][0], + '/example/play' if play else '/example/spd-say') + + def test_bursts_are_bounded_and_keep_recent_events(self): + announcer = self.make_announcer() + for number in range(100): + announcer.enqueue(('add', str(number))) + self.assertEqual(announcer.events.qsize(), 32) + self.assertEqual(announcer.events.get_nowait(), ('add', '68')) + + def test_shutdown_terminates_a_stuck_output_process(self): + announcer = self.make_announcer() + timer = threading.Timer(0.1, announcer.stopEvent.set) + startTime = time.monotonic() + timer.start() + try: + announcer.run_command([sys.executable, '-c', + 'import time; time.sleep(60)'], 5) + finally: + timer.cancel() + timer.join() + self.assertLess(time.monotonic() - startTime, 2) + + def test_output_timeout_does_not_stall_following_events(self): + announcer = self.make_announcer() + startTime = time.monotonic() + announcer.run_command([sys.executable, '-c', + 'import time; time.sleep(60)'], 0.1) + self.assertLess(time.monotonic() - startTime, 2) + self.assertFalse(announcer.stopEvent.is_set()) + + +class SessionTests(unittest.TestCase): + def test_singleton_is_per_display_and_releases_on_close(self): + with tempfile.TemporaryDirectory() as runtimeDir: + with mock.patch.dict(os.environ, {'XDG_RUNTIME_DIR': runtimeDir, + 'DISPLAY': ':99'}): + lockFile = usb.acquire_lock() + self.assertIsNotNone(lockFile) + try: + self.assertIsNone(usb.acquire_lock()) + with mock.patch.dict(os.environ, {'DISPLAY': ':100'}): + with usb.acquire_lock(): + pass + finally: + lockFile.close() + with usb.acquire_lock(): + pass + + @unittest.skipUnless(shutil.which('sox'), 'SoX is not installed') + def test_rendered_disconnect_is_the_exact_reverse(self): + with tempfile.TemporaryDirectory() as outputDir: + rendered = [] + for suffix in ([], ['reverse']): + outputPath = Path(outputDir) / ('%d.wav' % len(rendered)) + command = ['sox', '-D', '-r', '44100', '-c', '1', '-n', + '-b', '16', str(outputPath)] + list(usb.CONNECT_SOUND[7:]) + result = subprocess.run(command + suffix, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, timeout=5) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, b'') + with wave.open(str(outputPath), 'rb') as audio: + self.assertEqual(audio.getnchannels(), 1) + self.assertEqual(audio.getframerate(), 44100) + self.assertAlmostEqual(audio.getnframes() / 44100, 0.65, + delta=1 / 44100) + samples = array.array('h', audio.readframes(audio.getnframes())) + self.assertGreater(max(abs(sample) for sample in samples), 1000) + self.assertLess(max(abs(sample) for sample in samples), 7000) + rendered.append(samples.tolist()) + self.assertEqual(rendered[1], rendered[0][::-1]) + + +if __name__ == '__main__': + unittest.main()