📄 OutGridTree/OutGridTree.cs
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Threading;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;

namespace OutGridTree;

[Cmdlet(VerbsData.Out, "GridTree")]
[Alias("ogt")]
public sealed class OutGridTree : Cmdlet
{
    [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
    public PSObject InputObject { get; set; } = AutomationNull.Value;

    private ClassicDesktopStyleApplicationLifetime? lifetime;
    private Application? application;
    private Thread? uiThread;

    protected override void BeginProcessing()
    {
        uiThread = new Thread(RunUi);
        uiThread.Start();
    }

    private void RunUi()
    {
        lifetime = new ClassicDesktopStyleApplicationLifetime();
        AppBuilder
            .Configure(() =>
            {
                application = new();
                return application;
            })
            .UsePlatformDetect()
            .SetupWithLifetime(lifetime);

        lifetime.MainWindow = new Window() { Title = "Out-GridTree" };

        if (application is null)
        {
            ThrowTerminatingError(
                new(
                    new InvalidOperationException("Could not initialize UI system."),
                    "Initialize UI system",
                    ErrorCategory.InvalidOperation,
                    null
                )
            );
            return;
        }

        application.Run(lifetime.MainWindow);
    }

    protected override void ProcessRecord()
    {
        // TODO: Add record to window
        WriteDebug($"Processing record: {InputObject}");
    }

    protected override void EndProcessing()
    {
        // TODO: Wait for window to close
        WriteDebug("End processing");
        uiThread?.Join();
        WriteDebug("Exited");
    }

    protected override void StopProcessing()
    {
        // TODO: Close window
        WriteDebug("Stop processing");
        lifetime?.Shutdown();
        WriteDebug("Shutdown");
    }
}