Skip to content
Open

Ipc #296

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions AssetEditor/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Windows;
using System.Windows.Threading;
using AssetEditor.Services;
using AssetEditor.Services.Ipc;
using AssetEditor.ViewModels;
using AssetEditor.Views;
using AssetEditor.Views.Settings;
Expand All @@ -20,6 +21,7 @@ namespace AssetEditor
public partial class App : Application
{
IServiceProvider _serviceProvider;
AssetEditorIpcServer _ipcServer;

protected override void OnStartup(StartupEventArgs e)
{
Expand Down Expand Up @@ -77,6 +79,9 @@ protected override void OnStartup(StartupEventArgs e)
devConfigManager.OpenFileOnLoad();

ShowMainWindow();

_ipcServer = _serviceProvider.GetRequiredService<AssetEditorIpcServer>();
_ipcServer.Start();
}

void ShowMainWindow()
Expand All @@ -85,6 +90,7 @@ void ShowMainWindow()
ThemesController.SetTheme(applicationSettingsService.CurrentSettings.Theme);

var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
MainWindow = mainWindow;
mainWindow.DataContext = _serviceProvider.GetRequiredService<MainViewModel>();
mainWindow.Closed += OnMainWindowClosed;
mainWindow.Show();
Expand All @@ -99,11 +105,21 @@ void ShowMainWindow()

private void OnMainWindowClosed(object sender, EventArgs e)
{
_ipcServer?.Dispose();
_ipcServer = null;

foreach (Window window in Current.Windows)
window.Close();
Shutdown();
}

protected override void OnExit(ExitEventArgs e)
{
_ipcServer?.Dispose();
_ipcServer = null;
base.OnExit(e);
}

void DispatcherUnhandledExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs args)
{
Logging.Create<App>().Here().Fatal(args.Exception.ToString());
Expand Down
7 changes: 7 additions & 0 deletions AssetEditor/DependencyInjectionContainer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AssetEditor.Services;
using AssetEditor.Services.Ipc;
using AssetEditor.UiCommands;
using AssetEditor.ViewModels;
using AssetEditor.Views;
Expand Down Expand Up @@ -28,6 +29,12 @@ public override void Register(IServiceCollection serviceCollection)
serviceCollection.AddTransient<PrintScopesCommand>();
serviceCollection.AddTransient<OpenEditorCommand>();
serviceCollection.AddTransient<TogglePackFileExplorerCommand>();
serviceCollection.AddTransient<IExternalPackFileLookup, ExternalPackFileLookup>();
serviceCollection.AddTransient<IExternalPackLoader, ExternalPackLoader>();
serviceCollection.AddTransient<IIpcUserNotifier, IpcUserNotifier>();
serviceCollection.AddTransient<IExternalFileOpenExecutor, ExternalFileOpenExecutor>();
serviceCollection.AddTransient<IIpcRequestHandler, IpcRequestHandler>();
serviceCollection.AddSingleton<AssetEditorIpcServer>();

serviceCollection.AddTransient<SettingsWindow>();
serviceCollection.AddScoped<SettingsViewModel>();
Expand Down
212 changes: 212 additions & 0 deletions AssetEditor/Services/Ipc/AssetEditorIpcServer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Shared.Core.ErrorHandling;

namespace AssetEditor.Services.Ipc
{
public class AssetEditorIpcServer : IDisposable
{
public const string PipeName = "TheAssetEditor.Ipc";

private static readonly JsonSerializerOptions SerializerOptions = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

private readonly ILogger _logger = Logging.Create<AssetEditorIpcServer>();
private readonly IServiceScopeFactory _scopeFactory;
private readonly object _syncLock = new();

private CancellationTokenSource _cancellationTokenSource;
private Task _serverTask;
private NamedPipeServerStream _activePipe;
private bool _disposed;

public AssetEditorIpcServer(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}

public void Start()
{
lock (_syncLock)
{
if (_disposed)
throw new ObjectDisposedException(nameof(AssetEditorIpcServer));

if (_serverTask != null)
return;

_cancellationTokenSource = new CancellationTokenSource();
_serverTask = Task.Run(() => RunServerLoopAsync(_cancellationTokenSource.Token));
}
}

private async Task RunServerLoopAsync(CancellationToken cancellationToken)
{
_logger.Here().Information($"Starting IPC named pipe server on {PipeName}");

while (cancellationToken.IsCancellationRequested == false)
{
NamedPipeServerStream pipe = null;
try
{
pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
SetActivePipe(pipe);

await pipe.WaitForConnectionAsync(cancellationToken);

var response = await ProcessRequestAsync(pipe, cancellationToken);
await WriteResponseAsync(pipe, response);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.Here().Error(ex, "Unhandled exception in IPC server loop");
}
finally
{
ClearActivePipe(pipe);
pipe?.Dispose();
}
}

_logger.Here().Information("IPC named pipe server stopped");
}

private async Task<IpcResponse> ProcessRequestAsync(NamedPipeServerStream pipe, CancellationToken cancellationToken)
{
using var reader = new StreamReader(pipe, new UTF8Encoding(false), detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true);
var line = await reader.ReadLineAsync();

if (string.IsNullOrWhiteSpace(line))
return IpcResponse.Failure("Empty request");

IpcRequest request;
try
{
request = JsonSerializer.Deserialize<IpcRequest>(line, SerializerOptions);
}
catch (JsonException)
{
return IpcResponse.Failure("Invalid JSON");
}

if (request == null)
return IpcResponse.Failure("Invalid JSON");

using var scope = _scopeFactory.CreateScope();
var handler = scope.ServiceProvider.GetRequiredService<IIpcRequestHandler>();

try
{
return await handler.HandleAsync(request, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return IpcResponse.Failure("Canceled");
}
catch (Exception ex)
{
_logger.Here().Error(ex, "IPC request handling failed");
return IpcResponse.Failure("Internal server error");
}
}

private static async Task WriteResponseAsync(NamedPipeServerStream pipe, IpcResponse response)
{
using var writer = new StreamWriter(pipe, new UTF8Encoding(false), bufferSize: 1024, leaveOpen: true)
{
AutoFlush = true
};

var json = JsonSerializer.Serialize(response, SerializerOptions);
await writer.WriteLineAsync(json);
}

private void SetActivePipe(NamedPipeServerStream pipe)
{
lock (_syncLock)
{
_activePipe = pipe;
}
}

private void ClearActivePipe(NamedPipeServerStream pipe)
{
lock (_syncLock)
{
if (ReferenceEquals(_activePipe, pipe))
_activePipe = null;
}
}

public void Dispose()
{
CancellationTokenSource cancellationTokenSource;
Task serverTask;
NamedPipeServerStream activePipe;

lock (_syncLock)
{
if (_disposed)
return;

_disposed = true;
cancellationTokenSource = _cancellationTokenSource;
serverTask = _serverTask;
activePipe = _activePipe;

_cancellationTokenSource = null;
_serverTask = null;
_activePipe = null;
}

try
{
cancellationTokenSource?.Cancel();
}
catch
{
}

try
{
activePipe?.Dispose();
}
catch
{
}

if (serverTask != null)
{
try
{
_ = serverTask.Wait(TimeSpan.FromSeconds(2));
}
catch
{
}
}

cancellationTokenSource?.Dispose();
}
}
}
Loading
Loading