Files
hrynco-kswitcher/tests/files_quick_view.ps1
T
2026-11-25 22:10:49 +02:00

243 lines
13 KiB
PowerShell

param(
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
[string]$ProfileSubkey = 'Software\KSwitcher\Files',
[string]$Node = (Get-Command node -ErrorAction SilentlyContinue).Source,
[string]$RenderedImage = '',
[string]$BinaryImage = ''
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
$browserProbe = $Node -and ((& $Node -p "typeof WebSocket === 'function'") -eq 'true')
if($RenderedImage -and !$browserProbe){throw 'A Node runtime with WebSocket is required for a rendered screenshot'}
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesQuickViewProbe {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x,
int y, int width, int height, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")]
public static extern bool Post(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr Send(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr FindRow(IntPtr window, uint msg, IntPtr wp, string name);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr wp, StringBuilder text);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
}
'@
function Wait-Until([string]$Label,[scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 150; $attempt++) {
$result = & $Condition
if ($result) { return $result }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Label"
}
function Text([IntPtr]$Handle) {
$buffer = [Text.StringBuilder]::new(256)
[void][FilesQuickViewProbe]::Read($Handle, 13, [IntPtr]$buffer.Capacity, $buffer)
$buffer.ToString()
}
function Select-File([string]$Name) {
$row = [FilesQuickViewProbe]::FindRow($leftList, 0x1A2, [IntPtr](-1), $Name)
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
[void][FilesQuickViewProbe]::Send($leftList, 0x186, $row, 0)
[void][FilesQuickViewProbe]::Post($window, 273, [IntPtr](0x10000+102), $leftList)
}
function Preview-Bytes([int]$Count) {
[byte[]]$bytes = @(
for($i=0; $i -lt $Count; ++$i) {
[byte]([FilesQuickViewProbe]::Send($editor, 2007, [IntPtr]$i, 0).ToInt32() -band 255)
}
)
[Text.Encoding]::UTF8.GetString($bytes)
}
function Browser {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'html-quick' $RenderedImage 'preview.html'
if ($LASTEXITCODE) { throw 'WebView2 verification failed for rendered HTML' }
}
$exe = (Resolve-Path $Executable).Path
$source = Split-Path $exe
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ProfileSubkey)
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftPanelMode', 'RightPanelMode', 'WindowPlacement'
$saved = @{}
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$profile = $env:WEBVIEW2_USER_DATA_FOLDER
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$network = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$network.Start()
$probe = "http://127.0.0.1:$($network.LocalEndpoint.Port)/should-not-load"
$debug = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$debug.Start()
$port = $debug.LocalEndpoint.Port
$debug.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $fixture.FullName 'webview'
$app = $fixture.CreateSubdirectory('app')
Copy-Item -LiteralPath $exe,"$source\WebView2Loader.dll","$source\terminal" -Destination $app.FullName -Recurse
$left = $fixture.CreateSubdirectory('left')
$right = $fixture.CreateSubdirectory('right')
$document = Join-Path $left.FullName 'preview.txt'
[IO.File]::WriteAllText($document, 'Quick View fixture')
[IO.File]::WriteAllText((Join-Path $left.FullName 'preview.html'), @"
<!doctype html>
<html><head><title>Document title</title>
<meta http-equiv="refresh" content="0;url=$probe">
<link rel="stylesheet" href="$probe">
<style>@import url('$probe');</style>
<script>window.documentScriptRan = true;</script></head>
<body onload="window.documentScriptRan = true;"><main>
<h1 style="color: teal; position: fixed" onclick="window.documentScriptRan = true;">Offline HTML fixture</h1>
<table><tr><td><strong>Formatted table</strong></td></tr></table>
<a href="$probe">External link</a>
<img src="$probe" alt="Image description"><iframe src="$probe"></iframe>
<form action="$probe"><input type="submit"></form>
</main></body></html>
"@)
$data = [byte[]]::new(5000)
[byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255
$header.CopyTo($data,0)
for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 }
[IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data)
$expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f,
0x20,0x41,0xe07f,0xC7,0xe0ff))
$key.SetValue('LeftPanelMode', 1, 'DWord')
$key.SetValue('RightPanelMode', 1, 'DWord')
$key.SetValue('LeftPath', $left.FullName, 'String')
$key.SetValue('RightPath', $right.FullName, 'String')
$key.SetValue('LeftCursor', $document, 'String')
$key.DeleteValue('RightCursor', $false)
$key.DeleteValue('WindowPlacement', $false)
$process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal
$window = Wait-Until 'the Files window' {
$process.Refresh()
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20)
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
$rightPath = [FilesQuickViewProbe]::GetDlgItem($window, 143)
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
throw 'Expected both file panels in the test window.'
}
[void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) })
Invoke-FilesCommand $window 'Quick View*'
$preview = Wait-Until 'Quick View' {
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow }
}
$editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value)
[void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
$initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0)
$initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0)
foreach ($control in $rightList, $rightHeading, $rightPath) {
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control can draw over the Quick View content.'
}
}
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
Select-File 'preview.html'
$mode = [FilesQuickViewProbe]::GetDlgItem($preview,159)
[void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
[void][FilesQuickViewProbe]::Post($preview,273,159,$mode)
[void](Wait-Until 'the HTML source' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and
(Preview-Bytes 15) -eq '<!doctype html>'
})
[void][FilesQuickViewProbe]::Post($editor,0x100,117,0)
[void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' }
Select-File 'symbols.bin'
[void](Wait-Until 'binary glyphs in the embedded view' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2
})
if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) {
throw 'Binary control bytes were lost or decoded as text'
}
$expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length
if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or
[FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) {
throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling'
}
$escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() -
[FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32()
if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){
throw 'The control byte did not render as a full visible escape'
}
if($BinaryImage){
Add-Type -AssemblyName System.Drawing
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} }
finally { $graphics.ReleaseHdc($dc) }
$bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png)
} finally { $graphics.Dispose(); $bitmap.Dispose() }
}
$wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32()
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20)
[void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows })
Select-File 'preview.txt'
[void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or
[FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' }
[void][FilesQuickViewProbe]::Post($window,0x801F,0,0)
[void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero })
foreach ($control in $rightList, $rightHeading, $rightPath) {
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control remained hidden after closing Quick View.'
}
}
'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
}
if ($network) { $network.Stop() }
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
$env:WEBVIEW2_USER_DATA_FOLDER = $profile
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
}
$key.Dispose()
$path = [IO.Path]::GetFullPath($fixture.FullName)
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
for($attempt=0; $attempt -lt 50; ++$attempt){
try {
[IO.Directory]::Delete($path, $true)
break
} catch [System.IO.IOException] {
if($attempt -eq 49){throw}
Start-Sleep -Milliseconds 100
}
}
}
}