misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Lab: a fast Linux build and shot machine on WSL2 (#230)
Ahmed Nefzaouic068948ca3e7
diff --git a/.gitattributes b/.gitattributesindex 5b2c23cc..bc3a0d4d 100644--- a/.gitattributes+++ b/.gitattributes@@ -4,3 +4,5 @@ tools/installer/languages.iss text eol=crlftools/installer/languages/*.isl text eol=crlf# Test fixtures are compared byte for byte (a signed checksum list): never converted.crates/*/tests/fixtures/** -text+# Scripts that run inside Linux (mdm-lab copies them in from a Windows checkout).+tools/lab/wsl/*.sh text eol=lfdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb174683..9b0d62ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -365,6 +365,14 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, seesockets, and the bytes a sparse file takes on the drive. The slow-connection test now failswithout shedding (it passed without it before). The lab server can hand out such links(`/redirect?uses=N`) and pace answers to range requests on their own (`range_rate`).+- **Developers: Linux builds and window shots in minutes, on WSL2** (part of+ [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164)): `tools/lab/wsl/` sets up+ `mdm-lab`, an Ubuntu 24.04 WSL2 distribution of its own, which builds any branch or pull request+ for Linux at the computer's full speed (`build.sh`: about 5 minutes from scratch, under a minute+ after a change, against 15 to 60 in the VirtualBox machine), shoots MDM's windows in any language+ and mode on a virtual screen that never shows on Windows (`shots.sh`: about a second a window,+ against 40), compares OpenGL and Vulkan pixel by pixel (`renderers.sh`), and hands a build to a+ VirtualBox machine for what needs a real desktop (`deploy.ps1`).- **Developers: a Linux test machine, scripted** (part of [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164)):`tools/lab/linux-vm/` sets up an Ubuntu 24.04 desktop in VirtualBox from a Windows host(`vm.ps1`: hardware, headless start, linked clones; `setup.sh`: packages, Rust, Node, thediff --git a/ROADMAP.md b/ROADMAP.mdindex 70308bf6..744563e4 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,10 @@ Everything below ships together, in one release, as version 0.3.0.### Done+- ✅ Linux builds and window shots in minutes: a WSL2 machine builds any branch in about 5+ minutes (under one after a change) and shoots every window in any language in about a second+ each, never showing on the screen; the Linux desktops still check what needs them (part of+ [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164))- ✅ The Scheduler wakes the computer from sleep to run a queue, and keeps it awake while thequeue runs: on Windows when the power plan allows wake timers (the Scheduler says when itdoesn't), on Linux once an administrator allows it, and on macOS it says why it can'tdiff --git a/tools/lab/wsl/README.md b/tools/lab/wsl/README.mdnew file mode 100644index 00000000..c561c26f--- /dev/null+++ b/tools/lab/wsl/README.md@@ -0,0 +1,128 @@+# mdm-lab: Linux builds and window shots on WSL2++`mdm-lab` is a WSL2 distribution (Ubuntu 24.04) of its own. It builds MDM for Linux at the PC's+full speed and screenshots its windows on a virtual screen (Xvfb) that never shows on Windows.+The VirtualBox machines in [`../linux-vm/`](../linux-vm/) run on top of Hyper-V here (VirtualBox's+NEM mode), about three times slower: builds there took 15 to 60 minutes and a shot about 40 s.+Here a build of main takes under 5 minutes from scratch and about 35 s after a one-line change,+and a window shot about 1.2 s. This lab takes over those two jobs, and `deploy.ps1` hands its+builds to the VMs for the checks only a real desktop can do.++## Setting it up++From PowerShell on the Windows host, once:++```powershell+wsl --install -d Ubuntu-24.04 --name mdm-lab --location C:\mdm-wsl --no-launch+wsl -d mdm-lab -u root -- bash /mnt/d/Projects/misterdownloadmanager/tools/lab/wsl/setup.sh+wsl --terminate mdm-lab # its wsl.conf applies at the next start+```++`setup.sh` (as root) writes the distribution's `/etc/wsl.conf` (systemd, the `lab` user, and no+interop: nothing in mdm-lab can start a Windows program), installs the build's libraries (those of+`ci.yml` and the VMs), Xvfb, Metacity, ImageMagick, xwd, xdotool, wmctrl, Mesa's software OpenGL+and Vulkan (llvmpipe, lavapipe), ffmpeg, 7-Zip and an Ubuntu desktop's fonts with every script+MDM's languages need, then, as `lab`: Rust, the VMs' `vmtest`+cargo profile, the checkout in `~/src/mdm` (the distribution's own ext4 disk: building from+`/mnt/c` or `/mnt/d` goes through 9P and is many times slower) and the lab scripts in+`~/lab/tools/`. Running it again only adds what's missing and refreshes the scripts.++After a change to these scripts, the same `setup.sh` line copies them in again (a minute: the+packages are there already).++From Git Bash rather than PowerShell, prefix `MSYS_NO_PATHCONV=1` (or Git Bash rewrites `/mnt/...`+and `~/...` paths) and use `wsl -d mdm-lab --exec bash -c '...'` when the command has `$VARIABLES`:+without `--exec`, `wsl.exe` hands the line to a shell that expands them first.++It changes nothing outside mdm-lab: never `%USERPROFILE%\.wslconfig` and never another+distribution. Never run `wsl --shutdown` for it (that stops every distribution): `wsl --terminate+mdm-lab` stops this one.++## Building++```powershell+wsl -d mdm-lab -- bash ~/lab/tools/build.sh main # ~/lab/bin/main/+wsl -d mdm-lab -- bash ~/lab/tools/build.sh pr/167 pr-167 # a pull request, labelled+wsl -d mdm-lab -- bash ~/lab/tools/build.sh --release main # fat LTO, what ships: main-release+```++A branch, `pr/<number>` or a commit is fetched and checked out (detached), built with the+`vmtest` profile (release without LTO, incremental) on every core, and its four programs+(`misterdownloadmanager`, `-nmhost`, `-cli`, `labserver`) copied to `~/lab/bin/<label>/` with a+`COMMIT` file. The target folder stays, so the next build recompiles only what changed. The log+is `~/lab/build.log`. Builds take turns (a lock): every caller shares the one checkout. From Windows the builds are at `\\wsl$\mdm-lab\home\lab\lab\bin\`.++## Window shots++```powershell+wsl -d mdm-lab -- bash ~/lab/tools/shots.sh main --langs en,de,ar,ja,hi+wsl -d mdm-lab -- bash ~/lab/tools/shots.sh pr-199 --modes light,dark --theme adwaita `+ --windows main,options-general=options:general,about+```++One MDM per language and mode: each window opens through MDM's own `/show <window>` command line,+is shot once it has painted (`capture.py`: two reads of it in a row the same, at most 2 s for a+window that never settles, such as progress), with its title bar and borders, is closed from its+title bar, then the next. No restart per shot. The default list is 21 windows: the main window and the 20+dialogs of `tools/lab/docs-shots.ps1` (`<file name>=<show argument>` when they differ). Lists+take commas: `wsl.exe` hands its command line to a shell again, which splits quoted spaces. A+`menu:...` show is shot with the main window, grown by `MDM_GROW` pixels (default 300).++Each run has its own data folder (`MDM_DATA_DIR`), download folder and lab server (port 8197),+under `~/lab/run/<label>`; the list is downloaded once, for the first language, and given to the+others. `--finished-only` leaves out the download still running (shots that must not change+between runs); `--keep-list` reuses the label's last list (the same names and dates: two runs+compared pixel by pixel). Shots land in `~/lab/shots/<label>/<lang>-<mode>/` with `timing.txt`.+`MDM_SET` adds settings (a JSON object), as in `../linux-vm/win.sh`; other `MDM_*` variables+(`MDM_RENDERER`, `MDM_OFFSCREEN`, ...) reach MDM.++`renderers.sh <label>` compares OpenGL and Vulkan (lavapipe) on nine windows, pixel by pixel+(`pixdiff.py` from `../linux-vm/`), for builds with View → Draw with → Vulkan: forced, as the+saved choice (OpenGL, saying why, with no hardware driver) and with `MDM_TEST_SOFTWARE_CARD=1`.++`screen.sh start|stop|status` runs the virtual screen by hand (`shots.sh` starts it itself):+Xvfb `:99` at 1600x1000, a session bus, and Metacity (GNOME's window manager, without a+compositor) for title bars and borders. For anything else on that screen:++```bash+. ~/lab/tools/env.sh && bash ~/lab/tools/screen.sh start+~/lab/bin/main/misterdownloadmanager & # on :99, never on Windows+import -window root /tmp/screen.png # or capture.py <window id> <out.png>+bash ~/lab/tools/screen.sh stop # MDM, the lab server and the screen ended+```++### Why nothing shows on Windows++WSLg shows Linux windows on the Windows desktop and plays their sound there, and it can only be+turned off for every distribution at once (`guiApplications` in `.wslconfig`), which the lab leaves+alone. So `env.sh`, which every lab script sources, removes `WAYLAND_DISPLAY` and `PULSE_SERVER`,+points `DISPLAY` at `:99` and `XDG_RUNTIME_DIR` at the lab's own folder (WSLg's Wayland and+PulseAudio sockets are in its own), and draws with software OpenGL (llvmpipe). With interop off,+`xdg-open` can't reach a Windows browser either.++## Into a VM++```powershell+tools\lab\wsl\deploy.ps1 main mdm-ubuntu # mdm-lab's ~/lab/bin/main -> the VM's+tools\lab\wsl\deploy.ps1 pr-167 mdm-kde -DryRun # what it would copy (no VBoxManage call)+```++The programs are read from `\\wsl$\mdm-lab\...` and copied with `VBoxManage guestcontrol copyto`+into a folder beside `~/lab/bin/<label>/`, then swapped in whole. The VM must be running. Its+account comes from `MDM_VM_USER` / `MDM_VM_PASSWORD` or the git-ignored `k\vm-ubuntu.txt`. The VM's+own harnesses (`win.sh`, `shots.sh`, `streams.mjs`, ...) then run that build as one of theirs.++## What mdm-lab can't replace++Builds and window shots, yes; a desktop, no. These still need the VMs in `../linux-vm/`:++- **The desktop's portals and settings**: the GNOME and KDE file choosers (xdg-desktop-portal),+ the system's dark mode, accent and contrast as MDM reads them, notifications.+- **The tray**: there is no StatusNotifier host or AppIndicator on Xvfb, so the tray icon, its+ menu and Hide to the notification area can't be checked here.+- **Real browsers and native messaging**: the Snap Firefox, Chromium and Google Chrome with the+ extension handing downloads and streams to MDM (`streams.mjs`, `store-check.mjs`, ...).+- **Desktop-specific behaviour**: GNOME Shell's, KWin's, Cinnamon's or XFCE's own window+ placement, focus, frames and Wayland sessions; AT-SPI and screen readers; real hardware OpenGL.+ Metacity's frames look like GNOME's but are not GNOME Shell's.+- **Sound** and anything else that leaves the machine through the desktop.diff --git a/tools/lab/wsl/build.sh b/tools/lab/wsl/build.shnew file mode 100644index 00000000..16b2a4e8--- /dev/null+++ b/tools/lab/wsl/build.sh@@ -0,0 +1,51 @@+#!/usr/bin/env bash+# Build a branch, PR or commit of MDM in mdm-lab and copy its programs to ~/lab/bin/<label>/.+#+# build.sh [--release] [<branch, pr/<number> or commit>] [<label>] e.g. build.sh main+# build.sh pr/167 pr-167+# From Windows: wsl -d mdm-lab -- bash ~/lab/tools/build.sh main+#+# The checkout is ~/src/mdm on the distribution's own disk (ext4); its target folder stays there,+# so each build after the first recompiles only what changed. The profile is `vmtest` (the VMs'+# own: release without the shipping build's fat LTO, incremental), or `release` with --release+# (fat LTO, what ships: for checks of speed or size). All cores. No ref (or ""): the checkout as+# it is, e.g. `build.sh "" try` after an edit in ~/src/mdm.+# The log is ~/lab/build.log (the last build's).+set -uo pipefail+. "$HOME/.cargo/env"+profile=${MDM_PROFILE:-vmtest}+if [ "${1:-}" = --release ]; then profile=release; shift; fi+cd "$HOME/src/mdm" || { echo "== no checkout at ~/src/mdm: run setup.sh"; exit 1; }+# One build at a time: every caller shares the checkout (another one waits here, not mid-way+# through a checkout of a different ref).+mkdir -p "$HOME/lab"+exec 9>"$HOME/lab/build.lock"+flock -n 9 || { echo "== another build is running; waiting for it"; flock 9; }+ref_name=${1:-HEAD} # "" or none: the checkout as it is+if [ -n "${1:-}" ]; then+ git fetch -q origin '+refs/heads/*:refs/remotes/origin/*' '+refs/pull/*/head:refs/remotes/origin/pr/*'+ ref=$(git rev-parse -q --verify "origin/$1^{commit}" || git rev-parse -q --verify "$1^{commit}") || {+ echo "== no branch, PR or commit named $1"; exit 1; }+ # A scratch checkout: a Cargo.lock a test run rewrote must not keep it on the last commit.+ git checkout -q -f --detach "$ref" || { echo "== could not check out $1"; exit 1; }+fi+label=${2:-$(echo "$ref_name" | tr '/' '-')}+[ "$profile" = release ] && [ $# -lt 2 ] && label="$label-release"+mkdir -p "$HOME/lab"+log="$HOME/lab/build.log"+jobs=$(nproc)+{+ echo "== $(git log --oneline -1)"+ echo "== cargo build --profile $profile -j $jobs (app, browser host, command line, lab server) -> ~/lab/bin/$label"+} | tee "$log"+start=$(cut -d. -f1 /proc/uptime) # not the wall clock: WSL's jumps when it syncs+cargo build --profile "$profile" -j "$jobs" -p mdm-app -p mdm-nmhost -p mdm-cli -p mdm-labserver 2>&1 | tee -a "$log"+status=${PIPESTATUS[0]}+if [ "$status" = 0 ]; then+ out=target/$profile; [ "$profile" = dev ] && out=target/debug+ mkdir -p "$HOME/lab/bin/$label"+ cp "$out"/misterdownloadmanager{,-nmhost,-cli} "$out"/labserver "$HOME/lab/bin/$label/"+ git log --oneline -1 > "$HOME/lab/bin/$label/COMMIT"+fi+echo "== exit $status after $(( $(cut -d. -f1 /proc/uptime) - start )) s" | tee -a "$log"+exit "$status"diff --git a/tools/lab/wsl/capture.py b/tools/lab/wsl/capture.pynew file mode 100644index 00000000..0db41d38--- /dev/null+++ b/tools/lab/wsl/capture.py@@ -0,0 +1,96 @@+"""One window of the lab's virtual screen into a PNG, once it has painted (shots.sh).++ python3 capture.py <window id> <out.png> [grow px] [wait s]++Whether the window has painted is read from its client area with xwd (about 20 ms a read): two+reads in a row the same, and more than one colour. A window that never settles (a progress+window's numbers, a blinking text caret) is taken as it is after `wait` seconds. Before each+read the pointer moves a pixel at the screen's edge: on X11, menus and some repaints only paint+after the pointer moves. Then the shot itself: the window with its title bar and borders,+Metacity's frame window (the client's parent), through ImageMagick's `import -window <frame>`+(0.1 to 0.7 s, once; xwd reads a dialog's frame as black); grown by `grow` px on every side (a+menu past the window's edge), a part of the whole screen instead (`import -window root -crop`),+clipped to the screen. Exit 1: no shot.+"""+import hashlib+import io+import re+import struct+import subprocess+import sys+import time++from PIL import Image+++def run(*args):+ return subprocess.run(args, capture_output=True, check=False).stdout+++def grab(*args):+ """A PPM image from ImageMagick's import, or None."""+ data = run("import", "-silent", *args, "-depth", "8", "ppm:-")+ try:+ return Image.open(io.BytesIO(data)).convert("RGB")+ except OSError:+ return None+++def outer(win):+ """The frame window around `win` (its parent), or `win` itself when it has none."""+ tree = run("xwininfo", "-children", "-id", win).decode(errors="replace")+ parent = re.search(r"Parent window id: (0x[0-9a-f]+)( \(the root window\))?", tree)+ return win if not parent or parent.group(2) else parent.group(1)+++def box(win, grow, sw, sh):+ """The frame's rectangle on the screen, grown and clipped: (x, y, w, h)."""+ info = run("xwininfo", "-id", outer(win)).decode(errors="replace")+ num = lambda label: int(re.search(label + r":\s+(-?\d+)", info).group(1))+ x, y = num("Absolute upper-left X") - grow, num("Absolute upper-left Y") - grow+ w, h = num("Width") + 2 * grow, num("Height") + 2 * grow+ x0, y0 = max(x, 0), max(y, 0)+ return x0, y0, min(x + w, sw) - x0, min(y + h, sh) - y0+++def client(win):+ """The client area's pixels as xwd reads them (bytes), or None when the window is gone."""+ data = run("xwd", "-silent", "-id", win)+ if len(data) < 100:+ return None+ head = struct.unpack(">25I", data[:100])+ return data[head[0] + 12 * head[19] :]+++def main(win, out, grow=0, wait=2.0):+ grow, until = int(grow), time.monotonic() + float(wait)+ sw, sh = (int(v) for v in run("xdotool", "getdisplaygeometry").split())+ prev = None+ while time.monotonic() < until:+ run("xdotool", "mousemove", str(sw - 3), str(sh // 2))+ run("xdotool", "mousemove", str(sw - 2), str(sh // 2))+ pixels = client(win)+ if pixels is not None:+ digest = hashlib.md5(pixels).digest()+ # One colour (each 4-byte pixel the same as the first): not drawn yet.+ drawn = pixels[:4] * (len(pixels) // 4) != pixels[: len(pixels) // 4 * 4]+ if digest == prev and drawn:+ break+ prev = digest+ time.sleep(0.05)+ shot = None+ if grow:+ try:+ x, y, w, h = box(win, grow, sw, sh)+ shot = grab("-window", "root", "-crop", f"{w}x{h}+{x}+{y}", "+repage")+ except AttributeError: # the window is gone+ pass+ else:+ shot = grab("-window", outer(win))+ if shot is None:+ sys.exit(1)+ shot.save(out)+++if __name__ == "__main__":+ main(*sys.argv[1:])diff --git a/tools/lab/wsl/deploy.ps1 b/tools/lab/wsl/deploy.ps1new file mode 100644index 00000000..725cc330--- /dev/null+++ b/tools/lab/wsl/deploy.ps1@@ -0,0 +1,61 @@+<#+A build from mdm-lab (WSL2) into a VirtualBox lab machine's ~/lab/bin/<label>/, so a check on a+real desktop (GNOME or KDE portals, the tray, real browsers) never waits for the VM to build.++ tools/lab/wsl/deploy.ps1 <label> [<vm>] [-DryRun] e.g. deploy.ps1 main mdm-ubuntu++The programs are read straight from the distribution's disk (\\wsl$\mdm-lab\home\lab\lab\bin\<label>)+and copied with VBoxManage guestcontrol into a folder beside the target, then renamed into place+(a running program or script is never overwritten half-way). The VM must be running; nothing else+of it changes. Its account: MDM_VM_USER / MDM_VM_PASSWORD, or the git-ignored k/vm-ubuntu.txt+("user: <name>" and "password: <word>" lines), never printed. -DryRun: what it would copy, and+where, without calling VBoxManage (its guestcontrol copyto has no dry run of its own).+#>+param(+ [Parameter(Position = 0, Mandatory)] [string] $Label,+ [Parameter(Position = 1)] [string] $Vm = 'mdm-ubuntu',+ [string] $Distro = 'mdm-lab',+ [switch] $DryRun+)+$ErrorActionPreference = 'Stop'+$vbox = Join-Path $env:ProgramFiles 'Oracle\VirtualBox\VBoxManage.exe'+if ($Label -notmatch '^[A-Za-z0-9._-]+$') { throw "label: letters, digits, '.', '_' and '-' only" }++$user = $env:MDM_VM_USER; $pass = $env:MDM_VM_PASSWORD+# k\ is in the main checkout (a worktree has none): found through git's common folder.+$common = git -C $PSScriptRoot rev-parse --path-format=absolute --git-common-dir 2>$null+$keys = if ($common) { Join-Path (Split-Path -Parent $common) 'k\vm-ubuntu.txt' } else { '' }+if ((-not $user -or -not $pass) -and $keys -and (Test-Path $keys)) {+ foreach ($line in Get-Content $keys) {+ if (-not $user -and $line -match '^\s*user:\s*(\S+)') { $user = $Matches[1] }+ if (-not $pass -and $line -match '^\s*password:\s*(\S+)') { $pass = $Matches[1] }+ }+}+if (-not $user -or -not $pass) { throw "no VM account: set MDM_VM_USER and MDM_VM_PASSWORD, or k\vm-ubuntu.txt" }+$auth = @('--username', $user, '--password', $pass)++$src = "\\wsl$\$Distro\home\lab\lab\bin\$Label"+if (-not (Test-Path "$src\misterdownloadmanager")) { throw "no build $Label in $Distro (tools/lab/wsl/build.sh)" }++function Invoke-Guest([string] $Command) {+ & $vbox guestcontrol $Vm run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c $Command+ if ($LASTEXITCODE) { throw "guest command failed ($LASTEXITCODE)" }+}++$files = Get-ChildItem -File $src | ForEach-Object FullName+$incoming = "/home/$user/lab/bin/.incoming-$Label"+$started = Get-Date+if ($DryRun) {+ foreach ($f in Get-ChildItem -File $src) { " {0,-32} {1,10:N0} bytes" -f $f.Name, $f.Length }+ "dry run: these $($files.Count) files would go to $Vm ~/lab/bin/$Label (through $incoming/); nothing copied"+ return+}+$state = (& $vbox showvminfo $Vm --machinereadable | Select-String '^VMState=').ToString()+if ($state -notmatch 'running') { throw "$Vm is not running ($state)" }+Invoke-Guest "rm -rf '$incoming' && mkdir -p '$incoming'"+& $vbox guestcontrol $Vm copyto @auth --target-directory "$incoming/" @files+if ($LASTEXITCODE) { throw "copy to $Vm failed ($LASTEXITCODE)" }+# The copy keeps no file modes: the programs made runnable, then swapped in whole.+Invoke-Guest "chmod +x '$incoming'/* && rm -rf ~/lab/bin/'$Label' && mv '$incoming' ~/lab/bin/'$Label' && ls -l ~/lab/bin/'$Label'"+$mb = [math]::Round(((Get-ChildItem -File $src | Measure-Object Length -Sum).Sum / 1MB), 1)+"deployed $Label ($mb MB) to $Vm ~/lab/bin/$Label in $([math]::Round(((Get-Date) - $started).TotalSeconds, 1)) s"diff --git a/tools/lab/wsl/env.sh b/tools/lab/wsl/env.shnew file mode 100644index 00000000..53fd4da6--- /dev/null+++ b/tools/lab/wsl/env.sh@@ -0,0 +1,22 @@+# Sourced by every mdm-lab script that starts a program with a window: it opens on the lab's+# own virtual screen (Xvfb :99, screen.sh), never on Windows.+#+# WSLg would show a Linux window on the Windows desktop (Wayland at WAYLAND_DISPLAY, X11 at :0)+# and play its sound there (PULSE_SERVER), and it can't be turned off for one distribution+# (guiApplications is a global .wslconfig key, left alone). So its variables go, the display is+# :99, and the runtime folder (where Wayland and PulseAudio sockets are looked for) is the+# lab's own, never WSLg's /mnt/wslg/runtime-dir.+unset WAYLAND_DISPLAY WAYLAND_SOCKET PULSE_SERVER PULSE_RUNTIME_PATH+export DISPLAY=:99+export XDG_RUNTIME_DIR=$HOME/lab/xdg-run+mkdir -p "$XDG_RUNTIME_DIR" && chmod 700 "$XDG_RUNTIME_DIR"+export XDG_SESSION_TYPE=x11+# The session bus screen.sh starts for the virtual screen (GTK's dialogs want one).+export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus+# Software OpenGL (Mesa's llvmpipe), as on a machine without a GPU: the same pixels every run,+# and nothing goes through WSL's GPU bridge to Windows.+export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe+# A browser or file manager MDM asks for (xdg-open) has nowhere to go: interop is off and none+# is installed; BROWSER says so plainly.+export BROWSER=/bin/false+[ -f "$HOME/.cargo/env" ] && . "$HOME/.cargo/env"diff --git a/tools/lab/wsl/renderers.sh b/tools/lab/wsl/renderers.shnew file mode 100644index 00000000..95b0f85e--- /dev/null+++ b/tools/lab/wsl/renderers.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash+# OpenGL against Vulkan (Mesa's lavapipe, the lab's only Vulkan driver) on the same windows and+# the same list, pixel by pixel: four runs of shots.sh and pixdiff.py's report on each. For+# builds that have View -> Draw with -> Vulkan (#206).+#+# renderers.sh <label> e.g. renderers.sh pr-221 -> ~/lab/vk/<label>/+#+# Runs: opengl (the reference), opengl again (what differs between two identical runs: a text+# caret's blink), lavapipe (MDM_RENDERER: Vulkan forced onto the software driver), the saved+# choice Vulkan (with no hardware driver: OpenGL, saying why), and the saved choice with+# MDM_TEST_SOFTWARE_CARD=1 (an off-screen run that takes lavapipe for a card). Each run's+# "drawing with" lines from MDM's log are printed under it.+label=${1:?usage: renderers.sh <label>}+W=main,about,options-general=options:general,options-connection=options:connection,scheduler,add-url=addurl,speed-limiter=speedlimit,find,options-panels=options:panels+out=$HOME/lab/vk/$label; rm -rf "$out"; mkdir -p "$out"+logs() {+ grep -h -E 'drawing with|first frame drawn|failed here|software renderer counts' \+ "$HOME/lab/run/$label"/data-en-light/logs/*.log 2>/dev/null | cut -c1-220 | sed 's/^/ /'+}+keep=""+run() { # run <name> <VAR=value...>+ local name=$1; shift+ echo "== $name: $*"+ env "$@" bash "$HOME/lab/tools/shots.sh" "$label" --finished-only $keep --windows "$W" --out "$out/$name" | tail -1+ logs+ keep=--keep-list+}+run opengl MDM_RENDERER=opengl+run opengl-again MDM_RENDERER=opengl+run lavapipe MDM_RENDERER=lavapipe+run setting-vulkan 'MDM_SET={"renderer":"vulkan"}'+run setting-vulkan-softcard 'MDM_SET={"renderer":"vulkan"}' MDM_OFFSCREEN=1 MDM_OFFSCREEN_AT=0,0 MDM_TEST_SOFTWARE_CARD=1+for b in opengl-again lavapipe setting-vulkan setting-vulkan-softcard; do+ echo "== opengl against $b"+ python3 "$HOME/lab/tools/pixdiff.py" "$out/opengl/en-light" "$out/$b/en-light" "$out/diff-$b" | sed 's/^/ /'+donediff --git a/tools/lab/wsl/screen.sh b/tools/lab/wsl/screen.shnew file mode 100644index 00000000..0eba9aa2--- /dev/null+++ b/tools/lab/wsl/screen.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+# The lab's virtual screen: Xvfb :99 (1600x1000, 24-bit), a session bus and Metacity, GNOME's+# window manager without a compositor (title bars and borders as on a desktop; a capture of+# the screen reads what was drawn). Nothing of it shows on Windows (env.sh).+#+# screen.sh start started if it isn't (shots.sh starts it itself)+# screen.sh stop the screen ended, with every MDM, lab server and window on it (all of the+# lab user's: not while someone else's shots.sh runs, it holds ~/lab/screen.lock)+# screen.sh status+. "$HOME/lab/tools/env.sh"+run=$XDG_RUNTIME_DIR+# (Programs that stay are started with `9>&-`: shots.sh's lock, fd 9, must not stay with them.)+up() { xdpyinfo >/dev/null 2>&1; }+case "${1:-status}" in+ start)+ if ! up; then+ # WSLg mounts /tmp/.X11-unix read-only: Xvfb can't put its socket file there and listens+ # on the abstract socket alone, which every X client tries first.+ setsid -f Xvfb :99 -screen 0 1600x1000x24 -nolisten tcp -dpi 96 >"$run/xvfb.log" 2>&1 </dev/null 9>&-+ for _ in $(seq 50); do up && break; sleep 0.1; done+ up || { echo "Xvfb did not start:"; cat "$run/xvfb.log"; exit 1; }+ fi+ if [ ! -S "$run/bus" ]; then+ dbus-daemon --session --address="unix:path=$run/bus" --fork --print-pid >"$run/dbus.pid" 9>&-+ fi+ if ! pgrep -u "$(id -u)" -x metacity >/dev/null; then+ setsid -f metacity --replace --no-composite >"$run/metacity.log" 2>&1 </dev/null 9>&-+ for _ in $(seq 50); do xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | grep -q 'window id' && break; sleep 0.1; done+ fi+ # The pointer parked at the right edge: no hover or tooltip in a shot.+ xdotool mousemove 1598 500+ echo "screen :99 up ($(xdpyinfo | awk '/dimensions:/ {print $2}'), $(wmctrl -m | awk '/Name:/ {print $2}'))"+ ;;+ stop)+ exec 9>"$HOME/lab/screen.lock"+ flock -n 9 || { echo "shots.sh is running (~/lab/screen.lock): not stopped"; exit 1; }+ pkill -u "$(id -u)" -x misterdownloadm+ pkill -u "$(id -u)" -x labserver+ sleep 1+ pkill -9 -u "$(id -u)" -x misterdownloadm+ pkill -u "$(id -u)" -x metacity+ [ -f "$run/dbus.pid" ] && kill "$(cat "$run/dbus.pid")" 2>/dev/null; rm -f "$run/dbus.pid" "$run/bus"+ pkill -u "$(id -u)" -x Xvfb+ echo "screen :99 stopped"+ ;;+ status)+ if up; then echo "screen :99 up"; wmctrl -lp 2>/dev/null; else echo "screen :99 down"; fi+ ;;+ *) echo "screen.sh start|stop|status"; exit 2 ;;+esacdiff --git a/tools/lab/wsl/setup.sh b/tools/lab/wsl/setup.shnew file mode 100644index 00000000..798abecc--- /dev/null+++ b/tools/lab/wsl/setup.sh@@ -0,0 +1,99 @@+#!/usr/bin/env bash+# mdm-lab: a WSL2 distribution that builds MDM for Linux at the PC's full speed and screenshots+# its windows on a virtual screen (Xvfb) that never shows on Windows. It replaces the VirtualBox+# machines for builds and window shots (those run about 3x slower under Hyper-V); README.md says+# what still needs them.+#+# From Windows (PowerShell), once:+# wsl --install -d Ubuntu-24.04 --name mdm-lab --location C:\mdm-wsl --no-launch+# wsl -d mdm-lab -u root -- bash /mnt/c/<checkout>/tools/lab/wsl/setup.sh+# wsl --terminate mdm-lab # wsl.conf (no Windows programs, user lab) applies at the next start+# Running it again only adds what's missing and updates the checkout. It touches nothing outside+# mdm-lab: never %USERPROFILE%\.wslconfig, never another distribution.+set -euo pipefail+[ "$(id -u)" = 0 ] || { echo "run as root: wsl -d mdm-lab -u root -- bash $0" >&2; exit 2; }+user=lab+repo_url=https://github.com/anefzaoui/misterdownloadmanager.git+export DEBIAN_FRONTEND=noninteractive++# --- The distribution's own settings (per distribution; .wslconfig is global and stays as it is).+# Interop off: nothing in here can start a Windows program (a browser, explorer.exe), and+# Windows' PATH stays out of builds. WSLg can't be turned off per distribution (guiApplications+# is a .wslconfig key), so env.sh keeps every program off its display, sound and runtime folder.+cat > /etc/wsl.conf <<'EOF'+# mdm-lab: MDM's build and screenshot machine (tools/lab/wsl/setup.sh).+[boot]+systemd=true++[interop]+enabled=false+appendWindowsPath=false++[user]+default=lab+EOF+id "$user" >/dev/null 2>&1 || useradd -m -s /bin/bash -G sudo "$user"+echo "$user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$user+chmod 440 /etc/sudoers.d/$user++# --- Packages: the build's libraries (the same as ci.yml, release.yml and the VMs' setup.sh),+# the helpers MDM drives (ffmpeg, 7-Zip: their windows show what is found), the virtual screen+# with a window manager that frames windows as a desktop does (Metacity: GNOME's own frames,+# without a compositor, so a capture reads the screen as drawn), capture and input tools, and+# the fonts of an Ubuntu desktop with every script the languages need.+apt-get update -q+apt-get install -y -q --no-install-recommends \+ build-essential pkg-config git curl ca-certificates python3 python3-pil \+ libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \+ libgl1-mesa-dri libglx-mesa0 mesa-utils mesa-vulkan-drivers vulkan-tools \+ xvfb xauth x11-utils x11-apps x11-xserver-utils xdotool wmctrl imagemagick metacity dbus-x11 \+ adwaita-icon-theme gnome-themes-extra yaru-theme-gtk yaru-theme-icon \+ ffmpeg p7zip-full \+ fontconfig fonts-ubuntu fonts-dejavu-core fonts-freefont-ttf fonts-liberation \+ fonts-noto-core fonts-noto-ui-core fonts-noto-mono fonts-noto-cjk fonts-noto-color-emoji \+ fonts-kacst fonts-indic fonts-khmeros-core fonts-lao fonts-thai-tlwg fonts-sil-abyssinica+fc-cache -f >/dev/null++# --- As lab: Rust, the lab's cargo profile, the checkout on the distribution's own disk (ext4:+# building from /mnt/c or /mnt/d goes through 9P, many times slower).+here=$(cd "$(dirname "$0")" && pwd)+sudo -u "$user" -H bash -s "$repo_url" "$here" <<'USER'+set -euo pipefail+repo_url=$1; here=$2+if [ ! -x "$HOME/.cargo/bin/rustup" ]; then+ curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable+fi+. "$HOME/.cargo/env"+rustup update stable >/dev/null+# The VMs' profile (tools/lab/linux-vm/setup.sh): release without the shipping build's fat LTO,+# incremental, so a branch switch or a one-line change recompiles only what changed.+mkdir -p "$HOME/.cargo"+if ! grep -q 'profile.vmtest' "$HOME/.cargo/config.toml" 2>/dev/null; then+ cat >> "$HOME/.cargo/config.toml" <<'EOF'++[profile.vmtest]+inherits = "release"+lto = false+codegen-units = 256+incremental = true+debug = false+opt-level = 2++[profile.vmtest.package."*"]+opt-level = 3+EOF+fi+mkdir -p "$HOME/src" "$HOME/lab/bin"+[ -d "$HOME/src/mdm/.git" ] || git clone -q "$repo_url" "$HOME/src/mdm"+git -C "$HOME/src/mdm" fetch -q origin+# The lab scripts, copied in so they run from ext4 (refreshed by every setup run).+mkdir -p "$HOME/lab/tools"+cp "$here"/*.sh "$here"/*.py "$here/../linux-vm/pixdiff.py" "$HOME/lab/tools/"+# The toolchain rust-toolchain.toml names, installed now rather than at the first build.+# (Under build.sh's lock: never in the middle of someone's build.)+mkdir -p "$HOME/lab"+(cd "$HOME/src/mdm" && flock "$HOME/lab/build.lock" git checkout -q -f --detach origin/main \+ && rustup show active-toolchain >/dev/null)+echo "lab ready: $(. /etc/os-release; echo "$PRETTY_NAME"), $(rustc --version), $(nproc) cores"+USERdiff --git a/tools/lab/wsl/shots.sh b/tools/lab/wsl/shots.shnew file mode 100644index 00000000..74815753--- /dev/null+++ b/tools/lab/wsl/shots.sh@@ -0,0 +1,205 @@+#!/usr/bin/env bash+# Screenshots of MDM's windows on the lab's virtual screen: ONE MDM per language and mode, each+# window opened by MDM's own command line (`/show <window>`, as tools/lab/docs-shots.ps1 does+# on Windows), captured once it has painted, closed, then the next. Nothing shows on Windows+# (env.sh), nothing is clicked: the pointer only moves at the screen's edge.+#+# shots.sh <label> [--langs en,de,ar] [--modes light,dark] [--windows <name>[=<show>],...]+# [--theme <id>] [--out <dir>] [--finished-only] [--keep-list]+# e.g. shots.sh main --langs en,de,ar,ja,hi+# shots.sh pr-199 --modes dark --theme adwaita --windows main,options-general=options:general+# From Windows: wsl -d mdm-lab -- bash ~/lab/tools/shots.sh main --langs en,de+# (Lists take commas or spaces; commas pass through wsl.exe, which re-parses its command line.)+#+# <label>: a build in ~/lab/bin (build.sh). Shots go to ~/lab/shots/<label>/<lang>-<mode>/<name>.png+# (from Windows: \\wsl$\mdm-lab\home\lab\lab\shots\...), with timing.txt beside them. A window+# name is the file's; `=<show>` is MDM's `/show` argument when it differs (default list: the+# README's 21 windows). `main` is the main window; a `menu:...` show is captured with the main+# window, grown by MDM_GROW pixels (default 300) for menus past its edge.+#+# Each run has its own data folder (MDM_DATA_DIR) and download folder under ~/lab/run/<label>,+# and its own lab server (port 8197): the list looks used (the README's files), downloaded once+# for the first language and given to the others. --finished-only: no download still running (shots+# that must not change between runs: progress and the main window's speeds otherwise do);+# --keep-list: the list of the label's last run again (the same names and dates: two runs+# compared pixel by pixel, e.g. two renderers). MDM_SET: more settings, a JSON object; MDM_* in+# the environment (MDM_RENDERER, ...) reach MDM.+# MDM_OFFSCREEN passes through when set (Xvfb is off the user's screen already, so it's off by+# default: the shots show MDM as a person sees it).+set -uo pipefail+. "$HOME/lab/tools/env.sh"+label=${1:?usage: shots.sh <label> [--langs ...] [--modes ...] [--windows ...] [--theme ...] [--out ...]}+shift+langs="en"; modes="light"; theme=classic; out=""; finished_only=0; keep_list=0+windows="main add-url=addurl batch find speed-limiter=speedlimit properties scheduler about+ options-general=options:general options-connection=options:connection options-save-to=options:saveto+ options-panels=options:panels options-regional=options:regional options-file-types=options:types+ options-archives=options:archives grabber language-picker=language helpers extension+ delete-confirm=delete progress"+while [ $# -gt 0 ]; do+ case "$1" in+ --langs) langs=${2//,/ }; shift ;;+ --modes) modes=${2//,/ }; shift ;;+ --windows) windows=${2//,/ }; shift ;;+ --theme) theme=$2; shift ;;+ --out) out=$2; shift ;;+ --finished-only) finished_only=1 ;;+ --keep-list) keep_list=1 ;;+ *) echo "unknown option $1" >&2; exit 2 ;;+ esac+ shift+done+bin=$HOME/lab/bin/$label+app=$bin/misterdownloadmanager+[ -x "$app" ] || { echo "no build $label in ~/lab/bin (build.sh)"; exit 1; }+out=${out:-$HOME/lab/shots/$label}+work=$HOME/lab/run/$label+port=8197+base=http://127.0.0.1:$port+grow=${MDM_GROW:-300}+mkdir -p "$out"+# One run at a time on the screen (windows raised and closed by another run would land in its+# shots): a second one waits.+exec 9>"$HOME/lab/screen.lock"+flock -n 9 || { echo "another shots.sh is running; waiting for it"; flock 9; }+bash "$HOME/lab/tools/screen.sh" start >/dev/null || exit 1+read -r SW SH < <(xdotool getdisplaygeometry)+# Times from the kernel's uptime: WSL's wall clock jumps (back, too) when it syncs with Windows.+now() { cut -d' ' -f1 /proc/uptime; }+since() { awk -v a="$1" -v b="$(now)" 'BEGIN {printf "%.1f", b - a}'; }++# --- The lab server, ours alone (stopped at the end).+srv_pid=""+cleanup() {+ [ -n "${PID:-}" ] && { kill "$PID" 2>/dev/null; sleep 0.5; kill -9 "$PID" 2>/dev/null; }+ [ -n "$srv_pid" ] && kill "$srv_pid" 2>/dev/null+}+trap cleanup EXIT+if [ "$keep_list" = 1 ] && [ -f "$work/items.json" ]; then+ find "$work" -mindepth 1 -maxdepth 1 ! -name items.json ! -name Downloads -exec rm -rf {} ++else+ rm -rf "$work"+fi+mkdir -p "$work/Downloads"+"$bin/labserver" --bind "127.0.0.1:$port" >"$work/labserver.log" 2>&1 9>&- &+srv_pid=$!++# --- Windows of our MDM (the process id wmctrl reads from _NET_WM_PID), newest last.+mine() { wmctrl -lp 2>/dev/null | awk -v p="$PID" '$3 == p {print $1}'; }+# Capture `win` into `png` once it has painted (capture.py: two captures in a row the same, not+# one colour; at most MDM_SHOT_WAIT seconds, default 2), raised and focused first as a newly+# opened window is (an off-screen run, MDM_OFFSCREEN, leaves a dialog behind its window).+shoot() { # shoot <win> <png> [grow px]+ wmctrl -i -a "$1" 2>/dev/null; sleep 0.1+ python3 "$HOME/lab/tools/capture.py" "$1" "$2" "${3:-0}" "${MDM_SHOT_WAIT:-2}"+}+close_new() { # every window not in $1 (the ones before) closed as a person would (title bar ✕)+ local w+ for w in $(mine); do grep -qx "$w" <<<"$1" || wmctrl -i -c "$w"; done+ for _ in $(seq 30); do [ "$(mine | grep -cvxF -f <(echo "$1"))" = 0 ] && return; sleep 0.1; done+ xdotool key Escape 2>/dev/null+}++# --- The settings every run starts from (docs-shots.ps1's): the language chosen, nothing asked,+# nothing reaching out, every category's folder in the run's download folder.+write_state() { # write_state <data dir> <lang> <mode>+ python3 - "$1/downloads.json" "$2" "$3" "$theme" "$work/Downloads" "$work/items.json" <<'PY'+import json, os, sys+path, lang, mode, theme, dl, items = sys.argv[1:7]+cats = ["General", "Compressed", "Documents", "Music", "Programs", "Video", "Torrents"]+s = dict(language=lang, language_asked=True, helpers_asked=True, extension_never_ask=True,+ dark_mode_support=(mode != "light"), always_dark=(mode == "dark"), theme=theme,+ update_check=False, torrent_incoming=False, torrent_upnp=False, torrent_dht=False,+ torrent_lsd=False, torrent_stop_idle=True,+ category_dirs=[[c, dl if c == "General" else os.path.join(dl, c)] for c in cats])+s.update(json.loads(os.environ.get("MDM_SET") or "{}"))+d = {"next_id": 1, "items": [], "version": 2}+if os.path.exists(items):+ d.update(json.load(open(items)))+d["settings"] = s+json.dump(d, open(path, "w"))+PY+}+# The README's list: finished files and one still coming in (rate-limited per connection).+seed() {+ local f+ for f in big-buck-bunny-1080p.mp4:180M project-report-2026.pdf:4M holiday-photos.zip:64M \+ podcast-episode-42.mp3:38M rust-1.99.1-x86_64-unknown-linux-gnu.tar.xz:92M \+ open-data-2026.csv:12M "ubuntu-26.04-desktop-amd64.iso:6G:?rate=64K"; do+ IFS=: read -r name size q <<<"$f"+ [ "$finished_only" = 1 ] && [ -n "$q" ] && continue+ timeout 20 "$app" /d "$base/gen/$size/$name${q:-}" /p "$work/Downloads" /n >/dev/null 2>&1+ done+ # The finished ones' dialogs (Download complete) closed as they come, never the main window.+ for _ in $(seq 40); do+ for w in $(mine); do [ "$w" != "$MAIN" ] && wmctrl -i -c "$w" 2>/dev/null; done+ sleep 0.25+ done+ python3 - "$DATA/downloads.json" "$work/items.json" <<'PY'+import json, sys+d = json.load(open(sys.argv[1]))+json.dump({"items": d.get("items", []), "next_id": d.get("next_id", 1)}, open(sys.argv[2], "w"))+print(f" list: {len(d.get('items', []))} downloads")+PY+}++total_start=$(now); shots=0; shot_time=0+timing="$out/timing.txt"+echo "label $label ($(cat "$bin/COMMIT" 2>/dev/null)), langs: $langs, modes: $modes, theme $theme" | tee "$timing"+for lang in $langs; do+ for mode in $modes; do+ combo_start=$(now)+ DATA=$work/data-$lang-$mode+ rm -rf "$DATA"; mkdir -p "$DATA"+ write_state "$DATA" "$lang" "$mode"+ export MDM_DATA_DIR=$DATA+ dir="$out/$lang-$mode"; rm -rf "$dir"; mkdir -p "$dir"+ xdotool mousemove $((SW - 2)) $((SH / 2))+ (cd "$work" && setsid -f "$app" >"$DATA/stdout.log" 2>&1 </dev/null 9>&-)+ PID=""+ for _ in $(seq 300); do+ PID=$(pgrep -u "$(id -u)" -f "^$app$" | head -1)+ [ -n "$PID" ] && [ -n "$(mine)" ] && break+ sleep 0.1+ done+ MAIN=$(mine | head -1)+ [ -z "$MAIN" ] && { echo "$lang-$mode: MDM showed no window (see $DATA/stdout.log)"; continue; }+ [ -f "$work/items.json" ] || seed+ started=$(since "$combo_start")+ for entry in $windows; do+ name=${entry%%=*}; show=${entry#*=}+ t0=$(now)+ before=$(mine)+ win=$MAIN; g=0+ case "$show" in+ main) ;;+ menu:*|theme:*) timeout 20 "$app" /show "$show" >/dev/null 2>&1; g=$grow ;;+ *)+ timeout 20 "$app" /show "$show" >/dev/null 2>&1+ # Options with a dialog over it (options:panels): the dialog is the shot. The newest+ # window is the one created last (the highest id: the window manager's list doesn't+ # keep that order).+ want=1; [ "$show" = options:panels ] && want=2+ win=""+ for _ in $(seq 100); do+ new=$(mine | grep -vxF -f <(echo "$before"))+ [ "$(grep -c . <<<"$new")" -ge "$want" ] && {+ win=$(while read -r w; do printf '%d %s\n' "$w" "$w"; done <<<"$new" | sort -n | tail -1 | cut -d' ' -f2)+ break; }+ sleep 0.1+ done+ [ -z "$win" ] && { echo " $name: no window"; continue; }+ ;;+ esac+ shoot "$win" "$dir/$name.png" "$g"+ [ "$show" != main ] && close_new "$before"+ dt=$(since "$t0"); shots=$((shots + 1)); shot_time=$(awk -v a="$shot_time" -v b="$dt" 'BEGIN {print a + b}')+ echo " $lang-$mode/$name.png ${dt}s" >>"$timing"+ done+ kill "$PID" 2>/dev/null; for _ in $(seq 20); do kill -0 "$PID" 2>/dev/null || break; sleep 0.1; done+ kill -9 "$PID" 2>/dev/null; PID=""+ echo "$lang-$mode: start ${started}s, $(ls "$dir" | wc -l) shots, $(since "$combo_start")s in all" | tee -a "$timing"+ done+done+total=$(since "$total_start")+echo "== $shots shots in ${total}s: $(awk -v t="$total" -v n="$shots" 'BEGIN {printf "%.2f", t / (n ? n : 1)}') s per shot in all, $(awk -v t="$shot_time" -v n="$shots" 'BEGIN {printf "%.2f", t / (n ? n : 1)}') s per window shot -> $out" | tee -a "$timing"