Files
hrynco-kswitcher/tests/files_activation.ps1
T

1044 lines
57 KiB
PowerShell

param(
[Parameter(Mandatory)][string]$Executable,
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly,
[switch]$TerminalOnly,
[int]$ScanEntries = 0,
[string]$Node='node'
)
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesActivationUi {
public static void CreateScanFiles(string directory, int count) {
for (int i = 0; i < count; i++)
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
}
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
struct GuiInfo {
public int Size, Flags;
public IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret;
public Rect CaretRect;
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] static extern int GetSystemMetrics(int index);
[DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr window, IntPtr after,
int x, int y, int width, int height, uint flags);
public static void SizeTerminalWindow(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
if (!SetWindowPos(window, IntPtr.Zero, 20, 20, GetSystemMetrics(0) - 40,
GetSystemMetrics(1) - 100, 0x14))
throw new InvalidOperationException("Could not size the terminal test window.");
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static uint ReadScreenCenter(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect bounds;
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
var dc = GetDC(IntPtr.Zero);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
finally { ReleaseDC(IntPtr.Zero, dc); }
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static bool HasWarningBackground(IntPtr window) {
var dc = GetDC(window);
if (dc == IntPtr.Zero) return false;
try { return GetPixel(dc, 2, 2) == 0x80; }
finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
[DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiInfo info);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Write(IntPtr window, uint msg, IntPtr w, string text);
[DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, uint flags, IntPtr first, IntPtr second);
public static bool CompletionFollowsCaret(IntPtr input, IntPtr suggestions) {
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect inputBounds, popup;
return GetGUIThreadInfo(GetWindowThreadProcessId(input, IntPtr.Zero), ref info) &&
info.Caret == input && GetWindowRect(input, out inputBounds) &&
GetWindowRect(suggestions, out popup) && popup.Bottom <= inputBounds.Top &&
info.CaretRect.Left > 0 &&
Math.Abs(inputBounds.Left + info.CaretRect.Left - popup.Left) <= 4;
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static IntPtr Focus(IntPtr window) {
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
if (!GetGUIThreadInfo(GetWindowThreadProcessId(window, IntPtr.Zero), ref info))
throw new InvalidOperationException("Could not read Files focus.");
return info.Focus;
}
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
public static void ClickRow(IntPtr list, int row, bool doubleClick) {
Rect rect;
if (SendRect(list, 0x198, new IntPtr(row), out rect).ToInt32() == -1)
throw new InvalidOperationException("Missing listbox row.");
var point = new IntPtr(((rect.Top + rect.Bottom) / 2 << 16) | (rect.Left + 6));
PostMessage(list, 0x201, new IntPtr(1), point);
PostMessage(list, 0x202, IntPtr.Zero, point);
if (doubleClick) {
PostMessage(list, 0x203, new IntPtr(1), point);
PostMessage(list, 0x202, IntPtr.Zero, point);
}
}
}
"@
function Wait-Until([string]$Description, [scriptblock]$Condition) {
$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.Elapsed.TotalSeconds -lt 15) {
if (& $Condition) { return }
if ($process -and $process.HasExited) { throw "Files exited while waiting for $Description" }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Description"
}
function Invoke-ClipboardOperation([scriptblock]$Operation) {
for ($attempt = 1; $attempt -le 3; $attempt++) {
try { return (& $Operation) }
catch {
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
$attempt -eq 3) { throw }
[Windows.Forms.Application]::DoEvents()
Start-Sleep -Milliseconds 25
}
}
}
function Find-OperationDialog($Owner, [int]$Control) {
$candidate = [IntPtr]::Zero
while ($true) {
$candidate = [FilesActivationUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', [NullString]::Value)
if ($candidate -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
if (![FilesActivationUi]::IsWindowVisible($candidate) -or
[FilesActivationUi]::GetDlgItem($candidate, $Control) -eq [IntPtr]::Zero) { continue }
$parent = [FilesActivationUi]::GetWindow($candidate, 4)
while ($parent -ne [IntPtr]::Zero) {
if ($parent -eq $Owner) { return $candidate }
$parent = [FilesActivationUi]::GetWindow($parent, 4)
}
}
}
function Answer-OperationDialog([int]$Control, [int]$Answer) {
Wait-Until "operation dialog with control $Control" {
(Find-OperationDialog $window $Control) -ne [IntPtr]::Zero
}
$dialog = Find-OperationDialog $window $Control
[void][FilesActivationUi]::PostMessage($dialog, 0x111, [IntPtr]$Answer, [IntPtr]::Zero)
}
function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) {
$buffer = [Text.StringBuilder]::new(32768)
[void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer)
$buffer.ToString()
}
function Find-Row($List, [string]$Name) {
$count = [FilesActivationUi]::Send($List, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
for ($row = 0; $row -lt $count; $row++) {
if ((Read-Text $List 0x189 $row) -ceq $Name) { return $row }
}
-1
}
function Select-Row($List, [string]$Name, [switch]$DoubleClick) {
Wait-Until "row $Name" { (Find-Row $List $Name) -ge 0 }
$row = Find-Row $List $Name
[void][FilesActivationUi]::Send($List, 0x197, [IntPtr]$row, [IntPtr]::Zero)
[FilesActivationUi]::ClickRow($List, $row, $DoubleClick.IsPresent)
if (!$DoubleClick) {
Wait-Until "selection of $Name" {
[FilesActivationUi]::Focus($window) -eq $inputBox -and
[FilesActivationUi]::Send($List, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $List $Name)
}
}
}
function Press-Enter($Control) {
[void][FilesActivationUi]::PostMessage($Control, 0x100, [IntPtr]13, [IntPtr]::Zero)
}
function Invoke-Row($List, [string]$Name, [bool]$DoubleClick) {
Select-Row $List $Name -DoubleClick:$DoubleClick
if (!$DoubleClick) { Press-Enter $inputBox }
}
function Send-Terminal([string]$Command) {
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
Press-Enter $inputBox
}
function Send-InteractiveTerminal([string]$Command, [string]$EnterKey = '{ENTER}') {
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
$keys.SendKeys($EnterKey)
}
function Assert-Open($List, $Target, [bool]$DoubleClick) {
$report = "$Target.opened"
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
Invoke-Row $List ([IO.Path]::GetFileName($Target)) $DoubleClick
Wait-Until "launch of $Target (double click: $DoubleClick)" {
(Test-Path -LiteralPath $report) -and [IO.File]::ReadAllText($report) -eq 'opened'
}
}
$unique = [Guid]::NewGuid().ToString('N')
$root = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher test $unique"
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$classes = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Classes')
$extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement', 'FontPoints'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$webviewProfile=$env:WEBVIEW2_USER_DATA_FOLDER
try {
foreach ($name in $profileValues) {
if ($name -in $profile.GetValueNames()) {
$saved[$name] = @($profile.GetValue($name), $profile.GetValueKind($name))
}
}
$leftDir = Join-Path $root 'Left panel'
$rightDir = Join-Path $root 'Right panel'
$app = Join-Path $root 'Application'
New-Item -ItemType Directory -Path $leftDir, $rightDir, $app, "$leftDir\Test folder", "$rightDir\Test folder" | Out-Null
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
$testExe = Join-Path $app 'KSwitcher.Files.exe'
Copy-Item -LiteralPath $Executable -Destination $testExe
Copy-Item -LiteralPath "$source\WebView2Loader.dll", "$source\terminal" -Destination $app -Recurse
$program = Join-Path $leftDir 'Test program.exe'
Copy-Item -LiteralPath $Fixture -Destination $program
$document = Join-Path $(if($SystemOpenOnly -or $TerminalOnly){$leftDir}else{$rightDir}) "Test document$extension"
[IO.File]::WriteAllText($document, 'Document fixture')
$association = $classes.CreateSubKey($extension)
$association.SetValue('', $progId)
$association.Dispose()
$handler = $classes.CreateSubKey("$progId\shell\open\command")
$handler.SetValue('', ('"{0}" "%1"' -f (Resolve-Path -LiteralPath $Fixture).Path))
$handler.Dispose()
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
$batch = Join-Path $leftDir "Test's script.BAT"
$cmd = Join-Path $rightDir 'Test script.CMD'
[IO.File]::WriteAllLines($batch, @('@echo off', 'echo BAT=%KS_TEST_STATE%'))
[IO.File]::WriteAllLines($cmd, @('@echo off', 'echo CMD=%KS_TEST_STATE%'))
$profile.SetValue('LeftPath', $leftDir)
$profile.SetValue('RightPath', $rightDir)
foreach ($name in 'LeftCursor', 'RightCursor') { $profile.DeleteValue($name, $false) }
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$profile.SetValue('FontPoints',80,'DWord')
$terminalPage = Join-Path $app 'terminal/index.html'
$page = Get-Content -Raw -LiteralPath $terminalPage
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
[IO.File]::WriteAllText($terminalPage,$page)
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
function startTerminalFixture() {
document.querySelector('style').media = 'all';
const script = document.createElement('script');
script.src = 'terminal.js';
document.body.append(script);
}
'@)
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
$listener.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
}
if($SystemOpenOnly) {
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
}
if ($ScanEntries) {
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
}
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
if($TerminalOnly){[FilesActivationUi]::SizeTerminalWindow($window)}
$left = [FilesActivationUi]::GetDlgItem($window, 102)
$right = [FilesActivationUi]::GetDlgItem($window, 103)
$status = [FilesActivationUi]::GetDlgItem($window, 144)
$output = [FilesActivationUi]::GetDlgItem($window, 145)
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
if ($ScanEntries) {
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
$folderRow = Find-Row $left '[Test folder]'
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
Press-Enter $inputBox
Wait-Until 'nonzero folder scan progress' {
[FilesActivationUi]::IsWindowVisible($status) -and
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
}
$progress = Read-Text $status
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
$partialStatus = Read-Text $status
if ($partial -le 0 -or $partial -ge $ScanEntries -or
$partialStatus -ne "Partial: $partial" -or
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
throw "Unexpected partial listing of $partial entries."
}
$keys = New-Object -ComObject WScript.Shell
$fullScan = [Diagnostics.Stopwatch]::StartNew()
$keys.SendKeys('^r')
Wait-Until 'complete folder result after Ctrl+R' {
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
}
$fullScan.Stop()
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
$target = 65536
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
throw "Could not scroll row $target to the top."
}
$point = [IntPtr]((2 -shl 16) -bor 6)
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
Wait-Until 'mouse selection past the 16-bit row limit' {
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
}
Write-Output "Clicked row $target after scrolling it to the top."
return
}
if($SystemOpenOnly) {
$keys = New-Object -ComObject WScript.Shell
$explorer = New-Object -ComObject Shell.Application
$existingExplorerWindows = @($explorer.Windows() | ForEach-Object { $_.HWND })
Wait-Until 'Files ready for Shift+Enter' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$folderRow=Find-Row $left '[Test folder]'
if($folderRow -lt 0){throw 'The folder fixture is missing.'}
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$folderRow,[IntPtr]::Zero)
$keys.SendKeys('+{ENTER}')
$folderWindow = $null
Wait-Until 'Shift+Enter opening the selected folder in Explorer' {
$script:folderWindow = $explorer.Windows() | Where-Object {
$_.Document.Folder.Self.Path -eq "$leftDir\Test folder"
} | Select-Object -First 1
$null -ne $script:folderWindow
}
if($folderWindow.HWND -notin $existingExplorerWindows){$folderWindow.Quit()}
if((Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne $leftDir){
throw 'Shift+Enter changed the folder in the Files panel.'
}
Wait-Until 'Files active for the registered document test' { [FilesActivationUi]::Activate($window) }
$documentRow=Find-Row $left ([IO.Path]::GetFileName($document))
if($documentRow -lt 0){throw 'The document fixture is missing.'}
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$documentRow,[IntPtr]::Zero)
Wait-Until 'Files command line focused for document Shift+Enter' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('+{ENTER}')
Wait-Until 'Shift+Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
Wait-Until 'Files active for plain Enter' { [FilesActivationUi]::Activate($window) }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Remove-Item -LiteralPath "$document.opened"
$keys.SendKeys('{ENTER}')
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
$command="start '$($document.Replace("'","''"))'"
Wait-Until 'the system open action in terminal output and command history' {
$history=$profile.GetValue('CommandHistory')
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
}
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
$keys.SendKeys('%{F8}')
$historyDialog=[IntPtr]::Zero
Wait-Until 'command history showing only the opened file path' {
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
}
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$historyRow=Find-Row $historyList $document
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
if ($TerminalOnly) {
Wait-Until 'Files active for the terminal startup check' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('^o')
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
foreach ($frame in 1..10) {
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
Start-Sleep -Milliseconds 30
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
Wait-Until 'the terminal rendering after startup' {
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
}
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@{Name='enter-terminal'; Keys='{ENTER}'; HidePanes=$true},
@{Name='shift-enter-terminal'; Keys='+{ENTER}'}
)) {
Wait-Until 'Files command line active' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
if($case.HidePanes){
$keys.SendKeys('^o')
Wait-Until 'file panes hidden' { ![FilesActivationUi]::IsWindowVisible($left) }
}
$marker=Join-Path $root "$($case.Name).txt"
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
Send-InteractiveTerminal $command $case.Keys
Wait-Until "$($case.Name) running the command" {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
if(Test-Path -LiteralPath "$document.opened"){
throw "$($case.Name) did not give the command line priority."
}
}
Write-Output 'Verified command-line priority for Enter and Shift+Enter with panels visible and hidden.'
if(!$TerminalOnly){return}
foreach($name in 'zzzz-dir-first','zzzz-dir-second'){
[IO.File]::WriteAllText((Join-Path $leftDir $name),'dir marker')
Send-InteractiveTerminal 'dir'
Wait-Until "dir rendering $name in terminal output" {
!(Read-Text $inputBox) -and
(Select-String -LiteralPath $trace -SimpleMatch $name -Quiet -ErrorAction SilentlyContinue)
}
}
$keys.SendKeys('^o')
Wait-Until 'file panes visible again' { [FilesActivationUi]::IsWindowVisible($left) }
$listing=Join-Path $root 'dir-visible.txt'
Send-InteractiveTerminal "dir -Name | Set-Content -LiteralPath '$($listing.Replace("'","''"))'"
Wait-Until 'dir running after restoring the file panes' {
!(Read-Text $inputBox) -and (Test-Path -LiteralPath $listing) -and
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
}
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
$rightChild = Join-Path $rightDir "Command's [folder]"
[void][IO.Directory]::CreateDirectory($rightChild)
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
Wait-Until 'native command running in the newly active right panel' {
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
(Find-Row $right 'panel-cwd.txt') -ge 0
}
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
Press-Enter $inputBox
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
Wait-Until 'native command running in the navigated folder' {
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
(Find-Row $right 'child-cwd.txt') -ge 0
}
Send-InteractiveTerminal 'cd ..'
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
Wait-Until 'native command running back in the left panel' {
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
(Find-Row $left 'left-cwd.txt') -ge 0
}
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
$marker=Join-Path $root 'webview-enter.txt'
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'the terminal WebView forwarding Enter to the command line' {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
$keys.SendKeys('^o')
Wait-Until 'full-screen terminal prompt' { ![FilesActivationUi]::IsWindowVisible($left) }
$draft='чернетка термінала'
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-prompt-text' $draft
if ($LASTEXITCODE) { throw 'Could not type into the terminal WebView.' }
Wait-Until 'WebView input using the shared prompt' { (Read-Text $inputBox) -ceq $draft }
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]38,[IntPtr]0)
Wait-Until 'the terminal recalling a command from the visible command line' { (Read-Text $inputBox) -ceq $command }
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]40,[IntPtr]0)
Wait-Until 'Down restoring the in-progress draft' { (Read-Text $inputBox) -ceq $draft }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'cd Test')
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]7,[IntPtr]7)
$suggestions=[FilesActivationUi]::FindWindowEx($window,[IntPtr]::Zero,'ListBox','Command suggestions')
Wait-Until 'PowerShell path completion in the full-screen prompt' {
[FilesActivationUi]::IsWindowVisible($suggestions)
}
if(![FilesActivationUi]::CompletionFollowsCaret($inputBox,$suggestions)){
throw 'The terminal suggestions must open above the editing caret.'
}
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]9,[IntPtr]0)
Wait-Until 'Tab inserting the suggested path in the prompt' {
(Read-Text $inputBox) -like 'cd *Test folder*'
}
Press-Enter $inputBox
Wait-Until 'the prompt following cd while the file panels are hidden' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
}
foreach($key in 'terminal-interrupt','Escape'){
$running=Join-Path $root "$key-running.txt"
$finished=Join-Path $root "$key-finished.txt"
Send-InteractiveTerminal "[IO.File]::WriteAllText('$running','started'); Start-Sleep -Seconds 45; [IO.File]::WriteAllText('$finished','unexpected')"
Wait-Until "a running PowerShell command for $key" { Test-Path -LiteralPath $running }
if($key -eq 'Escape'){
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]27,[IntPtr]0)
} else {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $key
if ($LASTEXITCODE) { throw 'Could not send Ctrl+C to the terminal WebView.' }
}
$next=Join-Path $root "$key-next.txt"
Send-InteractiveTerminal "[IO.File]::WriteAllText('$next','ready')"
Wait-Until "PowerShell accepting a new command after $key" { Test-Path -LiteralPath $next }
if(Test-Path -LiteralPath $finished){throw "$key failed to interrupt the PowerShell command."}
}
Send-InteractiveTerminal 'cd ..'
Wait-Until 'the active panel returning to its original folder' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq $leftDir
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after editing in the terminal prompt' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified terminal prompt typing, the shared history and completion, panel synchronization and interruption.'
# The left panel is already active after the working-directory check.
$folderRow = Find-Row $left '[Test folder]'
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
$outputSelection = 'terminal-output-copy-fixture'
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
Wait-Until 'focus returned to the command line after selecting terminal output' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
# Require a new clipboard write without making the test process the clipboard owner.
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
}
} finally {
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'Enter from the terminal opening the selected folder in the pane' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
}
Write-Output 'Verified Enter from the terminal opens the selected folder with an empty command line.'
return
}
Select-Row $left '..'
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr]::Zero, [IntPtr]::Zero)
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]9, [IntPtr]::Zero)
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]40, [IntPtr]::Zero)
Wait-Until 'Tab and Down navigating the right pane with command-line focus' {
[FilesActivationUi]::Focus($window) -eq $inputBox -and
[FilesActivationUi]::Send($right, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 1 -and
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $left '..')
}
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
$shell = New-Object -ComObject WScript.Shell
Wait-Until 'Files activation for Ctrl+F' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach ($case in @(
@{ Row = '..'; Path = $rightDir },
@{ Row = '[Test folder]'; Path = (Join-Path $rightDir 'Test folder') }
)) {
Select-Row $right $case.Row
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
$shell.SendKeys('^f')
$path = if ($case.Path.Contains(' ')) { '"{0}"' -f $case.Path } else { $case.Path }
Wait-Until "Ctrl+F inserting the path for $($case.Row)" { (Read-Text $inputBox) -ceq "draft $path" }
}
$fileName = [IO.Path]::GetFileName($document)
foreach ($name in $fileName, 'Test folder') {
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
Select-Row $right $label
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
Wait-Until 'Files activation for Ctrl+Enter' {
[FilesActivationUi]::Activate($window) -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^{ENTER}')
$expected = 'draft "{0}"' -f $name
Wait-Until "Ctrl+Enter inserting $name" { (Read-Text $inputBox) -ceq $expected }
}
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, '')
Write-Output 'Tab and Down navigated the panes while preserving command-line focus and text.'
foreach ($double in $false, $true) {
Assert-Open $left $program $double
Assert-Open $right $document $double
}
Invoke-Row $left '[Test folder]' $false
Wait-Until 'folder navigation by Enter' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq "$leftDir\Test folder"
}
Invoke-Row $left '..' $false
Invoke-Row $right '[Test folder]' $true
Wait-Until 'folder navigation by double click' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq "$rightDir\Test folder"
}
Invoke-Row $right '..' $false
Write-Output 'Enter and double-click opened folders, the registered document, and the standalone EXE.'
$sessionValue = $unique.Substring(0, 8)
Send-Terminal ('$global:ksSession = "{0}"; $env:KS_TEST_STATE = $ksSession; "READY=" + $ksSession' -f $sessionValue)
Wait-Until 'initialized terminal session and rendered test marker' {
(Get-Content -LiteralPath $trace -ErrorAction SilentlyContinue) -contains "READY=$sessionValue"
}
Invoke-Row $left ([IO.Path]::GetFileName($batch)) $false
Wait-Until 'visible BAT output with the existing session environment' {
[FilesActivationUi]::IsWindowVisible($output) -and
(Get-Content -LiteralPath $trace) -contains "BAT=$sessionValue"
}
Invoke-Row $right ([IO.Path]::GetFileName($cmd)) $true
Wait-Until 'visible CMD output with the existing session environment' {
[FilesActivationUi]::IsWindowVisible($output) -and
(Get-Content -LiteralPath $trace) -contains "CMD=$sessionValue"
}
Send-Terminal '"AFTER=" + $global:ksSession'
Wait-Until 'unchanged PowerShell session state' {
(Get-Content -LiteralPath $trace) -contains "AFTER=$sessionValue"
}
Assert-Open $left $program $false
Write-Output 'BAT and CMD ran in the existing terminal and rendered their output.'
$external = 'External change.txt'
Select-Row $left ([IO.Path]::GetFileName($program))
foreach ($dir in $leftDir, $rightDir) { [IO.File]::WriteAllText((Join-Path $dir $external), 'one') }
Wait-Until 'external creation in both panels' {
(Find-Row $left $external) -ge 0 -and (Find-Row $right $external) -ge 0
}
if ([FilesActivationUi]::Focus($window) -ne $inputBox -or
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne
(Find-Row $left ([IO.Path]::GetFileName($program)))) { throw 'Creation moved focus or selection.' }
foreach ($panel in @(@{ List = $left; Dir = $leftDir }, @{ List = $right; Dir = $rightDir })) {
Select-Row $panel.List $external
Wait-Until 'initial file size' { (Read-Text $status) -match ' 3 B$' }
[IO.File]::AppendAllText((Join-Path $panel.Dir $external), 'two!')
Wait-Until 'updated file size' { (Read-Text $status) -match ' 7 B$' }
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Modification moved focus.' }
}
foreach ($dir in $leftDir, $rightDir) { [IO.File]::Delete((Join-Path $dir $external)) }
Wait-Until 'external deletion in both panels' {
(Find-Row $left $external) -eq -1 -and (Find-Row $right $external) -eq -1
}
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Deletion moved focus.' }
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
$programName=[IO.Path]::GetFileName($program)
$expectedNames="Test folder`r`n$programName"
try {
Select-Row $left '[Test folder]'
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
Select-Row $left $programName
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
Wait-Until 'Files activation for Ctrl+Insert' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
}
Select-Row $right $fileName
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
}
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
} finally {
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
$sizeA=Join-Path $rightDir 'Size A'
$sizeB=Join-Path $rightDir 'Size B'
$sizeC=Join-Path $rightDir 'Size C'
New-Item -ItemType Directory -Path "$sizeA\nested", $sizeB, $sizeC | Out-Null
[IO.File]::WriteAllBytes("$sizeA\file.bin",[byte[]]::new(4))
[IO.File]::WriteAllBytes("$sizeA\nested\file.bin",[byte[]]::new(7))
[IO.File]::WriteAllBytes("$sizeB\file.bin",[byte[]]::new(23))
[IO.File]::WriteAllBytes("$sizeC\file.bin",[byte[]]::new(31))
Select-Row $right '[Size A]'
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Wait-Until 'F3 recursive size for the current folder' { (Read-Text $status) -ceq 'Size A 11 B' }
foreach($name in 'Size A','Size B'){
Select-Row $right "[$name]"
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
}
Select-Row $right $fileName
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Select-Row $right '[Size B]'
Wait-Until 'F3 on a file measuring a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
Select-Row $right '[Size C]'
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
Select-Row $right '..'
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Select-Row $right '[Size C]'
Wait-Until 'F3 on the parent row measuring all folders' { (Read-Text $status) -ceq 'Size C 31 B' }
foreach($name in 'Size A','Size B'){
Select-Row $right "[$name]"
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
}
Select-Row $right $fileName
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
$viewerTitle='Viewer '+[char]0x2014+" $document"
Wait-Until 'F3 opening a file with no marked folders' {
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
}
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
Select-Row $right '[Size B]'
Wait-Until 'Files activation for Ctrl+R' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^r')
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
(Read-Text $status) -ceq 'Size B Folder' -and
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
(Find-Row $right '[Size B]')
}
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
$operationName = 'Background operation.txt'
$leftOperation = Join-Path $leftDir 'Operations'
$rightOperation = Join-Path $rightDir 'Operations'
New-Item -ItemType Directory -Path $leftOperation, $rightOperation | Out-Null
$operationSource = Join-Path $leftOperation $operationName
$operationTarget = Join-Path $rightOperation $operationName
Invoke-Row $left '[Operations]' $false
Invoke-Row $right '[Operations]' $false
Wait-Until 'operation folders loaded in both panes' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq $leftOperation -and
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq $rightOperation
}
[IO.File]::WriteAllText($operationSource, 'source contents')
[IO.File]::WriteAllText($operationTarget, 'original target')
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x74, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Answer-OperationDialog 230 6
Wait-Until 'copy after overwrite confirmation' {
(Read-Text $status) -ceq 'Copy complete.' -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
if ([IO.File]::ReadAllText($operationTarget) -cne 'source contents') {
throw 'Copy did not replace the target contents.'
}
[IO.File]::Delete($operationTarget)
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Wait-Until 'move destination field' { (Find-OperationDialog $window 211) -ne [IntPtr]::Zero }
$moveDialog = Find-OperationDialog $window 211
$destinationField = [FilesActivationUi]::GetDlgItem($moveDialog, 211)
$validDestination = Read-Text $destinationField
$missingDestination = Join-Path $rightOperation 'missing\destination.txt'
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $missingDestination)
Answer-OperationDialog 211 1
Answer-OperationDialog 100 1
Wait-Until 'focus returns to the move destination after asynchronous validation' {
[FilesActivationUi]::Focus($window) -eq $destinationField
}
if (!(Test-Path -LiteralPath $operationSource)) { throw 'Invalid destination started the move.' }
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $validDestination)
$lockReady = Join-Path $root 'lock.ready'
$locker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $operationSource,$lockReady) -WindowStyle Hidden -PassThru
try {
Wait-Until 'file locked by the fixture process' { Test-Path -LiteralPath $lockReady }
Answer-OperationDialog 211 1
Wait-Until 'red modal error for a locked file' {
$errorDialog = Find-OperationDialog $window 100
$errorDialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($errorDialog)
}
$errorDialog = Find-OperationDialog $window 100
$reason = Read-Text ([FilesActivationUi]::GetDlgItem($errorDialog, 100))
if (!$reason -or (Read-Text $status).Contains($reason)) {
throw 'The move failure reason must appear in the modal dialog.'
}
Answer-OperationDialog 100 103
Wait-Until 'the locker appears with its PID' {
$dialog = Find-OperationDialog $window 431
if ($dialog -eq [IntPtr]::Zero) { return $false }
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)) -ge 0
}
$dialog = Find-OperationDialog $window 431
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
$row = Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr]$row, [IntPtr]::Zero)
Answer-OperationDialog 431 433
Answer-OperationDialog 100 7
Wait-Until 'End process confirmation closes after No' {
(Find-OperationDialog $window 100) -eq [IntPtr]::Zero
}
if ($locker.HasExited) { throw 'Declining the confirmation ended the process.' }
Answer-OperationDialog 431 433
Answer-OperationDialog 100 6
if (!$locker.WaitForExit(5000)) { throw 'Confirming End process did not terminate the locker.' }
Wait-Until 'the process list refreshes after termination' {
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
}
Answer-OperationDialog 431 1
} finally {
if (!$locker.HasExited) { $locker.Kill(); $locker.WaitForExit() }
$locker.Dispose()
}
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Wait-Until 'move and asynchronous pane refresh' {
!(Test-Path -LiteralPath $operationSource) -and
(Find-Row $left $operationName) -eq -1 -and (Find-Row $right $operationName) -ge 0
}
Select-Row $right $operationName
Wait-Until 'Files activation for Shift+Delete' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('+{DELETE}')
Answer-OperationDialog 240 6
Wait-Until 'permanent deletion and asynchronous pane refresh' {
!(Test-Path -LiteralPath $operationTarget) -and (Find-Row $right $operationName) -eq -1 -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
Write-Output 'Copy overwrite, move and permanent deletion completed through their Files dialogs.'
$lockedFolder = Join-Path $leftOperation 'Locked folder'
[IO.Directory]::CreateDirectory($lockedFolder) | Out-Null
$folderReady = Join-Path $root 'folder-lock.ready'
$folderLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $lockedFolder,$folderReady) -WindowStyle Hidden -PassThru
try {
Wait-Until 'folder locked by the fixture process' { Test-Path -LiteralPath $folderReady }
Select-Row $left '[Locked folder]'
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Answer-OperationDialog 100 103
Wait-Until 'the folder locker appears with its PID' {
$dialog = Find-OperationDialog $window 431
if ($dialog -eq [IntPtr]::Zero) { return $false }
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $folderLocker.Id)) -ge 0
}
Answer-OperationDialog 431 1
} finally {
if (!$folderLocker.HasExited) { $folderLocker.Kill(); $folderLocker.WaitForExit() }
$folderLocker.Dispose()
}
Write-Output 'The blocking-process dialog identified both a file lock and a folder lock by PID.'
foreach ($useRecycleBin in $false, $true) {
$name = if ($useRecycleBin) { 'Held for Recycle Bin' } else { 'Held for permanent deletion.txt' }
$target = Join-Path $leftOperation $name
if ($useRecycleBin) { [IO.Directory]::CreateDirectory($target) | Out-Null }
else { [IO.File]::WriteAllText($target, 'fixture') }
$label = if ($useRecycleBin) { "[$name]" } else { $name }
$ready = Join-Path $root "delete-lock-$useRecycleBin.ready"
$deleteLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $target,$ready) -WindowStyle Hidden -PassThru
try {
Wait-Until 'deletion target held by the fixture' { Test-Path -LiteralPath $ready }
Select-Row $left $label
if ($useRecycleBin) {
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x77, [IntPtr]::Zero)
} else {
Wait-Until 'Files activation for blocked Shift+Delete' { [FilesActivationUi]::Activate($window) }
$shell.SendKeys('+{DELETE}')
}
Answer-OperationDialog 240 6
Wait-Until 'red failure dialog for blocked deletion' {
$dialog = Find-OperationDialog $window 100
$dialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($dialog)
}
Answer-OperationDialog 100 103
$processLabel = 'KSwitcherFilesActivationFixture.exe (PID {0})' -f $deleteLocker.Id
Wait-Until 'deletion blocker appears in the process list' {
$dialog = Find-OperationDialog $window 431
$dialog -ne [IntPtr]::Zero -and
(Find-Row ([FilesActivationUi]::GetDlgItem($dialog, 431)) $processLabel) -ge 0
}
$dialog = Find-OperationDialog $window 431
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr](Find-Row $list $processLabel), [IntPtr]::Zero)
Answer-OperationDialog 431 433
Answer-OperationDialog 100 6
if (!$deleteLocker.WaitForExit(5000)) { throw 'End process did not release the deletion target.' }
Wait-Until 'deletion blocker list refreshes' {
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
}
Answer-OperationDialog 431 1
Wait-Until 'Files regains focus after closing the process list' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
} finally {
if (!$deleteLocker.HasExited) { $deleteLocker.Kill(); $deleteLocker.WaitForExit() }
$deleteLocker.Dispose()
}
Select-Row $left $label
Wait-Until 'Files activation for deletion retry' { [FilesActivationUi]::Activate($window) }
$shell.SendKeys('+{DELETE}')
Answer-OperationDialog 240 6
Wait-Until 'deletion succeeds after ending the blocker' {
!(Test-Path -LiteralPath $target) -and (Find-Row $left $label) -eq -1
}
}
Write-Output 'Blocked permanent file deletion and folder recycling opened the shared process dialog and released their blockers.'
} catch {
if ($inputBox -and $status) {
Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)"
}
if ($trace -and (Test-Path -LiteralPath $trace)) {
Get-Content -LiteralPath $trace -Tail 25
}
throw
} finally {
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=$webviewFlags
$env:WEBVIEW2_USER_DATA_FOLDER=$webviewProfile
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
}
foreach ($name in $profileValues) {
if ($saved.ContainsKey($name)) { $profile.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $profile.DeleteValue($name, $false) }
}
$profile.Dispose()
$classes.DeleteSubKeyTree($extension, $false)
$classes.DeleteSubKeyTree($progId, $false)
$classes.Dispose()
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
if ($trace) { Remove-Item -LiteralPath $trace -ErrorAction SilentlyContinue }
$resolvedRoot = Resolve-Path -LiteralPath $root -ErrorAction SilentlyContinue
$tempPrefix = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
if ($resolvedRoot -and $resolvedRoot.Path.StartsWith($tempPrefix, [StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath $resolvedRoot.Path -Recurse -Force -ErrorAction SilentlyContinue
}
}