GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: watcher process for cleaning up after crashes (#360)
lars-bergerf424fd72a9de
diff --git a/.vscode/launch.json b/.vscode/launch.jsonindex 39180584..1ae96274 100755--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -10,7 +10,7 @@"request": "launch","preLaunchTask": "build",// If you have changed target frameworks, make sure to update the program path.- "program": "${workspaceFolder}/GlazeWM.App/bin/Debug/net7-windows10.0.17763.0/GlazeWM.dll",+ "program": "${workspaceFolder}/GlazeWM.App/bin/Debug/net7-windows10.0.17763.0/GlazeWM.exe","args": [],"cwd": "${workspaceFolder}/GlazeWM.App",// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Consolediff --git a/GlazeWM.App.Cli/CliStartup.cs b/GlazeWM.App.Cli/CliStartup.csindex ba692ece..7ede6eec 100644--- a/GlazeWM.App.Cli/CliStartup.cs+++ b/GlazeWM.App.Cli/CliStartup.cs@@ -1,6 +1,5 @@-using System.Text.Json;+using GlazeWM.Domain.Common;using GlazeWM.Infrastructure.Common;-using GlazeWM.Infrastructure.Utils;namespace GlazeWM.App.Cli{@@ -11,55 +10,37 @@ namespace GlazeWM.App.Cliint ipcServerPort,bool isSubscribeMessage){- var client = new WebSocketClient(ipcServerPort);+ var client = new IpcClient(ipcServerPort);try{- await client.ConnectAsync(CancellationToken.None);-- var clientMessage = string.Join(" ", args);- await client.SendTextAsync(clientMessage, CancellationToken.None);+ await client.ConnectAsync();// Wait for server to respond with a message.- var serverResponse = await client.ReceiveTextAsync(CancellationToken.None);+ var clientMessage = string.Join(" ", args);+ var firstResponse = await client.SendAndWaitReplyAsync(clientMessage);// Exit on first message received when not subscribing to an event.if (!isSubscribeMessage){- var parsedMessage = ParseMessage(serverResponse);- Console.WriteLine(parsedMessage);- await client.DisconnectAsync(CancellationToken.None);+ Console.WriteLine(firstResponse);+ await client.DisconnectAsync();return ExitCode.Success;}// When subscribing to events, continuously listen for server messages.while (true){- var message = await client.ReceiveTextAsync(CancellationToken.None);- var parsedMessage = ParseMessage(message);- Console.WriteLine(parsedMessage);+ var eventResponse = await client.ReceiveAsync();+ Console.WriteLine(eventResponse);}}catch (Exception exception){Console.Error.WriteLine(exception.Message);- await client.DisconnectAsync(CancellationToken.None);+ await client.DisconnectAsync();return ExitCode.Error;}}-- /// <summary>- /// Parse JSON in server message.- /// </summary>- private static string ParseMessage(string message)- {- var parsedMessage = JsonDocument.Parse(message).RootElement;- var error = parsedMessage.GetProperty("error").GetString();-- if (error is not null)- throw new Exception(error);-- return parsedMessage.GetProperty("data").ToString();- }}}diff --git a/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csproj b/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csprojnew file mode 100644index 00000000..3584b85b--- /dev/null+++ b/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csproj@@ -0,0 +1,13 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net7.0-windows10.0.17763</TargetFramework>+ <OutputType>Library</OutputType>+ <DebugType>embedded</DebugType>+ <Nullable>enable</Nullable>+ </PropertyGroup>++ <ItemGroup>+ <ProjectReference Include="..\GlazeWM.Domain\GlazeWM.Domain.csproj" />+ <ProjectReference Include="..\GlazeWM.Infrastructure\GlazeWM.Infrastructure.csproj" />+ </ItemGroup>+</Project>diff --git a/GlazeWM.App.Watcher/WatcherStartup.cs b/GlazeWM.App.Watcher/WatcherStartup.csnew file mode 100644index 00000000..0a80b904--- /dev/null+++ b/GlazeWM.App.Watcher/WatcherStartup.cs@@ -0,0 +1,96 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Threading.Tasks;+using GlazeWM.Domain.Common;+using GlazeWM.Infrastructure.Common;+using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;++namespace GlazeWM.App.Watcher+{+ public sealed class WatcherStartup+ {+ public static async Task<ExitCode> Run(int ipcServerPort)+ {+ var client = new IpcClient(ipcServerPort);+ var managedHandles = new List<IntPtr>();++ try+ {+ await client.ConnectAsync();++ // Get window handles that are initially managed on startup.+ foreach (var handle in await GetInitialHandles(client))+ managedHandles.Add(handle);++ // Subscribe to manage + unmanage window events.+ _ = await client.SendAndWaitReplyAsync(+ "subscribe -e window_managed,window_unmanaged"+ );++ // Continuously listen for manage + unmanage events.+ while (true)+ {+ var (isManaged, handle) = await GetManagedEvent(client);++ if (isManaged)+ managedHandles.Add(handle);+ else+ managedHandles.Remove(handle);+ }+ }+ catch (Exception)+ {+ // Restore managed handles on failure to communicate with the main process'+ // IPC server.+ RestoreHandles(managedHandles);+ await client.DisconnectAsync();+ return ExitCode.Success;+ }+ }++ /// <summary>+ /// Query for initial window handles via IPC server.+ /// </summary>+ private static async Task<IEnumerable<IntPtr>> GetInitialHandles(IpcClient client)+ {+ var response = await client.SendAndWaitReplyAsync("windows");++ return response+ .EnumerateArray()+ .Select(value => new IntPtr(value.GetInt64()));+ }++ /// <summary>+ /// Get window handles from managed and unmanaged window events.+ /// </summary>+ /// <returns>Tuple of whether the handle is managed, and the handle itself</returns>+ private static async Task<(bool, IntPtr)> GetManagedEvent(IpcClient client)+ {+ var response = await client.ReceiveAsync();++ return response.GetProperty("friendlyName").GetString() switch+ {+ "window_managed" => (+ true,+ new IntPtr(response.GetProperty("window").GetProperty("handle").GetInt64())+ ),+ "window_unmanaged" => (+ false,+ new IntPtr(response.GetProperty("removedHandle").GetInt64())+ ),+ _ => throw new Exception("Received unrecognized event.")+ };+ }++ /// <summary>+ /// Restore given window handles.+ /// </summary>+ private static void RestoreHandles(List<IntPtr> handles)+ {+ foreach (var handle in handles)+ // TODO: Change this.+ ShowWindow(handle, ShowWindowFlags.ShowDefault);+ }+ }+}diff --git a/GlazeWM.App/GlazeWM.App.csproj b/GlazeWM.App/GlazeWM.App.csprojindex 350e0f3c..20c07bb2 100644--- a/GlazeWM.App/GlazeWM.App.csproj+++ b/GlazeWM.App/GlazeWM.App.csproj@@ -11,6 +11,7 @@<ItemGroup><ProjectReference Include="..\GlazeWM.App.Cli\GlazeWM.App.Cli.csproj" /><ProjectReference Include="..\GlazeWM.App.IpcServer\GlazeWM.App.IpcServer.csproj" />+ <ProjectReference Include="..\GlazeWM.App.Watcher\GlazeWM.App.Watcher.csproj" /><ProjectReference Include="..\GlazeWM.App.WindowManager\GlazeWM.App.WindowManager.csproj" /><ProjectReference Include="..\GlazeWM.Bar\GlazeWM.Bar.csproj" /><ProjectReference Include="..\GlazeWM.Domain\GlazeWM.Domain.csproj" />diff --git a/GlazeWM.App/Program.cs b/GlazeWM.App/Program.csindex 3f9722b9..9eac5912 100644--- a/GlazeWM.App/Program.cs+++ b/GlazeWM.App/Program.cs@@ -1,12 +1,15 @@using System;+using System.Diagnostics;using System.IO;using System.Linq;+using System.Reflection;using System.Threading;using System.Threading.Tasks;using CommandLine;using GlazeWM.App.Cli;using GlazeWM.App.IpcServer;using GlazeWM.App.IpcServer.Messages;+using GlazeWM.App.Watcher;using GlazeWM.App.WindowManager;using GlazeWM.Bar;using GlazeWM.Domain;@@ -49,6 +52,7 @@ namespace GlazeWM.Appvar parsedArgs = Parser.Default.ParseArguments<WmStartupOptions,+ WatcherStartupOptions,InvokeCommandMessage,SubscribeMessage,GetMonitorsMessage,@@ -59,6 +63,7 @@ namespace GlazeWM.Appvar exitCode = parsedArgs.Value switch{WmStartupOptions options => StartWm(options, isSingleInstance),+ WatcherStartupOptions => await StartWatcher(isSingleInstance),InvokeCommandMessage orGetMonitorsMessage orGetWorkspacesMessage or@@ -90,6 +95,9 @@ namespace GlazeWM.AppThreadUtils.CreateSTA("GlazeWMBar", barService.StartApp);ThreadUtils.Create("GlazeWMIPC", () => ipcServerStartup.Run(IpcServerPort));+ // Spawn separate watcher process for cleaning up after crashes.+ Process.Start(Environment.ProcessPath, "watcher");+// Run the window manager on the main thread.return wmStartup.Run();}@@ -108,6 +116,17 @@ namespace GlazeWM.Appreturn await CliStartup.Run(args, IpcServerPort, isSubscribeMessage);}+ private static async Task<ExitCode> StartWatcher(bool isSingleInstance)+ {+ if (isSingleInstance)+ {+ Console.Error.WriteLine("No running instance found. Cannot start watcher.");+ return ExitCode.Error;+ }++ return await WatcherStartup.Run(IpcServerPort);+ }+private static ExitCode ExitWithError(Error error){Console.Error.WriteLine($"Failed to parse startup arguments: {error}.");diff --git a/GlazeWM.Domain/Common/IpcClient.cs b/GlazeWM.Domain/Common/IpcClient.csnew file mode 100644index 00000000..2f2714d3--- /dev/null+++ b/GlazeWM.Domain/Common/IpcClient.cs@@ -0,0 +1,94 @@+using System;+using System.Net.WebSockets;+using System.Text;+using System.Text.Json;+using System.Threading;+using System.Threading.Tasks;++namespace GlazeWM.Domain.Common+{+ public class IpcClient : IDisposable+ {+ private readonly ClientWebSocket _ws = new();+ private readonly int _port;++ public IpcClient(int port)+ {+ _port = port;+ }++ public async Task ConnectAsync()+ {+ await _ws.ConnectAsync(+ new Uri($"ws://localhost:{_port}"),+ CancellationToken.None+ );+ }++ public async Task<JsonElement> ReceiveAsync()+ {+ var buffer = new byte[1024 * 4];++ // Continuously listen until a text message is received.+ while (true)+ {+ var result = await _ws.ReceiveAsync(+ new ArraySegment<byte>(buffer),+ CancellationToken.None+ );++ if (result.MessageType != WebSocketMessageType.Text)+ continue;++ var message = Encoding.UTF8.GetString(buffer, 0, result.Count);+ return ParseMessage(message);+ }+ }++ private async Task SendTextAsync(string message)+ {+ var messageBytes = Encoding.UTF8.GetBytes(message);++ await _ws.SendAsync(+ new ArraySegment<byte>(messageBytes),+ WebSocketMessageType.Text,+ true,+ CancellationToken.None+ );+ }++ public async Task<JsonElement> SendAndWaitReplyAsync(string message)+ {+ await SendTextAsync(message);+ return await ReceiveAsync();+ }++ /// <summary>+ /// Parse JSON in server message.+ /// </summary>+ private static JsonElement ParseMessage(string message)+ {+ var parsedMessage = JsonDocument.Parse(message).RootElement;+ var error = parsedMessage.GetProperty("error").GetString();++ if (error is not null)+ throw new Exception(error);++ return parsedMessage.GetProperty("data");+ }++ public async Task DisconnectAsync()+ {+ await _ws.CloseAsync(+ WebSocketCloseStatus.NormalClosure,+ null,+ CancellationToken.None+ );+ }++ public void Dispose()+ {+ _ws.Dispose();+ }+ }+}diff --git a/GlazeWM.Domain/Common/WatcherStartupOptions.cs b/GlazeWM.Domain/Common/WatcherStartupOptions.csnew file mode 100644index 00000000..ee0e0bb3--- /dev/null+++ b/GlazeWM.Domain/Common/WatcherStartupOptions.cs@@ -0,0 +1,9 @@+using CommandLine;++namespace GlazeWM.Domain.Common+{+ [Verb("watcher")]+ public class WatcherStartupOptions+ {+ }+}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.csindex 8bb90b3f..24c085cf 100644--- a/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.cs+++ b/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.cs@@ -5,6 +5,7 @@ using GlazeWM.Domain.Containers.Commands;using GlazeWM.Domain.Monitors;using GlazeWM.Domain.UserConfigs;using GlazeWM.Domain.Windows.Commands;+using GlazeWM.Domain.Windows.Events;using GlazeWM.Domain.Workspaces;using GlazeWM.Infrastructure.Bussing;using GlazeWM.Infrastructure.WindowsApi;@@ -52,8 +53,6 @@ namespace GlazeWM.Domain.Windows.CommandHandlers// Create the window instance.var window = CreateWindow(windowHandle, targetParent);- _logger.LogWindowEvent("New window managed", window);-if (window is IResizable)_bus.Invoke(new AttachAndResizeContainerCommand(window, targetParent, targetIndex));else@@ -86,6 +85,9 @@ namespace GlazeWM.Domain.Windows.CommandHandlers// Set OS focus to the newly added window in case it's not already focused._bus.Invoke(new SetNativeFocusCommand(window));+ _logger.LogWindowEvent("New window managed", window);+ _bus.Emit(new WindowManagedEvent(window));+return CommandResponse.Ok;}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.csindex c46a35a8..0f763263 100644--- a/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.cs+++ b/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.cs@@ -1,6 +1,7 @@using GlazeWM.Domain.Containers;using GlazeWM.Domain.Containers.Commands;using GlazeWM.Domain.Windows.Commands;+using GlazeWM.Domain.Windows.Events;using GlazeWM.Infrastructure.Bussing;namespace GlazeWM.Domain.Windows.CommandHandlers@@ -37,6 +38,8 @@ namespace GlazeWM.Domain.Windows.CommandHandlers_containerService.PendingFocusContainer = focusTarget;_bus.InvokeAsync(new SetNativeFocusCommand(focusTarget));+ _bus.Emit(new WindowUnmanagedEvent(window.Id, window.Handle));+return CommandResponse.Ok;}}diff --git a/GlazeWM.Domain/Windows/Events/WindowManagedEvent.cs b/GlazeWM.Domain/Windows/Events/WindowManagedEvent.csnew file mode 100644index 00000000..413d3769--- /dev/null+++ b/GlazeWM.Domain/Windows/Events/WindowManagedEvent.cs@@ -0,0 +1,14 @@+using GlazeWM.Infrastructure.Bussing;++namespace GlazeWM.Domain.Windows.Events+{+ public class WindowManagedEvent : Event+ {+ public Window Window { get; }++ public WindowManagedEvent(Window window)+ {+ Window = window;+ }+ }+}diff --git a/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.cs b/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.csnew file mode 100644index 00000000..fa02b159--- /dev/null+++ b/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.cs@@ -0,0 +1,17 @@+using System;+using GlazeWM.Infrastructure.Bussing;++namespace GlazeWM.Domain.Windows.Events+{+ public class WindowUnmanagedEvent : Event+ {+ public Guid RemovedId { get; }+ public IntPtr RemovedHandle { get; }++ public WindowUnmanagedEvent(Guid removedId, IntPtr removedHandle)+ {+ RemovedId = removedId;+ RemovedHandle = removedHandle;+ }+ }+}diff --git a/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.cs b/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.csnew file mode 100644index 00000000..92f9a241--- /dev/null+++ b/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.cs@@ -0,0 +1,25 @@+using System;+using System.Text.Json;+using System.Text.Json.Serialization;++namespace GlazeWM.Infrastructure.Serialization+{+ public class JsonIntPtrConverter : JsonConverter<IntPtr>+ {+ public override IntPtr Read(+ ref Utf8JsonReader reader,+ Type typeToConvert,+ JsonSerializerOptions options)+ {+ return new IntPtr(reader.GetInt64());+ }++ public override void Write(+ Utf8JsonWriter writer,+ IntPtr value,+ JsonSerializerOptions options)+ {+ writer.WriteNumberValue(value.ToInt64());+ }+ }+}diff --git a/GlazeWM.Infrastructure/Serialization/JsonParser.cs b/GlazeWM.Infrastructure/Serialization/JsonParser.csindex 4d5e79ad..92db84ef 100644--- a/GlazeWM.Infrastructure/Serialization/JsonParser.cs+++ b/GlazeWM.Infrastructure/Serialization/JsonParser.cs@@ -18,6 +18,8 @@ namespace GlazeWM.Infrastructure.Serializationnew JsonStringEnumConverter(SnakeCaseNamingPolicy.Instance),// Enable boolean strings to be mapped to a C# bool (eg. `"true"` -> `true`).new JsonStringBoolConverter(),+ // Enable serialization/deserialization of `System.IntPtr`.+ new JsonIntPtrConverter(),}};diff --git a/GlazeWM.Infrastructure/Utils/WebSocketClient.cs b/GlazeWM.Infrastructure/Utils/WebSocketClient.csdeleted file mode 100644index 9b47dad5..00000000--- a/GlazeWM.Infrastructure/Utils/WebSocketClient.cs+++ /dev/null@@ -1,71 +0,0 @@-using System;-using System.Net.WebSockets;-using System.Text;-using System.Threading;-using System.Threading.Tasks;--namespace GlazeWM.Infrastructure.Utils-{- public class WebSocketClient- {- private readonly ClientWebSocket _ws = new();- private readonly string _address;- private readonly int _port;-- public WebSocketClient(string address, int port)- {- _address = address;- _port = port;- }-- public WebSocketClient(int port)- {- _address = "localhost";- _port = port;- }-- public async Task ConnectAsync(CancellationToken cancellationToken)- {- await _ws.ConnectAsync(- new Uri($"ws://{_address}:{_port}"),- cancellationToken- );- }-- public async Task<string> ReceiveTextAsync(CancellationToken cancellationToken)- {- var buffer = new byte[1024 * 4];-- // Continuously listen until a text message is received.- while (true)- {- var result = await _ws.ReceiveAsync(- new ArraySegment<byte>(buffer),- cancellationToken- );-- if (result.MessageType != WebSocketMessageType.Text)- continue;-- return Encoding.UTF8.GetString(buffer, 0, result.Count);- }- }-- public async Task SendTextAsync(string message, CancellationToken cancellationToken)- {- var messageBytes = Encoding.UTF8.GetBytes(message);-- await _ws.SendAsync(- new ArraySegment<byte>(messageBytes),- WebSocketMessageType.Text,- true,- cancellationToken- );- }-- public async Task DisconnectAsync(CancellationToken cancellationToken)- {- await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, cancellationToken);- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs b/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.csindex 5a073c7e..333f6eb1 100644--- a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs+++ b/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs@@ -245,6 +245,7 @@ namespace GlazeWM.Infrastructure.WindowsApi{Minimize = 2,Maximize = 3,+ ShowDefault = 10,Restore = 9,}diff --git a/GlazeWM.sln b/GlazeWM.slnindex 0c5a557a..7e09f53a 100644--- a/GlazeWM.sln+++ b/GlazeWM.sln@@ -17,9 +17,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution.editorconfig = .editorconfigEndProjectSectionEndProject-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlazeWM.App.WindowManager", "GlazeWM.App.WindowManager\GlazeWM.App.WindowManager.csproj", "{D160D151-C030-4A0E-A805-6E28B533F03F}"+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.App.WindowManager", "GlazeWM.App.WindowManager\GlazeWM.App.WindowManager.csproj", "{D160D151-C030-4A0E-A805-6E28B533F03F}"EndProject-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlazeWM.App.Cli", "GlazeWM.App.Cli\GlazeWM.App.Cli.csproj", "{BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}"+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.App.Cli", "GlazeWM.App.Cli\GlazeWM.App.Cli.csproj", "{BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlazeWM.App.Watcher", "GlazeWM.App.Watcher\GlazeWM.App.Watcher.csproj", "{1106BABE-DA67-423E-9B21-929953A79BB1}"EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolution@@ -55,6 +57,10 @@ Global{BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}.Debug|Any CPU.Build.0 = Debug|Any CPU{BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}.Release|Any CPU.ActiveCfg = Release|Any CPU{BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}.Release|Any CPU.Build.0 = Release|Any CPU+ {1106BABE-DA67-423E-9B21-929953A79BB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {1106BABE-DA67-423E-9B21-929953A79BB1}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {1106BABE-DA67-423E-9B21-929953A79BB1}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {1106BABE-DA67-423E-9B21-929953A79BB1}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE