Demo.ps1

# Demo.ps1 - the NativeHTMLKit Demo launcher (PowerShell).
#
# One window lists every catalogued example of the NativeHTMLKit SDKs and NativeHTMLKit UI, shows
# its Python, PowerShell, HTML and CSS source, and runs the Python or PowerShell version as a
# separate process. It uses only the public NativeHTMLKit module.
#
# Start it with Start-NativeHTMLKitDemo (which runs this file in a new PowerShell process), or
# directly: pwsh -File Demo.ps1 [-SelfTest]
param([switch]$SelfTest)
$ErrorActionPreference = 'Stop'
Import-Module NativeHTMLKit

if ($SelfTest -and -not $env:NATIVEHTMLKIT_TEST_MODE) { $env:NATIVEHTMLKIT_TEST_MODE = '1' }

$app = Start-NativeHTMLKitScript -Name 'NativeHTMLKit Demo'
# ---- below this line runs only in the backend process ----------------------------------------
try {
    $script:IsWindowsOS = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
    $script:Content = Join-Path $PSScriptRoot 'content'
    if (-not (Test-Path -LiteralPath (Join-Path $script:Content 'catalog.json'))) {
        $script:Content = Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) 'content'   # source checkout
    }
    $script:Catalog = [IO.File]::ReadAllText((Join-Path $script:Content 'catalog.json'), [Text.Encoding]::UTF8) | ConvertFrom-Json
    $script:Examples = @($script:Catalog.examples)
    $script:Tabs = @('python', 'powershell', 'html', 'css', 'output')
    $script:Selected = 0
    $script:Tab = 'python'
    $script:Runs = New-Object System.Collections.ArrayList
    $script:NextRun = 1
    $script:Quitting = $false
    # Keep this file ASCII: Windows PowerShell 5.1 reads a UTF-8 script without BOM as ANSI.
    $script:Dot = ' ' + [char]0x00B7 + ' '

    # ---- runtimes ---------------------------------------------------------------------------
    $script:PowerShellRuntime = @{ Label = 'PowerShell'; Checking = $false; Ready = $false; Message = ''; Modules = @(); Command = @() }
    $script:PythonRuntime = @{ Label = 'Python'; Checking = $true; Ready = $false; Message = 'Checking...'; Modules = @(); Command = @() }

    $exe = (Get-Process -Id $PID).Path
    $psCommand = @($exe, '-NoLogo', '-NoProfile', '-NonInteractive')
    if ($script:IsWindowsOS) { $psCommand += @('-ExecutionPolicy', 'Bypass') }
    $script:PowerShellRuntime.Command = $psCommand
    $script:PowerShellRuntime.Modules = @(Get-Module -ListAvailable -Name NativeHTMLKit, NativeHTMLKit.UI | Select-Object -ExpandProperty Name -Unique)
    $script:PowerShellRuntime.Ready = $script:PowerShellRuntime.Modules -contains 'NativeHTMLKit'
    if ($script:PowerShellRuntime.Ready) {
        $script:PowerShellRuntime.Message = 'PowerShell ' + $PSVersionTable.PSVersion.ToString()
    } else {
        $script:PowerShellRuntime.Message = 'Install the modules first: Install-Module NativeHTMLKit.UI -Scope CurrentUser'
    }

    function Format-Html([string]$Text) { [Net.WebUtility]::HtmlEncode($Text) }

    # Core limits one text value to 16 KiB; sources can be longer, so the text goes in as spans.
    function ConvertTo-TextHtml([string]$Text) {
        $builder = New-Object Text.StringBuilder
        for ($i = 0; $i -lt $Text.Length; $i += 4096) {
            $chunk = $Text.Substring($i, [Math]::Min(4096, $Text.Length - $i))
            [void]$builder.Append('<span>').Append((Format-Html $chunk)).Append('</span>')
        }
        $builder.ToString()
    }

    function Get-Op([string]$Op, [string]$Element, [hashtable]$Extra) {
        $value = @{ op = $Op; element = $Element }
        if ($Extra) { foreach ($k in $Extra.Keys) { $value[$k] = $Extra[$k] } }
        $value
    }

    function Get-ClassOp([bool]$On, [string]$Element, [string]$Name) {
        $op = 'remove_class'
        if ($On) { $op = 'add_class' }
        @{ op = $op; element = $Element; name = $Name }
    }

    function Get-RunRoot {
        $root = Join-Path ([IO.Path]::GetTempPath()) 'nativehtmlkit-demo'
        if (-not (Test-Path -LiteralPath $root)) { $null = New-Item -ItemType Directory -Path $root }
        $root
    }

    function Get-SourceText($Entry, [string]$Language) {
        $item = $Entry.$Language
        if (-not $item) { return '' }
        $path = Join-Path (Join-Path $script:Content 'examples') $item.file
        [IO.File]::ReadAllText($path, [Text.Encoding]::UTF8)
    }

    function Get-Tail([string]$Path) {
        if (-not (Test-Path -LiteralPath $Path)) { return '' }
        $stream = New-Object IO.FileStream($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]'ReadWrite, Delete')
        try {
            $limit = 65536
            $size = $stream.Length
            $null = $stream.Seek([Math]::Max(0, $size - $limit), [IO.SeekOrigin]::Begin)
            $buffer = New-Object byte[] ([Math]::Min($size, $limit))
            $read = $stream.Read($buffer, 0, $buffer.Length)
            $text = [Text.Encoding]::UTF8.GetString($buffer, 0, $read)
            if ($size -gt $limit) { $text = "[...]`n" + $text }
            $text -replace ([string][char]27 + '\[[0-9;?]*[ -/]*[@-~]'), ''   # colour codes of PowerShell 7 errors
        } finally { $stream.Dispose() }
    }

    # ---- rendering --------------------------------------------------------------------------
    function Get-ListHtml {
        $builder = New-Object Text.StringBuilder
        foreach ($group in @(@('sdk', 'SDK examples'), @('ui', 'NativeHTMLKit UI examples'))) {
            [void]$builder.Append("<div class=`"group`" id=`"group-$($group[0])`">$($group[1])</div>")
            for ($i = 0; $i -lt $script:Examples.Count; $i++) {
                $entry = $script:Examples[$i]
                if ($entry.layer -ne $group[0]) { continue }
                $langs = @()
                if ($entry.python) { $langs += 'Py' }
                if ($entry.powershell) { $langs += 'PS' }
                [void]$builder.Append("<button type=`"button`" class=`"item`" role=`"listitem`" id=`"ex-$i`">")
                [void]$builder.Append((Format-Html $entry.title)).Append('<span class="langs">').Append(($langs -join $script:Dot)).Append('</span></button>')
            }
        }
        $builder.ToString()
    }

    function Get-LatestRun($Entry) {
        for ($i = $script:Runs.Count - 1; $i -ge 0; $i--) {
            if ($script:Runs[$i].Entry.key -eq $Entry.key) { return $script:Runs[$i] }
        }
        $null
    }

    function Get-LanguageLabel([string]$Language) {
        if ($Language -eq 'python') { 'Python' } else { 'PowerShell' }
    }

    function Get-RunState($Run) {
        if ($null -eq $Run.ExitCode) { return "running (process $($Run.Process.Id))" }
        if ($Run.Stopped) { return 'stopped' }
        if ($Run.ExitCode -eq 0) { return 'finished' }
        "exited with code $($Run.ExitCode); see Output"
    }

    function Get-TabContent($Entry) {
        $tab = $script:Tab
        if ($tab -eq 'python' -or $tab -eq 'powershell') {
            $item = $Entry.$tab
            if (-not $item) {
                $this = Get-LanguageLabel $tab
                $other = 'Python'
                if ($tab -eq 'python') { $other = 'PowerShell' }
                return @('', "This example has no $this version; see the $other tab.", '')
            }
            $label = ($item.file -split '/', 3)[2]
            return @((Get-SourceText $Entry $tab), '', $label)
        }
        if ($tab -eq 'html' -or $tab -eq 'css') {
            $text = [string]$Entry.$tab
            return @($text, [string]$Entry.($tab + '_note'), '')
        }
        $run = Get-LatestRun $Entry
        if (-not $run) { return @('', 'Run the example to see what it prints here (standard output and errors).', '') }
        @((Get-Tail $run.Output), "Output of the last run: $(Get-LanguageLabel $run.Language)$($script:Dot)$(Get-RunState $run).", '')
    }

    function Show-Tab {
        $entry = $script:Examples[$script:Selected]
        $content = Get-TabContent $entry
        $ops = New-Object System.Collections.ArrayList
        [void]$ops.Add(@{ op = 'replace_children_html'; element = 'code'; html = (ConvertTo-TextHtml $content[0]) })
        [void]$ops.Add(@{ op = 'set_text'; element = 'note'; text = [string]$content[1] })
        [void]$ops.Add(@{ op = 'set_text'; element = 'file'; text = [string]$content[2] })
        foreach ($name in $script:Tabs) {
            $selected = $name -eq $script:Tab
            [void]$ops.Add((Get-ClassOp $selected "tab-$name" 'selected'))
            $aria = 'false'
            if ($selected) { $aria = 'true' }
            [void]$ops.Add(@{ op = 'set_attribute'; element = "tab-$name"; name = 'aria-selected'; value = $aria })
            $empty = ($name -ne 'output') -and -not $entry.$name
            [void]$ops.Add((Get-ClassOp $empty "tab-$name" 'empty'))
        }
        Invoke-NativeHTMLKitBatch -Document $script:Doc -Operations $ops.ToArray()
    }

    function Get-RuntimeState($Runtime, $Entry, [string]$Language) {
        if (-not $Entry.$Language) { return @($false, "No $($Runtime.Label) version") }
        if ($Runtime.Checking -or -not $Runtime.Ready) { return @($false, $Runtime.Message) }
        if ($Language -eq 'powershell' -and $Entry.layer -eq 'ui' -and -not ($Runtime.Modules -contains 'NativeHTMLKit.UI')) {
            return @($false, 'Needs the NativeHTMLKit.UI module: Install-Module NativeHTMLKit.UI -Scope CurrentUser')
        }
        if ($Language -eq 'python' -and $Entry.layer -eq 'ui' -and -not ($Runtime.Modules -contains 'nativehtmlkit_ui')) {
            return @($false, 'Needs the Python package: python -m pip install nativehtmlkit-demo')
        }
        @($true, $Runtime.Message)
    }

    function Show-Runtimes {
        $entry = $script:Examples[$script:Selected]
        $ops = @()
        foreach ($pair in @(@('python', $script:PythonRuntime), @('powershell', $script:PowerShellRuntime))) {
            $state = Get-RuntimeState $pair[1] $entry $pair[0]
            if ($state[0]) { $ops += @{ op = 'remove_attribute'; element = "run-$($pair[0])"; name = 'disabled' } }
            else { $ops += @{ op = 'set_attribute'; element = "run-$($pair[0])"; name = 'disabled'; value = '' } }
            $ops += @{ op = 'set_text'; element = "runtime-$($pair[0])"; text = [string]$state[1] }
        }
        Invoke-NativeHTMLKitBatch -Document $script:Doc -Operations $ops
    }

    function Show-Runs {
        if ($script:Runs.Count -eq 0) {
            $markup = '<li class="muted">Nothing is running. Pick an example and press Run.</li>'
        } else {
            $builder = New-Object Text.StringBuilder
            for ($i = $script:Runs.Count - 1; $i -ge 0; $i--) {
                $run = $script:Runs[$i]
                $css = 'state'
                if ($run.ExitCode -eq 0 -or $run.Stopped) { $css = 'state ok' }
                elseif ($null -ne $run.ExitCode) { $css = 'state bad' }
                if ($null -eq $run.ExitCode) { $action = "<button type=`"button`" id=`"stop-$($run.Number)`">Stop</button>" }
                else { $action = "<button type=`"button`" id=`"dismiss-$($run.Number)`">Dismiss</button>" }
                [void]$builder.Append('<li><span>').Append((Format-Html "$($run.Entry.title)$($script:Dot)$(Get-LanguageLabel $run.Language)")).Append('</span>')
                [void]$builder.Append("<span class=`"$css`">").Append((Format-Html (Get-RunState $run))).Append('</span>')
                [void]$builder.Append("<button type=`"button`" id=`"output-$($run.Number)`">Output</button>$action</li>")
            }
            $markup = $builder.ToString()
        }
        Set-NativeHTMLKitDocumentHtml -Document $script:Doc -Element runs -Html $markup
    }

    function Select-Example([int]$Index) {
        $previous = $script:Selected
        $script:Selected = $Index
        $entry = $script:Examples[$Index]
        if (($script:Tab -eq 'python' -or $script:Tab -eq 'powershell') -and -not $entry.($script:Tab)) {
            if ($entry.python) { $script:Tab = 'python' } else { $script:Tab = 'powershell' }
        }
        $layer = 'NativeHTMLKit UI example'
        if ($entry.layer -eq 'sdk') { $layer = 'SDK example' }
        $teaches = (@($entry.teaches) | ForEach-Object { '<li>' + (Format-Html $_) + '</li>' }) -join ''
        Invoke-NativeHTMLKitBatch -Document $script:Doc -Operations @(
            @{ op = 'remove_class'; element = "ex-$previous"; name = 'selected' }
            @{ op = 'add_class'; element = "ex-$Index"; name = 'selected' }
            @{ op = 'set_text'; element = 'layer'; text = $layer }
            @{ op = 'set_text'; element = 'title'; text = [string]$entry.title }
            @{ op = 'set_text'; element = 'summary'; text = [string]$entry.summary }
            @{ op = 'replace_children_html'; element = 'teaches'; html = $teaches }
        )
        Show-Runtimes
        Show-Tab
    }

    function Update-Filter {
        $words = @(([string](Get-NativeHTMLKitValue -Document $script:Doc -Element search)).ToLowerInvariant() -split '\s+' | Where-Object { $_ })
        $visible = @{ sdk = 0; ui = 0 }
        $ops = New-Object System.Collections.ArrayList
        for ($i = 0; $i -lt $script:Examples.Count; $i++) {
            $entry = $script:Examples[$i]
            $haystack = (@($entry.title, $entry.summary, $entry.id) + @($entry.teaches)) -join ' '
            $haystack = $haystack.ToLowerInvariant()
            $shown = $true
            foreach ($word in $words) { if (-not $haystack.Contains($word)) { $shown = $false; break } }
            if ($shown) { $visible[$entry.layer]++ }
            [void]$ops.Add((Get-ClassOp (-not $shown) "ex-$i" 'hidden'))
        }
        foreach ($layer in @('sdk', 'ui')) { [void]$ops.Add((Get-ClassOp ($visible[$layer] -eq 0) "group-$layer" 'hidden')) }
        [void]$ops.Add((Get-ClassOp (($visible.sdk + $visible.ui) -gt 0) 'list-empty' 'hidden'))
        Invoke-NativeHTMLKitBatch -Document $script:Doc -Operations $ops.ToArray()
    }

    # ---- processes --------------------------------------------------------------------------
    function Get-SampleLine([int]$Number) {
        $level = @('INFO', 'INFO', 'WARN', 'INFO', 'ERROR', 'DEBUG')[$Number % 6]
        '{0} {1,-5} demo: sample log line {2}' -f (Get-Date -Format 'HH:mm:ss'), $level, $Number
    }

    function Start-Example($Entry, [string]$Language) {
        if ($Language -eq 'python') { $runtime = $script:PythonRuntime } else { $runtime = $script:PowerShellRuntime }
        $state = Get-RuntimeState $runtime $Entry $Language
        if (-not $state[0]) { return $null }
        $item = $Entry.$Language
        $scriptPath = Join-Path (Join-Path $script:Content 'examples') $item.file
        $directory = Join-Path (Get-RunRoot) "$($Entry.layer)-$($Entry.id)-$Language"
        if (-not (Test-Path -LiteralPath $directory)) { $null = New-Item -ItemType Directory -Path $directory }
        $sampleLog = $null
        $arguments = @()
        foreach ($argument in @($item.args)) {
            if ($argument -eq '{sample_log}') {
                $sampleLog = Join-Path $directory 'sample.log'
                [IO.File]::WriteAllLines($sampleLog, [string[]](0..11 | ForEach-Object { Get-SampleLine $_ }))
                $arguments += $sampleLog
            } else { $arguments += [string]$argument }
        }
        $command = @($runtime.Command)
        if ($Language -eq 'python') { $command += @([IO.Path]::GetFileName($scriptPath)) }
        else { $command += @('-File', [IO.Path]::GetFileName($scriptPath)) }
        $command += $arguments

        $info = New-Object Diagnostics.ProcessStartInfo
        $info.FileName = $command[0]
        $info.Arguments = (@($command | Select-Object -Skip 1) | ForEach-Object { ConvertTo-Argument $_ }) -join ' '
        $info.WorkingDirectory = Split-Path -Parent $scriptPath
        $info.UseShellExecute = $false
        $info.CreateNoWindow = $true
        $info.RedirectStandardInput = $true
        $info.RedirectStandardOutput = $true
        $info.RedirectStandardError = $true
        foreach ($name in @($info.EnvironmentVariables.Keys)) {
            if ($name -like 'UI4ME_*' -or $name -eq 'NATIVEHTMLKIT_DIAGNOSTIC_SESSION_ID') { $info.EnvironmentVariables.Remove($name) }
        }
        $info.EnvironmentVariables['PYTHONUNBUFFERED'] = '1'
        if (-not $info.EnvironmentVariables.ContainsKey('PYTHONIOENCODING')) { $info.EnvironmentVariables['PYTHONIOENCODING'] = 'utf-8' }
        $output = Join-Path $directory 'output.log'
        try {
            $process = [Diagnostics.Process]::Start($info)
        } catch {
            Set-NativeHTMLKitDocumentText -Document $script:Doc -Element "runtime-$Language" -Text ('Could not start: ' + $_.Exception.Message)
            return $null
        }
        $process.StandardInput.Close()
        $log = New-Object IO.FileStream($output, [IO.FileMode]::Create, [IO.FileAccess]::Write, [IO.FileShare]'ReadWrite, Delete')
        $run = [pscustomobject]@{
            Number = $script:NextRun; Entry = $Entry; Language = $Language; Process = $process; Output = $output
            Log = $log; SampleLog = $sampleLog; SampleLines = 12; ExitCode = $null; Stopped = $false
            Readers = @(
                @{ Stream = $process.StandardOutput.BaseStream; Buffer = (New-Object byte[] 8192); Task = $null },
                @{ Stream = $process.StandardError.BaseStream; Buffer = (New-Object byte[] 8192); Task = $null })
        }
        $script:NextRun++
        [void]$script:Runs.Add($run)
        $finished = @($script:Runs | Where-Object { $null -ne $_.ExitCode })
        if ($finished.Count -gt 6) { foreach ($old in $finished[0..($finished.Count - 7)]) { $script:Runs.Remove($old) } }
        Read-RunOutput $run
        Show-Runs
        if ($script:Tab -eq 'output' -and $Entry.key -eq $script:Examples[$script:Selected].key) { Show-Tab }
        $run
    }

    # Quote one argument for ProcessStartInfo.Arguments (Windows command-line rules; also correct on Linux).
    function ConvertTo-Argument([string]$Value) {
        if ($Value -and $Value -notmatch '[\s"]') { return $Value }
        '"' + ($Value -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"'
    }

    # Output is read with ReadAsync and copied to the log file from the UI runspace (no callbacks
    # on other threads), so the Output tab can show it while the example runs.
    function Read-RunOutput($Run) {
        if (-not $Run.Log) { return }
        foreach ($reader in $Run.Readers) {
            if ($reader.Done) { continue }
            while ($true) {
                if ($null -eq $reader.Task) { $reader.Task = $reader.Stream.ReadAsync($reader.Buffer, 0, $reader.Buffer.Length) }
                if (-not $reader.Task.IsCompleted) { break }
                $count = 0
                if (-not $reader.Task.IsFaulted -and -not $reader.Task.IsCanceled) { $count = $reader.Task.Result }
                if ($count -le 0) { $reader.Task = $null; $reader.Done = $true; break }
                $Run.Log.Write($reader.Buffer, 0, $count)
                $reader.Task = $null
            }
        }
        $Run.Log.Flush()
    }

    function Stop-Example($Run) {
        if ($Run.Process.HasExited) { return }
        $Run.Stopped = $true
        try {
            if ($PSVersionTable.PSVersion.Major -ge 7) { $Run.Process.Kill($true) }
            else { $null = & taskkill.exe /T /F /PID $Run.Process.Id 2>&1 }
        } catch { try { $Run.Process.Kill() } catch { } }
    }

    function Update-Runs {
        $changed = $false
        foreach ($run in @($script:Runs)) {
            if ($null -ne $run.ExitCode) { continue }
            Read-RunOutput $run
            if ($run.Process.HasExited) {
                $run.Process.WaitForExit()
                # Drain what is still in the pipes (bounded: a grandchild could keep a pipe open).
                $deadline = [DateTime]::UtcNow.AddSeconds(3)
                do {
                    Read-RunOutput $run
                    $pending = @($run.Readers | Where-Object { -not $_.Done })
                    foreach ($reader in $pending) { if ($reader.Task) { $null = $reader.Task.Wait(100) } }
                } while ($pending.Count -gt 0 -and [DateTime]::UtcNow -lt $deadline)
                $run.ExitCode = $run.Process.ExitCode
                $run.Log.Dispose(); $run.Log = $null
                $changed = $true
            } elseif ($run.SampleLog) {
                [IO.File]::AppendAllText($run.SampleLog, (Get-SampleLine $run.SampleLines) + [Environment]::NewLine)
                $run.SampleLines++
            }
        }
        if ($changed) { Show-Runs }
        $entry = $script:Examples[$script:Selected]
        if ($script:Tab -eq 'output' -and (Get-LatestRun $entry)) { Show-Tab }
    }

    # A task that sleeps is the timer; rescheduling from -OnCompleted gives a periodic tick.
    function Start-Poll {
        if ($script:Quitting) { return }
        $null = Start-NativeHTMLKitTask -Application $app -ScriptBlock { Start-Sleep -Milliseconds 700 } -OnCompleted {
            try { Update-Runs } catch [NativeHTMLKit.StaleObjectException], [NativeHTMLKit.RpcException], [NativeHTMLKit.DisconnectedException] { return }
            Start-Poll
        }
    }

    # The Python runtime check runs as a background task: starting an interpreter can take a while.
    function Start-PythonProbe {
        $null = Start-NativeHTMLKitTask -Application $app -ArgumentList @($script:IsWindowsOS) -ScriptBlock {
            param([bool]$IsWindowsOS)
            $candidates = @(@('python3'), @('python'))
            if ($IsWindowsOS) { $candidates = @(@('py', '-3'), @('python'), @('python3')) }
            # No double quotes: Windows PowerShell 5.1 drops them from native-command arguments.
            $probe = 'import sys, importlib.util as u; print(sys.version.split()[0]); print(chr(44).join(m for m in (''nativehtmlkit'', ''nativehtmlkit_ui'') if u.find_spec(m)))'
            $first = $null
            foreach ($candidate in $candidates) {
                $exe = Get-Command $candidate[0] -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
                if (-not $exe) { continue }
                $arguments = @($candidate | Select-Object -Skip 1) + @('-c', $probe)
                try { $lines = @(& $exe.Source @arguments 2>$null) } catch { continue }
                if ($LASTEXITCODE -ne 0 -or $lines.Count -lt 1) { continue }
                $modules = @()
                if ($lines.Count -ge 2) { $modules = @($lines[1] -split ',' | Where-Object { $_ }) }
                $found = [pscustomobject]@{ Command = @($exe.Source) + @($candidate | Select-Object -Skip 1); Version = $lines[0]; Modules = $modules }
                if (-not $first) { $first = $found }
                if ($modules -contains 'nativehtmlkit') { return $found }
            }
            $first
        } -OnCompleted {
            param($result)
            $found = $null
            if ($result) { $found = @($result)[0] }
            $runtime = $script:PythonRuntime
            $runtime.Checking = $false
            if (-not $found) {
                $runtime.Message = 'Python 3.10 or later was not found.'
            } else {
                $runtime.Command = @($found.Command) + @('-u')
                $runtime.Modules = @($found.Modules)
                $runtime.Ready = $runtime.Modules -contains 'nativehtmlkit'
                if ($runtime.Ready) { $runtime.Message = "Python $($found.Version)" }
                else { $runtime.Message = 'Install the Python packages first: python -m pip install nativehtmlkit-demo' }
            }
            Show-Runtimes
        } -OnFailed {
            param($failure)
            $script:PythonRuntime.Checking = $false
            $script:PythonRuntime.Message = 'Python check failed: ' + $failure.Message
            Show-Runtimes
        }
    }

    # ---- window -----------------------------------------------------------------------------
    $window = New-NativeHTMLKitWindow -Application $app -Title 'NativeHTMLKit Demo' -Width 1180 -Height 780 -MinWidth 860 -MinHeight 560
    $script:Doc = Open-NativeHTMLKitFile -Window $window -Path (Join-Path (Join-Path $script:Content 'launcher') 'launcher.html')
    Set-NativeHTMLKitDocumentHtml -Document $script:Doc -Element list -Html (Get-ListHtml)

    $null = Register-NativeHTMLKitDocumentEvent -Document $script:Doc -Type click -Element list -Callback {
        param($evt)
        if ($evt.element -match '^ex-(\d+)$') { Select-Example ([int]$Matches[1]) }
    }
    $null = Register-NativeHTMLKitDocumentEvent -Document $script:Doc -Type input -Element search -Callback { Update-Filter }
    $null = Register-NativeHTMLKitDocumentEvent -Document $script:Doc -Type click -Element tabs -Callback {
        param($evt)
        if ($evt.element -match '^tab-(\w+)$' -and $script:Tabs -contains $Matches[1]) { $script:Tab = $Matches[1]; Show-Tab }
    }
    $null = Register-NativeHTMLKitDocumentEvent -Document $script:Doc -Type click -Element actions -Callback {
        param($evt)
        if ($evt.element -eq 'run-python') { $null = Start-Example $script:Examples[$script:Selected] 'python' }
        elseif ($evt.element -eq 'run-powershell') { $null = Start-Example $script:Examples[$script:Selected] 'powershell' }
    }
    $null = Register-NativeHTMLKitDocumentEvent -Document $script:Doc -Type click -Element runs -Callback {
        param($evt)
        if ($evt.element -notmatch '^(stop|dismiss|output)-(\d+)$') { return }
        $kind = $Matches[1]
        $number = [int]$Matches[2]
        $run = $script:Runs | Where-Object { $_.Number -eq $number } | Select-Object -First 1
        if (-not $run) { return }
        switch ($kind) {
            'stop' { Stop-Example $run }
            'dismiss' { $script:Runs.Remove($run); Show-Runs }
            'output' {
                for ($i = 0; $i -lt $script:Examples.Count; $i++) { if ($script:Examples[$i].key -eq $run.Entry.key) { Select-Example $i; break } }
                $script:Tab = 'output'
                Show-Tab
            }
        }
    }

    Select-Example 0
    Set-NativeHTMLKitReady -Application $app
    Start-PythonProbe
    Start-Poll

    if ($SelfTest) {
        . (Join-Path $PSScriptRoot 'SelfTest.ps1')
        $failed = Invoke-DemoSelfTest
        $script:Quitting = $true
        $null = Request-NativeHTMLKitQuit -Application $app
        Wait-NativeHTMLKit -Application $app -UntilShutdown
        if ($failed) { exit 1 }
        return
    }

    Wait-NativeHTMLKit -Application $app -UntilShutdown
} finally {
    $script:Quitting = $true
    # Closing the demo also closes the examples it started.
    foreach ($run in @($script:Runs)) { if ($run.Process) { Stop-Example $run } }
    Close-NativeHTMLKit -Application $app
}