Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/quake/quake.ps1

Raw
# Win + physical key below Esc: summon/hide. Ctrl+Alt+Shift+F11: stop controller.
# -Check compiles and checks discovery/hotkey availability without launching a GUI.
# -Background starts hidden. -Stop stops controller, restoring its hidden GUI.
# -InstallTask / -UninstallTask manage explicit, non-elevated per-user logon startup.
# Use -WhatIf with either task switch to preview without changing Task Scheduler.
[CmdletBinding(SupportsShouldProcess)]
param([switch]$Check, [switch]$Background, [switch]$Stop, [string]$ConfigFile,
    [switch]$InstallTask, [switch]$UninstallTask, [string]$WezTermPath)
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSVersion.Major -lt 7) {
    throw 'WezTerm Quake requires PowerShell 7 (pwsh.exe). Install PowerShell 7, then launch this script with pwsh -File.'
}
if (-not $IsWindows) { throw 'WezTerm Quake supports Windows only.' }
$eventName = 'Local\bugabinga.wezterm-quake.prototype.stop'
$stateDir = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'wezterm/quake-prototype'
$log = Join-Path $stateDir 'quake.log'
$pwsh = Join-Path $PSHOME 'pwsh.exe'
if ($InstallTask -and $UninstallTask) { throw 'Choose -InstallTask or -UninstallTask, not both.' }
# Stopping/removing a task must still work after WezTerm has been uninstalled.
if (-not $Stop -and -not $UninstallTask) {
    if ($WezTermPath) {
        $exe = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($WezTermPath)
        if (-not (Test-Path -LiteralPath $exe -PathType Leaf) -or [IO.Path]::GetFileName($exe) -ine 'wezterm-gui.exe') {
            throw "WezTerm GUI not found at '$WezTermPath'. -WezTermPath must name an existing wezterm-gui.exe."
        }
    } else {
        $candidates = @()
        $gui = Get-Command wezterm-gui.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($gui) { $candidates += $gui.Source }
        $cli = Get-Command wezterm.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($cli) { $candidates += Join-Path (Split-Path $cli.Source) 'wezterm-gui.exe' }
        $candidates += Join-Path $PSScriptRoot 'wezterm-gui.exe'
        foreach ($root in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
            if ($root) { $candidates += Join-Path $root 'WezTerm/wezterm-gui.exe' }
        }
        $candidates += Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Programs/WezTerm/wezterm-gui.exe'
        $exe = $candidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1
        if (-not $exe) {
            throw 'WezTerm is not installed or could not be found. Install WezTerm from https://wezterm.org/install/windows.html, add it to PATH, or pass -WezTermPath with the full path to wezterm-gui.exe.'
        }
    }
    # A shim owns no terminal windows and must not become our executable identity.
    if (Test-Path -LiteralPath ([IO.Path]::ChangeExtension($exe, '.shim')) -PathType Leaf) {
        throw "WezTerm path '$exe' is a launcher shim. Pass -WezTermPath pointing to the real installed wezterm-gui.exe, not the shims directory."
    }
    $config = if ($ConfigFile) { $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ConfigFile) } else { $null }
    if ($config -and -not (Test-Path -LiteralPath $config -PathType Leaf)) { throw "WezTerm config file not found: $config. Omit -ConfigFile to use normal WezTerm discovery." }
}
if ($InstallTask -or $UninstallTask) {
    $taskName = 'WezTerm Quake Prototype'
    $taskArguments = '-NoProfile -NonInteractive -WindowStyle Hidden -File "' + $PSCommandPath + '"'
    # Pin resolved executable: logon tasks need not inherit an interactive shell's PATH.
    if ($InstallTask) { $taskArguments += ' -WezTermPath "' + $exe + '"' }
    if ($InstallTask -and $ConfigFile) { $taskArguments += ' -ConfigFile "' + $config + '"' }
    $existing = Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction SilentlyContinue
    if ($existing -and (@($existing.Actions).Count -ne 1 -or
        $existing.Actions[0].Execute -ne $pwsh -or
        -not $existing.Actions[0].Arguments.StartsWith('-NoProfile -NonInteractive -WindowStyle Hidden -File "' + $PSCommandPath + '"', [StringComparison]::OrdinalIgnoreCase))) {
        throw "Task '$taskName' belongs to another launcher; refusing to replace or remove it."
    }
    if ($UninstallTask) {
        if ($existing -and $PSCmdlet.ShouldProcess($taskName, 'Remove logon task; running controller remains unchanged')) {
            Unregister-ScheduledTask -TaskName $taskName -TaskPath '\' -Confirm:$false
        }
        return
    }
    $user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
    $action = New-ScheduledTaskAction -Execute $pwsh -Argument $taskArguments -WorkingDirectory $PSScriptRoot
    $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
    $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
    $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
        -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
    if ($PSCmdlet.ShouldProcess($taskName, "Register hidden controller at logon for $user (no elevation)")) {
        Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $action -Trigger $trigger `
            -Principal $principal -Settings $settings -Description 'Dedicated WezTerm quake hotkey controller; GUI starts on first toggle.' -Force | Out-Null
        "Registered '$taskName'; starts at next logon. Current controller unchanged."
    }
    return
}
if ($Stop) {
    $event = [Threading.EventWaitHandle]::OpenExisting($eventName)
    try { [void]$event.Set() } finally { $event.Dispose() }
    return
}
if ($Background) {
    $arguments = @('-NoProfile', '-NonInteractive', '-File', ('"' + $PSCommandPath + '"'))
    if ($ConfigFile) { $arguments += @('-ConfigFile', ('"' + $config + '"')) }
    $arguments += @('-WezTermPath', ('"' + $exe + '"'))
    $process = Start-Process $pwsh -WindowStyle Hidden -ArgumentList $arguments -PassThru
    "Controller PID: $($process.Id); log: $log"
    return
}
[void][IO.Directory]::CreateDirectory($stateDir)
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public static class QuakePrototype {
    const string ClassName = "bugabinga.wezterm.quake.prototype";
    const string MutexName = @"Local\bugabinga.wezterm-quake.prototype";
    const string StopName = @"Local\bugabinga.wezterm-quake.prototype.stop";
    const uint WM_HOTKEY = 0x0312, WM_QUIT = 0x0012;
    const uint Modifiers = 0x0008 | 0x4000; // Win, no repeat
    const uint PhysicalKey = 0x29; // Standard PC key below Esc
    const uint StopModifiers = 0x0002 | 0x0001 | 0x0004 | 0x4000; // Ctrl, Alt, Shift, no repeat
    const uint StopKey = 0x7A; // F11
    static string exe, config, log;
    static IntPtr previous;
    static long repaintGeneration;
    static string LaunchGuard { get { return Path.Combine(Path.GetDirectoryName(log), "launch.guard"); } }
    static void ClearLaunchGuard() { if (File.Exists(LaunchGuard)) File.Delete(LaunchGuard); }
    static void CheckLaunchGuard() {
        if (!File.Exists(LaunchGuard)) return;
        var fields = File.ReadAllText(LaunchGuard).Split('|');
        if (fields.Length != 2) throw new InvalidOperationException("Interrupted launch has unknown PID; refusing duplicate. Inspect quake processes before removing launch.guard.");
        int pid = Int32.Parse(fields[0]); long ticks = Int64.Parse(fields[1]);
        bool running = false;
        try {
            using (var process = Process.GetProcessById(pid))
                running = !process.HasExited && process.StartTime.ToUniversalTime().Ticks == ticks &&
                    String.Equals(process.MainModule.FileName, exe, StringComparison.OrdinalIgnoreCase);
        } catch (ArgumentException) { }
        if (running) throw new InvalidOperationException("Previous GUI launch still running without an identified window; refusing another GUI.");
        ClearLaunchGuard();
    }

    [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; }
    [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; }
    [StructLayout(LayoutKind.Sequential)] struct MSG {
        public IntPtr hwnd; public uint message; public UIntPtr wParam;
        public IntPtr lParam; public uint time; public POINT pt; public uint lPrivate;
    }
    [StructLayout(LayoutKind.Sequential)] struct MONITORINFO {
        public int cbSize; public RECT rcMonitor, rcWork; public uint dwFlags;
    }
    delegate bool EnumProc(IntPtr window, IntPtr param);
    [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc callback, IntPtr param);
    [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetClassName(IntPtr window, StringBuilder name, int max);
    [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
    [DllImport("user32.dll")] static extern bool IsWindow(IntPtr window);
    [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr window);
    [DllImport("user32.dll")] static extern bool IsIconic(IntPtr window);
    [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out RECT rect);
    [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr window, int command);
    [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
    [DllImport("user32.dll", SetLastError=true)] static extern bool InvalidateRect(IntPtr window, IntPtr rect, bool erase);
    [DllImport("user32.dll", SetLastError=true)] static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
    [DllImport("user32.dll")] static extern bool GetCursorPos(out POINT point);
    [DllImport("user32.dll")] static extern IntPtr MonitorFromPoint(POINT point, uint flags);
    [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool GetMonitorInfo(IntPtr monitor, ref MONITORINFO info);
    [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
    [DllImport("user32.dll", SetLastError=true)] static extern bool RegisterHotKey(IntPtr window, int id, uint modifiers, uint key);
    [DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr window, int id);
    [DllImport("user32.dll", SetLastError=true)] static extern int GetMessage(out MSG message, IntPtr window, uint min, uint max);
    [DllImport("user32.dll")] static extern bool PeekMessage(out MSG message, IntPtr window, uint min, uint max, uint remove);
    [DllImport("user32.dll", SetLastError=true)] static extern bool PostThreadMessage(uint thread, uint message, UIntPtr wParam, IntPtr lParam);
    [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
    [DllImport("user32.dll")] static extern IntPtr GetKeyboardLayout(uint thread);
    [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern uint MapVirtualKeyEx(uint code, uint mapping, IntPtr layout);

    static void Log(string message) {
        File.AppendAllText(log, DateTimeOffset.Now.ToString("o") + " " + message + Environment.NewLine);
    }
    static bool IsOurWindow(IntPtr window) {
        var name = new StringBuilder(256);
        GetClassName(window, name, name.Capacity);
        if (name.ToString() != ClassName) return false;
        uint pid;
        GetWindowThreadProcessId(window, out pid);
        try {
            using (var process = Process.GetProcessById((int)pid))
                return String.Equals(process.MainModule.FileName, exe, StringComparison.OrdinalIgnoreCase);
        } catch (ArgumentException) { return false; }
          catch (InvalidOperationException) { return false; }
          catch (Win32Exception) { return false; }
    }
    // Include hidden windows; never use MainWindowHandle or generic process-name selection.
    static IntPtr Find() {
        var matches = new List<IntPtr>();
        if (!EnumWindows((window, unused) => {
            if (!IsOurWindow(window)) return true;
            matches.Add(window);
            return true;
        }, IntPtr.Zero)) throw new InvalidOperationException("Window enumeration failed.");
        if (matches.Count > 1) throw new InvalidOperationException("Multiple dedicated WezTerm windows: refusing ambiguous target.");
        return matches.Count == 1 ? matches[0] : IntPtr.Zero;
    }
    public static ProcessStartInfo StartInfo() {
        var start = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) };
        // Keep native config selection, strip inherited mux/pane routing and old adapter state.
        var remove = new List<string>();
        foreach (var key in start.Environment.Keys)
            if (key.StartsWith("WEZTERM_", StringComparison.OrdinalIgnoreCase) && !key.Equals("WEZTERM_CONFIG_FILE", StringComparison.OrdinalIgnoreCase)) remove.Add(key);
        foreach (var key in remove) start.Environment.Remove(key);
        if (!String.IsNullOrEmpty(config)) {
            start.ArgumentList.Add("--config-file");
            start.ArgumentList.Add(config);
        }
        foreach (var arg in new [] { "--config", "use_resize_increments=false", "--config", "default_workspace='quake'", "--config", "window_close_confirmation='AlwaysPrompt'", "start", "--always-new-process", "--class", ClassName, "--no-auto-connect", "--domain", "local", "--workspace", "quake" }) start.ArgumentList.Add(arg);
        return start;
    }
    static IntPtr FindOrStart() {
        var window = Find();
        if (window != IntPtr.Zero) { ClearLaunchGuard(); return window; }
        CheckLaunchGuard();
        var start = StartInfo();
        // Intent first: even termination between Process.Start and recording PID fails closed.
        File.WriteAllText(LaunchGuard, "starting");
        using (var process = Process.Start(start)) {
            File.WriteAllText(LaunchGuard, process.Id + "|" + process.StartTime.ToUniversalTime().Ticks);
            Log("Started dedicated GUI PID " + process.Id);
            var timer = Stopwatch.StartNew();
            while (timer.ElapsedMilliseconds < 15000) {
                window = Find();
                if (window != IntPtr.Zero) { ClearLaunchGuard(); return window; }
                if (process.HasExited) throw new InvalidOperationException("Dedicated GUI exited before terminal appeared.");
                Thread.Sleep(50);
            }
        }
        throw new TimeoutException("Quake terminal did not appear within 15 seconds; no automatic relaunch.");
    }
    static void Toggle() {
        var foreground = GetForegroundWindow();
        var window = FindOrStart();
        if (!IsOurWindow(window)) throw new InvalidOperationException("Target identity changed.");
        if (foreground == window && IsWindowVisible(window) && !IsIconic(window)) {
            Interlocked.Increment(ref repaintGeneration);
            ShowWindowAsync(window, 0); // SW_HIDE: do not close shells
            if (previous != IntPtr.Zero && IsWindow(previous) && IsWindowVisible(previous)) SetForegroundWindow(previous);
            Log("Hidden");
            return;
        }
        if (foreground != window) previous = foreground;
        POINT cursor;
        if (!GetCursorPos(out cursor)) throw new InvalidOperationException("Cursor monitor unavailable.");
        var info = new MONITORINFO { cbSize = Marshal.SizeOf(typeof(MONITORINFO)) };
        if (!GetMonitorInfo(MonitorFromPoint(cursor, 2), ref info)) throw new InvalidOperationException("Monitor work area unavailable.");
        var area = info.rcWork;
        Log("Restore requested; visible=" + IsWindowVisible(window) + "; minimized=" + IsIconic(window));
        ShowWindowAsync(window, 9); // SW_RESTORE may queue behind cold-start initialization.
        var restore = Stopwatch.StartNew();
        while (IsOurWindow(window) && (!IsWindowVisible(window) || IsIconic(window)) && restore.ElapsedMilliseconds < 15000) Thread.Sleep(20);
        if (!IsOurWindow(window) || !IsWindowVisible(window) || IsIconic(window))
            throw new InvalidOperationException("Quake window did not restore after " + restore.ElapsedMilliseconds + "ms; visible=" + IsWindowVisible(window) + "; minimized=" + IsIconic(window));
        Log("Restore ready after " + restore.ElapsedMilliseconds + "ms");
        // Topmost, no activation during placement, show, async cross-thread positioning.
        if (!SetWindowPos(window, new IntPtr(-1), area.Left, area.Top, area.Right-area.Left,
            (int)Math.Round((area.Bottom-area.Top)*0.60), 0x0010 | 0x0040 | 0x4000))
            throw new Win32Exception(Marshal.GetLastWin32Error());
        var placement = Stopwatch.StartNew();
        RECT actual;
        while (!GetWindowRect(window, out actual) || actual.Left != area.Left || actual.Top != area.Top ||
            actual.Right != area.Right || actual.Bottom != area.Top + (int)Math.Round((area.Bottom-area.Top)*0.60)) {
            if (!IsOurWindow(window) || placement.ElapsedMilliseconds >= 5000)
                throw new InvalidOperationException("Quake window did not reach requested monitor geometry.");
            Thread.Sleep(20);
        }
        bool focused = SetForegroundWindow(window);
        // Request a fresh GPU frame after external hide/show, without erasing its background.
        if (!InvalidateRect(window, IntPtr.Zero, false))
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Quake repaint request failed.");
        // One later frame opportunity: immediate invalidation alone still reproduced white frames.
        long generation = Interlocked.Increment(ref repaintGeneration);
        Task.Delay(250).ContinueWith(_ => {
            if (Interlocked.Read(ref repaintGeneration) == generation && IsOurWindow(window) && IsWindowVisible(window))
                InvalidateRect(window, IntPtr.Zero, false);
        }, TaskScheduler.Default);
        Log("Summoned; foreground request " + (focused ? "accepted" : "denied by Windows") + "; repaint requested; 250ms retry scheduled");
    }
    public static void Run(string executable, string configuration, string logfile, bool check) {
        exe = Path.GetFullPath(executable); config = configuration; log = logfile;
        using (var mutex = new Mutex(false, MutexName)) {
            bool held;
            try { held = mutex.WaitOne(0); } catch (AbandonedMutexException) { held = true; }
            if (!held) throw new InvalidOperationException("Quake controller already running.");
            bool registered = false, exitRegistered = false;
            IntPtr oldDpi = IntPtr.Zero;
            try {
                if (!String.IsNullOrEmpty(config) && !File.Exists(config)) throw new FileNotFoundException("WezTerm config missing", config);
                var target = Find();
                uint foregroundPid;
                uint foregroundThread = GetWindowThreadProcessId(GetForegroundWindow(), out foregroundPid);
                uint key = MapVirtualKeyEx(PhysicalKey, 3, GetKeyboardLayout(foregroundThread));
                if (key == 0) throw new InvalidOperationException("Cannot map the physical key below Esc on the active keyboard layout.");
                if (!RegisterHotKey(IntPtr.Zero, 1, Modifiers, key)) throw new Win32Exception(Marshal.GetLastWin32Error(), "Win + key below Esc unavailable; check Windows Terminal quake-mode or other global shortcuts.");
                registered = true;
                if (!RegisterHotKey(IntPtr.Zero, 2, StopModifiers, StopKey)) throw new Win32Exception(Marshal.GetLastWin32Error(), "Ctrl+Alt+Shift+F11 unavailable");
                exitRegistered = true;
                if (check) { Console.WriteLine("PASS: compiled; unique controller; both hotkeys available; toggle VK=0x" + key.ToString("X") + "; enumeration complete; target=" + target); return; }
                oldDpi = SetThreadDpiAwarenessContext(new IntPtr(-4));
                MSG ignored; PeekMessage(out ignored, IntPtr.Zero, 0, 0, 0);
                uint thread = GetCurrentThreadId();
                using (var stop = new EventWaitHandle(false, EventResetMode.ManualReset, StopName)) {
                    var waiter = new Thread(() => {
                        stop.WaitOne();
                        PostThreadMessage(thread, WM_QUIT, UIntPtr.Zero, IntPtr.Zero);
                    });
                    waiter.IsBackground = true; waiter.Start();
                    Log("Ready: Win + key below Esc toggle (VK=0x" + key.ToString("X") + "); Ctrl+Alt+Shift+F11 stop. GUI launches only on toggle.");
                    try {
                        MSG message; int result;
                        while ((result = GetMessage(out message, IntPtr.Zero, 0, 0)) > 0) {
                            if (message.message != WM_HOTKEY) continue;
                            if (message.wParam.ToUInt64() == 2) break;
                            try { Toggle(); } catch (Exception error) { Log("ERROR " + error.Message); }
                        }
                        if (result == -1) throw new Win32Exception(Marshal.GetLastWin32Error());
                    } finally {
                        Interlocked.Increment(ref repaintGeneration);
                        stop.Set(); waiter.Join();
                        // A stopped controller must not strand an invisible terminal.
                        try {
                            var window = Find();
                            if (window != IntPtr.Zero && !IsWindowVisible(window)) ShowWindowAsync(window, 4);
                        } catch (Exception error) { Log("Recovery: " + error.Message); }
                    }
                }
                Log("Stopped; dedicated GUI left running.");
            } finally {
                if (exitRegistered) UnregisterHotKey(IntPtr.Zero, 2);
                if (registered) UnregisterHotKey(IntPtr.Zero, 1);
                if (oldDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(oldDpi);
                mutex.ReleaseMutex();
            }
        }
    }
}
'@
try {
    [QuakePrototype]::Run($exe, $config, $log, $Check.IsPresent)
    if ($Check) {
        $launch = [QuakePrototype]::StartInfo()
        [pscustomobject]@{ Executable=$launch.FileName; Arguments=@($launch.ArgumentList); WorkingDirectory=$launch.WorkingDirectory }
    }
}
catch {
    Add-Content -LiteralPath $log -Value "$(Get-Date -Format o) FATAL $_"
    throw
}