Files
Il2CppInspectorRedux/Il2CppInspector.Redux.GUI/UiProcessService.cs
2026-03-19 15:22:12 +01:00

71 lines
2.3 KiB
C#

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Il2CppInspector.Redux.GUI;
public class UiProcessService(IHostApplicationLifetime lifetime) : BackgroundService
{
// TODO: This needs to be adjusted for multiplatform support
private const string UiExecutableName = "il2cppinspectorredux.exe";
private Process? _uiProcess;
private string? _uiExectuablePath;
private readonly TaskCompletionSource _uiProcessCreatedTask = new();
public void LaunchUiProcess(int port)
{
_uiExectuablePath ??= ExtractUiExecutable();
_uiProcess = Process.Start(new ProcessStartInfo(_uiExectuablePath, [port.ToString()]));
_uiProcessCreatedTask.SetResult();
}
private static string ExtractUiExecutable()
{
try
{
using var executable =
typeof(UiProcessService).Assembly.GetManifestResourceStream(
$"{typeof(UiProcessService).Namespace!}.{UiExecutableName}");
if (executable == null)
throw new FileNotFoundException("Failed to open resource as stream.");
var tempDir = Directory.CreateTempSubdirectory("il2cppinspectorredux-ui");
var uiExePath = Path.Join(tempDir.FullName, UiExecutableName);
using var fs = File.Create(uiExePath);
executable.CopyTo(fs);
return uiExePath;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to find embedded UI executable: {ex}");
}
}
[MemberNotNull(nameof(_uiProcess))]
private async Task WaitForUiLaunchAsync(CancellationToken cancellationToken)
{
await _uiProcessCreatedTask.Task.WaitAsync(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(_uiProcess != null);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await WaitForUiLaunchAsync(stoppingToken);
await _uiProcess.WaitForExitAsync(stoppingToken);
lifetime.StopApplication();
}
public override Task StopAsync(CancellationToken cancellationToken)
{
if (_uiProcess is { HasExited: false })
_uiProcess.Kill();
if (_uiExectuablePath != null)
File.Delete(_uiExectuablePath);
return base.StopAsync(cancellationToken);
}
}