From 9b541ac7ccedf9729454ef87125bddd7cd3d6e64 Mon Sep 17 00:00:00 2001 From: Johannes Grof <147989511+jx-grxf@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:30:42 +0100 Subject: [PATCH] Ship rebuilt Wine artifacts and verify engine setup assets --- README.md | 12 + scripts/build-compat-runtime.sh | 19 +- scripts/check-bundle.py | 14 + scripts/check-core.sh | 2 +- scripts/install-candidate-wine.sh | 23 ++ scripts/package-engine.sh | 7 + scripts/tests/test_check_bundle.py | 17 + scripts/tests/test_engine_packaging.py | 112 +++++++ scripts/tests/test_runtime_baseline.py | 25 ++ scripts/update-candidate-runtime.sh | 13 +- .../tests/README-foreground-desktop-probe.md | 66 ++++ winrt/tests/foreground_desktop_probe.c | 294 ++++++++++++++++++ 12 files changed, 577 insertions(+), 27 deletions(-) create mode 100755 scripts/install-candidate-wine.sh create mode 100644 scripts/tests/test_engine_packaging.py create mode 100644 winrt/tests/README-foreground-desktop-probe.md create mode 100644 winrt/tests/foreground_desktop_probe.c diff --git a/README.md b/README.md index f839dfa..3c46613 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,9 @@ room-specific graphics profiles and managed runtime overrides. Live rooms wait until their running programs finish. No component or Windows-version selection is exposed in the normal interface. Concurrent starts share preparation; failed preparation never produces a ready marker and can be retried. +After an engine update, a room whose required files and components are complete +receives the engine/registry/graphics refresh without rerunning its installers. +A failed refresh keeps the previous completion marker so the next launch retries. EXE, MSI and LNK imports share this launch path, including Finder's Open With. Portable applications retain their working directory and must keep their complete folder. Installers are tracked with their child processes, and newly installed @@ -352,6 +355,15 @@ the new engine on their next launch. If `~/WinMac_Virtual` is an unmodified git scripts are updated with `git pull --ff-only` as well. The check can be turned off in the settings; without a window: `"Virtual.app/Contents/MacOS/Virtual" --update`. +Release packaging checks the installed Mac driver's foreground-clearing API +import. Candidate builds install the completed Wine build into staging and copy +all rebuilt artifacts into the isolated runtime, preserving additional graphics +and media libraries. The bundle gate also compares packaged setup scripts and +baseline manifests with the source checkout, so preparation fixes require a +matching engine. The symbol check covers the known stale-driver regression. +App-switch and desktop-lifecycle acceptance checks remain part of runtime testing +in [the foreground probe instructions](winrt/tests/README-foreground-desktop-probe.md). + Publish a new version (requires the GitHub CLI `gh`): ```bash diff --git a/scripts/build-compat-runtime.sh b/scripts/build-compat-runtime.sh index 9763dc4..0e0af2c 100755 --- a/scripts/build-compat-runtime.sh +++ b/scripts/build-compat-runtime.sh @@ -58,23 +58,14 @@ fi echo "==> Kandidat $CANDIDATE (Klon von runtime/)…" rm -rf "$CANDIDATE" cp -cR "$ROOT/runtime" "$CANDIDATE" -replaced=0 +# Refresh the whole completed build. Deployment-target checks alone cannot +# distinguish a current driver from an older implementation targeting macOS 13. +"$ROOT/scripts/install-candidate-wine.sh" "$COMPAT" "$CANDIDATE" >>"$LOG" 2>&1 while IFS= read -r -d '' f; do - m="$(minos "$f")"; [ -n "$m" ] && newer "$m" || continue - rel="${f#$CANDIDATE/wine-build/}"; name="$(basename "$f")"; src="" - case "$rel" in - lib/wine/x86_64-unix/wine) src="$COMPAT/loader/wine" ;; - lib/wine/x86_64-unix/*.so) src="$(find "$COMPAT/dlls" -maxdepth 2 -name "$name" -type f | head -1)" ;; - bin/wineserver) src="$COMPAT/server/wineserver" ;; - bin/wine) src="$COMPAT/tools/wine/wine" ;; - bin/*) src="$(find "$COMPAT/tools" -maxdepth 2 -name "$name" -type f | head -1)" ;; + case "$(file -b "$f")" in + *Mach-O*) codesign -f -s - "$f" >/dev/null 2>&1 ;; esac - case "$name" in winemetal.so) continue ;; esac # DXMT (eigener Build, braucht ohnehin macOS 15) - [ -n "$src" ] && [ -f "$src" ] || { echo "Kein neu gebautes Gegenstück für $rel" >&2; exit 1; } - rm -f "$f"; cp "$src" "$f"; codesign -f -s - "$f" >/dev/null 2>&1 - replaced=$((replaced + 1)) done < <(find "$CANDIDATE/wine-build" -type f \( -name '*.so' -o -perm -u+x \) -print0) -echo " ersetzt: $replaced Dateien" # Wie scripts/bundle-gstreamer.sh: winegstreamer.so findet das gebündelte GStreamer unter lib/gst. GSO="$CANDIDATE/wine-build/lib/wine/x86_64-unix/winegstreamer.so" if [ -f "$GSO" ] && ! otool -l "$GSO" | grep -q "@loader_path/../../gst"; then diff --git a/scripts/check-bundle.py b/scripts/check-bundle.py index d629eb3..ed7c2b2 100644 --- a/scripts/check-bundle.py +++ b/scripts/check-bundle.py @@ -73,6 +73,19 @@ def require_bundle(bundle): return plistlib.load(f) +def require_current_engine_scripts(engine): + # App-only releases can reuse an engine, but a changed preparation script + # must reach users together with the app that was tested against it. + for relative in ('scripts/init-prefix.sh', 'scripts/prepare-room.py', + 'scripts/setup-dotnet48.sh', 'scripts/setup-webview2.sh', + 'scripts/setup-dependencies.sh', 'scripts/install-dotnet-runtime.py', + 'support/runtime-baseline.json', 'support/components.lock.json', + 'setup-graphics.sh'): + packaged = engine / relative + if not packaged.is_file() or digest(packaged) != digest(ROOT / relative): + raise ValueError(f'Engine contains stale or missing setup assets: {relative}') + + def git(*args): return subprocess.check_output(['git', '-C', str(ROOT), *args]).decode().strip() @@ -90,6 +103,7 @@ def main(): # A failed retry must never leave a stale successful receipt at this path. receipt.unlink(missing_ok=True) info = require_bundle(bundle) + require_current_engine_scripts(bundle / 'Contents/Resources/Engine') subprocess.run(['codesign', '--verify', '--deep', '--strict', str(bundle)], check=True) before, entries = inventory(bundle) revision = git('rev-parse', 'HEAD') diff --git a/scripts/check-core.sh b/scripts/check-core.sh index 8b46426..658c27e 100755 --- a/scripts/check-core.sh +++ b/scripts/check-core.sh @@ -10,7 +10,7 @@ if [ -z "${DEVELOPER_DIR:-}" ] && [ -d /Applications/Xcode.app/Contents/Develope fi (cd app && swift test) uv run --with pyyaml python -m unittest discover -s scripts/tests -v -python3 -m unittest discover -s scripts -p test_dotnet_cache.py -v +uv run --with pyyaml python -m unittest discover -s scripts -p test_dotnet_cache.py -v python3 scripts/test-window-levels.py # Prefer the engine bundled in the local app. WINMAC_HOME can select a candidate. diff --git a/scripts/install-candidate-wine.sh b/scripts/install-candidate-wine.sh new file mode 100755 index 0000000..36f3b0f --- /dev/null +++ b/scripts/install-candidate-wine.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Install one completed Wine build into an existing isolated runtime candidate. +set -euo pipefail +BUILD="${1:?Wine build directory required}" +CANDIDATE="${2:?Candidate runtime directory required}" +[ -d "$CANDIDATE/wine-build" ] || { echo "Candidate runtime is missing wine-build." >&2; exit 1; } +STAGE="$(mktemp -d "${TMPDIR:-/tmp}/virtual-wine-install.XXXXXX")" +trap 'rm -rf "$STAGE"' EXIT +if [ -f "$CANDIDATE/wine-build/share/wine/wine.inf" ]; then + cp -p "$CANDIDATE/wine-build/share/wine/wine.inf" "$STAGE/previous-wine.inf" +fi +make -C "$BUILD" install DESTDIR="$STAGE" +INSTALLED="$(find "$STAGE" -type d -name wine-build -prune | head -1)" +[ -n "$INSTALLED" ] && [ -x "$INSTALLED/bin/wine" ] || { + echo "Staged Wine install is missing bin/wine." >&2; exit 1; +} +# Copy every rebuilt artifact, including binaries whose deployment target was +# already supported. Keep the candidate's additional graphics/media libraries. +rsync -a -c "$INSTALLED/" "$CANDIDATE/wine-build/" +INF="$CANDIDATE/wine-build/share/wine/wine.inf" +if [ -f "$STAGE/previous-wine.inf" ] && cmp -s "$STAGE/previous-wine.inf" "$INF"; then + touch -r "$STAGE/previous-wine.inf" "$INF" +fi diff --git a/scripts/package-engine.sh b/scripts/package-engine.sh index 863adc1..0d42c4e 100755 --- a/scripts/package-engine.sh +++ b/scripts/package-engine.sh @@ -7,6 +7,13 @@ DEST="${1:?Destination Engine directory required}" [ "$(basename "$DEST")" = Engine ] || { echo "Destination must be named Engine." >&2; exit 1; } RUNTIME="${WINMAC_RUNTIME:-$ROOT/runtime}" [ -x "$RUNTIME/wine-build/bin/wine" ] || { echo "A source-built Wine engine is required for releases." >&2; exit 1; } +# A build-only Wine run leaves the installed runtime unchanged. Check the driver +# being packaged, since the old foreground path can shut down kiosk desktops. +MAC_DRIVER="$RUNTIME/wine-build/lib/wine/x86_64-unix/winemac.so" +nm -u "$MAC_DRIVER" | awk '$NF == "_NtUserSetForegroundWindow" { found = 1 } END { exit !found }' || { + echo "The installed Mac driver lacks the foreground-clearing API. Rebuild and install Wine before packaging (without WINMAC_BUILD_ONLY=1)." >&2 + exit 1 +} [ -f "$RUNTIME/wine-build/share/wine/mono/wine-mono-10.4.1/support/winemono-support.msi" ] || { echo "Wine Mono is missing; run scripts/setup-managed-runtime.sh first." >&2; exit 1; } diff --git a/scripts/tests/test_check_bundle.py b/scripts/tests/test_check_bundle.py index 54f0d6b..4b93a94 100644 --- a/scripts/tests/test_check_bundle.py +++ b/scripts/tests/test_check_bundle.py @@ -1,5 +1,6 @@ """A passing receipt must identify exact portable bundle bytes.""" import importlib.util +import shutil from pathlib import Path import tempfile import unittest @@ -55,6 +56,22 @@ def test_bundle_without_engine_cannot_be_certified(self): with self.assertRaisesRegex(ValueError, 'Unvollständiges'): gate.require_bundle(root) + def test_current_engine_scripts_are_accepted_and_stale_preparation_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + engine = Path(temporary) + for relative in ('scripts/init-prefix.sh', 'scripts/prepare-room.py', + 'scripts/setup-dotnet48.sh', 'scripts/setup-webview2.sh', + 'scripts/setup-dependencies.sh', 'scripts/install-dotnet-runtime.py', + 'support/runtime-baseline.json', 'support/components.lock.json', + 'setup-graphics.sh'): + target = engine / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(gate.ROOT / relative, target) + gate.require_current_engine_scripts(engine) + (engine / 'scripts/prepare-room.py').write_text('old preparation implementation') + with self.assertRaisesRegex(ValueError, 'scripts/prepare-room.py'): + gate.require_current_engine_scripts(engine) + def test_failed_retry_invalidates_previous_success_receipt(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) diff --git a/scripts/tests/test_engine_packaging.py b/scripts/tests/test_engine_packaging.py new file mode 100644 index 0000000..477f775 --- /dev/null +++ b/scripts/tests/test_engine_packaging.py @@ -0,0 +1,112 @@ +"""Exercise candidate installation and the packaged Mac driver's import gate.""" +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +@unittest.skipUnless(shutil.which('make') and shutil.which('rsync'), 'make and rsync required') +class CandidateInstallationTests(unittest.TestCase): + def test_complete_build_replaces_old_artifacts_and_preserves_additional_libraries(self): + with tempfile.TemporaryDirectory(prefix='virtual-candidate-') as temporary: + root = Path(temporary) + build = root / 'build with spaces' + candidate = root / 'candidate runtime' + staged = build / 'artifacts/wine-build' + existing = candidate / 'wine-build' + for base in (staged, existing): + (base / 'bin').mkdir(parents=True) + (base / 'lib/wine/x86_64-unix').mkdir(parents=True) + (base / 'share/wine').mkdir(parents=True) + (base / 'bin/wine').write_text('#!/bin/sh\nexit 0\n') + (base / 'bin/wine').chmod(0o755) + (base / 'share/wine/wine.inf').write_text('unchanged wine.inf') + old = existing / 'lib/wine/x86_64-unix/winemac.so' + fresh = staged / 'lib/wine/x86_64-unix/winemac.so' + old.write_bytes(b'old driver with an already-supported minimum OS') + fresh.write_bytes(b'rebuilt driver with the same supported minimum OS') + extra = existing / 'lib/wine/x86_64-unix/winemetal.so' + extra.write_bytes(b'additional graphics bridge') + inf = existing / 'share/wine/wine.inf' + os.utime(inf, (1600000000, 1600000000)) + before_mtime = inf.stat().st_mtime_ns + (build / 'Makefile').write_text( + 'install:\n\tmkdir -p "$(DESTDIR)/configured prefix"\n' + '\tcp -R artifacts/wine-build "$(DESTDIR)/configured prefix/"\n') + subprocess.run(['bash', str(ROOT / 'scripts/install-candidate-wine.sh'), + str(build), str(candidate)], check=True, capture_output=True) + self.assertEqual(old.read_bytes(), fresh.read_bytes()) + self.assertEqual(extra.read_bytes(), b'additional graphics bridge') + self.assertEqual(inf.stat().st_mtime_ns, before_mtime) + + def test_incomplete_staged_install_preserves_candidate(self): + with tempfile.TemporaryDirectory(prefix='virtual-candidate-incomplete-') as temporary: + root = Path(temporary) + build = root / 'build' + existing = root / 'candidate/wine-build' + build.mkdir() + existing.mkdir(parents=True) + sentinel = existing / 'driver' + sentinel.write_bytes(b'previous working runtime') + (build / 'Makefile').write_text('install:\n\tmkdir -p "$(DESTDIR)/configured/wine-build"\n') + result = subprocess.run(['bash', str(ROOT / 'scripts/install-candidate-wine.sh'), + str(build), str(existing.parent)], capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('missing bin/wine', result.stderr) + self.assertEqual(sentinel.read_bytes(), b'previous working runtime') + + def test_failed_install_preserves_candidate(self): + with tempfile.TemporaryDirectory(prefix='virtual-candidate-failed-') as temporary: + root = Path(temporary) + build = root / 'build' + existing = root / 'candidate/wine-build' + build.mkdir() + existing.mkdir(parents=True) + sentinel = existing / 'driver' + sentinel.write_bytes(b'previous working runtime') + (build / 'Makefile').write_text('install:\n\texit 23\n') + result = subprocess.run(['bash', str(ROOT / 'scripts/install-candidate-wine.sh'), + str(build), str(existing.parent)], capture_output=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(sentinel.read_bytes(), b'previous working runtime') + + +@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('clang'), 'Mach-O compiler required') +class DriverPackagingTests(unittest.TestCase): + def check_driver(self, symbol): + with tempfile.TemporaryDirectory(prefix='virtual-driver-gate-') as temporary: + root = Path(temporary) + runtime = root / 'runtime' + driver = runtime / 'wine-build/lib/wine/x86_64-unix/winemac.so' + driver.parent.mkdir(parents=True) + wine = runtime / 'wine-build/bin/wine' + wine.parent.mkdir(parents=True) + wine.write_text('#!/bin/sh\nexit 0\n') + wine.chmod(0o755) + source = root / 'driver.c' + source.write_text(f'extern void {symbol}(void);\nvoid deactivate(void) {{ {symbol}(); }}\n') + subprocess.run(['clang', '-dynamiclib', '-Wl,-undefined,dynamic_lookup', + str(source), '-o', str(driver)], check=True, capture_output=True) + return subprocess.run(['bash', str(ROOT / 'scripts/package-engine.sh'), str(root / 'Engine')], + env=dict(os.environ, WINMAC_RUNTIME=str(runtime)), + capture_output=True, text=True) + + def test_old_foreground_driver_is_rejected_before_packaging(self): + result = self.check_driver('NtUserCallHwnd') + self.assertNotEqual(result.returncode, 0) + self.assertIn('lacks the foreground-clearing API', result.stderr) + + def test_correct_import_passes_driver_gate_and_reaches_dependency_checks(self): + result = self.check_driver('NtUserSetForegroundWindow') + self.assertNotEqual(result.returncode, 0) + self.assertIn('Wine Mono is missing', result.stderr) + self.assertNotIn('lacks the foreground-clearing API', result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/tests/test_runtime_baseline.py b/scripts/tests/test_runtime_baseline.py index fff326a..62a3003 100644 --- a/scripts/tests/test_runtime_baseline.py +++ b/scripts/tests/test_runtime_baseline.py @@ -165,6 +165,31 @@ def test_engine_update_migrates_every_existing_room_and_preserves_each_room_data self.assertEqual((second / 'drive_c/two.txt').read_text(), 'second room') self.assertTrue(last.health(second)) + def test_complete_room_refreshes_after_engine_update_without_running_installers(self): + self.prepare() + before = self.operations() + self.write(self.assets / 'engine-version', 'updated-engine') + self.prepare() + self.assertEqual([op[0] for op in self.operations()[len(before):]], ['init']) + self.assertEqual(len(list((self.root / '.virtual/system-bases').glob('*/ready'))), 1) + + def test_failed_refresh_keeps_old_marker_and_can_be_retried(self): + self.prepare() + marker = self.prefix / '.virtual/runtime-baseline' + old = marker.read_text() + self.write(self.assets / 'engine-version', 'updated-engine') + init = self.assets / 'scripts/init-prefix.sh' + original = init.read_text() + self.write(init, '#!/bin/sh\nexit 23\n', executable=True) + with self.assertRaisesRegex(RuntimeError, 'status 23'): + self.prepare() + self.assertEqual(marker.read_text(), old) + self.write(init, original, executable=True) + retry = self.prepare() + self.assertEqual(marker.read_text(), retry.version) + self.assertNotEqual(marker.read_text(), old) + self.assertEqual([op[0] for op in self.operations()], ['init', 'dotnet48', 'components', 'init']) + def test_failed_common_base_cannot_create_a_partially_supported_room(self): self.write(self.root / 'fail', 'installer failure') with self.assertRaisesRegex(RuntimeError, 'status 23'): diff --git a/scripts/update-candidate-runtime.sh b/scripts/update-candidate-runtime.sh index 2743f02..c91f6f6 100755 --- a/scripts/update-candidate-runtime.sh +++ b/scripts/update-candidate-runtime.sh @@ -13,22 +13,16 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" CANDIDATE="$ROOT/${1:-runtime-next}" BUILD="$ROOT/thirdparty/wine-cx-build" -STAGE="$(mktemp -d "${TMPDIR:-/tmp}/virtual-stage.XXXXXX")" -trap 'rm -rf "$STAGE"' EXIT export PATH=/opt/homebrew/opt/bison/bin:/opt/homebrew/opt/flex/bin:/opt/homebrew/bin:$PATH echo "==> Baue $BUILD" nice -n 10 make -C "$BUILD" -j"$(sysctl -n hw.perflevel0.physicalcpu 2>/dev/null || echo 4)" >"$BUILD/make-candidate.out" 2>&1 || { tail -20 "$BUILD/make-candidate.out"; exit 1; } -make -C "$BUILD" install DESTDIR="$STAGE" >"$BUILD/install-candidate.out" 2>&1 -INSTALLED="$(find "$STAGE" -type d -name wine-build -prune | head -1)" -[ -x "$INSTALLED/bin/wine" ] || { echo "make install ohne bin/wine"; exit 1; } echo "==> Kandidat $CANDIDATE (Klon von runtime/)" rm -rf "$CANDIDATE" cp -cR "$ROOT/runtime" "$CANDIDATE" -# Nur geänderte Inhalte übernehmen; zusätzliche Dateien (gst, icu, winemetal) bleiben. -rsync -a -c "$INSTALLED/" "$CANDIDATE/wine-build/" --itemize-changes | { grep -c '^>f' || true; } | sed 's/^/ geänderte Dateien: /' +"$ROOT/scripts/install-candidate-wine.sh" "$BUILD" "$CANDIDATE" >"$BUILD/install-candidate.out" 2>&1 bash "$ROOT/scripts/bundle-gstreamer.sh" "$CANDIDATE/wine-build" >/dev/null for arch in x86_64 i386; do [ -f "$ROOT/thirdparty/icu/out/$arch-windows/icu.dll" ] || continue @@ -36,9 +30,4 @@ for arch in x86_64 i386; do cp "$ROOT/thirdparty/icu/out/$arch-windows/"{icu,icuuc,icuin}.dll "$CANDIDATE/wine-build/lib/icu/$arch-windows/" done "$ROOT/scripts/write-runtime-wrappers.sh" "$CANDIDATE" -if cmp -s "$ROOT/runtime/wine-build/share/wine/wine.inf" "$CANDIDATE/wine-build/share/wine/wine.inf"; then - touch -r "$ROOT/runtime/wine-build/share/wine/wine.inf" "$CANDIDATE/wine-build/share/wine/wine.inf" -else - echo " Hinweis: wine.inf hat sich geändert – Räume aktualisieren sich beim nächsten Start." -fi echo "==> Fertig: $CANDIDATE ($("$CANDIDATE/wine-build/bin/wine" --version))" diff --git a/winrt/tests/README-foreground-desktop-probe.md b/winrt/tests/README-foreground-desktop-probe.md new file mode 100644 index 0000000..bb5d1d3 --- /dev/null +++ b/winrt/tests/README-foreground-desktop-probe.md @@ -0,0 +1,66 @@ +# Foreground and input-desktop probe + +`foreground_desktop_probe.c` is a standalone Win32 probe. It creates only a +visible probe window, an intentionally hidden sentinel, and (for the custom +case) a desktop named `VirtualFocusProbe`. It does not change SEB or another +application's focus policy. + +## Build + +With Zig installed, build the PE executable without a Wine build tree: + +```sh +TEST_DIR=/path/to/Virtual/winrt/tests +ZIG_LOCAL_CACHE_DIR=/tmp/foreground-desktop-probe-zig-cache \ + zig cc -target x86_64-windows-gnu -Wall -Wextra -Werror \ + "$TEST_DIR/foreground_desktop_probe.c" \ + -o /tmp/foreground_desktop_probe.exe -Wl,/subsystem:console +``` + +## Isolated process-exit cases + +Use the `wine` and `wineboot` belonging to the engine under evaluation. Create +a new disposable prefix for each case; never point these commands at a user +room. Initialize each prefix with its engine's `wineboot -u`, then run: + +```sh +WINEPREFIX=/tmp/foreground-probe-graceful WINEARCH=win64 VIRTUAL_STAY_ACTIVE=0 \ + /path/to/engine/bin/wine /tmp/foreground_desktop_probe.exe --lifecycle graceful +WINEPREFIX=/tmp/foreground-probe-abrupt WINEARCH=win64 VIRTUAL_STAY_ACTIVE=0 \ + /path/to/engine/bin/wine /tmp/foreground_desktop_probe.exe --lifecycle abrupt +``` + +The parent must report `custom_seen=1`, `default_restored=1`, the expected child +exit code (`0` graceful, `23` abrupt), and `hidden_visible=0`. The graceful +child destroys its visible window then exits without switching desktops back; +the abrupt child is terminated while its custom desktop is still active. Both +exercise automatic input-desktop restoration. After each run, stop and wait on +only that disposable prefix's wineserver before removing the prefix. +These Win32 assertions do not establish native Mac window visibility. Also +verify that the default desktop's visible window reappears on macOS and that +the intentionally hidden window remains absent. + +## macOS app deactivation observation + +Run one focus case at a time from its own disposable prefix: + +```sh +WINEPREFIX=/tmp/foreground-probe-default WINEARCH=win64 VIRTUAL_STAY_ACTIVE=0 \ + /path/to/engine/bin/wine /tmp/foreground_desktop_probe.exe --focus default 90 +WINEPREFIX=/tmp/foreground-probe-custom WINEARCH=win64 VIRTUAL_STAY_ACTIVE=0 \ + /path/to/engine/bin/wine /tmp/foreground_desktop_probe.exe --focus custom 90 +``` + +While each visible window is active, switch normally to another macOS app once, +wait briefly, then return to the probe. The log records `WM_ACTIVATEAPP`, +`WM_ACTIVATE`, `WM_KILLFOCUS`, the input desktop name, `GetForegroundWindow()`, +and its classification (`zero`, `desktop`, `probe-window`, or +`other-window`). On macOS app deactivation the foreground must become `zero`, +never `desktop`; on return the probe window must be foreground again. +The focus run does not periodically force +foreground after startup, so the user's ordinary deactivation remains real. + +For custom mode, `VirtualFocusProbe` must remain the input desktop through the +macOS app switch and return; this distinguishes app deactivation from a Windows +desktop switch. These are manual UI acceptance cases; merely building or +starting the probe does not establish them. diff --git a/winrt/tests/foreground_desktop_probe.c b/winrt/tests/foreground_desktop_probe.c new file mode 100644 index 0000000..9203c96 --- /dev/null +++ b/winrt/tests/foreground_desktop_probe.c @@ -0,0 +1,294 @@ +/* + * Synthetic Wine foreground/input-desktop probe. + * It creates only its own windows and a uniquely named temporary desktop. + * No application-specific state or focus suppression is involved. + */ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include + +static const char class_name[] = "VirtualForegroundDesktopProbe"; +static HWND main_window; +static BOOL quit_requested; +static BOOL saw_activateapp_off; +static BOOL saw_activateapp_on; + +static void log_foreground(const char *tag) +{ + HWND foreground = GetForegroundWindow(); + HWND desktop = GetDesktopWindow(); + char kind[16]; + + if (!foreground) strcpy(kind, "zero"); + else if (foreground == desktop) strcpy(kind, "desktop"); + else if (foreground == main_window) strcpy(kind, "probe-window"); + else strcpy(kind, "other-window"); + + printf("SAMPLE %s fg=%p kind=%s desktop=%p input=", tag, foreground, kind, desktop); + { + HDESK input = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS); + char name[128] = "unavailable"; + if (input) + { + if (GetUserObjectInformationA(input, UOI_NAME, name, sizeof(name), NULL)) + printf("%s", name); + else printf("unreadable"); + CloseDesktop(input); + } + else printf("unavailable"); + } + printf("\n"); + fflush(stdout); +} + +static LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) +{ + switch (message) + { + case WM_ACTIVATEAPP: + if (wparam) saw_activateapp_on = TRUE; + else saw_activateapp_off = TRUE; + printf("EVENT WM_ACTIVATEAPP active=%u hwnd=%p\n", (unsigned)wparam, hwnd); + log_foreground("activateapp"); + fflush(stdout); + return 0; + case WM_ACTIVATE: + printf("EVENT WM_ACTIVATE state=%u hwnd=%p\n", LOWORD(wparam), hwnd); + log_foreground("activate"); + fflush(stdout); + break; + case WM_KILLFOCUS: + printf("EVENT WM_KILLFOCUS hwnd=%p next=%p\n", hwnd, (HWND)wparam); + log_foreground("killfocus"); + fflush(stdout); + break; + case WM_CLOSE: + quit_requested = TRUE; + DestroyWindow(hwnd); + return 0; + case WM_DESTROY: + if (hwnd == main_window) PostQuitMessage(0); + return 0; + } + return DefWindowProcA(hwnd, message, wparam, lparam); +} + +static BOOL register_window_class(void) +{ + WNDCLASSA cls; + ZeroMemory(&cls, sizeof(cls)); + cls.lpfnWndProc = window_proc; + cls.hInstance = GetModuleHandleA(NULL); + cls.hCursor = LoadCursor(NULL, IDC_ARROW); + cls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + cls.lpszClassName = class_name; + return RegisterClassA(&cls) != 0; +} + +static BOOL input_desktop_is(const char *expected) +{ + char name[128]; + HDESK input = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS); + BOOL matches = FALSE; + if (!input) return FALSE; + if (GetUserObjectInformationA(input, UOI_NAME, name, sizeof(name), NULL)) + matches = lstrcmpiA(name, expected) == 0; + CloseDesktop(input); + return matches; +} + +static int run_child(const char *mode) +{ + HDESK original, temporary; + HWND window; + ULONGLONG deadline; + MSG msg; + + if (strcmp(mode, "graceful") && strcmp(mode, "abrupt")) return 2; + original = OpenInputDesktop(0, FALSE, DESKTOP_SWITCHDESKTOP | DESKTOP_READOBJECTS); + temporary = CreateDesktopA("VirtualFocusProbe", NULL, NULL, 0, GENERIC_ALL, NULL); + if (!original || !temporary || !SetThreadDesktop(temporary)) return 10; + if (!register_window_class()) return 11; + window = CreateWindowA(class_name, "Temporary desktop lifecycle probe", + WS_OVERLAPPEDWINDOW, 100, 100, 460, 240, + NULL, NULL, GetModuleHandleA(NULL), NULL); + if (!window || !SwitchDesktop(temporary)) return 12; + main_window = window; + ShowWindow(window, SW_SHOW); + SetForegroundWindow(window); + UpdateWindow(window); + printf("CHILD mode=%s switched=VirtualFocusProbe window=%p\n", mode, window); + log_foreground("child-start"); + fflush(stdout); + + /* Keep a real Win32 window present while the parent observes the desktop. */ + deadline = GetTickCount64() + 2500; + while (GetTickCount64() < deadline) + { + while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessageA(&msg); + } + Sleep(10); + } + if (!strcmp(mode, "abrupt")) TerminateProcess(GetCurrentProcess(), 23); + /* Destroy the visible window, then exit without SwitchDesktop. Desktop and + * process-handle teardown must restore Default on the server side. */ + DestroyWindow(window); + puts("CHILD graceful-window-close; exiting without SwitchDesktop"); + fflush(stdout); + return 0; +} + +static int run_lifecycle(const char *mode) +{ + char exe[MAX_PATH], command[MAX_PATH + 64]; + STARTUPINFOA startup; + PROCESS_INFORMATION process; + HWND hidden; + BOOL saw_custom = FALSE, saw_default_after = FALSE; + DWORD child_status = STILL_ACTIVE; + ULONGLONG deadline; + + if (strcmp(mode, "graceful") && strcmp(mode, "abrupt")) return 2; + if (!register_window_class()) return 20; + main_window = CreateWindowA(class_name, "Default desktop lifecycle observer", + WS_OVERLAPPEDWINDOW, 40, 40, 460, 240, + NULL, NULL, GetModuleHandleA(NULL), NULL); + hidden = CreateWindowA(class_name, "Intentionally hidden lifecycle sentinel", + WS_OVERLAPPEDWINDOW, 80, 80, 300, 140, + NULL, NULL, GetModuleHandleA(NULL), NULL); + if (!main_window || !hidden) return 21; + ShowWindow(main_window, SW_SHOW); + UpdateWindow(main_window); + if (!input_desktop_is("Default")) return 22; + printf("PHASE initial input=Default hidden_visible=%u\n", IsWindowVisible(hidden)); + log_foreground("initial"); + + GetModuleFileNameA(NULL, exe, sizeof(exe)); + snprintf(command, sizeof(command), "\"%s\" --child %s", exe, mode); + ZeroMemory(&startup, sizeof(startup)); + ZeroMemory(&process, sizeof(process)); + startup.cb = sizeof(startup); + if (!CreateProcessA(exe, command, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process)) + return 23; + + deadline = GetTickCount64() + 15000; + while (GetTickCount64() < deadline) + { + MSG msg; + while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessageA(&msg); + } + if (!saw_custom && input_desktop_is("VirtualFocusProbe")) + { + saw_custom = TRUE; + puts("PHASE temporary input=VirtualFocusProbe"); + log_foreground("temporary"); + } + else if (saw_custom && input_desktop_is("Default")) + { + saw_default_after = TRUE; + puts("PHASE restored input=Default"); + log_foreground("restored"); + break; + } + Sleep(20); + } + WaitForSingleObject(process.hProcess, 3000); + GetExitCodeProcess(process.hProcess, &child_status); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + + if (IsWindowVisible(hidden)) + { + puts("FAIL hidden sentinel became visible"); + return 24; + } + printf("RESULT mode=%s custom_seen=%u default_restored=%u child_exit=%lu hidden_visible=%u\n", + mode, saw_custom, saw_default_after, (unsigned long)child_status, + IsWindowVisible(hidden)); + DestroyWindow(hidden); + DestroyWindow(main_window); + if (!saw_custom || !saw_default_after || child_status != (!strcmp(mode, "abrupt") ? 23u : 0u)) + return 25; + puts("PASS lifecycle: input desktop returned to Default; hidden sentinel stayed hidden"); + return 0; +} + +static int run_focus(BOOL custom, DWORD seconds) +{ + HDESK original = NULL, temporary = NULL; + ULONGLONG deadline, next_sample; + MSG msg; + unsigned long samples = 0; + + if (custom) + { + original = OpenInputDesktop(0, FALSE, DESKTOP_SWITCHDESKTOP | DESKTOP_READOBJECTS); + temporary = CreateDesktopA("VirtualFocusProbe", NULL, NULL, 0, GENERIC_ALL, NULL); + if (!original || !temporary || !SetThreadDesktop(temporary)) return 30; + if (!SwitchDesktop(temporary)) return 31; + } + if (!register_window_class()) return 32; + main_window = CreateWindowA(class_name, + custom ? "Custom desktop focus probe" : "Default desktop focus probe", + WS_OVERLAPPEDWINDOW, 50, 50, 520, 260, + NULL, NULL, GetModuleHandleA(NULL), NULL); + if (!main_window) return 33; + ShowWindow(main_window, SW_SHOW); + SetForegroundWindow(main_window); + UpdateWindow(main_window); + printf("PHASE focus-start desktop=%s hwnd=%p foreground=%p desktop-hwnd=%p\n", + custom ? "VirtualFocusProbe" : "Default", main_window, + GetForegroundWindow(), GetDesktopWindow()); + puts("Observe one ordinary macOS app switch away and back; no focus is forced after startup."); + log_foreground("focus-start"); + deadline = GetTickCount64() + (ULONGLONG)seconds * 1000; + next_sample = GetTickCount64(); + while (GetTickCount64() < deadline && !quit_requested) + { + while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) + { + if (msg.message == WM_QUIT) goto done; + TranslateMessage(&msg); + DispatchMessageA(&msg); + } + if (GetTickCount64() >= next_sample) + { + log_foreground("periodic"); + samples++; + next_sample = GetTickCount64() + 1000; + } + Sleep(20); + } +done: + printf("RESULT focus custom=%u samples=%lu activateapp_off=%u activateapp_on=%u\n", + custom, samples, saw_activateapp_off, saw_activateapp_on); + if (main_window && IsWindow(main_window)) DestroyWindow(main_window); + if (custom && original) SwitchDesktop(original); + if (temporary) CloseDesktop(temporary); + if (original) CloseDesktop(original); + return 0; +} + +int main(int argc, char **argv) +{ + if (argc >= 3 && !strcmp(argv[1], "--child")) return run_child(argv[2]); + if (argc >= 3 && !strcmp(argv[1], "--lifecycle")) return run_lifecycle(argv[2]); + if (argc >= 2 && !strcmp(argv[1], "--focus")) + { + BOOL custom = argc >= 3 && !strcmp(argv[2], "custom"); + DWORD seconds = argc >= 4 ? strtoul(argv[3], NULL, 10) : 60; + if (!seconds || seconds > 3600) return 2; + return run_focus(custom, seconds); + } + fprintf(stderr, "Usage: %s --focus [default|custom] [seconds]\n" + " %s --lifecycle [graceful|abrupt]\n", argv[0], argv[0]); + return 2; +}