Files
hrynco-kswitcher/tests/files_command_completion.ps1
T

447 lines
20 KiB
PowerShell

param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class CompletionTest {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern bool AttachThreadInput(uint first, uint second, bool attach);
[DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
public static void Activate(IntPtr window) {
var own = GetCurrentThreadId();
var foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
bool attached = foreground != 0 && own != foreground && AttachThreadInput(own, foreground, true);
try { SetForegroundWindow(window); }
finally { if (attached) AttachThreadInput(own, foreground, false); }
}
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect bounds);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, int message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, int message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr window, int message, IntPtr w, string text);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr window, int message, IntPtr w, StringBuilder text);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr ItemRect(IntPtr window, int message, IntPtr w, out Rect bounds);
}
"@
function Wait-Until([string]$Description, [scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 120; ++$attempt) {
if (& $Condition) { return }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Description"
}
function Set-Line([string]$Line) {
[void][CompletionTest]::SetText($edit, 0x000C, 0, $Line)
[void][CompletionTest]::Send($edit, 0x00B1, $Line.Length, $Line.Length)
}
function Read-Line {
$text = [Text.StringBuilder]::new(2049)
[void][CompletionTest]::GetText($edit, 0x000D, $text.Capacity, $text)
$text.ToString()
}
function Suggestions([string]$Expected, [int]$Count = -1) {
Wait-Until "suggestion '$Expected' (count $Count)" {
if (![CompletionTest]::IsWindowVisible($list)) { return $false }
$found = [CompletionTest]::SetText($list, 0x01A2, -1, $Expected).ToInt64()
$size = [CompletionTest]::Send($list, 0x018B, 0, 0).ToInt64()
$found -ge 0 -and ($Count -lt 0 -or $size -eq $Count)
}
}
function Press-Key([int]$Key) {
if (![CompletionTest]::PostMessage($edit, 0x0100, $Key, 1)) { throw 'Could not post key' }
}
function Toggle-Panels {
Wait-Until 'foreground Files window before toggling panes' {
if ([CompletionTest]::GetForegroundWindow() -eq $window) { return $true }
[void]$keyboard.AppActivate($process.Id)
[CompletionTest]::Activate($window)
[CompletionTest]::GetForegroundWindow() -eq $window
}
$keyboard.SendKeys('^o')
}
function Read-SuggestionFrameColor {
$frame = [CompletionTest]::GetWindow($list, 2)
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($frame, [ref]$bounds)
$pixel = [Drawing.Bitmap]::new(1, 1)
$graphics = [Drawing.Graphics]::FromImage($pixel)
try {
$graphics.CopyFromScreen($bounds.Left + 2, $bounds.Top + 2, 0, 0, $pixel.Size)
$pixel.GetPixel(0, 0).ToArgb()
} finally {
$graphics.Dispose()
$pixel.Dispose()
}
}
function Test-DotnetCompletion {
if (!$hasDotnetSdk) { return }
Set-Line 'dotnet '
Suggestions 'build'
Set-Line 'dotnet bu'
Suggestions 'build'
Set-Line 'dotnet build --no-res'
Suggestions '--no-restore'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '--no-restore')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'dotnet option insertion' { (Read-Line) -ceq 'dotnet build --no-restore' }
}
function Test-GitCompletion {
if (!$gitFixture) { return }
Set-Line 'git ch'
Suggestions 'checkout'
Set-Line 'git --ver'
Suggestions '--version'
$switch = 'git -C "' + $gitFixture + '" switch '
Set-Line ($switch + '--de')
Suggestions '--detach'
$prefix = $switch + 'comp'
Set-Line $prefix
Suggestions 'completion-one'
Suggestions 'completion-two'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'completion-one')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'Git branch insertion' { (Read-Line) -ceq ($prefix + 'letion-one') }
}
function Test-WindowsCommandCompletion {
Set-Line 'ipconfig '
Suggestions '/all'
Set-Line 'ipconfig /re'
Suggestions '/renew'
Suggestions '/release'
Set-Line 'ipconfig ?'
Suggestions '/?'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '/?')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'ipconfig help switch insertion' { (Read-Line) -ceq 'ipconfig /?' }
Set-Line 'tasklist.exe /f'
Suggestions '/fo'
Set-Line 'robocopy /mi'
Suggestions '/mir'
Set-Line 'reg q'
Suggestions 'query'
Set-Line 'reg query /r'
Suggestions '/reg:64'
Set-Line 'cmd /c dir /'
Suggestions '/w'
Set-Line 'dir -Fi'
Suggestions 'File'
}
function Test-NestedWindowsCommandCompletion {
Set-Line 'netsh interface ip'
Suggestions 'ipv4'
Set-Line 'netsh interface ipv4 sh'
Suggestions 'show'
Set-Line 'netsh interface ipv4 show co'
Suggestions 'config'
Set-Line 'netsh interface ipv4 show config na'
Suggestions 'name='
Set-Line 'fsutil file queryallocranges of'
Suggestions 'offset='
Set-Line 'wevtutil query-events /sb'
Suggestions '/sbm:'
Set-Line 'schtasks /query /fo L'
Suggestions 'LIST'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'LIST')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'nested Windows option insertion' { (Read-Line) -ceq 'schtasks /query /fo LIST' }
}
function Test-IpconfigAdapterCompletion {
$adapters = foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
try {
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
} catch {}
}
if (!$adapters) { return }
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+ [\p{L}\p{N} ]+$' } | Select-Object -First 1
if ($name) {
$prefix = '"' + $name.Substring(0, $name.IndexOf(' ') + 1)
$expected = "'" + $name + "'"
} else {
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+$' } | Select-Object -First 1
if (!$name) { return }
$prefix = $name.Substring(0, 1).ToUpperInvariant()
$expected = $name
}
Set-Line 'ipconfig /renew '
Suggestions $name
Set-Line ('ipconfig.exe /release ' + $prefix)
Suggestions $name
$row = [CompletionTest]::SetText($list, 0x01A2, -1, $name)
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'ipconfig adapter insertion' { (Read-Line) -ceq ('ipconfig.exe /release ' + $expected) }
}
function Test-PathCompletion {
$prefix = 'cd "' + $root + '\Al'
Set-Line $prefix
Suggestions 'Alpine' 2
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'p', 1)
Suggestions 'Alpha Space' 2
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'h', 1)
Suggestions 'Alpha Space' 1
$row = [CompletionTest+Rect]::new()
[void][CompletionTest]::ItemRect($list, 0x0198, 0, [ref]$row)
$listBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($list, [ref]$listBounds)
$mouse = [CompletionTest+Point]::new()
$mouse.X = $listBounds.Left + 5
$mouse.Y = $listBounds.Top + (($row.Top + $row.Bottom) -shr 1)
if ([CompletionTest]::WindowFromPoint($mouse) -ne $list) { throw 'The suggestions list is covered' }
$point = ((($row.Top + $row.Bottom) -shr 1) -shl 16) -bor 5
[void][CompletionTest]::PostMessage($list, 0x0201, 1, $point)
Wait-Until 'click insertion with quotes' { (Read-Line) -ceq ('cd "' + $root + '\Alpha Space"') }
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'\', 1)
Suggestions 'Nested' 1
Press-Key 0x1B
Wait-Until 'Escape dismissal' { ![CompletionTest]::IsWindowVisible($list) }
if ((Read-Line) -cne ('cd "' + $root + '\Alpha Space\"')) { throw 'Escape changed the command line' }
}
$root = Join-Path ([IO.Path]::GetTempPath()) ("KSwitcherCompletion-" + [guid]::NewGuid().ToString('N'))
$process = $null
$dotnet = Get-Command dotnet.exe -CommandType Application -ErrorAction SilentlyContinue
$hasDotnetSdk = $dotnet -and [bool](& $dotnet.Source --list-sdks)
$historyKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$historyPrefix = "Write-Output 'completion-$([guid]::NewGuid().ToString('N'))"
$latest = "$historyPrefix-alpha-recent'"
$earlier = "$historyPrefix-alpha-earlier'"
$other = "$historyPrefix-beta'"
$combined = "Get-ChildItem -Name # $([guid]::NewGuid().ToString('N'))"
$clearPrefix = ' cls '
$clearHistory = "$clearPrefix# $([guid]::NewGuid().ToString('N'))"
$fixture = "2026-01-01`0$earlier`02026-01-01`0$other`02026-01-01`0$earlier`02026-01-01`0$latest`02026-01-01`0$combined`02026-01-01`0$clearHistory`0"
function Remove-HistoryFixture {
$bytes = $historyKey.GetValue('CommandHistory')
if ($bytes -isnot [byte[]]) { return }
$current = [Text.Encoding]::Unicode.GetString($bytes)
$clean = $current.Replace($fixture, '')
if ($clean -ceq $current) { return }
if ($clean.Length -eq 0 -and $null -eq $originalHistory) {
$historyKey.DeleteValue('CommandHistory', $false)
} else {
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($clean), 'Binary')
}
}
try {
$originalHistory = $historyKey.GetValue('CommandHistory')
$history = if ($null -ne $originalHistory) { [Text.Encoding]::Unicode.GetString($originalHistory) } else { '' }
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($history + $fixture), 'Binary')
[void](New-Item -ItemType Directory -Path "$root\Alpha Space\Nested", "$root\Alpine")
$gitFixture = $null
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($git) {
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source))
for ($level = 0; $location -and $level -lt 3; ++$level) {
$installation = $location.FullName
$location = $location.Parent
if (!(Test-Path -LiteralPath (Join-Path $installation 'usr/bin/bash.exe'))) { continue }
$gitFixture = Join-Path $root 'Git Repo'
[void](New-Item -ItemType Directory -Path $gitFixture)
& $git.Source -C $gitFixture init --quiet --template= --initial-branch=main
if ($LASTEXITCODE) { throw 'Could not initialize the Git fixture' }
& $git.Source -C $gitFixture -c user.name=Test -c user.email=test@example.invalid -c commit.gpgSign=false -c core.hooksPath=NUL commit --quiet --allow-empty -m fixture
if ($LASTEXITCODE) { throw 'Could not create the Git fixture commit' }
& $git.Source -C $gitFixture branch completion-one
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-one' }
& $git.Source -C $gitFixture branch completion-two
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-two' }
break
}
}
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru -WindowStyle Normal
Wait-Until 'Files window' {
$process.Refresh()
$process.MainWindowHandle -ne [IntPtr]::Zero
}
Remove-HistoryFixture
$window = $process.MainWindowHandle
$keyboard = New-Object -ComObject WScript.Shell
Wait-Until 'foreground Files window' {
[void]$keyboard.AppActivate($process.Id)
[CompletionTest]::Activate($window)
[CompletionTest]::GetForegroundWindow() -eq $window
}
$edit = [CompletionTest]::FindWindowEx($window, 0, 'Edit', [System.Management.Automation.Language.NullString]::Value)
$list = [CompletionTest]::GetDlgItem($window, 149)
if (!$edit -or !$list) { throw 'Missing command line or suggestions list' }
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
$status = [CompletionTest]::GetDlgItem($window, 144)
$panel = [CompletionTest]::GetDlgItem($window, 102)
$statusBounds = [CompletionTest+Rect]::new()
$panelBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($panel, [ref]$panelBounds)
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
if ($statusBounds.Left -ge $panelBounds.Right) {
Press-Key 0x09
Wait-Until 'left panel active' {
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($status, [ref]$bounds)
$bounds.Left -lt $panelBounds.Right
}
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
}
Set-Line $clearPrefix
Suggestions $clearHistory 1
Set-Line 'Get-Chi'
Suggestions 'Get-ChildItem'
Suggestions $combined
$frame = [CompletionTest]::GetWindow($list, 2)
$frameBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($frame, [ref]$frameBounds)
$x = [Math]::Max($statusBounds.Left, $frameBounds.Left)
$y = [Math]::Max($statusBounds.Top, $frameBounds.Top)
$w = [Math]::Min($statusBounds.Right, $frameBounds.Right) - $x
$h = [Math]::Min($statusBounds.Bottom, $frameBounds.Bottom) - $y
if ($w -le 0 -or $h -le 0) { throw 'Suggestions and status must overlap for the repaint check' }
$before = [Drawing.Bitmap]::new($w, $h)
$after = [Drawing.Bitmap]::new($w, $h)
try {
$graphics = [Drawing.Graphics]::FromImage($before)
try { $graphics.CopyFromScreen($x, $y, 0, 0, $before.Size) } finally { $graphics.Dispose() }
[void][CompletionTest]::SetText($status, 0x000C, 0, ('Status repaint test ' * 48))
[void][CompletionTest]::RedrawWindow($status, 0, 0, 0x0105)
$graphics = [Drawing.Graphics]::FromImage($after)
try { $graphics.CopyFromScreen($x, $y, 0, 0, $after.Size) } finally { $graphics.Dispose() }
for ($rowPixel = 0; $rowPixel -lt $h; ++$rowPixel) {
for ($columnPixel = 0; $columnPixel -lt $w; ++$columnPixel) {
if ($before.GetPixel($columnPixel, $rowPixel) -ne $after.GetPixel($columnPixel, $rowPixel)) {
throw 'Status repaint drew over command suggestions'
}
}
}
} finally {
$before.Dispose()
$after.Dispose()
}
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Get-ChildItem')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x09
Wait-Until 'Tab insertion' { (Read-Line) -ceq 'Get-ChildItem' }
Set-Line ($historyPrefix.ToUpperInvariant())
Suggestions $latest 3
Set-Line "$historyPrefix-alpha"
Suggestions $earlier 2
Press-Key 0x09
Wait-Until 'most recent history insertion' { (Read-Line) -ceq $latest }
Set-Line 'Get-ChildItem -Pa'
Suggestions 'Path'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Path')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'Enter insertion' { (Read-Line) -ceq 'Get-ChildItem -Path' }
Test-PathCompletion
Test-DotnetCompletion
Test-GitCompletion
Test-WindowsCommandCompletion
Test-NestedWindowsCommandCompletion
Test-IpconfigAdapterCompletion
# Toggle with a populated list and verify the same draft and suggestions remain accessible.
Set-Line "$historyPrefix-alpha"
Suggestions $latest 2
$frameColor = Read-SuggestionFrameColor
$output = [CompletionTest]::GetDlgItem($window, 145)
Toggle-Panels
Wait-Until 'terminal-only view' {
[CompletionTest]::IsWindowVisible($output) -and ![CompletionTest]::IsWindowVisible($panel) -and
[CompletionTest]::GetWindow($output, 5) -ne [IntPtr]::Zero
}
Suggestions $latest 2
# Let WebView2 finish its first compositor update after showing the terminal.
Start-Sleep -Milliseconds 350
if ((Read-SuggestionFrameColor) -ne $frameColor) {
throw 'Terminal output drew over command suggestions with panels hidden'
}
if ($Screenshot) {
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($window, [ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right - $bounds.Left, $bounds.Bottom - $bounds.Top)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size)
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
} finally {
$graphics.Dispose()
$bitmap.Dispose()
}
}
Press-Key 0x28
Press-Key 0x0D
Wait-Until 'history insertion with panels hidden' { (Read-Line) -ceq $latest }
Test-PathCompletion
Test-DotnetCompletion
Test-GitCompletion
Test-WindowsCommandCompletion
Test-NestedWindowsCommandCompletion
Test-IpconfigAdapterCompletion
Toggle-Panels
Wait-Until 'panels restored' { [CompletionTest]::IsWindowVisible($panel) }
Set-Line "$historyPrefix-alpha"
Suggestions $latest 2
'Command completion passed with panels visible and hidden'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id }
Remove-HistoryFixture
$historyKey.Dispose()
if ($gitFixture -and (Test-Path -LiteralPath $gitFixture)) {
$resolved = (Resolve-Path -LiteralPath $gitFixture).ProviderPath
if ($resolved -eq [IO.Path]::GetFullPath((Join-Path $root 'Git Repo'))) {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
foreach ($path in "$root\Alpha Space\Nested", "$root\Alpha Space", "$root\Alpine", $root) {
if (Test-Path -LiteralPath $path) { [IO.Directory]::Delete($path) }
}
}