feat: queue actions while a job is running, with reorder and cancel (#5207)

* Queue user actions instead of refusing them while a job runs

Start-WinUtilJob -QueueIfBusy parks the job in $sync.JobQueue under the
same lock as the busy test, and Clear-WinUtilActiveJob starts the next
one when a job ends, failed or not. A clock button in the top bar lists
the running and queued jobs and reorders or cancels the queued ones.
Closing the window warns about and discards anything still queued.

* Hold the freed job slot for the queue until its head starts

Clear-WinUtilActiveJob sets \.JobHandoff while queued work remains,
so a new action queues behind the head instead of taking the slot in
the gap before the dispatch runs. Closing with only queued work left
now prompts, and discarding it closes without a console wait.

* Ignore a queued job that repeats work already queued

A second click on the same action with the same selection while the slot
is busy queued the work again, so it ran several times. Jobs are compared
by name and a serialisation of their parameters inside the queue lock.

* Shut the queue atomically when a queued-only close is accepted

The check that nothing started during the prompt and the shutdown flag,
queue clear and handoff reset now happen in one SyncRoot step, so a
handoff either wins and the running-job question is asked again, or is
refused as WinUtil is closing. The XAML test now checks the queue
button's own click handler.

* Stop the queue handing out the slot when the running job is stopped on close

Answering No to the close question set ForceClose but not the shutdown flag,
so the stopped job ending could start a queued one while the window closed.
Both close branches now share Stop-WinUtilQueuedWork, which sets the flag,
clears the queue and ends any handoff under the lock.

* Keep queued operations accessible in a bounded scrolling list

* Snapshot the package manager for queued upgrades

* Prevent queued work from racing close decisions

* Name queued job actions for assistive technology

* Preserve repeated queue actions after intervening work

---------

Co-authored-by: Chris Titus <contact@christitus.com>
This commit is contained in:
Vyas DevgnaandChris Titus authored and GitHub committed 2026-11-03 22:01:08 -06:00
1 parent 8c549c5034
commit 2ef5e5dc78
22 files changed
+1412 -30

No files matched your search

+1
View File
@@ -69,6 +69,7 @@ Because the final script is concatenated, code cannot rely on runtime module imp
- WinUtil runs in PowerShell on Windows and uses WPF for the UI.
- Shared mutable state is stored in `$sync`, including configs, UI element references, runspace state, selections, and progress.
- Long-running operations use runspaces or existing async patterns so the UI remains responsive.
- User actions that opt into the job queue run one at a time with their selected inputs. Queued work can be reordered or cancelled, pauses during close confirmation, and is discarded when the window closes. ISO and USB jobs still refuse to queue.
- UI updates from background work are dispatched back to the WPF UI thread.
- Every runspace logs to the timestamped `%LocalAppData%\winutil\logs` session file through `Write-WinUtilLog`, which shares one writer through `$sync`. Job output and the UI runspace's warnings, errors and `Write-Host` output are collected into it; console-only output such as banners and progress uses `Write-WinUtilHost`.
- Declarative features such as apps, tweaks, presets, DNS providers, and navigation stay in `config/*.json` unless code is required.
@@ -461,6 +461,15 @@ restoring the interface in a `finally` whatever happens.
job; anything that only changes what the interface is showing runs on the interface thread.
That single classification is why no workflow arranges its own progress, banner or busy state.
**Queueing**: an action the user starts passes `-QueueIfBusy`, so while another job runs it waits
in `$sync.JobQueue` instead of being refused. The busy test and the enqueue happen under one
`$sync.SyncRoot` lock. When a job ends, successfully or not, `Clear-WinUtilActiveJob` posts
`Start-WinUtilNextQueuedJob` to the interface thread, which starts the oldest entry. The queue
compares only its last entry when suppressing identical requests, preserving repeated actions after intervening work. It holds the job's parameters as they were at click time, so later selection changes do not alter
it. The clock button in the header lists the running and queued jobs and lets the user reorder
or cancel the queued ones. Handoffs pause while the close question is open, so its answer cannot affect a different queued job. Closing the window discards whatever is still queued. The ISO and USB
jobs do not pass the switch and still refuse.
```powershell
Start-WinUtilJob -Name "Features" -Description "Installing Windows Features" -Parameters @{
Features = @($sync.selectedFeatures)
@@ -94,6 +94,8 @@ WinUtil opens with a clean, tabbed interface:
- **Updates**: Manage Windows updates
- **Win11 Creator**: Build a customized Windows 11 ISO from an official Microsoft image
**Running more than one action**: if you start an install, tweak or fix while another is running, it waits its turn instead of being refused. A clock button appears in the top bar with the number waiting; open it to see what is running, move waiting items up or down, or cancel them. Consecutive identical requests are queued once; repeating an action after a different request keeps your chosen order. Closing WinUtil discards anything still waiting.
## Your first actions
Here are some recommended first steps for new users:
@@ -9,18 +9,47 @@ function Invoke-WinUtilCloseRequest {
everything closes now.
.PARAMETER RunningJob
The name of the job in flight, so the question names what is at stake.
The name of the job in flight, so the question names what is at stake. With nothing
running and only queued jobs left, the question is just whether to discard them.
.PARAMETER QueuedCount
How many queued jobs closing will discard, so they are not a surprise.
#>
param(
[Parameter(Mandatory)]
[string]$RunningJob
[string]$RunningJob,
[int]$QueuedCount = 0
)
if (-not $sync.ActiveJob) {
$discard = Show-WinUtilJobCloseMessage -Button "YesNo" -Icon "Warning" -Title "Queued operations" -Message "Nothing is running. $QueuedCount queued operation(s) will be discarded.`n`nClose WinUtil anyway?"
if ("$discard" -ne "Yes") {
Write-WinUtilLog -Component "UI" -Message "Close cancelled, $QueuedCount operation(s) are still queued."
return
}
# Recheck under the queue lock in case a concurrent caller claimed the slot before the
# prompt paused handoffs. Closing must ask about that job rather than silently stop it.
$startedMeanwhile = Stop-WinUtilQueuedWork -OnlyIfIdle
if ($startedMeanwhile) {
Invoke-WinUtilCloseRequest -RunningJob $startedMeanwhile -QueuedCount $sync.JobQueue.Count
return
}
Write-WinUtilLog -Component "UI" -Message "Close requested: closing with $QueuedCount queued operation(s) discarded."
$sync.ForceClose = $true
Request-WinUtilWindowClose
return
}
$queuedNote = if ($QueuedCount -gt 0) { "`n$QueuedCount queued operation(s) will be discarded.`n" } else { "" }
# The question carries the meaning rather than naming buttons: Windows labels them in its own
# language, so "Yes" in the text would not match a button reading "Ja".
$answer = Show-WinUtilMessage -Button "YesNoCancel" -Icon "Warning" -Title "$RunningJob is still running" -Message @"
$answer = Show-WinUtilJobCloseMessage -Button "YesNoCancel" -Icon "Warning" -Title "$RunningJob is still running" -Message @"
$RunningJob has not finished yet.
$queuedNote
Close the window and let it finish in the console?
WinUtil will exit on its own once it is done. If you do not, it will be
@@ -42,6 +71,8 @@ stopped and everything closes now. Cancel keeps WinUtil open.
}
"No" {
Write-WinUtilLog -Component "UI" -Message "Close requested: stopping $RunningJob."
# The job ending must not hand its slot to a queued one while the window closes
$null = Stop-WinUtilQueuedWork
Step-WinUtilJob -Status "Stopping $RunningJob" -State "Indeterminate"
$sync.ForceClose = $true
@@ -56,6 +87,68 @@ stopped and everything closes now. Cancel keeps WinUtil open.
}
}
function Show-WinUtilJobCloseMessage {
<#
.SYNOPSIS
Holds queued work until the user answers which work may outlive the window
#>
param($Button, $Icon, $Title, $Message)
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$alreadyOpen = [bool]$sync.JobClosePromptOpen
$sync.JobClosePromptOpen = $true
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
try {
Show-WinUtilMessage @PSBoundParameters
} finally {
if (-not $alreadyOpen) {
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$sync.JobClosePromptOpen = $false
$resume = -not $sync.ActiveJob -and $sync.JobQueue.Count -gt 0
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($resume) {
# Posted work runs after the caller applies the answer's shutdown/console flags.
Invoke-WPFUIThread -Async -ScriptBlock { Start-WinUtilNextQueuedJob }
}
}
}
}
function Stop-WinUtilQueuedWork {
<#
.SYNOPSIS
Stops the queue handing out the slot because WinUtil is about to close
.DESCRIPTION
Sets the shutdown flag the queue honours, drops what is queued and ends any handoff,
in one step under the lock so a job cannot start in between.
.PARAMETER OnlyIfIdle
Do nothing and return the running job's name if a job holds the slot. Otherwise
returns $null.
#>
param([switch]$OnlyIfIdle)
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
if ($OnlyIfIdle -and $sync.ActiveJob) {
return $sync.ActiveJob
}
$sync.ShuttingDown = $true
$null = Clear-WinUtilJobQueue
$sync.JobHandoff = $false
return $null
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
}
function Request-WinUtilWindowClose {
<#
.SYNOPSIS
+94 -5
View File
@@ -26,6 +26,16 @@ function Start-WinUtilJob {
.PARAMETER DisableAppList
Greys out the app list for the duration, for jobs that change what is installed.
.PARAMETER QueueIfBusy
Waits in $sync.JobQueue for its turn instead of being refused, for actions the user
starts. The parameters are held as they were when it was queued. A job with the same
name and parameters as the last queued job is ignored, so consecutive clicks do not repeat
the work.
.PARAMETER FromQueue
Internal to Start-WinUtilNextQueuedJob: this is the queued job taking its turn, so it
may claim the slot while $sync.JobHandoff holds it for the queue.
.EXAMPLE
Start-WinUtilJob -Name "Install" -Parameters @{ Packages = $packages } -ScriptBlock {
param($Packages)
@@ -43,10 +53,15 @@ function Start-WinUtilJob {
[string]$Description,
[switch]$DisableAppList
[switch]$DisableAppList,
[switch]$QueueIfBusy,
[switch]$FromQueue
)
if ($sync.ShuttingDown -or $sync.FinishInConsole) {
if ($FromQueue) { Reset-WinUtilJobHandoff }
Write-WinUtilLog -Level "WARN" -Component $Name -Message "Refused to start $Name, WinUtil is closing."
return $null
}
@@ -64,10 +79,55 @@ function Start-WinUtilJob {
# still unwinding cannot release a slot the next job holds.
$jobToken = [guid]::NewGuid().ToString()
$blockedBy = $null
$queuePosition = 0
$duplicate = $false
# Built outside the lock. A value that cannot be serialised just leaves the job undeduplicated.
$signature = $null
if ($QueueIfBusy) {
try {
$sortedKeys = [string[]]$Parameters.Keys
[array]::Sort($sortedKeys)
$ordered = [ordered]@{}
foreach ($key in $sortedKeys) { $ordered[$key] = $Parameters[$key] }
$signature = "$Name|" + (ConvertTo-Json -InputObject $ordered -Compress -Depth 5 -WarningAction SilentlyContinue)
} catch {
Write-WinUtilLog -Level "WARN" -Component $Name -Message "Could not compare $Name with the queue, so it will not be checked for duplicates: $($_.Exception.Message)"
}
}
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
if ($sync.ActiveJob) {
$blockedBy = $sync.ActiveJob
# Closing can win while the signature is built or this caller waits for the lock.
if ($sync.ShuttingDown -or $sync.FinishInConsole) {
if ($FromQueue) { $sync.JobHandoff = $false }
Write-WinUtilLog -Level "WARN" -Component $Name -Message "Refused to start $Name, WinUtil is closing."
return $null
}
if ($FromQueue) {
$sync.JobHandoff = $false
}
# A finished job's slot is promised to the queue until its head has started
if ($sync.ActiveJob -or $sync.JobHandoff) {
$blockedBy = if ($sync.ActiveJob) { $sync.ActiveJob } else { "Queued operations" }
# In the same lock as the busy test: a job finishing between the two would leave
# this one queued behind nothing
if ($QueueIfBusy -and $signature -and $sync.JobQueue.Count -gt 0) {
# An intervening action can change the state again; only collapse adjacent clicks.
$duplicate = $sync.JobQueue[$sync.JobQueue.Count - 1].Signature -eq $signature
}
if ($QueueIfBusy -and -not $duplicate) {
$sync.JobQueue.Add([pscustomobject]@{
Id = [guid]::NewGuid().ToString()
Signature = $signature
Name = $Name
Description = $Description
ScriptBlock = $ScriptBlock.ToString()
Parameters = $Parameters
DisableAppList = [bool]$DisableAppList
})
$queuePosition = $sync.JobQueue.Count
}
} else {
$sync.ActiveJob = $Name
$sync.ActiveJobToken = $jobToken
@@ -77,6 +137,17 @@ function Start-WinUtilJob {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($duplicate) {
Write-WinUtilLog -Component $Name -Message "$Name is already queued, ignored."
return $null
}
if ($queuePosition -gt 0) {
Write-WinUtilLog -Component $Name -Message "$Name queued behind $blockedBy, position $queuePosition."
Invoke-WPFUIThread -Async -ScriptBlock { Update-WinUtilJobQueueUI }
return $null
}
if ($blockedBy) {
Show-WinUtilMessage -Message "$blockedBy is still running. Wait for it to finish before starting another action." -Title "WinUtil" -Button "OK" -Icon "Warning" | Out-Null
return $null
@@ -87,6 +158,7 @@ function Start-WinUtilJob {
$timingStartIndex = if ($sync.StepTimings) { $sync.StepTimings.Count } else { 0 }
Write-WinUtilLog -Component $Name -Message "$Name job started."
Invoke-WPFUIThread -Async -ScriptBlock { Update-WinUtilJobQueueUI }
Write-WinUtilJobBanner -Message $label
Step-WinUtilJob -Status "$label..." -Percent 0 -State "Normal" -Overlay "logo"
@@ -279,15 +351,32 @@ function Clear-WinUtilActiveJob {
#>
param([string]$Token)
$released = $false
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
if (-not $Token -or $sync.ActiveJobToken -eq $Token) {
$sync.ActiveJobToken = $null
$sync.ActiveJob = $null
return $true
$released = $true
# Between here and the posted dispatch the slot is free, and a new action must not
# take it ahead of the queue
if ($Token -and $sync.JobQueue.Count -gt 0 -and -not $sync.ShuttingDown -and -not $sync.FinishInConsole) {
$sync.JobHandoff = $true
}
}
return $false
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
# A job that ended, however it ended, hands the slot to the next queued one. A release with no
# token is a forced reset, which must not start anything.
if ($released -and $Token) {
try {
Invoke-WPFUIThread -Async -ScriptBlock { Start-WinUtilNextQueuedJob }
} catch {
Reset-WinUtilJobHandoff
Write-WinUtilLog -Level "WARN" -Component "UI" -Message "Could not start the next queued job: $($_.Exception.Message)"
}
}
return $released
}
@@ -0,0 +1,238 @@
function Start-WinUtilNextQueuedJob {
<#
.SYNOPSIS
Starts the oldest queued job if the slot is free
.DESCRIPTION
Runs on the interface thread, posted by Clear-WinUtilActiveJob when a job finishes
whether it succeeded or not. Until the job it starts claims the slot, $sync.JobHandoff
keeps new actions queueing behind it, and every way out of here clears the flag.
#>
if ($sync.ShuttingDown -or $sync.FinishInConsole) {
Reset-WinUtilJobHandoff
return
}
$next = $null
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
if ($sync.JobClosePromptOpen) { return }
if (-not $sync.ActiveJob -and $sync.JobQueue.Count -gt 0) {
$next = $sync.JobQueue[0]
$sync.JobQueue.RemoveAt(0)
} else {
$sync.JobHandoff = $false
}
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($null -eq $next) {
Update-WinUtilJobQueueUI
return
}
Write-WinUtilLog -Component $next.Name -Message "Starting queued $($next.Name) job."
# FromQueue clears the handoff in the same lock that claims the slot, or when it refuses
Start-WinUtilJob -Name $next.Name -Description $next.Description -ScriptBlock ([scriptblock]::Create($next.ScriptBlock)) -Parameters $next.Parameters -DisableAppList:$next.DisableAppList -FromQueue
}
function Reset-WinUtilJobHandoff {
<#
.SYNOPSIS
Lets new actions claim the slot again after a handoff that will not complete
#>
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$sync.JobHandoff = $false
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
}
function Get-WinUtilQueuedJobIndex {
<#
.SYNOPSIS
Finds a queued job by Id, or -1. The caller holds the SyncRoot lock.
#>
param([string]$Id)
for ($index = 0; $index -lt $sync.JobQueue.Count; $index++) {
if ($sync.JobQueue[$index].Id -eq $Id) {
return $index
}
}
return -1
}
function Move-WinUtilQueuedJob {
<#
.SYNOPSIS
Moves a queued job one place earlier or later, doing nothing at either end
.PARAMETER Id
The Id of the queued job.
.PARAMETER Direction
Up runs it sooner, Down later.
#>
param(
[Parameter(Mandatory)]
[string]$Id,
[Parameter(Mandatory)]
[ValidateSet("Up", "Down")]
[string]$Direction
)
$moved = $null
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$index = Get-WinUtilQueuedJobIndex -Id $Id
$target = if ($Direction -eq "Up") { $index - 1 } else { $index + 1 }
if ($index -ge 0 -and $target -ge 0 -and $target -lt $sync.JobQueue.Count) {
$moved = $sync.JobQueue[$index]
$sync.JobQueue.RemoveAt($index)
$sync.JobQueue.Insert($target, $moved)
}
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($moved) {
Write-WinUtilLog -Component $moved.Name -Message "Moved queued $($moved.Name) job $($Direction.ToLower())."
Update-WinUtilJobQueueUI
}
}
function Remove-WinUtilQueuedJob {
<#
.SYNOPSIS
Cancels a queued job before it starts
.PARAMETER Id
The Id of the queued job. A job that has already started is not in the queue.
#>
param(
[Parameter(Mandatory)]
[string]$Id
)
$removed = $null
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$index = Get-WinUtilQueuedJobIndex -Id $Id
if ($index -ge 0) {
$removed = $sync.JobQueue[$index]
$sync.JobQueue.RemoveAt($index)
}
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($removed) {
Write-WinUtilLog -Component $removed.Name -Message "Cancelled queued $($removed.Name) job."
Update-WinUtilJobQueueUI
}
}
function Clear-WinUtilJobQueue {
<#
.SYNOPSIS
Drops every queued job and returns how many were dropped
.DESCRIPTION
For the window closing: nothing queued may start once it is gone.
#>
$dropped = 0
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$dropped = $sync.JobQueue.Count
$sync.JobQueue.Clear()
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
if ($dropped -gt 0) {
Write-WinUtilLog -Component "UI" -Message "Discarded $dropped queued job(s) because the window is closing."
}
return $dropped
}
function Update-WinUtilJobQueueUI {
<#
.SYNOPSIS
Shows the queue button while anything runs or waits, and rebuilds the open dropdown
.DESCRIPTION
Interface thread only. Other threads post it through Invoke-WPFUIThread.
#>
if ($null -eq $sync.JobQueueButton) {
return
}
# A copy, so the rows are built without holding the lock the workers need
[System.Threading.Monitor]::Enter($sync.SyncRoot)
try {
$queued = $sync.JobQueue.ToArray()
$running = $sync.ActiveJob
} finally {
[System.Threading.Monitor]::Exit($sync.SyncRoot)
}
$busy = $running -or $queued.Count -gt 0
$sync.JobQueueButton.Visibility = if ($busy) { "Visible" } else { "Collapsed" }
$sync.JobQueueCount.Text = if ($queued.Count -gt 0) { [string]$queued.Count } else { "" }
if (-not $busy) {
$sync.JobQueuePopup.IsOpen = $false
}
if (-not $sync.JobQueuePopup.IsOpen) {
return
}
$sync.JobQueueRunning.Text = if ($running) { "Running: $running" } else { "Nothing running" }
$sync.JobQueueItems.Children.Clear()
for ($index = 0; $index -lt $queued.Count; $index++) {
$row = New-Object Windows.Controls.Grid
$row.ColumnDefinitions.Add((New-Object System.Windows.Controls.ColumnDefinition -Property @{Width = "*"}))
for ($column = 0; $column -lt 3; $column++) {
$row.ColumnDefinitions.Add((New-Object System.Windows.Controls.ColumnDefinition -Property @{Width = "30"}))
}
# Trimmed with a tooltip because the dropdown has a fixed width
$label = New-Object Windows.Controls.TextBlock
$label.Text = $queued[$index].Name
$label.ToolTip = $queued[$index].Name
$label.TextTrimming = "CharacterEllipsis"
$label.VerticalAlignment = "Center"
$label.Margin = "5,0,5,0"
$label.SetResourceReference([Windows.Controls.TextBlock]::FontSizeProperty, "ButtonFontSize")
$label.SetResourceReference([Windows.Controls.TextBlock]::ForegroundProperty, "MainForegroundColor")
$row.Children.Add($label) | Out-Null
$column = 1
foreach ($action in @(
@{ Glyph = 0xE70E; Tip = "Run sooner"; Enabled = $index -gt 0; Click = { Move-WinUtilQueuedJob -Id $this.Tag -Direction Up } },
@{ Glyph = 0xE70D; Tip = "Run later"; Enabled = $index -lt ($queued.Count - 1); Click = { Move-WinUtilQueuedJob -Id $this.Tag -Direction Down } },
@{ Glyph = 0xE711; Tip = "Cancel"; Enabled = $true; Click = { Remove-WinUtilQueuedJob -Id $this.Tag } }
)) {
$button = New-Object Windows.Controls.Button
$button.FontFamily = "Segoe MDL2 Assets"
$button.Content = [string][char]$action.Glyph
$button.ToolTip = $action.Tip
[Windows.Automation.AutomationProperties]::SetName($button, "$($action.Tip): $($queued[$index].Name)")
$button.Tag = $queued[$index].Id
$button.IsEnabled = $action.Enabled
$button.Opacity = if ($action.Enabled) { 1 } else { 0.3 }
$button.SetResourceReference([Windows.Controls.Control]::ForegroundProperty, "MainForegroundColor")
$button.SetResourceReference([Windows.Controls.Control]::StyleProperty, "HoverButtonStyle")
$button.Add_Click($action.Click)
[System.Windows.Controls.Grid]::SetColumn($button, $column++)
$row.Children.Add($button) | Out-Null
}
$sync.JobQueueItems.Children.Add($row) | Out-Null
}
}
@@ -176,12 +176,16 @@ function Start-WinUtilUserInterface {
# The pool cannot be torn down under work that is still running: the runspace error that
# follows is unhandled and ends the process
if ($sync.ActiveJob -and -not $sync.ForceClose) {
if (($sync.ActiveJob -or $sync.JobQueue.Count -gt 0) -and -not $sync.ForceClose) {
$closingArgs.Cancel = $true
Invoke-WinUtilCloseRequest -RunningJob $sync.ActiveJob
$runningJob = if ($sync.ActiveJob) { $sync.ActiveJob } else { "Queued operations" }
Invoke-WinUtilCloseRequest -RunningJob $runningJob -QueuedCount $sync.JobQueue.Count
return
}
# Past the prompt the window is closing for good, and nothing queued may start after it
$null = Clear-WinUtilJobQueue
# Work that is meant to outlive the window needs the pool it is running on. main.ps1
# waits for it and shuts the pool down once it is done.
if ($sync.FinishInConsole) {
@@ -414,6 +418,16 @@ function Start-WinUtilUserInterface {
Invoke-WinutilThemeChange -theme "Light"
})
# A popup that closes on outside clicks also closes on the click that would toggle it, which
# would then reopen it, so a click straight after a close is that same click
$sync.JobQueuePopupClosedAt = [DateTime]::MinValue
$sync["JobQueuePopup"].Add_Closed({ $sync.JobQueuePopupClosedAt = [DateTime]::UtcNow })
$sync["JobQueuePopup"].Add_Opened({ Update-WinUtilJobQueueUI })
$sync["JobQueueButton"].Add_Click({
if (([DateTime]::UtcNow - $sync.JobQueuePopupClosedAt).TotalMilliseconds -lt 300) { return }
Invoke-WPFPopup -PopupActionTable @{ "Settings" = "Hide"; "Theme" = "Hide"; "FontScaling" = "Hide"; "JobQueue" = "Show" }
})
$sync["SettingsButton"].Add_Click({
Invoke-WPFPopup -PopupActionTable @{ "Settings" = "Toggle"; "Theme" = "Hide"; "FontScaling" = "Hide" }
})
+1 -1
View File
@@ -4,7 +4,7 @@ function Invoke-WPFAppxInstall {
return
}
Start-WinUtilJob -Name "AppX install" -Description "Installing AppX packages" -Parameters @{
Start-WinUtilJob -Name "AppX install" -Description "Installing AppX packages" -QueueIfBusy -Parameters @{
Selected = @($sync.selectedAppx)
Apps = $sync.configs.appxHashtable
} -ScriptBlock {
+1 -1
View File
@@ -11,7 +11,7 @@ function Invoke-WPFAppxRemoval {
return
}
Start-WinUtilJob -Name "AppX" -Description "Removing AppX packages" -Parameters @{
Start-WinUtilJob -Name "AppX" -Description "Removing AppX packages" -QueueIfBusy -Parameters @{
Selected = @($sync.selectedAppx)
Apps = $sync.configs.appxHashtable
} -ScriptBlock {
+11 -6
View File
@@ -52,13 +52,17 @@ function Invoke-WPFButton {
}
}
Start-WinUtilJob -Name (Get-WinUtilButtonLabel -Button $Button) -Parameters @{
$jobParameters = @{
Button = $Button
UpdatesDisableConfirmed = $updatesDisableConfirmed
} -ScriptBlock {
param($Button, $UpdatesDisableConfirmed)
}
if ($Button -eq "WPFInstallUpgrade") {
$jobParameters.ManagerPreference = $sync.preferences.packagemanager
}
Start-WinUtilJob -Name (Get-WinUtilButtonLabel -Button $Button) -QueueIfBusy -Parameters $jobParameters -ScriptBlock {
param($Button, $UpdatesDisableConfirmed, $ManagerPreference)
Invoke-WPFButtonAction -Button $Button -UpdatesDisableConfirmed:$UpdatesDisableConfirmed
Invoke-WPFButtonAction -Button $Button -UpdatesDisableConfirmed:$UpdatesDisableConfirmed -ManagerPreference $ManagerPreference
}
return
}
@@ -122,7 +126,8 @@ function Invoke-WPFButtonAction {
Param (
[string]$Button,
[switch]$UpdatesDisableConfirmed
[switch]$UpdatesDisableConfirmed,
[string]$ManagerPreference = $sync.preferences.packagemanager
)
# Check if button is defined in feature config with function or InvokeScript
@@ -154,7 +159,7 @@ function Invoke-WPFButtonAction {
"WPFTab?BT" {Invoke-WPFTab $Button}
"WPFInstall" {Invoke-WPFInstall}
"WPFUninstall" {Invoke-WPFUnInstall}
"WPFInstallUpgrade" {Invoke-WPFInstallUpgrade}
"WPFInstallUpgrade" {Invoke-WPFInstallUpgrade -ManagerPreference $ManagerPreference}
"WPFCollapseAllCategories" {Invoke-WPFToggleAllCategories -Action "Collapse"}
"WPFExpandAllCategories" {Invoke-WPFToggleAllCategories -Action "Expand"}
"WPFStandard" {Invoke-WPFPresets "Standard" -checkboxfilterpattern "WPFTweak*"}
@@ -11,7 +11,7 @@ function Invoke-WPFFeatureInstall {
return
}
Start-WinUtilJob -Name "Features" -Description "Installing Windows features" -Parameters @{
Start-WinUtilJob -Name "Features" -Description "Installing Windows features" -QueueIfBusy -Parameters @{
Features = @($sync.selectedFeatures)
} -ScriptBlock {
param($Features)
+1 -1
View File
@@ -19,7 +19,7 @@ function Invoke-WPFInstall {
$packageSummary = Get-WinUtilPackageLogSummary -Packages $PackagesToInstall -Preference $ManagerPreference
Write-WinUtilLog -Component "Install" -Message "Install selected package(s): $($packageSummary -join '; ')"
Start-WinUtilJob -Name "Install" -Description "Installing apps" -DisableAppList -Parameters @{
Start-WinUtilJob -Name "Install" -Description "Installing apps" -DisableAppList -QueueIfBusy -Parameters @{
PackagesToInstall = $PackagesToInstall
ManagerPreference = $ManagerPreference
} -ScriptBlock {
@@ -10,9 +10,10 @@ function Invoke-WPFInstallUpgrade {
#>
# The radio button belongs to the interface thread; this body runs on a worker. The
# preference it maintains carries the same answer and is what every other workflow reads.
if ($sync.preferences.packagemanager -eq "Choco") {
param([string]$ManagerPreference = $sync.preferences.packagemanager)
# Queued work receives the preference selected when the user requested the upgrade.
if ($ManagerPreference -eq "Choco") {
Step-WinUtilJob -Status "Preparing Chocolatey" -State "Indeterminate"
Install-WinUtilChoco
+1 -1
View File
@@ -29,7 +29,7 @@ function Invoke-WPFUnInstall {
$packageSummary = Get-WinUtilPackageLogSummary -Packages $PackagesToUninstall -Preference $ManagerPreference
Write-WinUtilLog -Component "Uninstall" -Message "Uninstall selected package(s): $($packageSummary -join '; ')"
Start-WinUtilJob -Name "Uninstall" -Description "Uninstalling apps" -DisableAppList -Parameters @{
Start-WinUtilJob -Name "Uninstall" -Description "Uninstalling apps" -DisableAppList -QueueIfBusy -Parameters @{
PackagesToUninstall = $PackagesToUninstall
ManagerPreference = $ManagerPreference
} -ScriptBlock {
+1 -1
View File
@@ -19,7 +19,7 @@ function Invoke-WPFtweaksbutton {
Write-WinUtilLog -Component "Tweaks" -Message "Tweaks requested: $(@($Tweaks).Count) selected tweak(s), DNS provider: $dnsProvider"
Start-WinUtilJob -Name "Tweaks" -Description "Applying tweaks" -Parameters @{
Start-WinUtilJob -Name "Tweaks" -Description "Applying tweaks" -QueueIfBusy -Parameters @{
Tweaks = @($Tweaks)
DnsProvider = $dnsProvider
} -ScriptBlock {
+1 -1
View File
@@ -13,7 +13,7 @@ function Invoke-WPFundoall {
return
}
Start-WinUtilJob -Name "Undo tweaks" -Description "Undoing tweaks" -Parameters @{
Start-WinUtilJob -Name "Undo tweaks" -Description "Undoing tweaks" -QueueIfBusy -Parameters @{
Tweaks = @($tweaks)
} -ScriptBlock {
param($Tweaks)
+758 -3
View File
@@ -8,6 +8,7 @@ BeforeAll {
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilErrorRecord.ps1")
. (Join-Path $script:repoRoot "functions\private\Complete-WinUtilPackageRun.ps1")
. (Join-Path $script:repoRoot "functions\private\Start-WinUtilJob.ps1")
. (Join-Path $script:repoRoot "functions\private\Start-WinUtilNextQueuedJob.ps1")
. (Join-Path $script:repoRoot "functions\private\Set-WinUtilWorkingView.ps1")
. (Join-Path $script:repoRoot "functions\private\Invoke-WinUtilCloseRequest.ps1")
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFUIThread.ps1")
@@ -616,9 +617,8 @@ Describe "Start-WinUtilJob" {
$script:dispatchCount = 0
Mock Invoke-WPFUIThread {
$script:dispatchCount++
# The Install working view takes the first dispatch (show), the app-list
# disable the second, so the worker's restore is the third to fail.
if ($script:dispatchCount -gt 2) {
# Queue refresh, working-view show and app-list disable precede the worker restore.
if ($script:dispatchCount -gt 3) {
throw [System.Threading.Tasks.TaskCanceledException]::new("dispatcher stopped")
}
& $ScriptBlock
@@ -661,3 +661,758 @@ Describe "Job timing summaries" {
}
}
}
Describe "Job queue" {
BeforeEach {
$script:sync = [Hashtable]::Synchronized(@{
ActiveJob = $null
JobQueue = [System.Collections.Generic.List[object]]::new()
Form = [pscustomobject]@{ Dispatcher = [pscustomobject]@{} }
})
$script:started = [System.Collections.Generic.List[object]]::new()
Mock Show-WinUtilMessage { "OK" }
Mock Write-WinUtilLog { }
Mock Step-WinUtilJob { }
Mock Update-WinUtilJobQueueUI { }
Mock Invoke-WPFUIThread { & $ScriptBlock }
Mock Invoke-WPFRunspace {
$runArgs = @{}
foreach ($parameter in $ParameterList) { $runArgs[$parameter[0]] = $parameter[1] }
$script:started.Add([pscustomobject]@{ Body = $ScriptBlock; Args = $runArgs })
}
}
AfterEach {
Remove-Variable -Name sync, started -Scope Script -ErrorAction SilentlyContinue
}
# Runs the worker body the way the pool would, which releases the slot and posts the next job
function script:Complete-TestJob {
param($Run, [string]$Body = '$null = $true')
& $Run.Body -JobName $Run.Args["JobName"] -JobLabel $Run.Args["JobLabel"] -JobBody $Body `
-JobParameters @{} -JobRestoresAppList $false -JobToken $Run.Args["JobToken"]
}
It "queues instead of refusing when asked to and the slot is taken" {
$script:sync.ActiveJob = "Install"
$result = Start-WinUtilJob -Name "Tweaks" -Description "Applying tweaks" -DisableAppList -QueueIfBusy -Parameters @{ Tweaks = @("A", "B") } -ScriptBlock { param($Tweaks) $Tweaks }
$result | Should -BeNullOrEmpty
$script:sync.JobQueue.Count | Should -Be 1
$item = $script:sync.JobQueue[0]
$item.Name | Should -Be "Tweaks"
$item.Description | Should -Be "Applying tweaks"
$item.DisableAppList | Should -BeTrue
$item.Parameters.Tweaks | Should -Be @("A", "B")
$item.ScriptBlock | Should -Match 'param\(\$Tweaks\)'
[guid]::Parse($item.Id) | Should -Not -BeNullOrEmpty
Should -Invoke -CommandName Show-WinUtilMessage -Times 0 -Exactly
$script:started.Count | Should -Be 0
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "Tweaks" -and $Message -like "*queued behind Install*position 1*"
}
}
It "starts at once with the switch when the slot is free" {
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 0
$script:sync.ActiveJob | Should -Be "Tweaks"
$script:started.Count | Should -Be 1
}
It "still refuses with a message and leaves the queue alone without the switch" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "ISO mount" -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 0
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter {
$Message -like "Install is still running*"
}
}
It "does not queue a nested job, which runs inline" {
$script:sync.ActiveJob = "Install"
$global:WinUtilIsJobWorker = $true
try {
Start-WinUtilJob -Name "Inner" -QueueIfBusy -Parameters @{ Value = 7 } -ScriptBlock { param($Value) $script:innerRan = $Value } | Out-Null
} finally {
$global:WinUtilIsJobWorker = $false
}
$script:innerRan | Should -Be 7
$script:sync.JobQueue.Count | Should -Be 0
}
It "does not queue while WinUtil is closing" {
$script:sync.ActiveJob = "Install"
$script:sync.ShuttingDown = $true
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 0
}
It "refuses work when closing wins before the queue lock (<Flag>, <Running>)" -TestCases @(
@{ Flag = "ShuttingDown"; Running = "Install" }
@{ Flag = "ShuttingDown"; Running = $null }
@{ Flag = "FinishInConsole"; Running = "Install" }
@{ Flag = "FinishInConsole"; Running = $null }
) {
param($Flag, $Running)
$script:sync.ActiveJob = $Running
Mock ConvertTo-Json { $script:sync[$Flag] = $true; '{}' }
Start-WinUtilJob -Name "Late" -QueueIfBusy -Parameters @{ Value = 1 } -ScriptBlock { } | Out-Null
$script:sync.ActiveJob | Should -Be $Running
$script:sync.JobQueue.Count | Should -Be 0
$script:started.Count | Should -Be 0
}
It "runs queued jobs first in, first out, and carries on after one fails" {
Start-WinUtilJob -Name "First" -QueueIfBusy -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Second" -QueueIfBusy -Parameters @{ Value = 2 } -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Third" -QueueIfBusy -DisableAppList -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 2
Complete-TestJob -Run $script:started[0] -Body 'throw "boom"'
$script:started.Count | Should -Be 2
$script:started[1].Args["JobName"] | Should -Be "Second"
$script:started[1].Args["JobParameters"].Value | Should -Be 2
$script:sync.ActiveJob | Should -Be "Second"
$script:sync.JobQueue.Count | Should -Be 1
Complete-TestJob -Run $script:started[1]
$script:started.Count | Should -Be 3
$script:started[2].Args["JobName"] | Should -Be "Third"
$script:started[2].Args["JobRestoresAppList"] | Should -BeTrue
$script:sync.JobQueue.Count | Should -Be 0
Complete-TestJob -Run $script:started[2]
$script:started.Count | Should -Be 3
$script:sync.ActiveJob | Should -BeNullOrEmpty
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "Second" -and $Message -eq "Starting queued Second job."
}
}
It "starts the next job when scheduling the current one fails" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Queued" -QueueIfBusy -ScriptBlock { } | Out-Null
$script:sync.ActiveJob = $null
Mock Invoke-WPFRunspace {
$script:started.Add($null)
if ($script:started.Count -eq 1) { throw "pool is gone" }
}
Start-WinUtilJob -Name "Broken" -QueueIfBusy -ScriptBlock { } | Out-Null
# Broken failed to schedule, released the slot, and the queued job took it
$script:started.Count | Should -Be 2
$script:sync.JobQueue.Count | Should -Be 0
}
It "does not start anything while the slot is held" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Queued" -QueueIfBusy -ScriptBlock { } | Out-Null
Start-WinUtilNextQueuedJob
$script:sync.JobQueue.Count | Should -Be 1
$script:started.Count | Should -Be 0
}
It "does not start the queue when WinUtil is closing" {
foreach ($flag in @("ShuttingDown", "FinishInConsole")) {
$script:sync.Remove("ShuttingDown")
$script:sync.Remove("FinishInConsole")
$script:sync.JobQueue.Clear()
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Queued" -QueueIfBusy -ScriptBlock { } | Out-Null
$script:sync.ActiveJobToken = "t"
$script:sync[$flag] = $true
$null = Clear-WinUtilActiveJob -Token "t"
$script:sync.ActiveJob | Should -BeNullOrEmpty
$script:sync.JobQueue.Count | Should -Be 1
$script:started.Count | Should -Be 0
}
}
It "does not start the queue when the slot is reset without a token" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Queued" -QueueIfBusy -ScriptBlock { } | Out-Null
$null = Clear-WinUtilActiveJob
$script:sync.JobQueue.Count | Should -Be 1
$script:started.Count | Should -Be 0
}
It "moves a job up and down and leaves the ends alone" {
$script:sync.ActiveJob = "Install"
foreach ($name in "A", "B", "C") {
Start-WinUtilJob -Name $name -QueueIfBusy -ScriptBlock { } | Out-Null
}
$ids = @($script:sync.JobQueue | ForEach-Object Id)
$order = { (@($script:sync.JobQueue | ForEach-Object Name)) -join "" }
Move-WinUtilQueuedJob -Id $ids[0] -Direction Up
& $order | Should -Be "ABC"
Move-WinUtilQueuedJob -Id $ids[2] -Direction Down
& $order | Should -Be "ABC"
Move-WinUtilQueuedJob -Id $ids[1] -Direction Up
& $order | Should -Be "BAC"
Move-WinUtilQueuedJob -Id $ids[1] -Direction Down
& $order | Should -Be "ABC"
Move-WinUtilQueuedJob -Id $ids[0] -Direction Down
& $order | Should -Be "BAC"
Move-WinUtilQueuedJob -Id "not-an-id" -Direction Up
& $order | Should -Be "BAC"
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "B" -and $Message -eq "Moved queued B job up."
}
}
It "cancels a queued job and ignores one that already started" {
$script:sync.ActiveJob = "Install"
foreach ($name in "A", "B") {
Start-WinUtilJob -Name $name -QueueIfBusy -ScriptBlock { } | Out-Null
}
$ids = @($script:sync.JobQueue | ForEach-Object Id)
Remove-WinUtilQueuedJob -Id $ids[0]
Remove-WinUtilQueuedJob -Id $ids[0]
@($script:sync.JobQueue | ForEach-Object Name) | Should -Be @("B")
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "A" -and $Message -eq "Cancelled queued A job."
}
# B starts, so cancelling it now finds nothing in the queue and leaves the running job be
$script:sync.ActiveJob = $null
Start-WinUtilNextQueuedJob
Remove-WinUtilQueuedJob -Id $ids[1]
$script:sync.ActiveJob | Should -Be "B"
$script:started.Count | Should -Be 1
}
It "keeps a queued job's parameters as they were when the user clicked" {
$script:sync.ActiveJob = "Install"
$selection = [System.Collections.Generic.List[string]]::new()
$selection.Add("WPFTweaksOne")
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @($selection) } -ScriptBlock { } | Out-Null
$selection.Add("WPFTweaksTwo")
$script:sync.JobQueue[0].Parameters.Tweaks | Should -Be @("WPFTweaksOne")
}
It "snapshots the selection in each caller that queues" {
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFtweaksbutton.ps1")
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFFeatureInstall.ps1")
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFAppxInstall.ps1")
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFAppxRemoval.ps1")
. (Join-Path $script:repoRoot "functions\public\Invoke-WPFundoall.ps1")
$script:captured = @{}
Mock Start-WinUtilJob { $script:captured[$Name] = @{ Queue = [bool]$QueueIfBusy; Parameters = $Parameters } }
$newSelection = { $l = [System.Collections.Generic.List[string]]::new(); $l.Add("One"); , $l }
$script:sync["WPFchangedns"] = [pscustomobject]@{ text = "Default" }
$script:sync.configs = @{ appxHashtable = @{} }
$script:sync.selectedTweaks = & $newSelection
$script:sync.selectedFeatures = & $newSelection
$script:sync.selectedAppx = & $newSelection
Invoke-WPFtweaksbutton
Invoke-WPFundoall
Invoke-WPFFeatureInstall
Invoke-WPFAppxInstall
Invoke-WPFAppxRemoval
$script:sync.selectedTweaks.Add("Two")
$script:sync.selectedFeatures.Add("Two")
$script:sync.selectedAppx.Add("Two")
foreach ($name in "Tweaks", "Undo tweaks", "Features", "AppX install", "AppX") {
$script:captured[$name].Queue | Should -BeTrue -Because $name
}
$script:captured["Tweaks"].Parameters.Tweaks | Should -Be @("One")
$script:captured["Undo tweaks"].Parameters.Tweaks | Should -Be @("One")
$script:captured["Features"].Parameters.Features | Should -Be @("One")
$script:captured["AppX install"].Parameters.Selected | Should -Be @("One")
$script:captured["AppX"].Parameters.Selected | Should -Be @("One")
}
It "keeps queued upgrades for different package managers distinct and uses the requested one" {
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFButton.ps1')
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFInstallUpgrade.ps1')
$script:sync.ActiveJob = 'Held'
$script:sync.configs = @{ feature = @{} }
$script:sync.preferences = @{ packagemanager = 'Choco' }
Mock Invoke-WPFInstallUpgrade {}
Invoke-WPFButton -Button WPFInstallUpgrade
$script:sync.preferences.packagemanager = 'Winget'
Invoke-WPFButton -Button WPFInstallUpgrade
$script:sync.JobQueue.Count | Should -Be 2
$script:sync.JobQueue[0].Parameters.ManagerPreference | Should -Be 'Choco'
$script:sync.JobQueue[1].Parameters.ManagerPreference | Should -Be 'Winget'
$queued = $script:sync.JobQueue[0]
$parameters = $queued.Parameters
& ([scriptblock]::Create($queued.ScriptBlock)) @parameters
Should -Invoke Invoke-WPFInstallUpgrade -Times 1 -Exactly -ParameterFilter { $ManagerPreference -eq 'Choco' }
}
It "upgrades the explicit manager instead of a later preference (<Manager>)" -TestCases @(
@{ Manager = 'Choco'; Later = 'Winget' }
@{ Manager = 'Winget'; Later = 'Choco' }
) {
param($Manager, $Later)
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFInstallUpgrade.ps1')
function Install-WinUtilWinget {}
function Install-WinUtilChoco {}
function Install-WinUtilProgramWinget { param($Action, $Programs) }
function Install-WinUtilProgramChoco { param($Action, $Programs) }
Mock Install-WinUtilWinget {}
Mock Install-WinUtilChoco {}
Mock Install-WinUtilProgramWinget {}
Mock Install-WinUtilProgramChoco {}
Mock Measure-WinUtilStep { & $ScriptBlock }
Mock Complete-WinUtilPackageRun {}
$script:sync.preferences = @{ packagemanager = $Later }
Invoke-WPFInstallUpgrade -ManagerPreference $Manager
$expectedChoco = [int]($Manager -eq 'Choco')
Should -Invoke Install-WinUtilProgramChoco -Times $expectedChoco -Exactly -ParameterFilter { $Action -eq 'Upgrade' -and $Programs[0] -eq 'all' }
Should -Invoke Install-WinUtilProgramWinget -Times (1 - $expectedChoco) -Exactly -ParameterFilter { $Action -eq 'Upgrade' -and $Programs[0] -eq 'all' }
}
It "queues a new action behind the head while the slot is held for the queue" {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head"; Description = ""; ScriptBlock = ""; Parameters = @{}; DisableAppList = $false })
$script:sync.JobHandoff = $true
Start-WinUtilJob -Name "New" -QueueIfBusy -ScriptBlock { } | Out-Null
@($script:sync.JobQueue | ForEach-Object Name) | Should -Be @("Head", "New")
$script:sync.ActiveJob | Should -BeNullOrEmpty
$script:started.Count | Should -Be 0
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Message -like "*queued behind Queued operations, position 2*"
}
}
It "refuses an action without the switch while the slot is held for the queue" {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
$script:sync.JobHandoff = $true
Start-WinUtilJob -Name "ISO mount" -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 1
$script:started.Count | Should -Be 0
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter {
$Message -like "Queued operations is still running*"
}
}
It "holds the slot for the queue after a job ends and hands it to the head" {
Mock Invoke-WPFUIThread { }
Start-WinUtilJob -Name "First" -QueueIfBusy -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Head" -QueueIfBusy -Parameters @{ Value = 1 } -ScriptBlock { } | Out-Null
Complete-TestJob -Run $script:started[0]
$script:sync.ActiveJob | Should -BeNullOrEmpty
$script:sync.JobHandoff | Should -BeTrue
Start-WinUtilJob -Name "Late" -QueueIfBusy -ScriptBlock { } | Out-Null
@($script:sync.JobQueue | ForEach-Object Name) | Should -Be @("Head", "Late")
$script:started.Count | Should -Be 1
Start-WinUtilNextQueuedJob
$script:started.Count | Should -Be 2
$script:started[1].Args["JobName"] | Should -Be "Head"
$script:started[1].Args["JobParameters"].Value | Should -Be 1
$script:sync.ActiveJob | Should -Be "Head"
$script:sync.JobHandoff | Should -BeFalse
@($script:sync.JobQueue | ForEach-Object Name) | Should -Be @("Late")
}
It "does not hold the slot when nothing is queued or WinUtil is closing" {
$script:sync.ActiveJob = "A"
$script:sync.ActiveJobToken = "t"
$null = Clear-WinUtilActiveJob -Token "t"
$script:sync.JobHandoff | Should -BeFalse
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
$script:sync.ShuttingDown = $true
$script:sync.ActiveJob = "A"
$script:sync.ActiveJobToken = "t"
$null = Clear-WinUtilActiveJob -Token "t"
$script:sync.JobHandoff | Should -BeFalse
}
It "clears the handoff on every way out of the dispatch" {
$queued = [pscustomobject]@{ Id = "1"; Name = "Head"; Description = ""; ScriptBlock = ""; Parameters = @{}; DisableAppList = $false }
# closing
$script:sync.JobHandoff = $true
$script:sync.ShuttingDown = $true
Start-WinUtilNextQueuedJob
$script:sync.JobHandoff | Should -BeFalse
$script:sync.Remove("ShuttingDown")
# empty queue
$script:sync.JobHandoff = $true
Start-WinUtilNextQueuedJob
$script:sync.JobHandoff | Should -BeFalse
# slot taken, the queue is kept
$script:sync.JobQueue.Add($queued)
$script:sync.ActiveJob = "Other"
$script:sync.JobHandoff = $true
Start-WinUtilNextQueuedJob
$script:sync.JobHandoff | Should -BeFalse
$script:sync.JobQueue.Count | Should -Be 1
# the job refuses to start because WinUtil began closing after the dequeue
$script:sync.ActiveJob = $null
$script:sync.JobHandoff = $true
$script:sync.ShuttingDown = $true
Start-WinUtilJob -Name "Head" -FromQueue -ScriptBlock { } | Out-Null
$script:sync.JobHandoff | Should -BeFalse
$script:sync.ActiveJob | Should -BeNullOrEmpty
}
It "clears the handoff when the dispatch cannot be posted" {
Mock Invoke-WPFUIThread { throw "dispatcher is gone" }
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
$script:sync.ActiveJob = "A"
$script:sync.ActiveJobToken = "t"
$null = Clear-WinUtilActiveJob -Token "t"
$script:sync.JobHandoff | Should -BeFalse
}
It "preserves update choices separated by another action (<Sequence>)" -TestCases @(
@{ Sequence = @('WPFUpdatesdefault', 'WPFUpdatesdisable', 'WPFUpdatesdefault', 'WPFUpdatesdefault'); Expected = @('Default', 'Disable', 'Default') }
@{ Sequence = @('WPFUpdatesdefault', 'WPFUpdatesdefault'); Expected = @('Default') }
) {
param($Sequence, $Expected)
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFButton.ps1')
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFUpdatesdefault.ps1')
. (Join-Path $script:repoRoot 'functions/public/Invoke-WPFUpdatesdisable.ps1')
$script:sync.ActiveJob = 'Held'
$script:sync.configs = @{ feature = @{} }
$script:updateChoices = [System.Collections.Generic.List[string]]::new()
Mock Confirm-WPFUpdatesdisable { $true }
Mock Invoke-WPFUpdatesdefault { $script:updateChoices.Add('Default') }
Mock Invoke-WPFUpdatesdisable { $script:updateChoices.Add('Disable') } -ParameterFilter { $Confirmed }
foreach ($button in $Sequence) { Invoke-WPFButton -Button $button }
$script:sync.JobQueue.Count | Should -Be $Expected.Count
foreach ($queued in $script:sync.JobQueue) {
$parameters = $queued.Parameters
& ([scriptblock]::Create($queued.ScriptBlock)) @parameters
}
@($script:updateChoices) | Should -Be $Expected
$script:updateChoices[$script:updateChoices.Count - 1] | Should -Be 'Default'
}
It "queues identical work once and ignores repeated clicks" {
$script:sync.ActiveJob = "Install"
foreach ($click in 1..4) {
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A", "B"); DnsProvider = "Default" } -ScriptBlock { } | Out-Null
}
$script:sync.JobQueue.Count | Should -Be 1
Should -Invoke -CommandName Write-WinUtilLog -Times 3 -Exactly -ParameterFilter {
$Component -eq "Tweaks" -and $Message -eq "Tweaks is already queued, ignored."
}
Should -Invoke -CommandName Show-WinUtilMessage -Times 0 -Exactly
}
It "treats the same parameters given in a different key order as identical" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters ([ordered]@{ A = 1; B = 2 }) -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters ([ordered]@{ B = 2; A = 1 }) -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 1
}
It "queues the same name again when the selection differs" {
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A", "B") } -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Undo tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 3
}
It "does not compare against the running job" {
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
$script:sync.ActiveJob | Should -Be "Tweaks"
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 1
}
It "queues without the duplicate check when the parameters cannot be serialised" {
Mock ConvertTo-Json { throw "cannot serialise" }
$script:sync.ActiveJob = "Install"
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
Start-WinUtilJob -Name "Tweaks" -QueueIfBusy -Parameters @{ Tweaks = @("A") } -ScriptBlock { } | Out-Null
$script:sync.JobQueue.Count | Should -Be 2
Should -Invoke -CommandName Write-WinUtilLog -Times 2 -Exactly -ParameterFilter {
$Level -eq "WARN" -and $Message -like "Could not compare Tweaks*"
}
}
It "opts the user actions in and keeps the ISO and USB jobs refusing" {
foreach ($path in @(
"functions\public\Invoke-WPFInstall.ps1", "functions\public\Invoke-WPFUnInstall.ps1",
"functions\public\Invoke-WPFAppxInstall.ps1", "functions\public\Invoke-WPFAppxRemoval.ps1",
"functions\public\Invoke-WPFtweaksbutton.ps1", "functions\public\Invoke-WPFundoall.ps1",
"functions\public\Invoke-WPFFeatureInstall.ps1", "functions\public\Invoke-WPFButton.ps1"
)) {
(Get-Content -Path (Join-Path $script:repoRoot $path) -Raw) | Should -Match 'Start-WinUtilJob [^\r\n]*-QueueIfBusy' -Because $path
}
foreach ($path in @("functions\private\Invoke-WinUtilISO.ps1", "functions\private\Invoke-WinUtilISOUSB.ps1")) {
(Get-Content -Path (Join-Path $script:repoRoot $path) -Raw) | Should -Not -Match 'QueueIfBusy' -Because $path
}
}
}
Describe "Closing with queued jobs" {
BeforeEach {
$script:sync = [Hashtable]::Synchronized(@{
ActiveJob = "Install"
JobQueue = [System.Collections.Generic.List[object]]::new()
})
Mock Write-WinUtilLog { }
}
AfterEach {
Remove-Variable -Name sync -Scope Script -ErrorAction SilentlyContinue
}
It "holds queued work during a running-job close prompt and applies <Answer> before resuming" -TestCases @(
@{ Answer = 'Cancel'; ExpectedStarts = 1 }
@{ Answer = 'No'; ExpectedStarts = 0 }
@{ Answer = 'Yes'; ExpectedStarts = 0 }
) {
param($Answer, $ExpectedStarts)
$script:postedHandoffs = [Collections.Generic.List[scriptblock]]::new()
$script:sync.ActiveJobToken = 'running'
$script:sync.JobQueue.Add([pscustomobject]@{ Id = 'next'; Name = 'Next'; ScriptBlock = ''; Parameters = @{}; DisableAppList = $false })
Mock Start-WinUtilJob {}
Mock Request-WinUtilWindowClose {}
Mock Write-Host {}
Mock Invoke-WPFUIThread { $script:postedHandoffs.Add($ScriptBlock) }
Mock Show-WinUtilMessage {
$script:sync.JobClosePromptOpen | Should -BeTrue
# A real modal question pumps the dispatcher while the worker finishes.
$script:sync.ActiveJob = $null
$script:sync.ActiveJobToken = $null
$script:sync.JobHandoff = $true
Start-WinUtilNextQueuedJob
$script:sync.JobQueue.Count | Should -Be 1
$script:sync.JobHandoff | Should -BeTrue
return $Answer
}
Invoke-WinUtilCloseRequest -RunningJob 'Install' -QueuedCount 1
$script:sync.JobClosePromptOpen | Should -BeFalse
Should -Invoke Start-WinUtilJob -Times 0 -Exactly
$script:postedHandoffs.Count | Should -Be 1
foreach ($post in $script:postedHandoffs) { & $post }
Should -Invoke Start-WinUtilJob -Times $ExpectedStarts -Exactly
}
It "tells the user how many queued operations will be discarded" {
Mock Show-WinUtilMessage { "Cancel" }
Invoke-WinUtilCloseRequest -RunningJob "Install" -QueuedCount 2
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter {
$Message -like "*2 queued operation(s) will be discarded*"
}
}
It "says nothing about the queue when it is empty" {
Mock Show-WinUtilMessage { "Cancel" }
Invoke-WinUtilCloseRequest -RunningJob "Install"
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter {
$Message -notlike "*queued*"
}
}
It "empties the queue and reports how many it dropped" {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "A" })
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "2"; Name = "B" })
Clear-WinUtilJobQueue | Should -Be 2
$script:sync.JobQueue.Count | Should -Be 0
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Message -like "Discarded 2 queued job(s)*"
}
}
It "has the window's closing handler pass the count and clear the queue after the prompt" {
$source = Get-Content (Join-Path $script:repoRoot "functions\private\Start-WinUtilUserInterface.ps1") -Raw
$source | Should -Match 'Invoke-WinUtilCloseRequest -RunningJob \$runningJob -QueuedCount \$sync\.JobQueue\.Count'
$source.IndexOf('Clear-WinUtilJobQueue') | Should -BeGreaterThan $source.IndexOf('Invoke-WinUtilCloseRequest -RunningJob')
}
It "asks only whether to discard when nothing is running, and closes on yes" {
$script:sync.ActiveJob = $null
Mock Show-WinUtilMessage { "Yes" }
Mock Request-WinUtilWindowClose { }
Invoke-WinUtilCloseRequest -RunningJob "Queued operations" -QueuedCount 2
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter {
$Button -eq "YesNo" -and $Message -like "Nothing is running. 2 queued operation(s) will be discarded*"
}
$script:sync.ForceClose | Should -BeTrue
$script:sync.FinishInConsole | Should -Not -BeTrue
Should -Invoke -CommandName Request-WinUtilWindowClose -Times 1 -Exactly
}
It "shuts the queue before the accepted queued-only close is posted" {
$script:sync.ActiveJob = $null
$script:sync.JobHandoff = $true
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "2"; Name = "Next" })
Mock Show-WinUtilMessage { "Yes" }
$script:atClose = $null
Mock Request-WinUtilWindowClose {
$script:atClose = @{ Shutting = $script:sync.ShuttingDown; Queued = $script:sync.JobQueue.Count; Handoff = $script:sync.JobHandoff }
}
Invoke-WinUtilCloseRequest -RunningJob "Queued operations" -QueuedCount 2
$script:atClose.Shutting | Should -BeTrue
$script:atClose.Queued | Should -Be 0
$script:atClose.Handoff | Should -BeFalse
}
It "refuses a job that tries to start once the queued-only close is accepted" {
Mock Show-WinUtilMessage { "Yes" }
Mock Request-WinUtilWindowClose { }
$script:sync.ActiveJob = $null
Invoke-WinUtilCloseRequest -RunningJob "Queued operations" -QueuedCount 1
Mock Invoke-WPFRunspace { }
Mock Step-WinUtilJob { }
Mock Invoke-WPFUIThread { }
Start-WinUtilJob -Name "Late" -QueueIfBusy -ScriptBlock { } | Out-Null
$script:sync.ActiveJob | Should -BeNullOrEmpty
$script:sync.JobQueue.Count | Should -Be 0
Should -Invoke -CommandName Invoke-WPFRunspace -Times 0 -Exactly
}
It "keeps the window open and the queue when the queued-only close is declined" {
$script:sync.ActiveJob = $null
Mock Show-WinUtilMessage { "No" }
Mock Request-WinUtilWindowClose { }
Invoke-WinUtilCloseRequest -RunningJob "Queued operations" -QueuedCount 2
$script:sync.ForceClose | Should -Not -BeTrue
Should -Invoke -CommandName Request-WinUtilWindowClose -Times 0 -Exactly
}
It "shuts the queue before the stop-the-job close is posted, and nothing starts after it" {
$script:sync.JobHandoff = $true
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head"; Description = ""; ScriptBlock = ""; Parameters = @{}; DisableAppList = $false })
Mock Show-WinUtilMessage { "No" }
Mock Step-WinUtilJob { }
Mock Update-WinUtilJobQueueUI { }
Mock Start-WinUtilJob { }
$script:atClose = $null
Mock Request-WinUtilWindowClose {
$script:atClose = @{ Shutting = $script:sync.ShuttingDown; Queued = $script:sync.JobQueue.Count; Handoff = $script:sync.JobHandoff }
}
Invoke-WinUtilCloseRequest -RunningJob "Install" -QueuedCount 1
$script:atClose.Shutting | Should -BeTrue
$script:atClose.Queued | Should -Be 0
$script:atClose.Handoff | Should -BeFalse
$script:sync.ForceClose | Should -BeTrue
# the running job ends after the answer and its handoff finds nothing to start
$script:sync.ActiveJob = $null
Start-WinUtilNextQueuedJob
Should -Invoke -CommandName Start-WinUtilJob -Times 0 -Exactly
}
It "leaves the queue and flags alone when the close is cancelled or hands the job to the console" {
$script:sync.JobHandoff = $true
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
Mock Request-WinUtilWindowClose { }
Mock Write-Host { }
Mock Show-WinUtilMessage { "Cancel" }
Invoke-WinUtilCloseRequest -RunningJob "Install" -QueuedCount 1
Mock Show-WinUtilMessage { "Yes" }
Invoke-WinUtilCloseRequest -RunningJob "Install" -QueuedCount 1
$script:sync.ShuttingDown | Should -Not -BeTrue
$script:sync.JobQueue.Count | Should -Be 1
$script:sync.JobHandoff | Should -BeTrue
}
It "asks again about the running job when a queued job started during the prompt" {
$script:sync.ActiveJob = $null
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "1"; Name = "Head" })
$script:asked = 0
Mock Show-WinUtilMessage {
$script:asked++
if ($script:asked -eq 1) { $script:sync.ActiveJob = "Head"; return "Yes" }
return "Cancel"
}
Mock Request-WinUtilWindowClose { }
Invoke-WinUtilCloseRequest -RunningJob "Queued operations" -QueuedCount 2
Should -Invoke -CommandName Show-WinUtilMessage -Times 2 -Exactly
Should -Invoke -CommandName Show-WinUtilMessage -Times 1 -Exactly -ParameterFilter { $Title -eq "Head is still running" }
$script:sync.ForceClose | Should -Not -BeTrue
$script:sync.ShuttingDown | Should -Not -BeTrue
$script:sync.JobQueue.Count | Should -Be 1
Should -Invoke -CommandName Request-WinUtilWindowClose -Times 0 -Exactly
}
It "has the closing handler prompt for queued work even with nothing running" {
$source = Get-Content (Join-Path $script:repoRoot "functions\private\Start-WinUtilUserInterface.ps1") -Raw
$source | Should -Match '\(\$sync\.ActiveJob -or \$sync\.JobQueue\.Count -gt 0\) -and -not \$sync\.ForceClose'
}
}
+103
View File
@@ -0,0 +1,103 @@
# Native WPF queue layout and routed-event checks. No system-changing jobs run here.
BeforeAll {
Add-Type -AssemblyName PresentationFramework
$script:repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
. (Join-Path $script:repoRoot 'functions/private/Start-WinUtilNextQueuedJob.ps1')
. (Join-Path $script:repoRoot 'functions/private/Invoke-WinutilThemeChange.ps1')
function Write-WinUtilLog { param($Message, $Level, $Component) }
}
Describe 'Native job queue controls' {
BeforeEach {
[xml]$xaml = Get-Content (Join-Path $script:repoRoot 'xaml/inputXML.xaml') -Raw
$form = [Windows.Markup.XamlReader]::Load([Xml.XmlNodeReader]::new($xaml))
$script:sync = [hashtable]::Synchronized(@{
Form = $form
preferences = @{}
configs = @{ themes = Get-Content (Join-Path $script:repoRoot 'config/themes.json') -Raw | ConvertFrom-Json }
ActiveJob = 'Harmless placeholder'
JobQueue = [Collections.Generic.List[object]]::new()
JobQueueButton = $form.FindName('JobQueueButton')
JobQueueCount = $form.FindName('JobQueueCount')
JobQueueRunning = $form.FindName('JobQueueRunning')
JobQueueItems = $form.FindName('JobQueueItems')
# Open state only: measure the actual XAML child without displaying a popup in CI.
JobQueuePopup = [pscustomobject]@{ IsOpen = $true }
})
$script:queueBorder = $form.FindName('JobQueuePopup').Child
}
AfterEach {
$script:sync.Form.Close()
Remove-Variable sync, queueBorder -Scope Script
}
It 'keeps the running header visible while every queued row remains reachable (<Theme>)' -TestCases @(
@{ Theme = 'Light' }
@{ Theme = 'Dark' }
) {
param($Theme)
Invoke-WinutilThemeChange -theme $Theme
foreach ($index in 1..35) {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "$index"; Name = "Harmless queued job $index" })
}
Update-WinUtilJobQueueUI
$script:queueBorder.Measure([Windows.Size]::new(262, [double]::PositiveInfinity))
$script:queueBorder.Arrange([Windows.Rect]::new(0, 0, $script:queueBorder.DesiredSize.Width, $script:queueBorder.DesiredSize.Height))
$script:queueBorder.UpdateLayout()
$scroll = $script:sync.JobQueueItems.Parent
$scroll | Should -BeOfType ([Windows.Controls.ScrollViewer])
$scroll.ViewportHeight | Should -BeGreaterThan 0
$scroll.ViewportHeight | Should -BeLessOrEqual 240
$scroll.ExtentHeight | Should -BeGreaterThan $scroll.ViewportHeight
$scroll.ComputedVerticalScrollBarVisibility | Should -Be ([Windows.Visibility]::Visible)
$script:sync.JobQueueItems.Children.Count | Should -Be 35
$headerParent = $script:sync.JobQueueRunning.Parent
$headerParent | Should -Be $scroll.Parent
$headerOffset = $script:sync.JobQueueRunning.TranslatePoint([Windows.Point]::new(0, 0), $script:queueBorder).Y
$scroll.ScrollToEnd()
$script:queueBorder.UpdateLayout()
$scroll.VerticalOffset | Should -BeGreaterThan 0
$script:sync.JobQueueRunning.TranslatePoint([Windows.Point]::new(0, 0), $script:queueBorder).Y | Should -Be $headerOffset
$script:sync.JobQueueItems.Children[34].Children[0].Text | Should -Be 'Harmless queued job 35'
}
It 'announces each queue action and its job through native automation peers after reordering' {
Invoke-WinutilThemeChange -theme Dark
foreach ($name in @('Package updates', 'Selected tweaks')) {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = $name; Name = $name })
}
Update-WinUtilJobQueueUI
foreach ($rowIndex in 0..1) {
$actionIndex = 1
foreach ($action in @('Run sooner', 'Run later', 'Cancel')) {
$button = $script:sync.JobQueueItems.Children[$rowIndex].Children[$actionIndex++]
$peer = [Windows.Automation.Peers.ButtonAutomationPeer]::new($button)
$peer.GetName() | Should -Be "$action`: $($script:sync.JobQueue[$rowIndex].Name)"
$peer.GetAutomationControlType() | Should -Be ([Windows.Automation.Peers.AutomationControlType]::Button)
}
}
Move-WinUtilQueuedJob -Id 'Selected tweaks' -Direction Up
$peer = [Windows.Automation.Peers.ButtonAutomationPeer]::new($script:sync.JobQueueItems.Children[0].Children[3])
$peer.GetName() | Should -Be 'Cancel: Selected tweaks'
}
It 'routes row buttons by stable job identity through reorder and cancellation' {
Invoke-WinutilThemeChange -theme Dark
foreach ($index in 1..3) {
$script:sync.JobQueue.Add([pscustomobject]@{ Id = "$index"; Name = "Job$index" })
}
Update-WinUtilJobQueueUI
$script:sync.JobQueueItems.Children[0].Children[1].IsEnabled | Should -BeFalse
$script:sync.JobQueueItems.Children[2].Children[2].IsEnabled | Should -BeFalse
$script:sync.JobQueueItems.Children[1].Children[1].RaiseEvent([Windows.RoutedEventArgs]::new([Windows.Controls.Button]::ClickEvent))
@($script:sync.JobQueue.Name) | Should -Be @('Job2', 'Job1', 'Job3')
$script:sync.JobQueueItems.Children[0].Children[2].RaiseEvent([Windows.RoutedEventArgs]::new([Windows.Controls.Button]::ClickEvent))
@($script:sync.JobQueue.Name) | Should -Be @('Job1', 'Job2', 'Job3')
$script:sync.JobQueueItems.Children[1].Children[3].RaiseEvent([Windows.RoutedEventArgs]::new([Windows.Controls.Button]::ClickEvent))
@($script:sync.JobQueue.Name) | Should -Be @('Job1', 'Job3')
$script:sync.JobQueueCount.Text | Should -Be '2'
$script:sync.ActiveJob | Should -Be 'Harmless placeholder'
}
}
+2
View File
@@ -10,6 +10,7 @@ BeforeAll {
function Test-WinUtilUIAlive { $null -ne $sync.Form -and $null -ne $sync.Form.Dispatcher }
. (Join-Path $script:functionRoot "private\Invoke-WinUtilCloseRequest.ps1")
. (Join-Path $script:functionRoot "private\Start-WinUtilNextQueuedJob.ps1")
function Write-WinUtilLog { param($Level, $Component, $Message, [switch]$Detail) }
function Step-WinUtilJob { param($Status, $Percent, $State, $Overlay, [switch]$Hide) }
@@ -117,6 +118,7 @@ Describe "The close question" {
BeforeEach {
$global:sync = [hashtable]::Synchronized(@{})
$sync.ActiveJob = "Install"
$sync.JobQueue = [System.Collections.Generic.List[object]]::new()
Mock Write-WinUtilLog { }
Mock Step-WinUtilJob { }
}
+30
View File
@@ -329,6 +329,7 @@ Describe "XAML document" {
$minimizeButton = $script:xaml.SelectSingleNode('//*[local-name()="Button"][@Name="WPFMinimizeButton"]')
$actionPanel = $minimizeButton.ParentNode
$topBarButtonNames = @(
"JobQueueButton",
"ThemeButton",
"FontScalingButton",
"SettingsButton",
@@ -350,6 +351,31 @@ Describe "XAML document" {
It "has a queue button that starts hidden and a dropdown that closes on outside clicks" {
$button = $script:xaml.SelectSingleNode('//*[local-name()="Button"][@Name="JobQueueButton"]')
$popup = $script:xaml.SelectSingleNode('//*[local-name()="Popup"][@Name="JobQueuePopup"]')
$button.GetAttribute("Visibility") | Should -Be "Collapsed"
$button.ParentNode.GetAttribute("Orientation") | Should -Be "Horizontal"
$button.InnerText | Should -Match ([regex]::Escape([string][char]0xE823))
$popup.GetAttribute("StaysOpen") | Should -Be "False"
$popup.GetAttribute("Placement") | Should -Be "Bottom"
$popup.GetAttribute("PlacementTarget") | Should -Match 'JobQueueButton'
foreach ($name in "JobQueueCount", "JobQueueRunning", "JobQueueItems") {
$popup.OwnerDocument.SelectSingleNode("//*[@Name='$name']") | Should -Not -BeNullOrEmpty -Because $name
}
($button.OuterXml + $popup.OuterXml) | Should -Not -Match '="#[0-9A-Fa-f]{3,8}"'
}
It "wires the queue button and popup and refreshes the rows when the dropdown opens" {
$uiSource = Get-Content -Path $script:uiScriptPath -Raw
$uiSource | Should -Match '\$sync\["JobQueueButton"\]\.Add_Click'
$uiSource | Should -Match '\$sync\["JobQueuePopup"\]\.Add_Opened\(\{ Update-WinUtilJobQueueUI \}\)'
$clickHandler = [regex]::Match($uiSource, '(?s)\$sync\["JobQueueButton"\]\.Add_Click\(\{.*?\r?\n \}\)').Value
$clickHandler | Should -Match '"JobQueue" = "Show"'
}
It "scopes toggle button styles without leaking into combo boxes" {
$resources = $script:xaml.SelectSingleNode('//*[local-name()="Window.Resources"]')
$implicitToggleStyles = @($resources.SelectNodes('./*[local-name()="Style"][@TargetType="ToggleButton" or @TargetType="{x:Type ToggleButton}"][not(@x:Key)]', $script:xamlNamespace))
@@ -451,6 +477,10 @@ Describe "XAML and sync wiring" {
"ActiveJob",
"ActiveJobToken",
"LastJobResult",
"JobQueue",
"JobHandoff",
"JobClosePromptOpen",
"JobQueuePopupClosedAt",
# Intrinsic to the synchronized hashtable rather than WinUtil state; the job layer
# locks on it to claim and release the active job slot
"SyncRoot",
+7
View File
@@ -231,6 +231,13 @@ $sync.Buttons = [System.Collections.Generic.List[PSObject]]::new()
$sync.preferences = @{}
# Name of the job currently running, or $null when idle. Owned by Start-WinUtilJob.
$sync.ActiveJob = $null
# User actions waiting for the slot, oldest first. Changed only under $sync.SyncRoot.
$sync.JobQueue = [System.Collections.Generic.List[object]]::new()
# True from a job's release until the queued job that follows it claims the slot, so a new action
# cannot take the slot ahead of the queue.
$sync.JobHandoff = $false
# A modal close question must not start a different queued job behind its prompt.
$sync.JobClosePromptOpen = $false
# Serializes worker-pool startup with recycling and shutdown.
$sync.RunspacePoolLock = [object]::new()
# Serializes the speculative and UI-thread taskbar overlay renderers.
+33
View File
@@ -1176,6 +1176,39 @@
<!-- Buttons Container -->
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="5,5,5,5">
<Button Name="JobQueueButton"
Style="{StaticResource HoverButtonStyle}"
BorderBrush="Transparent"
Background="{DynamicResource MainBackgroundColor}"
Foreground="{DynamicResource MainForegroundColor}"
MinWidth="{DynamicResource IconButtonSize}" Height="{DynamicResource IconButtonSize}"
HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0,0,2,0"
Visibility="Collapsed"
ToolTip="Running and queued operations"
AutomationProperties.Name="Queue">
<StackPanel Orientation="Horizontal">
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="{DynamicResource SettingsIconFontSize}" VerticalAlignment="Center">&#xE823;</TextBlock>
<TextBlock Name="JobQueueCount" FontSize="{DynamicResource ButtonFontSize}" FontWeight="Bold" VerticalAlignment="Center" Margin="3,0,3,0"/>
</StackPanel>
</Button>
<Popup Name="JobQueuePopup"
IsOpen="False" StaysOpen="False"
PlacementTarget="{Binding ElementName=JobQueueButton}" Placement="Bottom"
HorizontalAlignment="Right" VerticalAlignment="Top">
<Border Background="{DynamicResource MainBackgroundColor}" BorderBrush="{DynamicResource MainForegroundColor}" BorderThickness="1" CornerRadius="0" Margin="0">
<StackPanel Width="260" Background="{DynamicResource MainBackgroundColor}">
<TextBlock Name="JobQueueRunning"
FontSize="{DynamicResource ButtonFontSize}" FontWeight="Bold"
Foreground="{DynamicResource MainForegroundColor}"
TextTrimming="CharacterEllipsis"
Margin="10,5,10,5"/>
<ScrollViewer MaxHeight="240" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel Name="JobQueueItems" Margin="5,0,5,5"/>
</ScrollViewer>
</StackPanel>
</Border>
</Popup>
<Button Name="ThemeButton"
Style="{StaticResource HoverButtonStyle}"
BorderBrush="Transparent"