GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
refactor: delete c# files
Lars Berger8c4dfe7d2547
diff --git a/GlazeWM.App.Cli/CliStartup.cs b/GlazeWM.App.Cli/CliStartup.csdeleted file mode 100644index 7ede6eec..00000000--- a/GlazeWM.App.Cli/CliStartup.cs+++ /dev/null@@ -1,46 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Common;--namespace GlazeWM.App.Cli-{- public sealed class CliStartup- {- public static async Task<ExitCode> Run(- string[] args,- int ipcServerPort,- bool isSubscribeMessage)- {- var client = new IpcClient(ipcServerPort);-- try- {- await client.ConnectAsync();-- // Wait for server to respond with a message.- var clientMessage = string.Join(" ", args);- var firstResponse = await client.SendAndWaitReplyAsync(clientMessage);-- // Exit on first message received when not subscribing to an event.- if (!isSubscribeMessage)- {- Console.WriteLine(firstResponse);- await client.DisconnectAsync();- return ExitCode.Success;- }-- // When subscribing to events, continuously listen for server messages.- while (true)- {- var eventResponse = await client.ReceiveAsync();- Console.WriteLine(eventResponse);- }- }- catch (Exception exception)- {- Console.Error.WriteLine(exception.Message);- await client.DisconnectAsync();- return ExitCode.Error;- }- }- }-}diff --git a/GlazeWM.App.Cli/GlazeWM.App.Cli.csproj b/GlazeWM.App.Cli/GlazeWM.App.Cli.csprojdeleted file mode 100644index 18154ae3..00000000--- a/GlazeWM.App.Cli/GlazeWM.App.Cli.csproj+++ /dev/null@@ -1,12 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">- <PropertyGroup>- <TargetFramework>net7-windows10.0.17763</TargetFramework>- <ImplicitUsings>enable</ImplicitUsings>- <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.IpcServer/ClientMessages/GetMonitorsMessage.cs b/GlazeWM.App.IpcServer/ClientMessages/GetMonitorsMessage.csdeleted file mode 100644index 3d087fd6..00000000--- a/GlazeWM.App.IpcServer/ClientMessages/GetMonitorsMessage.cs+++ /dev/null@@ -1,9 +0,0 @@-using CommandLine;--namespace GlazeWM.App.IpcServer.ClientMessages-{- [Verb("monitors", HelpText = "Get all monitors.")]- public class GetMonitorsMessage- {- }-}diff --git a/GlazeWM.App.IpcServer/ClientMessages/GetWindowsMessage.cs b/GlazeWM.App.IpcServer/ClientMessages/GetWindowsMessage.csdeleted file mode 100644index 5c17a4c0..00000000--- a/GlazeWM.App.IpcServer/ClientMessages/GetWindowsMessage.cs+++ /dev/null@@ -1,9 +0,0 @@-using CommandLine;--namespace GlazeWM.App.IpcServer.ClientMessages-{- [Verb("windows", HelpText = "Get all windows.")]- public class GetWindowsMessage- {- }-}diff --git a/GlazeWM.App.IpcServer/ClientMessages/GetWorkspacesMessage.cs b/GlazeWM.App.IpcServer/ClientMessages/GetWorkspacesMessage.csdeleted file mode 100644index eb3a0924..00000000--- a/GlazeWM.App.IpcServer/ClientMessages/GetWorkspacesMessage.cs+++ /dev/null@@ -1,9 +0,0 @@-using CommandLine;--namespace GlazeWM.App.IpcServer.ClientMessages-{- [Verb("workspaces", HelpText = "Get all workspaces.")]- public class GetWorkspacesMessage- {- }-}diff --git a/GlazeWM.App.IpcServer/ClientMessages/InvokeCommandMessage.cs b/GlazeWM.App.IpcServer/ClientMessages/InvokeCommandMessage.csdeleted file mode 100644index 6568b56e..00000000--- a/GlazeWM.App.IpcServer/ClientMessages/InvokeCommandMessage.cs+++ /dev/null@@ -1,26 +0,0 @@-using CommandLine;--namespace GlazeWM.App.IpcServer.ClientMessages-{- [Verb(- "command",- HelpText = "Invoke a WM command (eg. `command \"focus workspace 1\"`)."- )]- public class InvokeCommandMessage- {- [Value(- 0,- Required = true,- HelpText = "WM command to run (eg. \"focus workspace 1\")"- )]- public string Command { get; set; }-- [Option(- 'c',- "context-container-id",- Required = false,- HelpText = "ID of container to use as context."- )]- public string ContextContainerId { get; set; }- }-}diff --git a/GlazeWM.App.IpcServer/ClientMessages/SubscribeMessage.cs b/GlazeWM.App.IpcServer/ClientMessages/SubscribeMessage.csdeleted file mode 100644index 6c93ce17..00000000--- a/GlazeWM.App.IpcServer/ClientMessages/SubscribeMessage.cs+++ /dev/null@@ -1,19 +0,0 @@-using CommandLine;--namespace GlazeWM.App.IpcServer.ClientMessages-{- [Verb(- "subscribe",- HelpText = "Subscribe to a WM event (eg. `subscribe -e window_focus,window_close`)"- )]- public class SubscribeMessage- {- [Option(- 'e',- "events",- Required = true,- HelpText = "WM events to subscribe to."- )]- public string Events { get; set; }- }-}diff --git a/GlazeWM.App.IpcServer/DependencyInjection.cs b/GlazeWM.App.IpcServer/DependencyInjection.csdeleted file mode 100644index dbc1c539..00000000--- a/GlazeWM.App.IpcServer/DependencyInjection.cs+++ /dev/null@@ -1,15 +0,0 @@-using Microsoft.Extensions.DependencyInjection;--namespace GlazeWM.App.IpcServer-{- public static class DependencyInjection- {- public static IServiceCollection AddIpcServerServices(this IServiceCollection services)- {- services.AddSingleton<IpcMessageHandler>();- services.AddSingleton<IpcServerStartup>();-- return services;- }- }-}diff --git a/GlazeWM.App.IpcServer/EventSubscription.cs b/GlazeWM.App.IpcServer/EventSubscription.csdeleted file mode 100644index bc445609..00000000--- a/GlazeWM.App.IpcServer/EventSubscription.cs+++ /dev/null@@ -1,7 +0,0 @@-using System;-using System.Net.WebSockets;--namespace GlazeWM.App.IpcServer-{- public sealed record EventSubscription(Guid SubscriptionId, WebSocket WebSocket);-}diff --git a/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj b/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csprojdeleted file mode 100644index 30ac785a..00000000--- a/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj+++ /dev/null@@ -1,13 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk.Web">- <PropertyGroup>- <TargetFramework>net7-windows10.0.17763.0</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.IpcServer/IpcMessageHandler.cs b/GlazeWM.App.IpcServer/IpcMessageHandler.csdeleted file mode 100644index 5d2587cb..00000000--- a/GlazeWM.App.IpcServer/IpcMessageHandler.cs+++ /dev/null@@ -1,311 +0,0 @@-using System;-using System.Collections.Concurrent;-using System.Collections.Generic;-using System.Linq;-using System.Net.WebSockets;-using System.Reactive.Linq;-using System.Text;-using System.Text.Json;-using System.Text.RegularExpressions;-using System.Threading;-using System.Threading.Tasks;-using CommandLine;-using GlazeWM.App.IpcServer.ClientMessages;-using GlazeWM.App.IpcServer.ServerMessages;-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common;-using GlazeWM.Infrastructure.Serialization;-using Microsoft.Extensions.Logging;--namespace GlazeWM.App.IpcServer-{- public sealed class IpcMessageHandler- {- private readonly Bus _bus;- private readonly CommandParsingService _commandParsingService;- private readonly ContainerService _containerService;- private readonly ILogger<IpcMessageHandler> _logger;- private readonly MonitorService _monitorService;- private readonly WorkspaceService _workspaceService;- private readonly WindowService _windowService;-- private readonly JsonSerializerOptions _serializeOptions =- JsonParser.OptionsFactory((options) =>- {- options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;- options.Converters.Add(new JsonContainerConverter());- });-- /// <summary>- /// Matches words separated by spaces when not surrounded by double quotes.- /// Example: "a \"b c\" d" -> ["a", "\"b c\"", "d"]- /// </summary>- private static readonly Regex _messagePartsRegex = new("(\".*?\"|\\S+)");-- /// <summary>- /// Used to subscribe to all possible event types at once.- /// </summary>- private const string SubscribeAllKeyword = "all";-- /// <summary>- /// Allowed events to subscribe to via `subscribe` message.- /// </summary>- private static readonly List<string> SubscribableEvents = new()- {- DomainEvent.BindingModeChanged,- DomainEvent.FocusChanged,- DomainEvent.FocusedContainerMoved,- DomainEvent.MonitorAdded,- DomainEvent.MonitorRemoved,- DomainEvent.TilingDirectionChanged,- DomainEvent.UserConfigReloaded,- DomainEvent.WindowManaged,- DomainEvent.WindowUnmanaged,- DomainEvent.WorkspaceActivated,- DomainEvent.WorkspaceDeactivated,- DomainEvent.WorkingAreaResized,- InfraEvent.ApplicationExiting,- };-- /// <summary>- /// Dictionary of event names and connections subscribed to that event.- /// </summary>- internal ConcurrentDictionary<string, List<EventSubscription>> EventSubscriptions =- new(SubscribableEvents.ToDictionary(- (eventName) => eventName,- (_) => new List<EventSubscription>()- ));-- public IpcMessageHandler(- Bus bus,- CommandParsingService commandParsingService,- ContainerService containerService,- ILogger<IpcMessageHandler> logger,- MonitorService monitorService,- WorkspaceService workspaceService,- WindowService windowService)- {- _bus = bus;- _commandParsingService = commandParsingService;- _containerService = containerService;- _logger = logger;- _monitorService = monitorService;- _workspaceService = workspaceService;- _windowService = windowService;- }-- /// <summary>- /// Subscribe to events emitted on the bus and emit them to subscribed connections.- /// </summary>- internal void Init()- {- _bus.Events.Subscribe((@event) =>- {- var eventSubscriptions = EventSubscriptions.GetValueOrDefault(@event.Type, new());-- foreach (var subscription in eventSubscriptions)- {- try- {- _logger.LogDebug("Emitting event to IPC subscriber: {Event}", @event.Type);-- var serverMessage = new EventSubscriptionMessage<object?>(- SubscriptionId: subscription.SubscriptionId,- Success: true,- MessageType: ServerMessageType.EventSubscription,- Data: @event,- Error: null- );-- _ = subscription.WebSocket.SendAsync(- MessageToBytes(serverMessage),- WebSocketMessageType.Text,- true,- CancellationToken.None- );- }- catch { }- }- });- }-- internal async Task Handle(WebSocket ws)- {- var buffer = new byte[1024];-- while (ws.State == WebSocketState.Open)- {- try- {- var received = await ws.ReceiveAsync(- new ArraySegment<byte>(buffer),- CancellationToken.None- );-- // Handle close messages.- if (received.MessageType == WebSocketMessageType.Close)- await ws.CloseAsync(- received.CloseStatus ?? WebSocketCloseStatus.NormalClosure,- received.CloseStatusDescription,- CancellationToken.None- );-- // Ignore messages that aren't text.- if (received.MessageType != WebSocketMessageType.Text)- continue;-- var clientMessage = Encoding.UTF8.GetString(buffer, 0, received.Count);- var serverMessage = GetResponseMessage(clientMessage, ws);-- await ws.SendAsync(- MessageToBytes(serverMessage),- WebSocketMessageType.Text,- true,- CancellationToken.None- );- }- catch { }- }-- // Remove event subscription on websocket disconnect.- foreach (var (eventName, subscriptions) in EventSubscriptions)- {- EventSubscriptions.AddOrUpdate(- eventName,- new List<EventSubscription>(),- (_, subscriptions) =>- subscriptions.Where((subscription) => subscription.WebSocket != ws).ToList()- );- }- }-- private ClientResponseMessage<object?> GetResponseMessage(string message, WebSocket ws)- {- _logger.LogDebug("IPC message received: {Message}.", message);-- try- {- var messageParts = _messagePartsRegex.Matches(message)- .Select(match => match.Value)- .Where(match => match is not null);-- var parsedArgs = Parser.Default.ParseArguments<- InvokeCommandMessage,- SubscribeMessage,- GetMonitorsMessage,- GetWorkspacesMessage,- GetWindowsMessage- >(messageParts);-- var data = parsedArgs.Value switch- {- InvokeCommandMessage commandMsg => HandleInvokeCommandMessage(commandMsg),- SubscribeMessage subscribeMsg => HandleSubscribeMessage(subscribeMsg, ws),- GetMonitorsMessage => _monitorService.GetMonitors(),- GetWorkspacesMessage => _workspaceService.GetActiveWorkspaces(),- GetWindowsMessage => _windowService.GetWindows(),- _ => throw new Exception($"Invalid message '{message}'")- };-- return new ClientResponseMessage<object?>(- ClientMessage: message,- Success: true,- MessageType: ServerMessageType.ClientResponse,- Data: data,- Error: null- );- }- catch (Exception exception)- {- return new ClientResponseMessage<object?>(- ClientMessage: message,- Success: false,- MessageType: ServerMessageType.ClientResponse,- Data: null,- Error: exception.Message- );- }- }-- private object HandleInvokeCommandMessage(InvokeCommandMessage message)- {- var contextContainer =- message.ContextContainerId is not null- ? _containerService.GetContainerById(Guid.Parse(message.ContextContainerId))- : _containerService.FocusedContainer;-- var commandString = CommandParsingService.FormatCommand(message.Command);-- var command = _commandParsingService.ParseCommand(- commandString,- contextContainer- );-- _bus.Invoke((dynamic)command);- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());-- return new { contextContainerId = contextContainer.Id };- }-- private object HandleSubscribeMessage(SubscribeMessage message, WebSocket ws)- {- var eventNames = message.Events- .Split(',')- .Select(eventName => eventName.ToLowerInvariant());-- // Validate event names.- foreach (var eventName in eventNames)- {- if (!(eventName == SubscribeAllKeyword || SubscribableEvents.Contains(eventName)))- throw new ArgumentException($"Invalid event '{eventName}'.");- }-- var subscriptionId = Guid.NewGuid();-- // Handle subscription to all events.- if (eventNames.Contains(SubscribeAllKeyword))- {- foreach (var eventName in SubscribableEvents)- {- var subscriptions = EventSubscriptions.GetValueOrDefault(- eventName,- new()- );-- subscriptions.Add(new(subscriptionId, ws));- }-- return new { subscriptionId };- }-- foreach (var eventName in eventNames)- {- var subscriptions = EventSubscriptions.GetValueOrDefault(- eventName,- new()- );-- subscriptions.Add(new(subscriptionId, ws));- }-- return new { subscriptionId };- }-- private ArraySegment<byte> MessageToBytes<T>(T serverMessage)- where T : ServerMessage<object?>- {- var messageString = JsonParser.ToString(serverMessage, _serializeOptions);- var messageBytes = Encoding.UTF8.GetBytes(messageString);-- return new ArraySegment<byte>(messageBytes);- }- }-}diff --git a/GlazeWM.App.IpcServer/IpcServerStartup.cs b/GlazeWM.App.IpcServer/IpcServerStartup.csdeleted file mode 100644index e485c87f..00000000--- a/GlazeWM.App.IpcServer/IpcServerStartup.cs+++ /dev/null@@ -1,48 +0,0 @@-using Microsoft.AspNetCore.Builder;-using Microsoft.AspNetCore.Hosting;-using Microsoft.Extensions.Logging;--namespace GlazeWM.App.IpcServer-{- public sealed class IpcServerStartup- {- private readonly ILogger<IpcServerStartup> _logger;- private readonly IpcMessageHandler _ipcMessageHandler;-- public IpcServerStartup(- ILogger<IpcServerStartup> logger,- IpcMessageHandler ipcMessageHandler)- {- _logger = logger;- _ipcMessageHandler = ipcMessageHandler;- }-- /// <summary>- /// Start the IPC server on specified port.- /// </summary>- public void Run(int port)- {- _logger.LogDebug("Starting IPC server on port {Port}.", port);-- _ipcMessageHandler.Init();-- var builder = WebApplication.CreateBuilder();- builder.Logging.ClearProviders();- builder.WebHost.UseUrls($"http://localhost:{port}");-- var app = builder.Build();- app.UseWebSockets();-- app.Use(async (context, next) =>- {- if (!context.WebSockets.IsWebSocketRequest)- await next();-- using var ws = await context.WebSockets.AcceptWebSocketAsync();- await _ipcMessageHandler.Handle(ws);- });-- app.Run();- }- }-}diff --git a/GlazeWM.App.IpcServer/ServerMessages/ClientResponseMessage.cs b/GlazeWM.App.IpcServer/ServerMessages/ClientResponseMessage.csdeleted file mode 100644index 7fafaf43..00000000--- a/GlazeWM.App.IpcServer/ServerMessages/ClientResponseMessage.cs+++ /dev/null@@ -1,21 +0,0 @@-namespace GlazeWM.App.IpcServer.ServerMessages-{- internal sealed record ClientResponseMessage<T>(- /// <summary>- /// The client message that this is in response to.- /// </summary>- string ClientMessage,-- /// <inheritdoc/>- bool Success,-- /// <inheritdoc/>- ServerMessageType MessageType,-- /// <inheritdoc/>- T? Data,-- /// <inheritdoc/>- string? Error- ) : ServerMessage<T>(Success, MessageType, Data, Error);-}diff --git a/GlazeWM.App.IpcServer/ServerMessages/EventSubscriptionMessage.cs b/GlazeWM.App.IpcServer/ServerMessages/EventSubscriptionMessage.csdeleted file mode 100644index 35cf4093..00000000--- a/GlazeWM.App.IpcServer/ServerMessages/EventSubscriptionMessage.cs+++ /dev/null@@ -1,23 +0,0 @@-using System;--namespace GlazeWM.App.IpcServer.ServerMessages-{- internal sealed record EventSubscriptionMessage<T>(- /// <summary>- /// ID of the subscription.- /// </summary>- Guid SubscriptionId,-- /// <inheritdoc/>- bool Success,-- /// <inheritdoc/>- ServerMessageType MessageType,-- /// <inheritdoc/>- T? Data,-- /// <inheritdoc/>- string? Error- ) : ServerMessage<T>(Success, MessageType, Data, Error);-}diff --git a/GlazeWM.App.IpcServer/ServerMessages/ServerMessage.cs b/GlazeWM.App.IpcServer/ServerMessages/ServerMessage.csdeleted file mode 100644index bb88758f..00000000--- a/GlazeWM.App.IpcServer/ServerMessages/ServerMessage.cs+++ /dev/null@@ -1,22 +0,0 @@-namespace GlazeWM.App.IpcServer.ServerMessages-{- internal abstract record ServerMessage<T>(- bool Success,-- /// <summary>- /// The type of server message.- /// </summary>- ServerMessageType MessageType,-- /// <summary>- /// The response or event data. This property is only present for messages where- /// 'Success' is true.- /// </summary>- T? Data,-- /// <summary>- /// The error message. This property is only present for messages where 'Success'- /// is false.- /// </summary>- string? Error);-}diff --git a/GlazeWM.App.IpcServer/ServerMessages/ServerMessageType.cs b/GlazeWM.App.IpcServer/ServerMessages/ServerMessageType.csdeleted file mode 100644index 47f6732a..00000000--- a/GlazeWM.App.IpcServer/ServerMessages/ServerMessageType.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.App.IpcServer.ServerMessages-{- internal enum ServerMessageType- {- ClientResponse,- EventSubscription- }-}diff --git a/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csproj b/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csprojdeleted file mode 100644index 3584b85b..00000000--- a/GlazeWM.App.Watcher/GlazeWM.App.Watcher.csproj+++ /dev/null@@ -1,13 +0,0 @@-<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.csdeleted file mode 100644index c4dc747f..00000000--- a/GlazeWM.App.Watcher/WatcherStartup.cs+++ /dev/null@@ -1,99 +0,0 @@-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- {- /// <summary>- /// Watcher is responsible for restoring all managed handles when the main process is- /// killed unexpectedly.- /// </summary>- 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 {DomainEvent.WindowManaged},{DomainEvent.WindowUnmanaged}"- );-- // 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("type").GetString() switch- {- DomainEvent.WindowManaged => (- true,- new IntPtr(response.GetProperty("managedWindow").GetProperty("handle").GetInt64())- ),- DomainEvent.WindowUnmanaged => (- false,- new IntPtr(response.GetProperty("unmanagedHandle").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)- ShowWindowAsync(handle, ShowWindowFlags.ShowNoActivate);- }- }-}diff --git a/GlazeWM.App.WindowManager/GlazeWM.App.WindowManager.csproj b/GlazeWM.App.WindowManager/GlazeWM.App.WindowManager.csprojdeleted file mode 100644index 18154ae3..00000000--- a/GlazeWM.App.WindowManager/GlazeWM.App.WindowManager.csproj+++ /dev/null@@ -1,12 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">- <PropertyGroup>- <TargetFramework>net7-windows10.0.17763</TargetFramework>- <ImplicitUsings>enable</ImplicitUsings>- <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.WindowManager/WmStartup.cs b/GlazeWM.App.WindowManager/WmStartup.csdeleted file mode 100644index 4d29513f..00000000--- a/GlazeWM.App.WindowManager/WmStartup.cs+++ /dev/null@@ -1,151 +0,0 @@-using System.Reactive.Linq;-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.Common.Events;-using GlazeWM.Infrastructure.WindowsApi;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.App.WindowManager-{- public sealed class WmStartup- {- private readonly Bus _bus;- private readonly KeybindingService _keybindingService;- private readonly WindowService _windowService;- private readonly WindowEventService _windowEventService;- private readonly UserConfigService _userConfigService;-- private SystemTrayIcon? _systemTrayIcon { get; set; }-- public WmStartup(- Bus bus,- KeybindingService keybindingService,- WindowService windowService,- WindowEventService windowEventService,- UserConfigService userConfigService)- {- _bus = bus;- _keybindingService = keybindingService;- _windowService = windowService;- _windowEventService = windowEventService;- _userConfigService = userConfigService;- }-- public ExitCode Run()- {- try- {- // Set the process-default DPI awareness.- _ = SetProcessDpiAwarenessContext(DpiAwarenessContext.PerMonitorAwareV2);-- _bus.Events.OfType<ApplicationExitingEvent>()- .Subscribe(_ => OnApplicationExit());-- // Populate initial monitors, windows, workspaces and user config.- _bus.Invoke(new PopulateInitialStateCommand());- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());-- // Listen on registered keybindings.- _keybindingService.Start();-- // Listen for window events (eg. close, focus).- _windowEventService.Start();-- // Listen for changes to display settings.- // TODO: Unsubscribe on application exit.- SystemEvents.DisplaySettingsChanged.Subscribe((@event) => _bus.EmitAsync(@event));-- var systemTrayIconConfig = new SystemTrayIconConfig- {- HoverText = "GlazeWM",- IconResourceName = "GlazeWM.App.Resources.icon.ico",- Actions = new Dictionary<string, Action>- {- { "Reload config", () => _bus.Invoke(new ReloadUserConfigCommand()) },- { "Exit", () => _bus.Invoke(new ExitApplicationCommand(false)) },- }- };-- // Add application to system tray.- _systemTrayIcon = new SystemTrayIcon(systemTrayIconConfig);- _systemTrayIcon.Show();-- var windowAnimations = _userConfigService.GeneralConfig.WindowAnimations;-- // Enable/disable window transition animations.- if (windowAnimations is not WindowAnimations.Unchanged)- {- SystemSettings.SetWindowAnimationsEnabled(- windowAnimations is WindowAnimations.True- );- }-- if (_userConfigService.FocusBorderConfig.Active.Enabled ||- _userConfigService.FocusBorderConfig.Inactive.Enabled)- {- _bus.Events.OfType<FocusChangedEvent>().Subscribe((@event) =>- _bus.InvokeAsync(- new SetActiveWindowBorderCommand(@event.FocusedContainer as Window)- )- );- }-- // Hook mouse event for focus follows cursor.- if (_userConfigService.GeneralConfig.FocusFollowsCursor)- MouseEvents.MouseMoves.Sample(TimeSpan.FromMilliseconds(50)).Subscribe((@event) =>- {- if ([email protected] && [email protected])- _bus.InvokeAsync(new FocusContainerUnderCursorCommand(@event.Point));- });-- // Setup cursor follows focus- if (_userConfigService.GeneralConfig.CursorFollowsFocus)- {- var focusedContainerMoved = _bus.Events- .OfType<FocusedContainerMovedEvent>()- .Select(@event => @event.FocusedContainer);-- var nativeFocusSynced = _bus.Events- .OfType<NativeFocusSyncedEvent>()- .Select((@event) => @event.FocusedContainer);-- focusedContainerMoved.Merge(nativeFocusSynced)- .Where(container => container is Window)- .Subscribe((window) => _bus.InvokeAsync(new CenterCursorOnContainerCommand(window)));- }-- System.Windows.Forms.Application.Run();- return ExitCode.Success;- }- catch (Exception exception)- {- _bus.Invoke(new HandleFatalExceptionCommand(exception));- return ExitCode.Error;- }- }-- private void OnApplicationExit()- {- // Show all windows regardless of whether their workspace is displayed.- foreach (var window in _windowService.GetWindows())- ShowWindowAsync(window.Handle, ShowWindowFlags.ShowNoActivate);-- // Clear border on the active window.- _bus.Invoke(new SetActiveWindowBorderCommand(null));-- // Destroy the system tray icon.- _systemTrayIcon?.Remove();-- System.Windows.Forms.Application.Exit();- }- }-}diff --git a/GlazeWM.App/GlazeWM.App.csproj b/GlazeWM.App/GlazeWM.App.csprojdeleted file mode 100644index 219e5996..00000000--- a/GlazeWM.App/GlazeWM.App.csproj+++ /dev/null@@ -1,36 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <OutputType>WinExe</OutputType>- <TargetFramework>net7-windows10.0.17763.0</TargetFramework>- <UseWindowsForms>true</UseWindowsForms>- <DebugType>embedded</DebugType>- <ApplicationIcon>Resources\icon.ico</ApplicationIcon>- <AssemblyName>GlazeWM</AssemblyName>- </PropertyGroup>-- <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" />- <ProjectReference Include="..\GlazeWM.Infrastructure\GlazeWM.Infrastructure.csproj" />- </ItemGroup>-- <ItemGroup>- <None Remove="Resources\icon.ico" />- <None Remove="Resources\sample-config.yaml" />- </ItemGroup>-- <ItemGroup>- <EmbeddedResource Include="Resources\icon.ico">- <ExcludeFromSingleFile>true</ExcludeFromSingleFile>- </EmbeddedResource>- <Resource Include="Resources\MaterialIcons-Regular.ttf" />- <EmbeddedResource Include="Resources\sample-config.yaml">- <ExcludeFromSingleFile>true</ExcludeFromSingleFile>- </EmbeddedResource>- </ItemGroup>-</Project>diff --git a/GlazeWM.App/Program.cs b/GlazeWM.App/Program.csdeleted file mode 100644index eb953c09..00000000--- a/GlazeWM.App/Program.cs+++ /dev/null@@ -1,199 +0,0 @@-using System;-using System.Diagnostics;-using System.IO;-using System.Linq;-using System.Threading;-using System.Threading.Tasks;-using CommandLine;-using GlazeWM.App.Cli;-using GlazeWM.App.IpcServer;-using GlazeWM.App.IpcServer.ClientMessages;-using GlazeWM.App.Watcher;-using GlazeWM.App.WindowManager;-using GlazeWM.Bar;-using GlazeWM.Domain;-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common;-using GlazeWM.Infrastructure.Exceptions;-using GlazeWM.Infrastructure.Logging;-using GlazeWM.Infrastructure.Serialization;-using GlazeWM.Infrastructure.Utils;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.Logging;-using Microsoft.Extensions.Logging.Console;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.App-{- internal static class Program- {- private const string AppGuid = "325d0ed7-7f60-4925-8d1b-aa287b26b218";- private const int IpcServerPort = 6123;-- /// <summary>- /// The main entry point for the application. The thread must be an STA- /// thread in order to run a message loop.- /// </summary>- [STAThread]- public static async Task<int> Main(string[] args)- {- // Allows reading and writing to the console. This is needed since the `OutputType`- // is `WinExe` and not a console application.- AttachConsoleToParentProcess();-- bool isSingleInstance;- using var _ = new Mutex(false, "Global\\" + AppGuid, out isSingleInstance);-- var parsedArgs = Parser.Default.ParseArguments<- WmStartupOptions,- WatcherStartupOptions,- InvokeCommandMessage,- SubscribeMessage,- GetMonitorsMessage,- GetWorkspacesMessage,- GetWindowsMessage- >(args);-- var exitCode = parsedArgs.Value switch- {- WmStartupOptions options => StartWm(options, isSingleInstance),- WatcherStartupOptions => await StartWatcher(isSingleInstance),- InvokeCommandMessage or- GetMonitorsMessage or- GetWorkspacesMessage or- GetWindowsMessage => await StartCli(args, isSingleInstance, false),- SubscribeMessage => await StartCli(args, isSingleInstance, true),- _ => ExitWithError(parsedArgs.Errors.First())- };-- return (int)exitCode;- }-- private static ExitCode StartWm(WmStartupOptions options, bool isSingleInstance)- {- if (!isSingleInstance)- {- Console.Error.WriteLine("Application is already running.");- return ExitCode.Error;- }-- ServiceLocator.Provider = BuildWmServiceProvider(options);-- var (barService, ipcServerStartup, wmStartup) =- ServiceLocator.GetRequiredServices<- BarService,- IpcServerStartup,- WmStartup- >();-- ThreadUtils.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();- }-- private static async Task<ExitCode> StartCli(- string[] args,- bool isSingleInstance,- bool isSubscribeMessage)- {- if (isSingleInstance)- {- Console.Error.WriteLine("No running instance found. Cannot run CLI command.");- return ExitCode.Error;- }-- return 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}.");- return ExitCode.Error;- }-- private static ServiceProvider BuildWmServiceProvider(WmStartupOptions options)- {- var services = new ServiceCollection()- .AddLoggingService()- .AddExceptionHandler()- .AddInfrastructureServices()- .AddDomainServices()- .AddBarServices()- .AddIpcServerServices()- .AddSingleton<WmStartup>()- .AddSingleton(options);-- return services.BuildServiceProvider();- }- }-- public static class DependencyInjection- {- public static IServiceCollection AddLoggingService(this IServiceCollection services)- {- return services.AddLogging(builder =>- {- builder.ClearProviders();- builder.AddConsoleFormatter<LogFormatter, ConsoleFormatterOptions>();- builder.AddConsole(options => options.FormatterName = LogFormatter.Name);- builder.SetMinimumLevel(LogLevel.Debug);- });- }-- public static IServiceCollection AddExceptionHandler(this IServiceCollection services)- {- services- .AddOptions<ExceptionHandlingOptions>()- .Configure<Bus, ContainerService>((options, bus, containerService) =>- {- options.ErrorLogPath = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),- "./.glaze-wm/errors.log"- );-- options.ErrorLogMessageDelegate = (Exception exception) =>- {- var serializeOptions = JsonParser.OptionsFactory(- options => options.Converters.Add(new JsonContainerConverter())- );-- var stateDump = JsonParser.ToString(- containerService.ContainerTree,- serializeOptions- );-- // History of latest command invocations. Most recent is first.- var commandHistory = bus.CommandHistory- .Select(command => command.Name)- .Reverse();-- return $"{DateTime.Now}\n"- + $"{exception}\n"- + $"Command history: {string.Join(", ", commandHistory)} \n"- + $"State dump: {stateDump}\n\n";- };- });-- return services;- }- }-}diff --git a/GlazeWM.App/Resources/MaterialIcons-Regular.ttf b/GlazeWM.App/Resources/MaterialIcons-Regular.ttfdeleted file mode 100644index 9d09b0fe..00000000Binary files a/GlazeWM.App/Resources/MaterialIcons-Regular.ttf and /dev/null differdiff --git a/GlazeWM.App/Resources/icon.ico b/GlazeWM.App/Resources/icon.icodeleted file mode 100644index e6db364e..00000000Binary files a/GlazeWM.App/Resources/icon.ico and /dev/null differdiff --git a/GlazeWM.App/Resources/sample-config.yaml b/GlazeWM.App/Resources/sample-config.yamldeleted file mode 100644index f537afaf..00000000--- a/GlazeWM.App/Resources/sample-config.yaml+++ /dev/null@@ -1,258 +0,0 @@-general:- # Whether to automatically focus windows underneath the cursor.- focus_follows_cursor: false-- # Whether to jump the cursor between windows focused by the WM.- cursor_follows_focus: false-- # Whether to switch back and forth between the previously focused workspace- # when focusing the current workspace.- toggle_workspace_on_refocus: true-- # Whether to show floating windows as always on top.- show_floating_on_top: false-- # Amount to move floating windows by (eg. when using `alt+<hjkl>` on a floating window)- floating_window_move_amount: "5%"-- # Whether to center new floating windows.- center_new_floating_windows: true-- # *Strongly* recommended to set to 'false'. Whether to globally enable/disable- # window transition animations (on minimize, close, etc). Set to 'unchanged'- # to make no setting changes.- window_animations: "unchanged"--gaps:- # Gap between adjacent windows.- inner_gap: "20px"-- # Gap between windows and the screen edge.- outer_gap: "20px"--# Highlight active/inactive windows with a colored border.-# ** Exclusive to Windows 11 due to API limitations.-focus_borders:- active:- enabled: true- color: "#0000ff"-- inactive:- enabled: false- color: "#ff0000"--bar:- height: "30px"- position: "top"- opacity: 1.0- background: "#20242cc4"- foreground: "#ffffff"- font_family: "Segoe UI"- font_size: "13px"- padding: "4px 6px"- offset_x: "0"- offset_y: "0"- border_radius: "0"- components_left:- - type: "workspaces"- focused_workspace_background: "#ffffff33"- displayed_workspace_background: "#00000033"- default_workspace_background: "transparent"- components_center:- - type: "window title"- components_right:- - type: "system tray"- - type: "tiling direction"- label_horizontal: "⮂"- label_vertical: "⮁"- background: "#ffffff33"- margin: "0 4px"- padding: "0 8px"- - type: "binding mode"- background: "#ffffff33"- margin: "0 4px 0 0"- padding: "0 8px"- - type: "clock"- # Documentation on formatting date/time string:- # https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings- time_formatting: "hh:mm tt ddd MMM d"--workspaces:- - name: "1"- - name: "2"- - name: "3"- - name: "4"- - name: "5"- - name: "6"- - name: "7"- - name: "8"- - name: "9"--window_rules:- # Task Manager requires admin privileges to manage and should be ignored unless running- # the WM as admin.- - command: "ignore"- match_process_name: "/Taskmgr|ScreenClippingHost/"-- # Launches system dialogs as floating by default (eg. File Explorer save/open dialog).- - command: "set floating"- match_class_name: "#32770"-- # Do not manage picture-in-picture windows for browsers. Note that the default is for- # English; change `match_title` to the window's title if you use another language.- - command: "ignore"- match_title: "[Pp]icture.in.[Pp]icture"- match_class_name: "Chrome_WidgetWin_1|MozillaDialogClass"-- # Some applications (eg. Steam) have borders that extend past the normal border size.- - command: "resize borders 0px -7px -7px -7px"- match_process_name: "steam"--binding_modes:- - name: "resize"- keybindings:- # Resize focused window by a percentage or pixel amount.- - command: "resize width -2%"- bindings: ["H", "Left"]- - command: "resize width +2%"- bindings: ["L", "Right"]- - command: "resize height +2%"- bindings: ["K", "Up"]- - command: "resize height -2%"- bindings: ["J", "Down"]- # Press enter/escape to return to default keybindings.- - command: "binding mode none"- bindings: ["Escape", "Enter"]--keybindings:- # Shift focus in a given direction.- - command: "focus left"- bindings: ["Alt+H", "Alt+Left"]- - command: "focus right"- bindings: ["Alt+L", "Alt+Right"]- - command: "focus up"- bindings: ["Alt+K", "Alt+Up"]- - command: "focus down"- bindings: ["Alt+J", "Alt+Down"]-- # Move focused window in a given direction.- - command: "move left"- bindings: ["Alt+Shift+H", "Alt+Shift+Left"]- - command: "move right"- bindings: ["Alt+Shift+L", "Alt+Shift+Right"]- - command: "move up"- bindings: ["Alt+Shift+K", "Alt+Shift+Up"]- - command: "move down"- bindings: ["Alt+Shift+J", "Alt+Shift+Down"]-- # Resize focused window by a percentage or pixel amount.- - command: "resize width -2%"- binding: "Alt+U"- - command: "resize width +2%"- binding: "Alt+P"- - command: "resize height +2%"- binding: "Alt+O"- - command: "resize height -2%"- binding: "Alt+I"-- # As an alternative to the resize keybindings above, resize mode enables resizing via- # HJKL or arrow keys. The binding mode is defined above with the name "resize".- - command: "binding mode resize"- binding: "Alt+R"-- # Change tiling direction. This determines where new tiling windows will be inserted.- - command: "tiling direction toggle"- binding: "Alt+V"-- # Change focus between floating / tiling windows.- - command: "focus mode toggle"- binding: "Alt+Space"-- # Change the focused window to be floating / tiling.- - command: "toggle floating"- binding: "Alt+Shift+Space"-- # Change the focused window to be maximized / unmaximized.- - command: "toggle maximized"- binding: "Alt+X"-- # Minimize focused window.- - command: "set minimized"- binding: "Alt+M"-- # Close focused window.- - command: "close"- binding: "Alt+Shift+Q"-- # Kill GlazeWM process safely.- - command: "exit wm"- binding: "Alt+Shift+E"-- # Re-evaluate configuration file.- - command: "reload config"- binding: "Alt+Shift+R"-- # Launch CMD terminal (alternatively `exec wt` or `exec %ProgramFiles%/Git/git-bash.exe`- # to start Windows Terminal and Git Bash respectively.- - command: "exec cmd"- binding: "Alt+Enter"-- # Focus the workspace that last had focus.- - command: "focus workspace recent"- binding: "Alt+Y"-- # Focus the next/previous workspace defined in `workspaces` config.- - command: "focus workspace next"- binding: "Alt+T"- - command: "focus workspace prev"- binding: "Alt+Shift+T"-- # Change focus to a workspace defined in `workspaces` config.- - command: "focus workspace 1"- binding: "Alt+1"- - command: "focus workspace 2"- binding: "Alt+2"- - command: "focus workspace 3"- binding: "Alt+3"- - command: "focus workspace 4"- binding: "Alt+4"- - command: "focus workspace 5"- binding: "Alt+5"- - command: "focus workspace 6"- binding: "Alt+6"- - command: "focus workspace 7"- binding: "Alt+7"- - command: "focus workspace 8"- binding: "Alt+8"- - command: "focus workspace 9"- binding: "Alt+9"-- # Move focused workspace to a monitor in a given direction.- - command: "move workspace left"- binding: "Alt+A"- - command: "move workspace right"- binding: "Alt+F"- - command: "move workspace up"- binding: "Alt+D"- - command: "move workspace down"- binding: "Alt+S"-- # Move focused window to a workspace defined in `workspaces` config.- - commands: ["move to workspace 1", "focus workspace 1"]- binding: "Alt+Shift+1"- - commands: ["move to workspace 2", "focus workspace 2"]- binding: "Alt+Shift+2"- - commands: ["move to workspace 3", "focus workspace 3"]- binding: "Alt+Shift+3"- - commands: ["move to workspace 4", "focus workspace 4"]- binding: "Alt+Shift+4"- - commands: ["move to workspace 5", "focus workspace 5"]- binding: "Alt+Shift+5"- - commands: ["move to workspace 6", "focus workspace 6"]- binding: "Alt+Shift+6"- - commands: ["move to workspace 7", "focus workspace 7"]- binding: "Alt+Shift+7"- - commands: ["move to workspace 8", "focus workspace 8"]- binding: "Alt+Shift+8"- - commands: ["move to workspace 9", "focus workspace 9"]- bindings: ["Alt+Shift+9"]diff --git a/GlazeWM.Bar/AssemblyInfo.cs b/GlazeWM.Bar/AssemblyInfo.csdeleted file mode 100644index 90d553f3..00000000--- a/GlazeWM.Bar/AssemblyInfo.cs+++ /dev/null@@ -1,10 +0,0 @@-using System.Windows;--[assembly: ThemeInfo(- // Where theme specific resource dictionaries are located (used if a resource is not found in the- // page, or application resource dictionaries).- ResourceDictionaryLocation.None,- // Where the generic resource dictionary is located (used if a resource is not found in the page,- // app, or any theme specific resource dictionaries).- ResourceDictionaryLocation.SourceAssembly)-]diff --git a/GlazeWM.Bar/BarService.cs b/GlazeWM.Bar/BarService.csdeleted file mode 100644index 2350a55a..00000000--- a/GlazeWM.Bar/BarService.cs+++ /dev/null@@ -1,130 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Reactive.Linq;-using System.Threading;-using System.Windows;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Monitors.Events;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.Events;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Bar-{- public class BarService- {- private readonly Bus _bus;- private readonly MonitorService _monitorService;- private readonly UserConfigService _userConfigService;-- private Application _application;- private readonly Dictionary<string, MainWindow> _activeWindowsByDeviceName = new();-- public BarService(- Bus bus,- MonitorService monitorService,- UserConfigService userConfigService)- {- _bus = bus;- _monitorService = monitorService;- _userConfigService = userConfigService;- }-- public void StartApp()- {- var thread = new Thread(() =>- {- try- {- _application = new()- {- ShutdownMode = ShutdownMode.OnExplicitShutdown- };-- // Launch the bar window on the added monitor.- _bus.Events.OfType<MonitorAddedEvent>()- .Subscribe((@event) => ShowWindow(@event.AddedMonitor));-- _bus.Events.OfType<MonitorRemovedEvent>()- .Subscribe((@event) => CloseWindow(@event.RemovedDeviceName));-- _bus.Events.OfType<UserConfigReloadedEvent>()- .Subscribe((_) => RestartApp());-- _application.Run();- }- catch (Exception exception)- {- _bus.Invoke(new HandleFatalExceptionCommand(exception));- }- })- {- Name = "GlazeWMBar"- };- thread.SetApartmentState(ApartmentState.STA);- thread.Start();- }-- public void ExitApp()- {- _application.Dispatcher.Invoke(() => _application.Shutdown());- }-- private void RestartApp()- {- foreach (var deviceName in _activeWindowsByDeviceName.Keys.ToList())- CloseWindow(deviceName);-- foreach (var monitor in _monitorService.GetMonitors())- ShowWindow(monitor);- }-- public void ShowWindow(Domain.Monitors.Monitor targetMonitor)- {- var barConfig = _userConfigService.GetBarConfigForMonitor(targetMonitor);-- if (!barConfig.Enabled)- {- return;- }-- _application.Dispatcher.Invoke(() =>- {- var originalFocusedHandle = GetForegroundWindow();- var barViewModel = new BarViewModel(- targetMonitor,- _application.Dispatcher,- barConfig- );-- var barWindow = new MainWindow(barViewModel);- barWindow.Show();-- // Store active window.- _activeWindowsByDeviceName[targetMonitor.DeviceName] = barWindow;-- // Reset focus to whichever window was focused before the bar window was launched.- SetForegroundWindow(originalFocusedHandle);- });- }-- private void CloseWindow(string deviceName)- {- _application.Dispatcher.Invoke(() =>- {- var barWindow = _activeWindowsByDeviceName.GetValueOrDefault(deviceName);- var barViewModel = barWindow.BarViewModel;-- // Unsubscribe all component observables.- barViewModel.WindowClosing.OnNext(true);-- // Dispose view model and close the window.- barViewModel.Dispose();- barWindow.Close();- });- }- }-}diff --git a/GlazeWM.Bar/BarViewModel.cs b/GlazeWM.Bar/BarViewModel.csdeleted file mode 100644index d3bf00df..00000000--- a/GlazeWM.Bar/BarViewModel.cs+++ /dev/null@@ -1,126 +0,0 @@-using System;-using System.Collections.Generic;-using System.Reactive.Subjects;-using System.Windows.Threading;-using GlazeWM.Bar.Common;-using GlazeWM.Bar.Components;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Bar-{- public class BarViewModel : ViewModelBase- {- public readonly Subject<bool> WindowClosing = new();-- public Monitor Monitor { get; }- public Dispatcher Dispatcher { get; }- public BarConfig BarConfig { get; }-- public BarPosition Position => BarConfig.Position;- public bool AlwaysOnTop => BarConfig.AlwaysOnTop;- public string Background => XamlHelper.FormatColor(BarConfig.Background);- public string Foreground => XamlHelper.FormatColor(BarConfig.Foreground);- public string FontFamily => BarConfig.FontFamily;- public string FontWeight => BarConfig.FontWeight;- public string FontSize => XamlHelper.FormatSize(BarConfig.FontSize);- public string BorderColor => XamlHelper.FormatColor(BarConfig.BorderColor);- public string BorderWidth => XamlHelper.FormatRectShorthand(BarConfig.BorderWidth);- public string BorderRadius => XamlHelper.FormatSize(BarConfig.BorderRadius);- public string Padding => XamlHelper.FormatRectShorthand(BarConfig.Padding);- public double Opacity => BarConfig.Opacity;-- private TextComponentViewModel _componentSeparatorLeft => new(- this, new TextComponentConfig- {- Text = BarConfig.ComponentSeparator.LabelLeft- ?? BarConfig.ComponentSeparator.Label- }- );-- private TextComponentViewModel _componentSeparatorCenter => new(- this, new TextComponentConfig- {- Text = BarConfig.ComponentSeparator.LabelCenter- ?? BarConfig.ComponentSeparator.Label- }- );-- private TextComponentViewModel _componentSeparatorRight => new(- this, new TextComponentConfig- {- Text = BarConfig.ComponentSeparator.LabelRight- ?? BarConfig.ComponentSeparator.Label- }- );-- public List<ComponentViewModel> ComponentsLeft =>- InsertComponentSeparator(- CreateComponentViewModels(BarConfig.ComponentsLeft),- _componentSeparatorLeft);-- public List<ComponentViewModel> ComponentsCenter =>- InsertComponentSeparator(- CreateComponentViewModels(BarConfig.ComponentsCenter),- _componentSeparatorCenter);-- public List<ComponentViewModel> ComponentsRight =>- InsertComponentSeparator(- CreateComponentViewModels(BarConfig.ComponentsRight),- _componentSeparatorRight);-- private static List<ComponentViewModel> InsertComponentSeparator(- List<ComponentViewModel> componentViewModels, TextComponentViewModel componentSeparator- )- {- if (!string.IsNullOrEmpty(componentSeparator.Text))- componentViewModels.Intersperse(componentSeparator);-- return componentViewModels;- }-- protected override void Dispose(bool disposing)- {- if (disposing)- {- WindowClosing.Dispose();- }-- base.Dispose(disposing);- }-- private List<ComponentViewModel> CreateComponentViewModels(- List<BarComponentConfig> componentConfigs)- {- return componentConfigs.ConvertAll<ComponentViewModel>(config => config switch- {- BatteryComponentConfig bsc => new BatteryComponentViewModel(this, bsc),- BindingModeComponentConfig bmc => new BindingModeComponentViewModel(this, bmc),- ClockComponentConfig ccc => new ClockComponentViewModel(this, ccc),- TextComponentConfig tcc => new TextComponentViewModel(this, tcc),- WeatherComponentConfig wcc => new WeatherComponentViewModel(this, wcc),- NetworkComponentConfig ncc => new NetworkComponentViewModel(this, ncc),- TilingDirectionComponentConfig tdc => new TilingDirectionComponentViewModel(this, tdc),- WorkspacesComponentConfig wcc => new WorkspacesComponentViewModel(this, wcc),- WindowTitleComponentConfig wtcc => new WindowTitleComponentViewModel(this, wtcc),- VolumeComponentConfig vcc => new VolumeComponentViewModel(this, vcc),- ImageComponentConfig bscc => new ImageComponentViewModel(this, bscc),- SystemTrayComponentConfig stcc => new SystemTrayComponentViewModel(this, stcc),- CpuComponentConfig cpupc => new CpuComponentViewModel(this, cpupc),- GpuComponentConfig gpupc => new GpuComponentViewModel(this, gpupc),- MemoryComponentConfig rampc => new MemoryComponentViewModel(this, rampc),- TextFileComponentConfig stc => new TextFileComponentViewModel(this, stc),- MusicComponentConfig mcc => new MusicComponentViewModel(this, mcc),- _ => throw new ArgumentOutOfRangeException(nameof(config)),- });- }-- public BarViewModel(Monitor monitor, Dispatcher dispatcher, BarConfig barConfig)- {- Monitor = monitor;- Dispatcher = dispatcher;- BarConfig = barConfig;- }- }-}diff --git a/GlazeWM.Bar/Common/RelayCommand.cs b/GlazeWM.Bar/Common/RelayCommand.csdeleted file mode 100644index 627bdab9..00000000--- a/GlazeWM.Bar/Common/RelayCommand.cs+++ /dev/null@@ -1,75 +0,0 @@-using System;-using System.Windows.Input;--namespace GlazeWM.Bar.Common-{- public class RelayCommand : ICommand- {- private readonly Action _methodToExecute;- private readonly Func<bool> _canExecutePredicate;-- public event EventHandler CanExecuteChanged- {- add => CommandManager.RequerySuggested += value;- remove => CommandManager.RequerySuggested -= value;- }-- public RelayCommand(Action methodToExecute)- {- _methodToExecute = methodToExecute- ?? throw new ArgumentNullException(nameof(methodToExecute));- }-- public RelayCommand(Action methodToExecute, Func<bool> canExecutePredicate)- : this(methodToExecute)- {- _canExecutePredicate = canExecutePredicate- ?? throw new ArgumentNullException(nameof(canExecutePredicate));- }-- public bool CanExecute(object parameter)- {- return _canExecutePredicate?.Invoke() != false;- }-- public void Execute(object parameter)- {- _methodToExecute();- }- }-- public class RelayCommand<T> : ICommand- {- private readonly Action<T> _methodToExecute;- private readonly Predicate<T> _canExecutePredicate;-- public event EventHandler CanExecuteChanged- {- add => CommandManager.RequerySuggested += value;- remove => CommandManager.RequerySuggested -= value;- }-- public RelayCommand(Action<T> methodToExecute)- {- _methodToExecute = methodToExecute- ?? throw new ArgumentNullException(nameof(methodToExecute));- }-- public RelayCommand(Action<T> methodToExecute, Predicate<T> canExecutePredicate)- : this(methodToExecute)- {- _canExecutePredicate = canExecutePredicate- ?? throw new ArgumentNullException(nameof(canExecutePredicate));- }-- public bool CanExecute(object parameter)- {- return _canExecutePredicate?.Invoke((T)parameter) != false;- }-- public void Execute(object parameter)- {- _methodToExecute((T)parameter);- }- }-}diff --git a/GlazeWM.Bar/Common/ViewModelBase.cs b/GlazeWM.Bar/Common/ViewModelBase.csdeleted file mode 100644index 2f5a937a..00000000--- a/GlazeWM.Bar/Common/ViewModelBase.cs+++ /dev/null@@ -1,41 +0,0 @@-using System;-using System.Collections.Generic;-using System.ComponentModel;-using System.Runtime.CompilerServices;--namespace GlazeWM.Bar.Common-{- public class ViewModelBase : INotifyPropertyChanged, IDisposable- {- public event PropertyChangedEventHandler PropertyChanged;-- public void Dispose()- {- Dispose(true);- GC.SuppressFinalize(this);- }-- protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)- {- PropertyChanged?.Invoke(this, new(propertyName));- }-- protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)- {- if (EqualityComparer<T>.Default.Equals(field, value))- {- return false;- }-- field = value;-- OnPropertyChanged(propertyName);-- return true;- }-- protected virtual void Dispose(bool disposing)- {- }- }-}diff --git a/GlazeWM.Bar/Components/BatteryComponent.xaml b/GlazeWM.Bar/Components/BatteryComponent.xamldeleted file mode 100644index fd314bca..00000000--- a/GlazeWM.Bar/Components/BatteryComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.BatteryComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/BatteryComponent.xaml.cs b/GlazeWM.Bar/Components/BatteryComponent.xaml.csdeleted file mode 100644index a10412b2..00000000--- a/GlazeWM.Bar/Components/BatteryComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for BatteryComponent.xaml- /// </summary>- public partial class BatteryComponent : UserControl- {- public BatteryComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs b/GlazeWM.Bar/Components/BatteryComponentViewModel.csdeleted file mode 100644index 2ba5dc98..00000000--- a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs+++ /dev/null@@ -1,78 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Bar.Components-{- public class BatteryComponentViewModel : ComponentViewModel- {- private readonly BatteryComponentConfig _config;-- /// <summary>- /// Format the current power status with the user's formatting config.- /// </summary>- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public BatteryComponentViewModel(- BarViewModel parentViewModel,- BatteryComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- Observable- .Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5))- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(_ => Label = CreateLabel());- }-- public LabelViewModel CreateLabel()- {- WindowsApiService.GetSystemPowerStatus(out var ps);- var batteryLevel = ps.BatteryLifePercent.ToString(CultureInfo.InvariantCulture);-- // Display the battery level as a 100% if device has no dedicated battery.- if (ps.BatteryFlag == 128)- return XamlHelper.ParseLabel(- _config.LabelDraining,- CreateVariableDict(batteryLevel),- this- );-- if (ps.ACLineStatus == 1)- return XamlHelper.ParseLabel(- _config.LabelCharging,- CreateVariableDict(batteryLevel),- this- );-- if (ps.SystemStatusFlag == 1)- return XamlHelper.ParseLabel(- _config.LabelPowerSaver,- CreateVariableDict(batteryLevel),- this- );-- return XamlHelper.ParseLabel(- _config.LabelDraining,- CreateVariableDict(batteryLevel),- this- );- }-- public static Dictionary<string, Func<string>> CreateVariableDict(string batteryLevel)- {- return new()- {- { "battery_level", () => batteryLevel }- };- }- }-}diff --git a/GlazeWM.Bar/Components/BindingModeComponent.xaml b/GlazeWM.Bar/Components/BindingModeComponent.xamldeleted file mode 100644index f61656bf..00000000--- a/GlazeWM.Bar/Components/BindingModeComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.BindingModeComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/BindingModeComponent.xaml.cs b/GlazeWM.Bar/Components/BindingModeComponent.xaml.csdeleted file mode 100644index 81b55b76..00000000--- a/GlazeWM.Bar/Components/BindingModeComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for BindingModeComponent.xaml- /// </summary>- public partial class BindingModeComponent : UserControl- {- public BindingModeComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/BindingModeComponentViewModel.cs b/GlazeWM.Bar/Components/BindingModeComponentViewModel.csdeleted file mode 100644index 800ff603..00000000--- a/GlazeWM.Bar/Components/BindingModeComponentViewModel.cs+++ /dev/null@@ -1,62 +0,0 @@-using System;-using System.Collections.Generic;-using System.Reactive.Linq;-using GlazeWM.Domain.Common.Events;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Bar.Components-{- public class BindingModeComponentViewModel : ComponentViewModel- {- private readonly BindingModeComponentConfig _config;- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();-- /// <summary>- /// Name of the currently active binding mode (if one is active).- /// </summary>- public string ActiveBindingMode => _containerService.ActiveBindingMode;-- /// <summary>- /// Hide component when no binding mode is active.- /// </summary>- public override string Visibility =>- ActiveBindingMode is null ? "Collapsed" : "Visible";-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public BindingModeComponentViewModel(- BarViewModel parentViewModel,- BindingModeComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- _bus.Events.OfType<BindingModeChangedEvent>()- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((@event) =>- {- OnPropertyChanged(nameof(Visibility));- Label = CreateLabel(@event.NewBindingMode);- });- }-- private LabelViewModel CreateLabel(string bindingMode)- {- var variableDictionary = new Dictionary<string, Func<string>>()- {- { "binding_mode", () => bindingMode }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }- }-}diff --git a/GlazeWM.Bar/Components/ClockComponent.xaml b/GlazeWM.Bar/Components/ClockComponent.xamldeleted file mode 100644index 23a523fd..00000000--- a/GlazeWM.Bar/Components/ClockComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.ClockComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/ClockComponent.xaml.cs b/GlazeWM.Bar/Components/ClockComponent.xaml.csdeleted file mode 100644index 1c4b3c59..00000000--- a/GlazeWM.Bar/Components/ClockComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for ClockComponent.xaml- /// </summary>- public partial class ClockComponent : UserControl- {- public ClockComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/ClockComponentViewModel.cs b/GlazeWM.Bar/Components/ClockComponentViewModel.csdeleted file mode 100644index 0fe8e117..00000000--- a/GlazeWM.Bar/Components/ClockComponentViewModel.cs+++ /dev/null@@ -1,94 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using System.Text;-using GlazeWM.Domain.UserConfigs;--namespace GlazeWM.Bar.Components-{- public class ClockComponentViewModel : ComponentViewModel- {- private readonly ClockComponentConfig _config;- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public ClockComponentViewModel(- BarViewModel parentViewModel,- ClockComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- // Update the displayed time every second.- var updateInterval = TimeSpan.FromSeconds(1);-- Observable- .Interval(updateInterval)- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(_ => Label = CreateLabel());- }-- private LabelViewModel CreateLabel()- {- var timeFormatting = FormatCalendarWeek(_config.TimeFormatting);-- // Format the current time with the user's formatting config.- var formattedTime = DateTime.Now.ToString(timeFormatting, CultureInfo.InvariantCulture);-- var variableDictionary = new Dictionary<string, Func<string>>()- {- { "formatted_time", () => formattedTime }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }-- private static string FormatCalendarWeek(string timeFormat)- {- if (!timeFormat.Contains('w'))- return timeFormat;-- var now = DateTime.Now;- var i = 0;- var result = new StringBuilder();-- while (i < timeFormat.Length)- {- var nextChar = i + 1 < timeFormat.Length ? timeFormat[i + 1].ToString() : "";- switch (timeFormat[i])- {- case '\\':- result.Append(timeFormat[i])- .Append(nextChar);- i += 2;- break;-- case 'w':- if (nextChar.Equals("w", StringComparison.Ordinal))- {- i += 2;- result.Append(- ISOWeek.GetWeekOfYear(now).ToString("00", CultureInfo.InvariantCulture)- );- }- else- {- i++;- result.Append(ISOWeek.GetWeekOfYear(now));- }- break;-- default:- result.Append(timeFormat[i]);- i++;- break;- }- }- return result.ToString();- }- }-}diff --git a/GlazeWM.Bar/Components/ComponentPortal.xaml b/GlazeWM.Bar/Components/ComponentPortal.xamldeleted file mode 100644index 13d3e463..00000000--- a/GlazeWM.Bar/Components/ComponentPortal.xaml+++ /dev/null@@ -1,109 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.ComponentPortal"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <Grid- Visibility="{Binding Visibility}"- Margin="{Binding Margin}">- <Border- CornerRadius="{Binding BorderRadius}"- BorderThickness="{Binding BorderWidth}"- BorderBrush="{Binding BorderColor}">- <Grid>- <ContentPresenter Content="{Binding .}">- <ContentPresenter.Resources>- <DataTemplate DataType="{x:Type components:BatteryComponentViewModel}">- <components:BatteryComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:BindingModeComponentViewModel}">- <components:BindingModeComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:ClockComponentViewModel}">- <components:ClockComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:TextComponentViewModel}">- <components:TextComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:NetworkComponentViewModel}">- <components:NetworkComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:WindowTitleComponentViewModel}">- <components:WindowTitleComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:SystemTrayComponentViewModel}">- <components:SystemTrayComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:TilingDirectionComponentViewModel}">- <components:TilingDirectionComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:WorkspacesComponentViewModel}">- <components:WorkspacesComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:ImageComponentViewModel}">- <components:ImageComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:CpuComponentViewModel}">- <components:CpuComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:GpuComponentViewModel}">- <components:GpuComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:MemoryComponentViewModel}">- <components:MemoryComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:TextFileComponentViewModel}">- <components:TextFileComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:WeatherComponentViewModel}">- <components:WeatherComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:VolumeComponentViewModel}">- <components:VolumeComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- <DataTemplate DataType="{x:Type components:MusicComponentViewModel}">- <components:MusicComponent- Padding="{Binding Padding}"- Background="{Binding Background}" />- </DataTemplate>- </ContentPresenter.Resources>- </ContentPresenter>- </Grid>- </Border>- </Grid>-</UserControl>diff --git a/GlazeWM.Bar/Components/ComponentPortal.xaml.cs b/GlazeWM.Bar/Components/ComponentPortal.xaml.csdeleted file mode 100644index 134e515c..00000000--- a/GlazeWM.Bar/Components/ComponentPortal.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for ComponentPortal.xaml- /// </summary>- public partial class ComponentPortal : UserControl- {- public ComponentPortal()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/ComponentViewModel.cs b/GlazeWM.Bar/Components/ComponentViewModel.csdeleted file mode 100644index ff709fe9..00000000--- a/GlazeWM.Bar/Components/ComponentViewModel.cs+++ /dev/null@@ -1,34 +0,0 @@-using GlazeWM.Bar.Common;-using GlazeWM.Domain.UserConfigs;--namespace GlazeWM.Bar.Components-{- public abstract class ComponentViewModel : ViewModelBase- {- protected readonly BarViewModel _parentViewModel;- protected readonly BarComponentConfig _componentConfig;-- public virtual string Visibility { get; set; } = "Visible";- public string Background => XamlHelper.FormatColor(_componentConfig.Background);- public string Foreground =>- XamlHelper.FormatColor(_componentConfig.Foreground ?? _parentViewModel.Foreground);- public string FontFamily =>- _componentConfig.FontFamily ?? _parentViewModel.FontFamily;- public string FontWeight =>- _componentConfig.FontWeight ?? _parentViewModel.FontWeight;- public string FontSize =>- XamlHelper.FormatSize(_componentConfig.FontSize ?? _parentViewModel.FontSize);- public string BorderColor => XamlHelper.FormatColor(_componentConfig.BorderColor);- public string BorderWidth =>- XamlHelper.FormatRectShorthand(_componentConfig.BorderWidth);- public string BorderRadius => XamlHelper.FormatSize(_componentConfig.BorderRadius);- public string Padding => XamlHelper.FormatRectShorthand(_componentConfig.Padding);- public string Margin => XamlHelper.FormatRectShorthand(_componentConfig.Margin);-- protected ComponentViewModel(BarViewModel parentViewModel, BarComponentConfig baseConfig)- {- _parentViewModel = parentViewModel;- _componentConfig = baseConfig;- }- }-}diff --git a/GlazeWM.Bar/Components/CpuComponent.xaml b/GlazeWM.Bar/Components/CpuComponent.xamldeleted file mode 100644index cec71c2a..00000000--- a/GlazeWM.Bar/Components/CpuComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.CpuComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/CpuComponent.xaml.cs b/GlazeWM.Bar/Components/CpuComponent.xaml.csdeleted file mode 100644index 020ce530..00000000--- a/GlazeWM.Bar/Components/CpuComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for CpuComponent.xaml- /// </summary>- public partial class CpuComponent : UserControl- {- public CpuComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/CpuComponentViewModel.cs b/GlazeWM.Bar/Components/CpuComponentViewModel.csdeleted file mode 100644index 5abb143c..00000000--- a/GlazeWM.Bar/Components/CpuComponentViewModel.cs+++ /dev/null@@ -1,51 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Bar.Components-{- public class CpuComponentViewModel : ComponentViewModel- {- private readonly CpuComponentConfig _config;- private readonly CpuStatsService _cpuStatsService;-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public CpuComponentViewModel(- BarViewModel parentViewModel,- CpuComponentConfig config) : base(parentViewModel, config)- {- _config = config;- _cpuStatsService = ServiceLocator.GetRequiredService<CpuStatsService>();-- Observable.Timer(- TimeSpan.Zero,- TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((_) => Label = CreateLabel());- }-- private LabelViewModel CreateLabel()- {- var variableDictionary = new Dictionary<string, Func<string>>()- {- {- "percent_usage",- () => _cpuStatsService.GetCpuUsage().ToString("0", CultureInfo.InvariantCulture)- }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }- }-}diff --git a/GlazeWM.Bar/Components/GpuComponent.xaml b/GlazeWM.Bar/Components/GpuComponent.xamldeleted file mode 100644index 72234924..00000000--- a/GlazeWM.Bar/Components/GpuComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.GpuComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/GpuComponent.xaml.cs b/GlazeWM.Bar/Components/GpuComponent.xaml.csdeleted file mode 100644index 3d47bd15..00000000--- a/GlazeWM.Bar/Components/GpuComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for GpuComponent.xaml- /// </summary>- public partial class GpuComponent : UserControl- {- public GpuComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/GpuComponentViewModel.cs b/GlazeWM.Bar/Components/GpuComponentViewModel.csdeleted file mode 100644index 1fca9386..00000000--- a/GlazeWM.Bar/Components/GpuComponentViewModel.cs+++ /dev/null@@ -1,54 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Bar.Components-{- public class GpuComponentViewModel : ComponentViewModel- {- private readonly GpuComponentConfig _config;- private readonly GpuStatsService _gpuStatsService;-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public GpuComponentViewModel(- BarViewModel parentViewModel,- GpuComponentConfig config) : base(parentViewModel, config)- {- _config = config;- _gpuStatsService = ServiceLocator.GetRequiredService<GpuStatsService>();-- Observable.Timer(- TimeSpan.Zero,- TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((_) => Label = CreateLabel());- }-- private LabelViewModel CreateLabel()- {- var variableDictionary = new Dictionary<string, Func<string>>()- {- {- "percent_usage",- () =>- _gpuStatsService- .GetAverageLoadPercent(GpuPerformanceCategoryFlags.Graphics)- .ToString("0", CultureInfo.InvariantCulture)- }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }- }-}diff --git a/GlazeWM.Bar/Components/ImageComponent.xaml b/GlazeWM.Bar/Components/ImageComponent.xamldeleted file mode 100644index fa3e37fd..00000000--- a/GlazeWM.Bar/Components/ImageComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.ImageComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <Image Source="{Binding Source}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/ImageComponent.xaml.cs b/GlazeWM.Bar/Components/ImageComponent.xaml.csdeleted file mode 100644index 55aa005b..00000000--- a/GlazeWM.Bar/Components/ImageComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for ImageComponent.xaml- /// </summary>- public partial class ImageComponent : UserControl- {- public ImageComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/ImageComponentViewModel.cs b/GlazeWM.Bar/Components/ImageComponentViewModel.csdeleted file mode 100644index 3f8910a3..00000000--- a/GlazeWM.Bar/Components/ImageComponentViewModel.cs+++ /dev/null@@ -1,17 +0,0 @@-using GlazeWM.Domain.UserConfigs;--namespace GlazeWM.Bar.Components-{- public class ImageComponentViewModel : ComponentViewModel- {- private ImageComponentConfig _config => _componentConfig as ImageComponentConfig;-- public string Source => _config.Source;-- public ImageComponentViewModel(- BarViewModel parentViewModel,- ImageComponentConfig config) : base(parentViewModel, config)- {- }- }-}diff --git a/GlazeWM.Bar/Components/LabelComponent.xaml b/GlazeWM.Bar/Components/LabelComponent.xamldeleted file mode 100644index 94040d2d..00000000--- a/GlazeWM.Bar/Components/LabelComponent.xaml+++ /dev/null@@ -1,26 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.LabelComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- mc:Ignorable="d">- <ItemsControl ItemsSource="{Binding Spans}">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <StackPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>- <ItemsControl.ItemTemplate>- <DataTemplate>- <TextBlock- Text="{Binding Text}"- VerticalAlignment="Center"- Foreground="{Binding Foreground}"- FontFamily="{Binding FontFamily}"- FontWeight="{Binding FontWeight}"- FontSize="{Binding FontSize}" />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>-</UserControl>diff --git a/GlazeWM.Bar/Components/LabelComponent.xaml.cs b/GlazeWM.Bar/Components/LabelComponent.xaml.csdeleted file mode 100644index 2a385590..00000000--- a/GlazeWM.Bar/Components/LabelComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for LabelComponent.xaml- /// </summary>- public partial class LabelComponent : UserControl- {- public LabelComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/LabelSpan.cs b/GlazeWM.Bar/Components/LabelSpan.csdeleted file mode 100644index 72d7ef54..00000000--- a/GlazeWM.Bar/Components/LabelSpan.cs+++ /dev/null@@ -1,25 +0,0 @@-namespace GlazeWM.Bar.Components-{- public class LabelSpan- {- public string Text { get; }- public string Foreground { get; }- public string FontFamily { get; }- public string FontWeight { get; }- public string FontSize { get; }-- public LabelSpan(- string text,- string foreground,- string fontFamily,- string fontWeight,- string fontSize)- {- Text = text;- Foreground = foreground;- FontFamily = fontFamily;- FontWeight = fontWeight;- FontSize = fontSize;- }- }-}diff --git a/GlazeWM.Bar/Components/LabelViewModel.cs b/GlazeWM.Bar/Components/LabelViewModel.csdeleted file mode 100644index 11bca6ba..00000000--- a/GlazeWM.Bar/Components/LabelViewModel.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Collections.Generic;-using GlazeWM.Bar.Common;--namespace GlazeWM.Bar.Components-{- public class LabelViewModel : ViewModelBase- {- public List<LabelSpan> Spans { get; }-- public LabelViewModel(List<LabelSpan> spans)- {- Spans = spans;- }- }-}diff --git a/GlazeWM.Bar/Components/MemoryComponent.xaml b/GlazeWM.Bar/Components/MemoryComponent.xamldeleted file mode 100644index 5a007621..00000000--- a/GlazeWM.Bar/Components/MemoryComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.MemoryComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/MemoryComponent.xaml.cs b/GlazeWM.Bar/Components/MemoryComponent.xaml.csdeleted file mode 100644index 106fcd11..00000000--- a/GlazeWM.Bar/Components/MemoryComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for MemoryComponent.xaml- /// </summary>- public partial class MemoryComponent : UserControl- {- public MemoryComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/MemoryComponentViewModel.cs b/GlazeWM.Bar/Components/MemoryComponentViewModel.csdeleted file mode 100644index 49383639..00000000--- a/GlazeWM.Bar/Components/MemoryComponentViewModel.cs+++ /dev/null@@ -1,51 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Bar.Components-{- public class MemoryComponentViewModel : ComponentViewModel- {- private readonly MemoryComponentConfig _config;- private readonly MemoryStatsService _memoryStatsService;-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public MemoryComponentViewModel(- BarViewModel parentViewModel,- MemoryComponentConfig config) : base(parentViewModel, config)- {- _config = config;- _memoryStatsService = ServiceLocator.GetRequiredService<MemoryStatsService>();-- Observable.Timer(- TimeSpan.Zero,- TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((_) => Label = CreateLabel());- }-- private LabelViewModel CreateLabel()- {- var variableDictionary = new Dictionary<string, Func<string>>()- {- {- "percent_usage",- () => _memoryStatsService.GetMemoryUsage().ToString("0", CultureInfo.InvariantCulture)- }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }- }-}diff --git a/GlazeWM.Bar/Components/MusicComponent.xaml b/GlazeWM.Bar/Components/MusicComponent.xamldeleted file mode 100644index 51710d60..00000000--- a/GlazeWM.Bar/Components/MusicComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.MusicComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/MusicComponent.xaml.cs b/GlazeWM.Bar/Components/MusicComponent.xaml.csdeleted file mode 100644index eb0b03e0..00000000--- a/GlazeWM.Bar/Components/MusicComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for MusicComponent.xaml- /// </summary>- public partial class MusicComponent : UserControl- {- public MusicComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/MusicComponentViewModel.cs b/GlazeWM.Bar/Components/MusicComponentViewModel.csdeleted file mode 100644index 77b0ea1f..00000000--- a/GlazeWM.Bar/Components/MusicComponentViewModel.cs+++ /dev/null@@ -1,122 +0,0 @@-using System;-using System.Collections.Generic;-using GlazeWM.Domain.UserConfigs;-using Windows.Media.Control;-using WindowsMediaController;--namespace GlazeWM.Bar.Components-{- public class MusicComponentViewModel : ComponentViewModel- {- private readonly MusicComponentConfig _config;- private static MediaManager mediaManager;- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }- public struct SongSession- {- public SongSession(GlobalSystemMediaTransportControlsSessionPlaybackStatus musicStatus, string songTitle, string artistName)- {- SongTitle = songTitle;- ArtistName = artistName;- MusicStatus = musicStatus;- }- public string SongTitle { get; set; }- public string ArtistName { get; set; }- public GlobalSystemMediaTransportControlsSessionPlaybackStatus MusicStatus { get; set; }- }- private readonly Dictionary<string, SongSession> songSessionDict;- public MusicComponentViewModel(- BarViewModel parentViewModel,- MusicComponentConfig config) : base(parentViewModel, config)- {- songSessionDict = new Dictionary<string, SongSession>();- _config = config;- mediaManager = new MediaManager();- mediaManager.OnAnyMediaPropertyChanged += (session, args) => MusicTitleChanged(session.Id, args.Artist, args.Title);- mediaManager.OnAnyPlaybackStateChanged += (session, args) => PlaybackStateChanged(session.Id, args.PlaybackStatus);- mediaManager.OnAnySessionOpened += (session) => OpenedSession(session.Id);- mediaManager.OnAnySessionClosed += (session) => ClosedSession(session.Id);- mediaManager.Start();- }- private string GetLabel(GlobalSystemMediaTransportControlsSessionPlaybackStatus musicStatus)- {- return musicStatus switch- {- GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing => _config.LabelPlaying,- GlobalSystemMediaTransportControlsSessionPlaybackStatus.Paused => _config.LabelPaused,- _ => _config.LabelNotPlaying,- };- }- private void MusicTitleChanged(string sessionId, string artistName, string songTitle)- {- var session = songSessionDict[sessionId];- session.ArtistName = artistName;- session.SongTitle = songTitle;- songSessionDict[sessionId] = session;- Label = CreateLabel();- }- private void PlaybackStateChanged(string sessionId, GlobalSystemMediaTransportControlsSessionPlaybackStatus status)- {- var session = songSessionDict[sessionId];- session.MusicStatus = status;- songSessionDict[sessionId] = session;- Label = CreateLabel();- }- private void OpenedSession(string sessionId)- {- var session = new SongSession(GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing, "", "");- songSessionDict.Add(sessionId, session);- }- private void ClosedSession(string sessionId)- {- songSessionDict.Remove(sessionId);- Label = CreateLabel();- }- private LabelViewModel CreateLabel()- {- var label = _config.LabelNotPlaying;- var variableDictionary = new Dictionary<string, Func<string>>()- {- {- "song_title", () => ""- },- {- "artist_name", () => ""- }- };-- foreach (var session in songSessionDict)- {- var title = Truncate(session.Value.SongTitle, _config.MaxTitleLength);- var artist = Truncate(session.Value.ArtistName, _config.MaxArtistLength);- if (GetLabel(session.Value.MusicStatus) == _config.LabelPaused && label != _config.LabelPlaying)- {- label = _config.LabelPaused;- variableDictionary["song_title"] = () => title;- variableDictionary["artist_name"] = () => artist;- }- else if (GetLabel(session.Value.MusicStatus) == _config.LabelPlaying)- {- label = _config.LabelPlaying;- variableDictionary["song_title"] = () => title;- variableDictionary["artist_name"] = () => artist;- }- }- return XamlHelper.ParseLabel(- label,- variableDictionary,- this- );- }- public static string Truncate(string value, int maxLength, string truncationSuffix = "…")- {- return value?.Length > maxLength && maxLength >= 0- ? string.Concat(value.AsSpan(0, maxLength), truncationSuffix)- : value;- }- }-}diff --git a/GlazeWM.Bar/Components/NetworkComponent.xaml b/GlazeWM.Bar/Components/NetworkComponent.xamldeleted file mode 100644index 8d88f465..00000000--- a/GlazeWM.Bar/Components/NetworkComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.NetworkComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/NetworkComponent.xaml.cs b/GlazeWM.Bar/Components/NetworkComponent.xaml.csdeleted file mode 100644index d8991165..00000000--- a/GlazeWM.Bar/Components/NetworkComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for NetworkComponent.xaml- /// </summary>- public partial class NetworkComponent : UserControl- {- public NetworkComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/NetworkComponentViewModel.cs b/GlazeWM.Bar/Components/NetworkComponentViewModel.csdeleted file mode 100644index e7c770e3..00000000--- a/GlazeWM.Bar/Components/NetworkComponentViewModel.cs+++ /dev/null@@ -1,86 +0,0 @@-using System;-using System.Collections.Generic;-using System.Net.NetworkInformation;-using System.Reactive.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.WindowsApi;-using static Vanara.PInvoke.IpHlpApi;--namespace GlazeWM.Bar.Components-{- public class NetworkComponentViewModel : ComponentViewModel- {- private NetworkComponentConfig _config => _componentConfig as NetworkComponentConfig;-- /// <summary>- /// Format the current power status with the user's formatting config.- /// </summary>- private LabelViewModel _label;-- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- private string getNetworkIcon()- {- var primaryAdapter = NetworkService.GetPrimaryAdapter();- switch (primaryAdapter.IfType)- {- case IFTYPE.IF_TYPE_ETHERNET_CSMACD:- case IFTYPE.IF_TYPE_ETHERNET_3MBIT:- // Primary adapter is using ethernet.- return _config.LabelEthernet;- case IFTYPE.IF_TYPE_IEEE80211:- // Primary adapter is using wifi.- var rssi = NetworkService.GetWlanRSSI();- return assignWifiIcon(rssi);- default:- return _config.LabelNoInternet;- }- }-- private string assignWifiIcon(int signalQuality)- {- // Round to nearest multiple and assign icon.- return ((signalQuality % 25) > (25 / 2) ? (signalQuality / 25) + 1 : signalQuality / 25) switch- {- 0 => _config.LabelWifiStrength0,- 1 => _config.LabelWifiStrength25,- 2 => _config.LabelWifiStrength50,- 3 => _config.LabelWifiStrength75,- 4 => _config.LabelWifiStrength100,- _ => _config.LabelNoInternet,- };- }-- public NetworkComponentViewModel(- BarViewModel parentViewModel,- NetworkComponentConfig config) : base(parentViewModel, config)- {- Observable- .Interval(TimeSpan.FromSeconds(10))- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(_ => Label = CreateLabel());-- NetworkChange.NetworkAddressChanged +=- (s, e) => Label = CreateLabel();- }-- public LabelViewModel CreateLabel()- {- string icon;- if (!NetworkService.PingTest())- icon = _config.LabelNoInternet;- else- icon = getNetworkIcon();-- return XamlHelper.ParseLabel(- icon,- null,- this- );- }- }-}diff --git a/GlazeWM.Bar/Components/NotifyIcon.xaml b/GlazeWM.Bar/Components/NotifyIcon.xamldeleted file mode 100644index 9d375b90..00000000--- a/GlazeWM.Bar/Components/NotifyIcon.xaml+++ /dev/null@@ -1,48 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.NotifyIcon"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- xmlns:i="http://schemas.microsoft.com/xaml/behaviors">- <UserControl.Resources>- <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />- </UserControl.Resources>- <Border- x:Name="NotifyIconBorder"- ToolTip="{Binding Path=TrayIcon.Title}">- <Image- Margin="1,0"- Source="{Binding Path=TrayIcon.Icon, Mode=OneWay}"- Focusable="True"- Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"- Name="NotifyIconImage">- <i:Interaction.Triggers>- <i:EventTrigger EventName="MouseUp">- <i:InvokeCommandAction- Command="{Binding OnMouseUpCommand}"- PassEventArgsToCommand="True" />- </i:EventTrigger>- <i:EventTrigger EventName="MouseDown">- <i:InvokeCommandAction- Command="{Binding OnMouseDownCommand}"- PassEventArgsToCommand="True" />- </i:EventTrigger>- <i:EventTrigger EventName="MouseEnter">- <i:InvokeCommandAction- Command="{Binding OnMouseEnterCommand}"- PassEventArgsToCommand="True" />- </i:EventTrigger>- <i:EventTrigger EventName="MouseLeave">- <i:InvokeCommandAction- Command="{Binding OnMouseLeaveCommand}"- PassEventArgsToCommand="True" />- </i:EventTrigger>- <i:EventTrigger EventName="MouseMove">- <i:InvokeCommandAction- Command="{Binding OnMouseMoveCommand}"- PassEventArgsToCommand="True" />- </i:EventTrigger>- </i:Interaction.Triggers>- </Image>- </Border>-</UserControl>diff --git a/GlazeWM.Bar/Components/NotifyIcon.xaml.cs b/GlazeWM.Bar/Components/NotifyIcon.xaml.csdeleted file mode 100644index af0280ba..00000000--- a/GlazeWM.Bar/Components/NotifyIcon.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for NotifyIcon.xaml- /// </summary>- public partial class NotifyIcon : UserControl- {- public NotifyIcon()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/NotifyIconViewModel.cs b/GlazeWM.Bar/Components/NotifyIconViewModel.csdeleted file mode 100644index 35e08d9a..00000000--- a/GlazeWM.Bar/Components/NotifyIconViewModel.cs+++ /dev/null@@ -1,99 +0,0 @@-using System.Windows;-using System.Windows.Controls;-using System.Windows.Input;-using GlazeWM.Bar.Common;-using ManagedShell.Common.Helpers;-using ManagedShell.Interop;--namespace GlazeWM.Bar.Components-{- public class NotifyIconViewModel : ViewModelBase- {- public ManagedShell.WindowsTray.NotifyIcon TrayIcon { get; set; }- // Hide native tray icons- public bool IsVisible => !TrayIcon.Path.Contains("\\Windows\\explorer.exe");- public ICommand OnMouseUpCommand =>- new RelayCommand<MouseButtonEventArgs>(OnMouseUp);- public ICommand OnMouseDownCommand =>- new RelayCommand<MouseButtonEventArgs>(OnMouseDown);- public ICommand OnMouseEnterCommand => new RelayCommand<MouseEventArgs>(OnMouseEnter);- public ICommand OnMouseLeaveCommand => new RelayCommand<MouseEventArgs>(OnMouseLeave);- public ICommand OnMouseMoveCommand => new RelayCommand<MouseEventArgs>(OnMouseMove);-- public NotifyIconViewModel(ManagedShell.WindowsTray.NotifyIcon trayIcon)- {- TrayIcon = trayIcon;- }-- private void OnMouseDown(MouseButtonEventArgs e)- {- e.Handled = true;-- if (!Keyboard.IsKeyDown(Key.LeftAlt))- TrayIcon.IconMouseDown(- e.ChangedButton,- MouseHelper.GetCursorPositionParam(),- System.Windows.Forms.SystemInformation.DoubleClickTime- );- }-- private void OnMouseUp(MouseButtonEventArgs e)- {- e.Handled = true;-- if (Keyboard.IsKeyDown(Key.LeftAlt))- {- if (TrayIcon.IsPinned)- {- TrayIcon.Unpin();- return;- }-- TrayIcon.Pin();- return;- }-- TrayIcon.IconMouseUp(- e.ChangedButton,- MouseHelper.GetCursorPositionParam(),- System.Windows.Forms.SystemInformation.DoubleClickTime- );- }-- private void OnMouseEnter(MouseEventArgs e)- {- e.Handled = true;-- // Update icon position for `Shell_NotifyIconGetRect`.- var eventSource = e.Source as Image;- var location = eventSource.PointToScreen(new Point(0, 0));- var dpiScale = PresentationSource- .FromVisual(eventSource)- .CompositionTarget- .TransformToDevice- .M11;-- TrayIcon.Placement = new NativeMethods.Rect- {- Top = (int)location.Y,- Left = (int)location.X,- Bottom = (int)(eventSource.ActualHeight * dpiScale),- Right = (int)(eventSource.ActualWidth * dpiScale)- };-- TrayIcon.IconMouseEnter(MouseHelper.GetCursorPositionParam());- }-- private void OnMouseLeave(MouseEventArgs e)- {- e.Handled = true;- TrayIcon.IconMouseLeave(MouseHelper.GetCursorPositionParam());- }-- private void OnMouseMove(MouseEventArgs e)- {- e.Handled = true;- TrayIcon.IconMouseMove(MouseHelper.GetCursorPositionParam());- }- }-}diff --git a/GlazeWM.Bar/Components/SystemTrayComponent.xaml b/GlazeWM.Bar/Components/SystemTrayComponent.xamldeleted file mode 100644index 91a1901b..00000000--- a/GlazeWM.Bar/Components/SystemTrayComponent.xaml+++ /dev/null@@ -1,66 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.SystemTrayComponent"- x:Name="_workspacesComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- xmlns:i="http://schemas.microsoft.com/xaml/behaviors"- mc:Ignorable="d">- <UserControl.Resources>- <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />- </UserControl.Resources>- <StackPanel Orientation="Horizontal">- <components:LabelComponent- DataContext="{Binding Label}"- MouseEnter="OnLabelHoverEnter"- MouseLeave="OnLabelHoverLeave">- <i:Interaction.Triggers>- <i:EventTrigger EventName="MouseLeftButtonUp">- <i:CallMethodAction- MethodName="ToggleShowAllIcons"- TargetObject="{Binding Path=DataContext, ElementName=_workspacesComponent, Mode=OneWay}" />- </i:EventTrigger>- </i:Interaction.Triggers>- </components:LabelComponent>- <Border- x:Name="NotifyIconBorder"- ToolTip="{Binding Path=TrayIcon.Title}"- Visibility="{Binding Path=IsExpanded, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}">- <ItemsControl- Focusable="False"- ItemsSource="{Binding UnpinnedTrayIcons}"- HorizontalAlignment="Center"- VerticalAlignment="Center">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <WrapPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>- <ItemsControl.ItemTemplate>- <DataTemplate>- <local:NotifyIcon Cursor="Hand" />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </Border>- <ItemsControl- Focusable="False"- ItemsSource="{Binding PinnedTrayIcons}"- HorizontalAlignment="Center"- VerticalAlignment="Center">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <WrapPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>- <ItemsControl.ItemTemplate>- <DataTemplate>- <local:NotifyIcon Cursor="Hand" />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </StackPanel>-</UserControl>diff --git a/GlazeWM.Bar/Components/SystemTrayComponent.xaml.cs b/GlazeWM.Bar/Components/SystemTrayComponent.xaml.csdeleted file mode 100644index d8b3ee54..00000000--- a/GlazeWM.Bar/Components/SystemTrayComponent.xaml.cs+++ /dev/null@@ -1,26 +0,0 @@-using System.Windows.Controls;-using System.Windows.Input;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for SystemTrayComponent.xaml- /// </summary>- public partial class SystemTrayComponent : UserControl- {- public SystemTrayComponent()- {- InitializeComponent();- }-- public void OnLabelHoverEnter(object sender, MouseEventArgs e)- {- Cursor = Cursors.Hand;- }-- public void OnLabelHoverLeave(object sender, MouseEventArgs e)- {- Cursor = Cursors.Arrow;- }- }-}diff --git a/GlazeWM.Bar/Components/SystemTrayComponentViewModel.cs b/GlazeWM.Bar/Components/SystemTrayComponentViewModel.csdeleted file mode 100644index 1d6766c9..00000000--- a/GlazeWM.Bar/Components/SystemTrayComponentViewModel.cs+++ /dev/null@@ -1,70 +0,0 @@-using System;-using System.Collections.Generic;-using System.Collections.ObjectModel;-using System.Diagnostics;-using System.Linq;-using System.Windows.Input;-using GlazeWM.Bar.Common;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using ManagedShell;--namespace GlazeWM.Bar.Components-{- public class SystemTrayComponentViewModel : ComponentViewModel- {- private readonly SystemTrayComponentConfig _config;-- private readonly ShellManager _shellManager =- ServiceLocator.GetRequiredService<ShellManager>();-- private bool _isExpanded = true;- public bool IsExpanded- {- get => _isExpanded;- set- {- _isExpanded = value;- OnPropertyChanged(nameof(IsExpanded));- }- }-- public LabelViewModel Label => IsExpanded- ? XamlHelper.ParseLabel(_config.LabelCollapseText, new Dictionary<string, Func<string>>(), this)- : XamlHelper.ParseLabel(_config.LabelExpandText, new Dictionary<string, Func<string>>(), this);-- public ObservableCollection<NotifyIconViewModel> PinnedTrayIcons =>- new(_pinnedTrayIcons);- public ObservableCollection<NotifyIconViewModel> UnpinnedTrayIcons =>- new(_unpinnedTrayIcons);-- private IEnumerable<NotifyIconViewModel> _pinnedTrayIcons =>- _shellManager.NotificationArea.PinnedIcons- .Cast<ManagedShell.WindowsTray.NotifyIcon>()- .Select(trayIcon => new NotifyIconViewModel(trayIcon));-- private IEnumerable<NotifyIconViewModel> _unpinnedTrayIcons =>- _shellManager.NotificationArea.UnpinnedIcons- .Cast<ManagedShell.WindowsTray.NotifyIcon>()- .Select(trayIcon => new NotifyIconViewModel(trayIcon));-- public SystemTrayComponentViewModel(- BarViewModel parentViewModel,- SystemTrayComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- // Subscribe to collection changes of pinned/unpinned tray icons.- _shellManager.NotificationArea.UnpinnedIcons.CollectionChanged +=- (_, _) => OnPropertyChanged(nameof(UnpinnedTrayIcons));- _shellManager.NotificationArea.PinnedIcons.CollectionChanged +=- (_, _) => OnPropertyChanged(nameof(PinnedTrayIcons));- }-- public void ToggleShowAllIcons()- {- IsExpanded = !IsExpanded;- OnPropertyChanged(nameof(Label));- }- }-}diff --git a/GlazeWM.Bar/Components/TextComponent.xaml b/GlazeWM.Bar/Components/TextComponent.xamldeleted file mode 100644index 2af22ac9..00000000--- a/GlazeWM.Bar/Components/TextComponent.xaml+++ /dev/null@@ -1,21 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.TextComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <TextBlock- VerticalAlignment="Center"- Foreground="{Binding Foreground}"- FontFamily="{Binding FontFamily}"- FontWeight="{Binding FontWeight}"- FontSize="{Binding FontSize}"- Text="{Binding Text}">- <TextBlock.InputBindings>- <MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}" />- <MouseBinding Gesture="RightClick" Command="{Binding RightClickCommand}" />- </TextBlock.InputBindings>- </TextBlock>-</UserControl>diff --git a/GlazeWM.Bar/Components/TextComponent.xaml.cs b/GlazeWM.Bar/Components/TextComponent.xaml.csdeleted file mode 100644index 07a4b93e..00000000--- a/GlazeWM.Bar/Components/TextComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for TextComponent.xaml- /// </summary>- public partial class TextComponent : UserControl- {- public TextComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/TextComponentViewModel.cs b/GlazeWM.Bar/Components/TextComponentViewModel.csdeleted file mode 100644index 975d1d86..00000000--- a/GlazeWM.Bar/Components/TextComponentViewModel.cs+++ /dev/null@@ -1,56 +0,0 @@-using System.Windows.Input;-using GlazeWM.Bar.Common;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Bar.Components-{- public class TextComponentViewModel : ComponentViewModel- {- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();- private readonly CommandParsingService _commandParsingService =- ServiceLocator.GetRequiredService<CommandParsingService>();- private TextComponentConfig _config => _componentConfig as TextComponentConfig;-- public string Text => _config.Text;-- public ICommand LeftClickCommand => new RelayCommand(OnLeftClick);- public ICommand RightClickCommand => new RelayCommand(OnRightClick);-- public TextComponentViewModel(- BarViewModel parentViewModel,- TextComponentConfig config) : base(parentViewModel, config)- {- }-- public void OnLeftClick()- {- InvokeCommand(_config.LeftClickCommand);- }-- public void OnRightClick()- {- InvokeCommand(_config.RightClickCommand);- }-- private void InvokeCommand(string commandString)- {- if (string.IsNullOrEmpty(commandString))- return;-- var subjectContainer = _containerService.FocusedContainer;-- var parsedCommand = _commandParsingService.ParseCommand(- commandString,- subjectContainer- );-- // Use `dynamic` to resolve the command type at runtime and allow multiple dispatch.- _bus.Invoke((dynamic)parsedCommand);- }- }-}diff --git a/GlazeWM.Bar/Components/TextFileComponent.xaml b/GlazeWM.Bar/Components/TextFileComponent.xamldeleted file mode 100644index 9575773f..00000000--- a/GlazeWM.Bar/Components/TextFileComponent.xaml+++ /dev/null@@ -1,17 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.TextFileComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <TextBlock- VerticalAlignment="Center"- Foreground="{Binding Foreground}"- FontFamily="{Binding FontFamily}"- FontWeight="{Binding FontWeight}"- FontSize="{Binding FontSize}"- Text="{Binding Text}">- </TextBlock>-</UserControl>diff --git a/GlazeWM.Bar/Components/TextFileComponent.xaml.cs b/GlazeWM.Bar/Components/TextFileComponent.xaml.csdeleted file mode 100644index 0baa7f37..00000000--- a/GlazeWM.Bar/Components/TextFileComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for TextFileComponent.xaml- /// </summary>- public partial class TextFileComponent : UserControl- {- public TextFileComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/TextFileComponentViewModel.cs b/GlazeWM.Bar/Components/TextFileComponentViewModel.csdeleted file mode 100644index f4c0c22f..00000000--- a/GlazeWM.Bar/Components/TextFileComponentViewModel.cs+++ /dev/null@@ -1,85 +0,0 @@-using System;-using System.IO;-using System.Reactive.Linq;-using System.Threading;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.Events;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Bar.Components-{- public class TextFileComponentViewModel : ComponentViewModel- {- private readonly TextFileComponentConfig _baseConfig;- private readonly IDisposable _disposable;-- public string Text { get; set; } = "Loading...";-- public FileSystemWatcher Watcher { get; }-- public TextFileComponentViewModel(BarViewModel parentViewModel, TextFileComponentConfig baseConfig) : base(parentViewModel, baseConfig)- {- _baseConfig = baseConfig;-- var bus = ServiceLocator.GetRequiredService<Bus>();- _disposable = bus.Events.OfType<UserConfigReloadedEvent>().Subscribe(_ => Dispose(true));-- Watcher = new FileSystemWatcher(Path.GetDirectoryName(_baseConfig.FilePath)!)- {- Filter = Path.GetFileName(_baseConfig.FilePath)!,- EnableRaisingEvents = true,- NotifyFilter = NotifyFilters.LastWrite- };- Watcher.Changed += OnFileChanged;- Update();- }-- protected override void Dispose(bool disposing)- {- if (disposing)- {- Watcher.Dispose();- _disposable.Dispose();- }-- base.Dispose(disposing);- }-- private void OnFileChanged(object sender, FileSystemEventArgs e)- {- Update();- }-- private void Update()- {- var numAttempts = 0;- var sleepTime = 32;- const int maxRetries = 6;-- try- {- Watcher.EnableRaisingEvents = false;- while (true)- {- try- {- Text = File.ReadAllText(_baseConfig.FilePath);- OnPropertyChanged(nameof(Text));- break;- }- catch (Exception) when (numAttempts < maxRetries)- {- numAttempts++;- Thread.Sleep(sleepTime);- sleepTime *= 2;- }- }- }- finally- {- Watcher.EnableRaisingEvents = true;- }- }- }-}diff --git a/GlazeWM.Bar/Components/TilingDirectionComponent.xaml b/GlazeWM.Bar/Components/TilingDirectionComponent.xamldeleted file mode 100644index 9031eadc..00000000--- a/GlazeWM.Bar/Components/TilingDirectionComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.TilingDirectionComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/TilingDirectionComponent.xaml.cs b/GlazeWM.Bar/Components/TilingDirectionComponent.xaml.csdeleted file mode 100644index a26d63d0..00000000--- a/GlazeWM.Bar/Components/TilingDirectionComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for TilingDirectionComponent.xaml- /// </summary>- public partial class TilingDirectionComponent : UserControl- {- public TilingDirectionComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/TilingDirectionComponentViewModel.cs b/GlazeWM.Bar/Components/TilingDirectionComponentViewModel.csdeleted file mode 100644index 85c5f47d..00000000--- a/GlazeWM.Bar/Components/TilingDirectionComponentViewModel.cs+++ /dev/null@@ -1,58 +0,0 @@-using System;-using System.Collections.Generic;-using System.Reactive.Linq;-using System.Windows.Threading;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Bar.Components-{- public class TilingDirectionComponentViewModel : ComponentViewModel- {- private Dispatcher _dispatcher => _parentViewModel.Dispatcher;- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();-- private readonly TilingDirectionComponentConfig _config;-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public TilingDirectionComponentViewModel(- BarViewModel parentViewModel,- TilingDirectionComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- _bus.Events.Where(- (@event) => @event is TilingDirectionChangedEvent or FocusChangedEvent- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((_) => _dispatcher.Invoke(() => Label = CreateLabel()));- }-- private LabelViewModel CreateLabel()- {- // The tiling direction of the currently focused container. Can be null on app- // startup when workspaces haven't been created yet.- var tilingDirection =- (_containerService.FocusedContainer as SplitContainer)?.TilingDirection ??- (_containerService.FocusedContainer.Parent as SplitContainer)?.TilingDirection;-- var label = tilingDirection == TilingDirection.Vertical- ? _config.LabelVertical- : _config.LabelHorizontal;-- return XamlHelper.ParseLabel(label, new Dictionary<string, Func<string>>(), this);- }- }-}diff --git a/GlazeWM.Bar/Components/VolumeComponent.xaml b/GlazeWM.Bar/Components/VolumeComponent.xamldeleted file mode 100644index 64dddba5..00000000--- a/GlazeWM.Bar/Components/VolumeComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.VolumeComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/VolumeComponent.xaml.cs b/GlazeWM.Bar/Components/VolumeComponent.xaml.csdeleted file mode 100644index 1fccd698..00000000--- a/GlazeWM.Bar/Components/VolumeComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for WindowTitleComponent.xaml- /// </summary>- public partial class VolumeComponent : UserControl- {- public VolumeComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/VolumeComponentViewModel.cs b/GlazeWM.Bar/Components/VolumeComponentViewModel.csdeleted file mode 100644index 4a4764cf..00000000--- a/GlazeWM.Bar/Components/VolumeComponentViewModel.cs+++ /dev/null@@ -1,70 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Bar.Components-{- public class VolumeComponentViewModel : ComponentViewModel- {- private readonly VolumeComponentConfig _config;-- private readonly SystemVolumeInformation _sysVolume =- ServiceLocator.GetRequiredService<SystemVolumeInformation>();-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public VolumeComponentViewModel(- BarViewModel parentViewModel,- VolumeComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- var initVolume = _sysVolume.GetVolumeInformation();- Label = CreateLabel(initVolume);-- _sysVolume.VolumeChanged += (_, volumeInfo) =>- {- Label = CreateLabel(volumeInfo);- };- }-- private string GetVolumeLabel(VolumeInformation volumeInfo)- {- if (volumeInfo.Muted)- return _config.LabelMute;-- return volumeInfo.Volume switch- {- > 0 and < 33 => _config.LabelLow,- >= 33 and < 66 => _config.LabelMedium,- _ => _config.LabelHigh- };- }-- public LabelViewModel CreateLabel(VolumeInformation volumeInfo)- {- return XamlHelper.ParseLabel(- GetVolumeLabel(volumeInfo),- CreateVariableDict(volumeInfo),- this- );- }-- public static Dictionary<string, Func<string>> CreateVariableDict(- VolumeInformation volumeInfo)- {- return new()- {- { "volume_level", () => volumeInfo.Volume.ToString("0", CultureInfo.InvariantCulture) },- };- }- }-}diff --git a/GlazeWM.Bar/Components/WeatherComponent.xaml b/GlazeWM.Bar/Components/WeatherComponent.xamldeleted file mode 100644index 7e19f6dc..00000000--- a/GlazeWM.Bar/Components/WeatherComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.WeatherComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/WeatherComponent.xaml.cs b/GlazeWM.Bar/Components/WeatherComponent.xaml.csdeleted file mode 100644index 463ffa49..00000000--- a/GlazeWM.Bar/Components/WeatherComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for WeatherComponent.xaml- /// </summary>- public partial class WeatherComponent : UserControl- {- public WeatherComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/WeatherComponentViewModel.cs b/GlazeWM.Bar/Components/WeatherComponentViewModel.csdeleted file mode 100644index 26c9fc29..00000000--- a/GlazeWM.Bar/Components/WeatherComponentViewModel.cs+++ /dev/null@@ -1,77 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Reactive.Linq;-using System.Threading.Tasks;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.Services;--namespace GlazeWM.Bar.Components-{- public class WeatherComponentViewModel : ComponentViewModel- {- private readonly WeatherComponentConfig _config;-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public WeatherComponentViewModel(- BarViewModel parentViewModel,- WeatherComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- Observable.Timer(- TimeSpan.Zero,- TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(async (_) => await UpdateLabel());- }-- private async Task UpdateLabel()- {- var weather = await WeatherService.GetWeatherAsync(_config.Latitude, _config.Longitude);-- var variableDictionary = new Dictionary<string, Func<string>>()- {- {- "temperature_celsius",- () => weather.Result.CurrentWeather.Temperature.ToString("0", CultureInfo.InvariantCulture)- },- {- "temperature_fahrenheit",- () =>- WeatherService- .ToFahrenheit(weather.Result.CurrentWeather.Temperature)- .ToString("0", CultureInfo.InvariantCulture)- }- };-- var labelString = GetLabelStringFromStatus(weather.Status);- Label = XamlHelper.ParseLabel(labelString, variableDictionary, this);- }-- private string GetLabelStringFromStatus(WeatherStatus status)- {- return status switch- {- WeatherStatus.Sun => _config.LabelSun,- WeatherStatus.Moon => _config.LabelMoon,- WeatherStatus.CloudSun => _config.LabelCloudSun,- WeatherStatus.CloudMoon => _config.LabelCloudMoon,- WeatherStatus.Cloud => _config.LabelCloud,- WeatherStatus.CloudSunRain => _config.LabelCloudSunRain,- WeatherStatus.CloudMoonRain => _config.LabelCloudMoonRain,- WeatherStatus.CloudRain => _config.LabelCloudRain,- WeatherStatus.Snowflake => _config.LabelSnowflake,- WeatherStatus.Thunder => _config.LabelThunderstorm,- _ => _config.Label- };- }- }-}diff --git a/GlazeWM.Bar/Components/WindowTitleComponent.xaml b/GlazeWM.Bar/Components/WindowTitleComponent.xamldeleted file mode 100644index 733c945a..00000000--- a/GlazeWM.Bar/Components/WindowTitleComponent.xaml+++ /dev/null@@ -1,10 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.WindowTitleComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <components:LabelComponent DataContext="{Binding Label}" />-</UserControl>diff --git a/GlazeWM.Bar/Components/WindowTitleComponent.xaml.cs b/GlazeWM.Bar/Components/WindowTitleComponent.xaml.csdeleted file mode 100644index 176c2fea..00000000--- a/GlazeWM.Bar/Components/WindowTitleComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for WindowTitleComponent.xaml- /// </summary>- public partial class WindowTitleComponent : UserControl- {- public WindowTitleComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/WindowTitleComponentViewModel.cs b/GlazeWM.Bar/Components/WindowTitleComponentViewModel.csdeleted file mode 100644index e098c595..00000000--- a/GlazeWM.Bar/Components/WindowTitleComponentViewModel.cs+++ /dev/null@@ -1,73 +0,0 @@-using System;-using System.Collections.Generic;-using System.Reactive.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;--namespace GlazeWM.Bar.Components-{- public class WindowTitleComponentViewModel : ComponentViewModel- {- private readonly WindowTitleComponentConfig _config;- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();-- private LabelViewModel _label;- public LabelViewModel Label- {- get => _label;- protected set => SetField(ref _label, value);- }-- public WindowTitleComponentViewModel(- BarViewModel parentViewModel,- WindowTitleComponentConfig config) : base(parentViewModel, config)- {- _config = config;-- var windowFocused = _bus.Events- .OfType<WindowFocusedEvent>()- .Select(@event => @event.WindowHandle);-- var windowTitleChanged = _bus.Events- .OfType<WindowTitleChangedEvent>()- .Select(@event => @event.WindowHandle);-- windowFocused.Merge(windowTitleChanged)- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((windowHandle) =>- {- var focusedWindow = _containerService.FocusedContainer as Window;-- if (focusedWindow != null && windowHandle != focusedWindow.Handle)- return;-- var windowTitle = focusedWindow?.Title ?? string.Empty;- Label = CreateLabel(windowTitle);- });- }-- private LabelViewModel CreateLabel(string windowTitle)- {- var variableDictionary = new Dictionary<string, Func<string>>()- {- // TODO: Make truncate max length configurable from config.- { "window_title", () => Truncate(windowTitle, 60) }- };-- return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);- }-- public static string Truncate(string value, int maxLength, string truncationSuffix = "…")- {- return value?.Length > maxLength- ? string.Concat(value.AsSpan(0, maxLength), truncationSuffix)- : value;- }- }-}diff --git a/GlazeWM.Bar/Components/WorkspacesComponent.xaml b/GlazeWM.Bar/Components/WorkspacesComponent.xamldeleted file mode 100644index 54a3c19f..00000000--- a/GlazeWM.Bar/Components/WorkspacesComponent.xaml+++ /dev/null@@ -1,80 +0,0 @@-<UserControl- x:Class="GlazeWM.Bar.Components.WorkspacesComponent"- x:Name="_workspacesComponent"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:local="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d">- <ItemsControl ItemsSource="{Binding Workspaces}">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <StackPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>-- <ItemsControl.ItemTemplate>- <DataTemplate>- <Button- x:Name="WorkspaceButton"- Content="{Binding DisplayName}"- Padding="8,0"- Command="{Binding DataContext.FocusWorkspaceCommand, ElementName=_workspacesComponent}"- CommandParameter="{Binding Name}"- Background="{Binding DataContext.DefaultWorkspaceBackground, ElementName=_workspacesComponent}"- Foreground="{Binding DataContext.DefaultWorkspaceForeground, ElementName=_workspacesComponent}"- BorderBrush="{Binding DataContext.DefaultWorkspaceBorderColor, ElementName=_workspacesComponent}"- FontFamily="{Binding DataContext.FontFamily, ElementName=_workspacesComponent}"- FontWeight="{Binding DataContext.FontWeight, ElementName=_workspacesComponent}"- FontSize="{Binding DataContext.FontSize, ElementName=_workspacesComponent}"- BorderThickness="{Binding DataContext.DefaultWorkspaceBorderWidth, ElementName=_workspacesComponent}"- Cursor="Hand" />-- <DataTemplate.Triggers>- <DataTrigger- Binding="{Binding IsDisplayed}"- Value="True">- <Setter- TargetName="WorkspaceButton"- Property="Background"- Value="{Binding DataContext.DisplayedWorkspaceBackground, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="Foreground"- Value="{Binding DataContext.DisplayedWorkspaceForeground, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="BorderBrush"- Value="{Binding DataContext.DisplayedWorkspaceBorderColor, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="BorderThickness"- Value="{Binding DataContext.DisplayedWorkspaceBorderWidth, ElementName=_workspacesComponent}" />- </DataTrigger>-- <DataTrigger- Binding="{Binding HasFocus}"- Value="True">- <Setter- TargetName="WorkspaceButton"- Property="Background"- Value="{Binding DataContext.FocusedWorkspaceBackground, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="Foreground"- Value="{Binding DataContext.FocusedWorkspaceForeground, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="BorderBrush"- Value="{Binding DataContext.FocusedWorkspaceBorderColor, ElementName=_workspacesComponent}" />- <Setter- TargetName="WorkspaceButton"- Property="BorderThickness"- Value="{Binding DataContext.FocusedWorkspaceBorderWidth, ElementName=_workspacesComponent}" />- </DataTrigger>- </DataTemplate.Triggers>- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>-</UserControl>diff --git a/GlazeWM.Bar/Components/WorkspacesComponent.xaml.cs b/GlazeWM.Bar/Components/WorkspacesComponent.xaml.csdeleted file mode 100644index 67d06cde..00000000--- a/GlazeWM.Bar/Components/WorkspacesComponent.xaml.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Controls;--namespace GlazeWM.Bar.Components-{- /// <summary>- /// Interaction logic for WorkspacesComponent.xaml- /// </summary>- public partial class WorkspacesComponent : UserControl- {- public WorkspacesComponent()- {- InitializeComponent();- }- }-}diff --git a/GlazeWM.Bar/Components/WorkspacesComponentViewModel.cs b/GlazeWM.Bar/Components/WorkspacesComponentViewModel.csdeleted file mode 100644index dc77c891..00000000--- a/GlazeWM.Bar/Components/WorkspacesComponentViewModel.cs+++ /dev/null@@ -1,100 +0,0 @@-using System;-using System.Collections.Generic;-using System.Collections.ObjectModel;-using System.Linq;-using System.Reactive.Linq;-using System.Windows.Input;-using System.Windows.Threading;-using GlazeWM.Bar.Common;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Domain.Workspaces.Events;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Bar.Components-{- public class WorkspacesComponentViewModel : ComponentViewModel- {- private Dispatcher _dispatcher => _parentViewModel.Dispatcher;- private Monitor _monitor => _parentViewModel.Monitor;- private WorkspacesComponentConfig _config =>- _componentConfig as WorkspacesComponentConfig;- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- private readonly UserConfigService _userConfigService =- ServiceLocator.GetRequiredService<UserConfigService>();-- public ObservableCollection<Workspace> Workspaces => new(_orderedWorkspaces);-- /// <summary>- /// Get workspaces of the current monitor sorted in the order they appear in the- /// user's config.- /// </summary>- private IEnumerable<Workspace> _orderedWorkspaces => _monitor.Children- .Cast<Workspace>()- .OrderBy((workspace) =>- _userConfigService.WorkspaceConfigs.FindIndex(- (workspaceConfig) => workspaceConfig.Name == workspace.Name- )- );-- public string FocusedWorkspaceBackground =>- XamlHelper.FormatColor(_config.FocusedWorkspaceBackground);- public string FocusedWorkspaceForeground =>- XamlHelper.FormatColor(_config.FocusedWorkspaceForeground ?? Foreground);- public string FocusedWorkspaceBorderColor =>- XamlHelper.FormatColor(_config.FocusedWorkspaceBorderColor);- public string FocusedWorkspaceBorderWidth =>- XamlHelper.FormatRectShorthand(_config.FocusedWorkspaceBorderWidth);-- public string DisplayedWorkspaceBackground =>- XamlHelper.FormatColor(_config.DisplayedWorkspaceBackground);- public string DisplayedWorkspaceForeground =>- XamlHelper.FormatColor(_config.DisplayedWorkspaceForeground ?? Foreground);- public string DisplayedWorkspaceBorderColor =>- XamlHelper.FormatColor(_config.DisplayedWorkspaceBorderColor);- public string DisplayedWorkspaceBorderWidth =>- XamlHelper.FormatRectShorthand(_config.DisplayedWorkspaceBorderWidth);-- public string DefaultWorkspaceBackground =>- XamlHelper.FormatColor(_config.DefaultWorkspaceBackground);- public string DefaultWorkspaceForeground =>- XamlHelper.FormatColor(_config.DefaultWorkspaceForeground ?? Foreground);- public string DefaultWorkspaceBorderColor =>- XamlHelper.FormatColor(_config.DefaultWorkspaceBorderColor);- public string DefaultWorkspaceBorderWidth =>- XamlHelper.FormatRectShorthand(_config.DefaultWorkspaceBorderWidth);-- public ICommand FocusWorkspaceCommand => new RelayCommand<string>(FocusWorkspace);-- public WorkspacesComponentViewModel(- BarViewModel parentViewModel,- WorkspacesComponentConfig config) : base(parentViewModel, config)- {- var workspacesChangedEvent = _bus.Events.Where((@event) =>- @event is WorkspaceActivatedEvent- or WorkspaceDeactivatedEvent- or FocusChangedEvent- or FocusedContainerMovedEvent- );-- // Refresh contents of workspaces collection.- workspacesChangedEvent- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(_ =>- _dispatcher.Invoke(() => OnPropertyChanged(nameof(Workspaces)))- );- }-- public void FocusWorkspace(string workspaceName)- {- _bus.Invoke(new FocusWorkspaceCommand(workspaceName));- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- }- }-}diff --git a/GlazeWM.Bar/DependencyInjection.cs b/GlazeWM.Bar/DependencyInjection.csdeleted file mode 100644index 13c58ecf..00000000--- a/GlazeWM.Bar/DependencyInjection.cs+++ /dev/null@@ -1,16 +0,0 @@-using ManagedShell;-using Microsoft.Extensions.DependencyInjection;--namespace GlazeWM.Bar-{- public static class DependencyInjection- {- public static IServiceCollection AddBarServices(this IServiceCollection services)- {- services.AddSingleton<BarService>();- services.AddSingleton<ShellManager>();-- return services;- }- }-}diff --git a/GlazeWM.Bar/GlazeWM.Bar.csproj b/GlazeWM.Bar/GlazeWM.Bar.csprojdeleted file mode 100644index 37924522..00000000--- a/GlazeWM.Bar/GlazeWM.Bar.csproj+++ /dev/null@@ -1,39 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <OutputType>Library</OutputType>- <TargetFramework>net7-windows10.0.17763.0</TargetFramework>- <UseWPF>true</UseWPF>- <DebugType>embedded</DebugType>- </PropertyGroup>-- <ItemGroup>- <ProjectReference Include="..\GlazeWM.Domain\GlazeWM.Domain.csproj" />- <ProjectReference Include="..\GlazeWM.Infrastructure\GlazeWM.Infrastructure.csproj" />- </ItemGroup>-- <ItemGroup>- <PackageReference- Include="Microsoft.Xaml.Behaviors.Wpf"- Version="1.1.39" />- </ItemGroup>-- <ItemGroup>- <PackageReference Include="Dubya.WindowsMediaController">- <Version>2.5.2</Version>- </PackageReference>- </ItemGroup>-- <ItemGroup>- <Page Update="Components\TextFileComponent.xaml">- <Generator>MSBuild:Compile</Generator>- <XamlRuntime>Wpf</XamlRuntime>- <SubType>Designer</SubType>- </Page>- <Page Update="Components\WeatherComponent.xaml">- <Generator>MSBuild:Compile</Generator>- <XamlRuntime>Wpf</XamlRuntime>- <SubType>Designer</SubType>- </Page>- </ItemGroup>-</Project>diff --git a/GlazeWM.Bar/MainWindow.xaml b/GlazeWM.Bar/MainWindow.xamldeleted file mode 100644index 70a6d1a9..00000000--- a/GlazeWM.Bar/MainWindow.xaml+++ /dev/null@@ -1,79 +0,0 @@-<Window- x:Class="GlazeWM.Bar.MainWindow"- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- xmlns:local="clr-namespace:GlazeWM.Bar"- xmlns:components="clr-namespace:GlazeWM.Bar.Components"- mc:Ignorable="d"- WindowStyle="None"- ResizeMode="NoResize"- Title="GlazeWMBar"- ShowInTaskbar="False"- Width="800"- Height="50"- Background="Transparent"- FontFamily="{Binding FontFamily}"- FontWeight="{Binding FontWeight}"- FontSize="{Binding FontSize}"- Opacity="{Binding Opacity}"- AllowsTransparency="True"- Topmost="{Binding AlwaysOnTop}">- <Border- CornerRadius="{Binding BorderRadius}"- BorderThickness="{Binding BorderWidth}"- BorderBrush="{Binding BorderColor}"- Background="{Binding Background}">- <Grid Margin="{Binding Padding}">-- <ItemsControl- HorizontalAlignment="Left"- ItemsSource="{Binding ComponentsLeft}">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <StackPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>-- <ItemsControl.ItemTemplate>- <DataTemplate>- <components:ComponentPortal />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>-- <ItemsControl- HorizontalAlignment="Center"- ItemsSource="{Binding ComponentsCenter}">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <StackPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>-- <ItemsControl.ItemTemplate>- <DataTemplate>- <components:ComponentPortal />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>-- <ItemsControl- HorizontalAlignment="Right"- ItemsSource="{Binding ComponentsRight}">- <ItemsControl.ItemsPanel>- <ItemsPanelTemplate>- <StackPanel Orientation="Horizontal" />- </ItemsPanelTemplate>- </ItemsControl.ItemsPanel>-- <ItemsControl.ItemTemplate>- <DataTemplate>- <components:ComponentPortal />- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </Grid>- </Border>-</Window>diff --git a/GlazeWM.Bar/MainWindow.xaml.cs b/GlazeWM.Bar/MainWindow.xaml.csdeleted file mode 100644index 891260b5..00000000--- a/GlazeWM.Bar/MainWindow.xaml.cs+++ /dev/null@@ -1,97 +0,0 @@-using System;-using System.Reactive.Linq;-using System.Windows;-using System.Windows.Interop;-using System.Windows.Threading;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Monitors.Events;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Bar-{- /// <summary>- /// Interaction logic for MainWindow.xaml- /// </summary>- public partial class MainWindow : Window- {- private readonly Bus _bus = ServiceLocator.GetRequiredService<Bus>();- public BarViewModel BarViewModel { get; }- private Dispatcher _dispatcher => BarViewModel.Dispatcher;- private Monitor _monitor => BarViewModel.Monitor;-- public MainWindow(BarViewModel barViewModel)- {- BarViewModel = barViewModel;- DataContext = barViewModel;-- InitializeComponent();- }-- protected override void OnSourceInitialized(EventArgs e)- {- base.OnSourceInitialized(e);-- var windowHandle = new WindowInteropHelper(this).Handle;- HideFromTaskSwitcher(windowHandle);- PositionWindow(windowHandle);-- // Reposition window on changes to the monitor's working area.- _bus.Events.Where(@event => @event is WorkingAreaResizedEvent)- .Subscribe(_ => _dispatcher.Invoke(() => PositionWindow(windowHandle)));- }-- /// <summary>- /// Hide the WPF window from task switcher (alt+tab menu).- /// </summary>- private static void HideFromTaskSwitcher(IntPtr windowHandle)- {- var exstyle = (int)GetWindowLongPtr(windowHandle, GWLEXSTYLE);- exstyle |= (int)WindowStylesEx.ToolWindow;- SetWindowLongPtr(windowHandle, GWLEXSTYLE, (IntPtr)exstyle);- }-- /// <summary>- /// Position and size the WPF window manually using WinAPI. When using `PerMonitorAwareV2` DPI- /// awareness, positioning the window with WPF bindings is ambiguous and annoying.- /// Ref: https://github.com/dotnet/wpf/issues/4127#issuecomment-790194817- /// </summary>- private void PositionWindow(IntPtr windowHandle)- {- // Since window size is set manually, need to scale up height to make window DPI responsive.- var barHeight = UnitsHelper.TrimUnits(BarViewModel.BarConfig.Height);- var scaledBarHeight = Convert.ToInt32(barHeight * _monitor.ScaleFactor);-- // Get offset from top of monitor.- var barOffsetY = BarViewModel.BarConfig.Position == BarPosition.Bottom- ? _monitor.Height - scaledBarHeight- : 0;-- var floatBarOffsetX = UnitsHelper.TrimUnits(BarViewModel.BarConfig.OffsetX);- var floatBarOffsetY = UnitsHelper.TrimUnits(BarViewModel.BarConfig.OffsetY);-- // The first move puts it on the correct monitor, which triggers WM_DPICHANGED.- MoveWindow(- windowHandle,- _monitor.X + floatBarOffsetX,- _monitor.Y + barOffsetY + floatBarOffsetY,- _monitor.Width - (floatBarOffsetX * 2),- scaledBarHeight,- true- );-- // The +1/-1 coerces WPF to update Top/Left/Width/Height in the second move.- MoveWindow(- windowHandle,- _monitor.X + floatBarOffsetX,- _monitor.Y + barOffsetY + floatBarOffsetY,- _monitor.Width - (floatBarOffsetX * 2),- scaledBarHeight,- true- );- }- }-}diff --git a/GlazeWM.Bar/XamlHelper.cs b/GlazeWM.Bar/XamlHelper.csdeleted file mode 100644index 1b664f5f..00000000--- a/GlazeWM.Bar/XamlHelper.cs+++ /dev/null@@ -1,145 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Xml.Linq;-using GlazeWM.Bar.Components;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Bar-{- public static class XamlHelper- {- /// <summary>- /// Convert size properties from user config (eg. `FontSize`) to be XAML- /// compatible.- /// </summary>- public static string FormatSize(string size)- {- return $"{UnitsHelper.TrimUnits(size)}";- }-- /// <summary>- /// Convert color properties from user config (eg. `Background`) to be XAML- /// compatible. Colors in the user config are specified in RGBA, whereas XAML expects- /// ARGB.- /// </summary>- public static string FormatColor(string color)- {- var isHexColor = color.StartsWith("#", StringComparison.InvariantCulture);-- if (!isHexColor)- return color;-- var rgbaHex = color.Replace("#", "");- var argbHex = rgbaHex.Length == 8 ? rgbaHex[6..8] + rgbaHex[0..6] : rgbaHex;-- return $"#{argbHex}";- }-- /// <summary>- /// Convert shorthand properties from user config (ie. `Padding`, `Margin`, and- /// `BorderWidth`) to be compatible with their equivalent XAML properties (ie.- /// `Padding`, `Margin`, and `BorderThickness`). Shorthand properties follow the- /// 1-to-4 value syntax used in CSS.- /// </summary>- /// <exception cref="ArgumentException"></exception>- public static string FormatRectShorthand(string shorthand)- {- var shorthandParts = shorthand.Split(" ")- .Select(shorthandPart => UnitsHelper.TrimUnits(shorthandPart))- .ToList();-- return shorthandParts.Count switch- {- 1 => shorthand,- 2 => $"{shorthandParts[1]},{shorthandParts[0]},{shorthandParts[1]},{shorthandParts[0]}",- 3 => $"{shorthandParts[1]},{shorthandParts[0]},{shorthandParts[1]},{shorthandParts[2]}",- 4 => $"{shorthandParts[3]},{shorthandParts[0]},{shorthandParts[1]},{shorthandParts[2]}",- _ => throw new ArgumentException(null, nameof(shorthand)),- };- }-- public static LabelViewModel ParseLabel(- string labelString,- Dictionary<string, Func<string>> labelVariables,- ComponentViewModel viewModel)- {- var labelWithVariables = labelString;-- if (labelVariables is not null)- {- // Replace variables in label with their corresponding variable.- foreach (var (key, value) in labelVariables)- labelWithVariables = labelWithVariables.Replace($"{{{key}}}", value());- }-- var labelSpans = ToLabelSpans(labelWithVariables, viewModel);- return new LabelViewModel(labelSpans);- }-- private static List<LabelSpan> ToLabelSpans(- string labelWithVariables,- ComponentViewModel viewModel)- {- var unparsedLabelSpans = new List<LabelSpan>()- {- new(- labelWithVariables,- viewModel.Foreground,- viewModel.FontFamily,- viewModel.FontWeight,- viewModel.FontSize)- };-- if (!labelWithVariables.Contains("<attr"))- return unparsedLabelSpans;-- try- {- // Wrap `labelString` in arbitrary tag to make it valid XML.- var wrappedLabel = $"<Label>{labelWithVariables}</Label>";- var labelXml = XElement.Parse(wrappedLabel);-- return labelXml.Nodes().Select(node =>- {- var value = node switch- {- XText text => text.Value,- XElement element => element.Value,- _ => throw new ArgumentException("Invalid XML.", nameof(labelWithVariables))- };-- string foreground = null;- string fontFamily = null;- string fontWeight = null;- string fontSize = null;-- var ancestor = node;-- while (ancestor is not null)- {- foreground ??= (ancestor as XElement)?.Attribute("fg")?.Value;- fontFamily ??= (ancestor as XElement)?.Attribute("ff")?.Value;- fontWeight ??= (ancestor as XElement)?.Attribute("fw")?.Value;- fontSize ??= (ancestor as XElement)?.Attribute("fs")?.Value;-- // Traverse upwards to get attributes to apply.- ancestor = ancestor.Parent;- }-- return new LabelSpan(- value,- foreground ?? viewModel.Foreground,- fontFamily ?? viewModel.FontFamily,- fontWeight ?? viewModel.FontWeight,- fontSize ?? viewModel.FontSize- );- }).ToList();- }- catch (Exception)- {- return unparsedLabelSpans;- }- }- }-}diff --git a/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.cs b/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.csdeleted file mode 100644index 787cd288..00000000--- a/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.cs+++ /dev/null@@ -1,41 +0,0 @@-using System;-using System.Diagnostics;-using System.Windows.Forms;-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.CommandHandlers-{- public class ExecProcessHandler : ICommandHandler<ExecProcessCommand>- {- public CommandResponse Handle(ExecProcessCommand command)- {- var processName = command.ProcessName;- var args = command.Args;-- try- {- using var process = new Process();- process.StartInfo = new ProcessStartInfo- {- // Expand env variables in the process name (eg. "%ProgramFiles%").- FileName = Environment.ExpandEnvironmentVariables(processName),- Arguments = string.Join(" ", args),- UseShellExecute = true,- // Set user profile directory as the working dir. This affects the starting directory- // of terminal processes (eg. CMD, Git bash, etc).- WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),- };- process.Start();- }- catch (Exception exception)- {- // Alert the user of the error.- // TODO: Link to documentation for `exec` command (no proper documentation yet).- MessageBox.Show(exception.Message);- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Common/CommandHandlers/PopulateInitialStateHandler.cs b/GlazeWM.Domain/Common/CommandHandlers/PopulateInitialStateHandler.csdeleted file mode 100644index a2df4969..00000000--- a/GlazeWM.Domain/Common/CommandHandlers/PopulateInitialStateHandler.cs+++ /dev/null@@ -1,92 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Common.CommandHandlers-{- internal sealed class PopulateInitialStateHandler : ICommandHandler<PopulateInitialStateCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;- private readonly WindowService _windowService;- private readonly WorkspaceService _workspaceService;-- public PopulateInitialStateHandler(- Bus bus,- ContainerService containerService,- MonitorService monitorService,- WindowService windowService,- WorkspaceService workspaceService)- {- _bus = bus;- _containerService = containerService;- _monitorService = monitorService;- _windowService = windowService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(PopulateInitialStateCommand command)- {- // Read user config file and set its values in state.- _bus.Invoke(new EvaluateUserConfigCommand());-- var focusedHandle = GetForegroundWindow();- PopulateContainerTree();-- // Register appbar windows.- foreach (var windowHandle in WindowService.GetAllWindowHandles())- if (_windowService.IsHandleAppBar(windowHandle))- _windowService.AppBarHandles.Add(windowHandle);-- // Get the originally focused window when the WM is started.- var focusedWindow =- _windowService.GetWindows().FirstOrDefault(window => window.Handle == focusedHandle);-- // `GetForegroundWindow` might return a handle that is not in the tree. In that case, set- // focus to an arbitrary window. If there are no manageable windows in the tree, set focus to- // an arbitrary workspace.- var containerToFocus =- focusedWindow ??- _windowService.GetWindows().FirstOrDefault() ??- _workspaceService.GetActiveWorkspaces().FirstOrDefault() as Container;-- _bus.Invoke(new SetFocusedDescendantCommand(containerToFocus));- _containerService.HasPendingFocusSync = true;-- return CommandResponse.Ok;- }-- private void PopulateContainerTree()- {- // Create a Monitor and consequently a Workspace for each detected Screen. `AllScreens` is an- // abstraction over `EnumDisplayMonitors` native method.- foreach (var screen in System.Windows.Forms.Screen.AllScreens)- _bus.Invoke(new AddMonitorCommand(screen));-- // Add initial windows to the tree.- // TODO: Copy all the below over to populate with cache method, but filter out window handles- // that have already been added to state.- foreach (var windowHandle in WindowService.GetAllWindowHandles())- {- if (!WindowService.IsHandleManageable(windowHandle))- continue;-- // Get workspace that encompasses most of the window.- var targetMonitor = _monitorService.GetMonitorFromHandleLocation(windowHandle);- var targetWorkspace = targetMonitor.DisplayedWorkspace;-- _bus.Invoke(new ManageWindowCommand(windowHandle, targetWorkspace));- }- }- }-}diff --git a/GlazeWM.Domain/Common/CommandHandlers/SetBindingModeHandler.cs b/GlazeWM.Domain/Common/CommandHandlers/SetBindingModeHandler.csdeleted file mode 100644index ecaff6af..00000000--- a/GlazeWM.Domain/Common/CommandHandlers/SetBindingModeHandler.cs+++ /dev/null@@ -1,52 +0,0 @@-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Common.Events;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.CommandHandlers-{- public class SetBindingModeHandler : ICommandHandler<SetBindingModeCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly UserConfigService _userConfigService;-- public SetBindingModeHandler(- Bus bus,- ContainerService containerService,- UserConfigService userConfigService)- {- _bus = bus;- _containerService = containerService;- _userConfigService = userConfigService;- }-- public CommandResponse Handle(SetBindingModeCommand command)- {- var bindingModeName = command.BindingModeName;-- // If binding mode is "none", then reset keybindings to default.- if (bindingModeName == "none")- {- var defaultKeybindings = _userConfigService.Keybindings;- _bus.Invoke(new RegisterKeybindingsCommand(defaultKeybindings));-- _containerService.ActiveBindingMode = null;- _bus.Emit(new BindingModeChangedEvent(null));-- return CommandResponse.Ok;- }-- // Otherwise, set keybindings to those defined by the binding mode.- var bindingMode = _userConfigService.GetBindingModeByName(bindingModeName);- _bus.Invoke(new RegisterKeybindingsCommand(bindingMode.Keybindings));-- _containerService.ActiveBindingMode = bindingModeName;- _bus.Emit(new BindingModeChangedEvent(bindingModeName));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Common/Commands/ExecProcessCommand.cs b/GlazeWM.Domain/Common/Commands/ExecProcessCommand.csdeleted file mode 100644index 4ac16959..00000000--- a/GlazeWM.Domain/Common/Commands/ExecProcessCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using System.Collections.Generic;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.Commands-{- public class ExecProcessCommand : Command- {- public string ProcessName { get; }- public List<string> Args { get; }-- public ExecProcessCommand(string processName, List<string> args)- {- ProcessName = processName;- Args = args;- }- }-}diff --git a/GlazeWM.Domain/Common/Commands/PopulateInitialStateCommand.cs b/GlazeWM.Domain/Common/Commands/PopulateInitialStateCommand.csdeleted file mode 100644index d26c9517..00000000--- a/GlazeWM.Domain/Common/Commands/PopulateInitialStateCommand.cs+++ /dev/null@@ -1,11 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.Commands-{- /// <summary>- /// Populate initial monitors, windows, workspaces, and user config.- /// </summary>- public class PopulateInitialStateCommand : Command- {- }-}diff --git a/GlazeWM.Domain/Common/Commands/SetBindingModeCommand.cs b/GlazeWM.Domain/Common/Commands/SetBindingModeCommand.csdeleted file mode 100644index da1e36e4..00000000--- a/GlazeWM.Domain/Common/Commands/SetBindingModeCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.Commands-{- public class SetBindingModeCommand : Command- {- public string BindingModeName { get; }-- public SetBindingModeCommand(string bindingModeName)- {- BindingModeName = bindingModeName;- }- }-}diff --git a/GlazeWM.Domain/Common/ContainerType.cs b/GlazeWM.Domain/Common/ContainerType.csdeleted file mode 100644index 3e4a5971..00000000--- a/GlazeWM.Domain/Common/ContainerType.cs+++ /dev/null@@ -1,11 +0,0 @@-namespace GlazeWM.Domain.Common-{- public enum ContainerType- {- Root,- Monitor,- Workspace,- Split,- Window,- }-}diff --git a/GlazeWM.Domain/Common/DomainEvent.cs b/GlazeWM.Domain/Common/DomainEvent.csdeleted file mode 100644index 7eb80e45..00000000--- a/GlazeWM.Domain/Common/DomainEvent.cs+++ /dev/null@@ -1,19 +0,0 @@-namespace GlazeWM.Domain.Common-{- public static class DomainEvent- {- public const string BindingModeChanged = "binding_mode_changed";- public const string FocusChanged = "focus_changed";- public const string FocusedContainerMoved = "focused_container_moved";- public const string MonitorAdded = "monitor_added";- public const string MonitorRemoved = "monitor_removed";- public const string NativeFocusSynced = "native_focus_synced";- public const string TilingDirectionChanged = "tiling_direction_changed";- public const string UserConfigReloaded = "user_config_reloaded";- public const string WindowManaged = "window_managed";- public const string WindowUnmanaged = "window_unmanaged";- public const string WorkspaceActivated = "workspace_activated";- public const string WorkspaceDeactivated = "workspace_deactivated";- public const string WorkingAreaResized = "working_area_resized";- }-}diff --git a/GlazeWM.Domain/Common/Enums/Direction.cs b/GlazeWM.Domain/Common/Enums/Direction.csdeleted file mode 100644index 7a448ff6..00000000--- a/GlazeWM.Domain/Common/Enums/Direction.cs+++ /dev/null@@ -1,42 +0,0 @@-using System;--namespace GlazeWM.Domain.Common.Enums-{- public enum Direction- {- Up,- Down,- Left,- Right,- }-- public static class DirectionExtensions- {- /// <summary>- /// Get the inverse of a given direction (eg. `Direction.UP` is the inverse of `Direction.DOWN`).- /// </summary>- /// <exception cref="ArgumentOutOfRangeException"></exception>- public static Direction Inverse(this Direction direction)- {- return direction switch- {- Direction.Up => Direction.Down,- Direction.Down => Direction.Up,- Direction.Left => Direction.Right,- Direction.Right => Direction.Left,- _ => throw new ArgumentOutOfRangeException(nameof(direction)),- };- }-- /// <summary>- /// Get the tiling direction that is needed for when moving or switching focus in- /// given direction (eg. a horizontal tiling direction when moving horizontally).- /// </summary>- public static TilingDirection GetTilingDirection(this Direction direction)- {- return (direction is Direction.Left or Direction.Right)- ? TilingDirection.Horizontal- : TilingDirection.Vertical;- }- }-}diff --git a/GlazeWM.Domain/Common/Enums/DisplayState.cs b/GlazeWM.Domain/Common/Enums/DisplayState.csdeleted file mode 100644index 09f077fc..00000000--- a/GlazeWM.Domain/Common/Enums/DisplayState.cs+++ /dev/null@@ -1,12 +0,0 @@-using System;--namespace GlazeWM.Domain.Common.Enums-{- public enum DisplayState- {- Shown,- Showing,- Hidden,- Hiding,- }-}diff --git a/GlazeWM.Domain/Common/Enums/FocusMode.cs b/GlazeWM.Domain/Common/Enums/FocusMode.csdeleted file mode 100644index 528f17f7..00000000--- a/GlazeWM.Domain/Common/Enums/FocusMode.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Domain.Common.Enums-{- public enum FocusMode- {- Tiling,- Floating,- }-}diff --git a/GlazeWM.Domain/Common/Enums/ResizeDimension.cs b/GlazeWM.Domain/Common/Enums/ResizeDimension.csdeleted file mode 100644index 0fae62eb..00000000--- a/GlazeWM.Domain/Common/Enums/ResizeDimension.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Domain.Common.Enums-{- public enum ResizeDimension- {- Width,- Height,- }-}diff --git a/GlazeWM.Domain/Common/Enums/Sequence.cs b/GlazeWM.Domain/Common/Enums/Sequence.csdeleted file mode 100644index ea29af0d..00000000--- a/GlazeWM.Domain/Common/Enums/Sequence.cs+++ /dev/null@@ -1,11 +0,0 @@-namespace GlazeWM.Domain.Common.Enums-{- /// <summary>- /// Used to represent a given order (eg. previous/next workspace).- /// </summary>- public enum Sequence- {- Previous,- Next- }-}diff --git a/GlazeWM.Domain/Common/Enums/TilingDirection.cs b/GlazeWM.Domain/Common/Enums/TilingDirection.csdeleted file mode 100644index dbce6f0a..00000000--- a/GlazeWM.Domain/Common/Enums/TilingDirection.cs+++ /dev/null@@ -1,27 +0,0 @@-using System;--namespace GlazeWM.Domain.Common.Enums-{- public enum TilingDirection- {- Vertical,- Horizontal,- }-- public static class TilingDirectionExtensions- {- /// <summary>- /// Get the inverse of a given tiling direction.- /// </summary>- /// <exception cref="ArgumentOutOfRangeException"></exception>- public static TilingDirection Inverse(this TilingDirection tilingDirection)- {- return tilingDirection switch- {- TilingDirection.Vertical => TilingDirection.Horizontal,- TilingDirection.Horizontal => TilingDirection.Vertical,- _ => throw new ArgumentOutOfRangeException(nameof(tilingDirection)),- };- }- }-}diff --git a/GlazeWM.Domain/Common/Events/BindingModeChangedEvent.cs b/GlazeWM.Domain/Common/Events/BindingModeChangedEvent.csdeleted file mode 100644index ca1ea857..00000000--- a/GlazeWM.Domain/Common/Events/BindingModeChangedEvent.cs+++ /dev/null@@ -1,7 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Common.Events-{- public record BindingModeChangedEvent(string NewBindingMode)- : Event(DomainEvent.BindingModeChanged);-}diff --git a/GlazeWM.Domain/Common/IpcClient.cs b/GlazeWM.Domain/Common/IpcClient.csdeleted file mode 100644index 2f2714d3..00000000--- a/GlazeWM.Domain/Common/IpcClient.cs+++ /dev/null@@ -1,94 +0,0 @@-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/Utils/LoggerExtensions.cs b/GlazeWM.Domain/Common/Utils/LoggerExtensions.csdeleted file mode 100644index c1fa696f..00000000--- a/GlazeWM.Domain/Common/Utils/LoggerExtensions.cs+++ /dev/null@@ -1,24 +0,0 @@-using GlazeWM.Domain.Windows;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Common.Utils-{- public static class LoggerExtensions- {- /// <summary>- /// Extension method for consistently formatting window event logs.- /// </summary>- public static void LogWindowEvent<T>(- this ILogger<T> logger,- string message,- Window window)- {- logger.LogDebug(- "{Message}: {ProcessName} {ClassName}",- message,- window.ProcessName,- window.ClassName- );- }- }-}diff --git a/GlazeWM.Domain/Common/WatcherStartupOptions.cs b/GlazeWM.Domain/Common/WatcherStartupOptions.csdeleted file mode 100644index ee0e0bb3..00000000--- a/GlazeWM.Domain/Common/WatcherStartupOptions.cs+++ /dev/null@@ -1,9 +0,0 @@-using CommandLine;--namespace GlazeWM.Domain.Common-{- [Verb("watcher")]- public class WatcherStartupOptions- {- }-}diff --git a/GlazeWM.Domain/Common/WmStartupOptions.cs b/GlazeWM.Domain/Common/WmStartupOptions.csdeleted file mode 100644index 821795be..00000000--- a/GlazeWM.Domain/Common/WmStartupOptions.cs+++ /dev/null@@ -1,16 +0,0 @@-using CommandLine;--namespace GlazeWM.Domain.Common-{- [Verb("start", isDefault: true)]- public class WmStartupOptions- {- [Option(- 'c',- "config",- Required = false,- HelpText = "Custom path to user config file."- )]- public string ConfigPath { get; set; }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/AttachContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/AttachContainerHandler.csdeleted file mode 100644index 8cfda404..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/AttachContainerHandler.cs+++ /dev/null@@ -1,55 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class AttachContainerHandler : ICommandHandler<AttachContainerCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public AttachContainerHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(AttachContainerCommand command)- {- var childToAdd = command.ChildToAdd;- var targetParent = command.TargetParent;- var targetIndex = command.TargetIndex;-- if (!childToAdd.IsDetached())- throw new Exception("Cannot attach an already attached container. This is a bug.");-- targetParent.InsertChild(targetIndex, childToAdd);-- if (childToAdd is IResizable)- ResizeAttachedContainer(childToAdd);-- _containerService.ContainersToRedraw.Add(targetParent);-- return CommandResponse.Ok;- }-- public void ResizeAttachedContainer(Container attachedContainer)- {- var resizableSiblings = attachedContainer.SiblingsOfType<IResizable>();-- if (!resizableSiblings.Any())- {- (attachedContainer as IResizable).SizePercentage = 1;- return;- }-- var defaultPercent = 1.0 / (resizableSiblings.Count() + 1);-- // Set initial size percentage to 0, and then size up the container to `defaultPercent`.- (attachedContainer as IResizable).SizePercentage = 0;- _bus.Invoke(new ResizeContainerCommand(attachedContainer, defaultPercent));- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/CenterCursorOnContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/CenterCursorOnContainerHandler.csdeleted file mode 100644index 28b347b2..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/CenterCursorOnContainerHandler.cs+++ /dev/null@@ -1,35 +0,0 @@-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class CenterCursorOnContainerHandler : ICommandHandler<CenterCursorOnContainerCommand>- {- private readonly UserConfigService _userConfigService;-- public CenterCursorOnContainerHandler(UserConfigService userConfigService)- {- _userConfigService = userConfigService;- }-- public CommandResponse Handle(CenterCursorOnContainerCommand command)- {- var isEnabled = _userConfigService.GeneralConfig.CursorFollowsFocus;-- if (!isEnabled || command.TargetContainer.IsDetached() || command.TargetContainer.FocusIndex < 0)- return CommandResponse.Ok;-- var targetRect = command.TargetContainer.ToRect();-- // Calculate center point of focused window.- var centerX = targetRect.X + (targetRect.Width / 2);- var centerY = targetRect.Y + (targetRect.Height / 2);-- SetCursorPos(centerX, centerY);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/ChangeTilingDirectionHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/ChangeTilingDirectionHandler.csdeleted file mode 100644index 61a87ecb..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/ChangeTilingDirectionHandler.cs+++ /dev/null@@ -1,106 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class ChangeTilingDirectionHandler : ICommandHandler<ChangeTilingDirectionCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public ChangeTilingDirectionHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(ChangeTilingDirectionCommand command)- {- var container = command.Container;- var newTilingDirection = command.TilingDirection;-- if (container is TilingWindow)- ChangeWindowTilingDirection(container as Window, newTilingDirection);- else if (container is Workspace)- ChangeWorkspaceTilingDirection(container as Workspace, newTilingDirection);-- _bus.Emit(new TilingDirectionChangedEvent(newTilingDirection));-- return CommandResponse.Ok;- }-- private void ChangeWindowTilingDirection(- Window window,- TilingDirection newTilingDirection)- {- var parent = window.Parent as SplitContainer;- var currentTilingDirection = parent.TilingDirection;-- if (currentTilingDirection == newTilingDirection)- return;-- // If the window is an only child of a workspace, change tiling direction of the- // workspace.- if (!window.HasSiblings() && parent is Workspace)- {- ChangeWorkspaceTilingDirection(parent as Workspace, newTilingDirection);- return;- }-- // If the window is an only child and the parent is a normal split container, then flatten- // the split container.- if (!window.HasSiblings())- {- _bus.Invoke(new FlattenSplitContainerCommand(parent));- return;- }-- // Create a new split container to wrap the window.- var splitContainer = new SplitContainer- {- TilingDirection = newTilingDirection,- };-- // Replace the window with the wrapping split container. The window has to be attached to- // the split container after the replacement.- _bus.Invoke(new ReplaceContainerCommand(splitContainer, parent, window.Index));-- // Add the window as a child of the split container and ensure it takes up the full size- // of its parent split container.- splitContainer.InsertChild(0, window);- (window as IResizable).SizePercentage = 1;- }-- private void ChangeWorkspaceTilingDirection(- Workspace workspace,- TilingDirection newTilingDirection)- {- var currentTilingDirection = workspace.TilingDirection;-- if (currentTilingDirection == newTilingDirection)- return;-- workspace.TilingDirection = newTilingDirection;-- // Flatten any top-level split containers with the same tiling direction as the- // workspace. Clone the list since the number of workspace children changes when- // split containers are flattened.- foreach (var child in workspace.Children.ToList())- {- var childSplitContainer = child as SplitContainer;-- if (childSplitContainer?.TilingDirection != newTilingDirection)- continue;-- _bus.Invoke(new FlattenSplitContainerCommand(childSplitContainer));- }-- _containerService.ContainersToRedraw.Add(workspace);- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/DetachContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/DetachContainerHandler.csdeleted file mode 100644index 355c5061..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/DetachContainerHandler.cs+++ /dev/null@@ -1,85 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class DetachContainerHandler : ICommandHandler<DetachContainerCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public DetachContainerHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(DetachContainerCommand command)- {- var childToRemove = command.ChildToRemove;- var parent = childToRemove.Parent;- var grandparent = parent.Parent;- var siblings = childToRemove.Siblings;-- if (parent == null)- throw new Exception("Cannot detach an already detached container. This is a bug.");-- parent.RemoveChild(childToRemove);-- var parentSiblings = parent.Siblings;- var isEmptySplitContainer =- !parent.HasChildren() && parent is SplitContainer and not Workspace;-- // Get the freed up space after container is detached.- var availableSizePercentage = isEmptySplitContainer- ? (parent as IResizable).SizePercentage- : (childToRemove as IResizable)?.SizePercentage ?? 0;-- // Resize children of grandparent if `childToRemove`'s parent is also to be detached.- var containersToResize = isEmptySplitContainer- ? grandparent.ChildrenOfType<IResizable>()- : parent.ChildrenOfType<IResizable>();-- // If the parent of the removed child is now an empty split container, detach the- // split container as well.- // TODO: Move out calls to `ContainersToRedraw.Add(...)`, since detaching might not- // always require a redraw.- if (isEmptySplitContainer)- {- _containerService.ContainersToRedraw.Add(parent.Parent);- grandparent.RemoveChild(parent);- }- else- _containerService.ContainersToRedraw.Add(parent);-- if (availableSizePercentage != 0)- {- var sizePercentageIncrement = availableSizePercentage / containersToResize.Count();-- // Adjust `SizePercentage` of the siblings of the removed container.- foreach (var containerToResize in containersToResize)- ((IResizable)containerToResize).SizePercentage += sizePercentageIncrement;- }-- var detachedSiblings = isEmptySplitContainer ? parentSiblings : siblings;- var detachedParent = isEmptySplitContainer ? grandparent : parent;-- // If there is exactly *one* sibling to the detached container, then flatten that- // sibling if it's a split container. This is to handle layouts like H[1 V[2 H[3]]],- // where container 2 gets detached.- if (detachedSiblings.Count() == 1 && detachedSiblings.ElementAt(0) is SplitContainer && childToRemove is not Workspace)- {- _bus.Invoke(- new FlattenSplitContainerCommand(detachedSiblings.ElementAt(0) as SplitContainer)- );- if (detachedParent is not Workspace)- _bus.Invoke(new FlattenSplitContainerCommand(detachedParent as SplitContainer));- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/FlattenSplitContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/FlattenSplitContainerHandler.csdeleted file mode 100644index dfb5ec1d..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/FlattenSplitContainerHandler.cs+++ /dev/null@@ -1,56 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class FlattenSplitContainerHandler : ICommandHandler<FlattenSplitContainerCommand>- {- private readonly ContainerService _containerService;-- public FlattenSplitContainerHandler(ContainerService containerService)- {- _containerService = containerService;- }-- public CommandResponse Handle(FlattenSplitContainerCommand command)- {- var splitContainer = command.ContainerToFlatten;-- // Keep references to properties of container to flatten prior to detaching.- var parent = splitContainer.Parent;- var index = splitContainer.Index;- var focusIndex = splitContainer.FocusIndex;- var children = splitContainer.Children.ToList();- var focusOrder = splitContainer.ChildFocusOrder.ToList();-- foreach (var (child, childIndex) in children.WithIndex())- {- // Insert child at its original index in the parent.- splitContainer.RemoveChild(child);- parent.Children.Insert(index + childIndex, child);- child.Parent = parent;-- if (child is IResizable childResizable)- childResizable.SizePercentage = splitContainer.SizePercentage * childResizable.SizePercentage;-- // Inverse the tiling direction of any child split containers.- if (child is SplitContainer childSplitContainer)- childSplitContainer.TilingDirection = childSplitContainer.TilingDirection.Inverse();- }-- // Remove the split container from the tree.- parent.RemoveChild(splitContainer);-- // Correct focus order of the inserted containers.- parent.ChildFocusOrder.InsertRange(focusIndex, focusOrder);-- // TODO: Remove unnecessary redraws.- _containerService.ContainersToRedraw.Add(parent);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.csdeleted file mode 100644index 6a377c14..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.cs+++ /dev/null@@ -1,74 +0,0 @@-using System;-using System.Collections.Generic;-using System.Diagnostics;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class FocusContainerUnderCursorHandler : ICommandHandler<FocusContainerUnderCursorCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private List<IntPtr> _focusedWindows = new();- private readonly WindowService _windowService;- public FocusContainerUnderCursorHandler(Bus bus, ContainerService containerService, WindowService windowService)- {- _bus = bus;- _containerService = containerService;- _windowService = windowService;- }-- public CommandResponse Handle(FocusContainerUnderCursorCommand command)- {- // Returns window underneath cursor. This could be a child window or parent.- var windowHandle = WindowFromPoint(command.TargetPoint);-- // If the mouse is hovering over the currently focused main window or one of it's children, do nothing.- if (_focusedWindows.Contains(windowHandle))- return CommandResponse.Ok;-- // If the FocusedWindows list didn't contain the window, this might be a new window being focused.- var newFocusedWindowsList = new List<IntPtr>- {- windowHandle- };-- // Check if the window is the main window or a child window.- var parentWindow = GetParent(windowHandle);-- // Walk the window up each parent window until you have the main window.- while (parentWindow != IntPtr.Zero)- {- windowHandle = parentWindow;- newFocusedWindowsList.Add(windowHandle);- parentWindow = GetParent(windowHandle);- }-- // Determine if the same window or a new window is being hovered- if (_focusedWindows.Contains(newFocusedWindowsList.Last()))- {- _focusedWindows = _focusedWindows.Union(newFocusedWindowsList).ToList();- }- else- {- _focusedWindows = newFocusedWindowsList;- var foundWindow = _windowService- .GetWindows()- .FirstOrDefault(window => window.Handle == windowHandle);-- if (foundWindow is not null)- {- // Focus the new window- SetForegroundWindow(foundWindow.Handle);- SetFocus(foundWindow.Handle);- }- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/FocusInDirectionHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/FocusInDirectionHandler.csdeleted file mode 100644index bc19e347..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/FocusInDirectionHandler.cs+++ /dev/null@@ -1,140 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class FocusInDirectionHandler : ICommandHandler<FocusInDirectionCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;-- public FocusInDirectionHandler(- Bus bus,- ContainerService containerService,- MonitorService monitorService)- {- _bus = bus;- _containerService = containerService;- _monitorService = monitorService;- }-- public CommandResponse Handle(FocusInDirectionCommand command)- {- var direction = command.Direction;- var focusedContainer = _containerService.FocusedContainer;-- if (focusedContainer is MaximizedWindow)- return CommandResponse.Ok;-- var focusTarget = GetFocusTarget(focusedContainer, direction);-- if (focusTarget is null || focusTarget == focusedContainer)- return CommandResponse.Ok;-- _bus.Invoke(new SetFocusedDescendantCommand(focusTarget));- _containerService.HasPendingFocusSync = true;-- return CommandResponse.Ok;- }-- private Container GetFocusTarget(Container focusedContainer, Direction direction)- {- if (focusedContainer is FloatingWindow)- return GetFocusTargetFromFloating(focusedContainer, direction);-- return GetFocusTargetFromTiling(focusedContainer, direction);- }-- private static Container GetFocusTargetFromFloating(Container focusedContainer, Direction direction)- {- // Cannot focus vertically from a floating window.- if (direction is Direction.Up or Direction.Down)- return null;-- var focusTarget = direction is Direction.Right- ? focusedContainer.NextSiblingOfType<FloatingWindow>()- : focusedContainer.PreviousSiblingOfType<FloatingWindow>();-- if (focusTarget is not null)- return focusTarget;-- // Wrap if next/previous floating window is not found.- return direction is Direction.Right- ? focusedContainer.SelfAndSiblingsOfType<FloatingWindow>().FirstOrDefault()- : focusedContainer.SelfAndSiblingsOfType<FloatingWindow>().LastOrDefault();- }-- private Container GetFocusTargetFromTiling(Container focusedContainer, Direction direction)- {- var focusTargetWithinWorkspace = GetFocusTargetWithinWorkspace(focusedContainer, direction);-- if (focusTargetWithinWorkspace != null)- return focusTargetWithinWorkspace;-- // If a suitable focus target isn't found in the current workspace, attempt to find- // a workspace in the given direction.- return GetFocusTargetOutsideWorkspace(direction);- }-- /// <summary>- /// Attempt to find a focus target within the focused workspace. Traverse upwards from the- /// focused container to find an adjacent container that can be focused.- /// </summary>- private Container GetFocusTargetWithinWorkspace(- Container focusedContainer,- Direction direction)- {- var tilingDirection = direction.GetTilingDirection();- var focusReference = focusedContainer;-- // Traverse upwards from the focused container. Stop searching when a workspace is- // encountered.- while (focusReference is not Workspace)- {- var parent = focusReference.Parent as SplitContainer;-- if (!focusReference.HasSiblings() || parent.TilingDirection != tilingDirection)- {- focusReference = parent;- continue;- }-- var focusTarget = direction is Direction.Up or Direction.Left- ? focusReference.PreviousSiblingOfType<IResizable>()- : focusReference.NextSiblingOfType<IResizable>();-- if (focusTarget == null)- {- focusReference = parent;- continue;- }-- return _containerService.GetDescendantInDirection(focusTarget, direction.Inverse());- }-- return null;- }-- /// <summary>- /// Attempt to find a focus target in a different workspace than the focused workspace.- /// </summary>- private Container GetFocusTargetOutsideWorkspace(Direction direction)- {- var focusedMonitor = _monitorService.GetFocusedMonitor();-- var monitorInDirection = _monitorService.GetMonitorInDirection(direction, focusedMonitor);- var workspaceInDirection = monitorInDirection?.DisplayedWorkspace;-- if (workspaceInDirection == null)- return null;-- return _containerService.GetDescendantInDirection(workspaceInDirection, direction.Inverse());- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/MoveContainerWithinTreeHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/MoveContainerWithinTreeHandler.csdeleted file mode 100644index 7f8893ef..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/MoveContainerWithinTreeHandler.cs+++ /dev/null@@ -1,126 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class MoveContainerWithinTreeHandler : ICommandHandler<MoveContainerWithinTreeCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public MoveContainerWithinTreeHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(MoveContainerWithinTreeCommand command)- {- var containerToMove = command.ContainerToMove;- var targetParent = command.TargetParent;- var targetIndex = command.TargetIndex;-- // Get lowest common ancestor (LCA) between `containerToMove` and `targetParent`. This could- // be the `targetParent` itself.- var lowestCommonAncestor = ContainerService.GetLowestCommonAncestor(- containerToMove,- targetParent- );-- var focusedContainer = _containerService.FocusedContainer;-- // Handle case where target parent is the LCA (eg. in the case of swapping sibling containers- // or moving a container to a direct ancestor).- if (targetParent == lowestCommonAncestor)- {- MoveToLowestCommonAncestor(- containerToMove,- lowestCommonAncestor,- targetIndex- );-- if (containerToMove == focusedContainer)- _bus.Emit(new FocusedContainerMovedEvent(containerToMove));-- return CommandResponse.Ok;- }-- // Get ancestors of `containerToMove` and `targetParent` that are direct children of the LCA.- // This could be the `containerToMove` or `targetParent` itself.- var containerToMoveAncestor = containerToMove.SelfAndAncestors- .First(ancestor => ancestor.Parent == lowestCommonAncestor);-- // Get whether the container is the focused descendant in its original subtree.- var isFocusedDescendant = containerToMove == containerToMoveAncestor- || containerToMoveAncestor.LastFocusedDescendant.SelfAndAncestors.Contains(containerToMove);-- var targetParentAncestor = targetParent.SelfAndAncestors- .First(ancestor => ancestor.Parent == lowestCommonAncestor);-- // Get whether the ancestor of `containerToMove` appears before `targetParent`'s ancestor in- // the `ChildFocusOrder` of LCA.- var originalFocusIndex = containerToMoveAncestor.FocusIndex;- var isSubtreeFocused = originalFocusIndex < targetParentAncestor.FocusIndex;-- _bus.Invoke(new DetachContainerCommand(containerToMove));- _bus.Invoke(new AttachContainerCommand(containerToMove, targetParent, targetIndex));-- // Set `containerToMove` as focused descendant within target subtree if its original subtree- // had focus more recently (even if the container is not the last focused within that subtree).- if (isSubtreeFocused)- _bus.Invoke(new SetFocusedDescendantCommand(containerToMove, targetParentAncestor));-- // If the focused descendant is moved to the targets subtree, then the target's ancestor- // should be placed before the original ancestor in LCA's `ChildFocusOrder`.- if (isFocusedDescendant && isSubtreeFocused)- lowestCommonAncestor.ChildFocusOrder.ShiftToIndex(- originalFocusIndex,- targetParentAncestor- );-- if (containerToMove == focusedContainer)- _bus.Emit(new FocusedContainerMovedEvent(containerToMove));-- return CommandResponse.Ok;- }-- private void MoveToLowestCommonAncestor(- Container containerToMove,- Container lowestCommonAncestor,- int targetIndex)- {- // Keep reference to focus index of container's ancestor in LCA's `ChildFocusOrder`.- var originalFocusIndex = containerToMove.SelfAndAncestors- .First(ancestor => ancestor.Parent == lowestCommonAncestor)- .FocusIndex;-- // Keep reference to container index and number of children that LCA has.- var originalIndex = containerToMove.Index;- var originalLcaChildCount = lowestCommonAncestor.Children.Count;-- _bus.Invoke(new DetachContainerCommand(containerToMove));-- var newLcaChildCount = lowestCommonAncestor.Children.Count;- var shouldAdjustTargetIndex = originalLcaChildCount > newLcaChildCount- && originalIndex < targetIndex;-- // Adjust for when target index changes on detach of container. For example, when shifting a- // top-level container to the right in a workspace.- var adjustedTargetIndex = shouldAdjustTargetIndex ? targetIndex - 1 : targetIndex;-- _bus.Invoke(- new AttachContainerCommand(- containerToMove,- lowestCommonAncestor,- adjustedTargetIndex- )- );-- lowestCommonAncestor.ChildFocusOrder.ShiftToIndex(originalFocusIndex, containerToMove);- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/RedrawContainersHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/RedrawContainersHandler.csdeleted file mode 100644index 4404aba3..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/RedrawContainersHandler.cs+++ /dev/null@@ -1,137 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class RedrawContainersHandler : ICommandHandler<RedrawContainersCommand>- {- private readonly ContainerService _containerService;- private readonly UserConfigService _userConfigService;-- public RedrawContainersHandler(- ContainerService containerService,- UserConfigService userConfigService)- {- _containerService = containerService;- _userConfigService = userConfigService;- }-- public CommandResponse Handle(RedrawContainersCommand command)- {- // Get windows that should be redrawn. When redrawing after a keybinding that- // changes a window's type (eg. tiling -> floating), the original detached window- // might still be queued for a redraw and should be ignored.- var windowsToRedraw = _containerService.ContainersToRedraw- .SelectMany(container => container.Flatten())- .OfType<Window>()- .Distinct()- .Where(window => !window.IsDetached())- .ToList();-- // Get windows that are minimized/maximized and shouldn't be.- var windowsToRestore = windowsToRedraw- .Where(- (window) =>- (window is not MinimizedWindow && window.HasWindowStyle(WindowStyles.Minimize)) ||- (window is not MaximizedWindow && window.HasWindowStyle(WindowStyles.Maximize))- )- .ToList();-- // Restore minimized/maximized windows. Needed to be able to move and resize them.- foreach (var window in windowsToRestore)- ShowWindowAsync(window.Handle, ShowWindowFlags.Restore);-- foreach (var window in windowsToRedraw)- {- SetWindowPosition(window);-- // When there's a mismatch between the DPI of the monitor and the window,- // `SetWindowPos` might size the window incorrectly. By calling `SetWindowPos`- // twice, inconsistencies after the first move are resolved.- if (window.HasPendingDpiAdjustment)- {- SetWindowPosition(window);- window.HasPendingDpiAdjustment = false;- }- }-- _containerService.ContainersToRedraw.Clear();-- return CommandResponse.Ok;- }-- private void SetWindowPosition(Window window)- {- var defaultFlags =- SetWindowPosFlags.FrameChanged |- SetWindowPosFlags.NoActivate |- SetWindowPosFlags.NoCopyBits |- SetWindowPosFlags.NoSendChanging |- SetWindowPosFlags.AsyncWindowPos;-- var workspace = window.Ancestors.OfType<Workspace>().First();- var isWorkspaceDisplayed = workspace.IsDisplayed;-- // Show or hide the window depending on whether the workspace is displayed.- if (isWorkspaceDisplayed)- defaultFlags |= SetWindowPosFlags.ShowWindow;- else- defaultFlags |= SetWindowPosFlags.HideWindow;-- if (window is MaximizedWindow)- {- defaultFlags |= SetWindowPosFlags.NoSize;- defaultFlags |= SetWindowPosFlags.NoMove;- }-- // Transition display state depending on whether window will be shown/hidden.- window.DisplayState = window.DisplayState switch- {- DisplayState.Hidden or- DisplayState.Hiding when isWorkspaceDisplayed => DisplayState.Showing,- DisplayState.Shown or- DisplayState.Showing when !isWorkspaceDisplayed => DisplayState.Hiding,- _ => window.DisplayState- };-- if (window is TilingWindow)- {- SetWindowPos(- window.Handle,- new IntPtr((int)ZOrderFlags.NoTopMost),- window.X - window.BorderDelta.Left,- window.Y - window.BorderDelta.Top,- window.Width + window.BorderDelta.Left + window.BorderDelta.Right,- window.Height + window.BorderDelta.Top + window.BorderDelta.Right,- defaultFlags- );- return;- }-- // Get z-order to set for floating windows.- var shouldShowOnTop = _userConfigService.GeneralConfig.ShowFloatingOnTop;- var floatingZOrder = shouldShowOnTop- ? ZOrderFlags.TopMost- : ZOrderFlags.NoTopMost;-- // Avoid adjusting the borders of floating windows. Otherwise the window will- // increase in size from its original placement.- SetWindowPos(- window.Handle,- new IntPtr((int)floatingZOrder),- window.X,- window.Y,- window.Width,- window.Height,- defaultFlags- );- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/ReplaceContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/ReplaceContainerHandler.csdeleted file mode 100644index b49dd298..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/ReplaceContainerHandler.cs+++ /dev/null@@ -1,61 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class ReplaceContainerHandler : ICommandHandler<ReplaceContainerCommand>- {- private readonly ContainerService _containerService;-- public ReplaceContainerHandler(ContainerService containerService)- {- _containerService = containerService;- }-- public CommandResponse Handle(ReplaceContainerCommand command)- {- var replacementContainer = command.ReplacementContainer;- var targetParent = command.TargetParent;- var targetIndex = command.TargetIndex;-- if (!replacementContainer.IsDetached())- throw new Exception(- "Cannot use an already attached container as replacement container. This is a bug."- );-- var containerToReplace = targetParent.Children[targetIndex];-- if (containerToReplace is IResizable && replacementContainer is IResizable)- (replacementContainer as IResizable).SizePercentage =- (containerToReplace as IResizable).SizePercentage;-- // Adjust `SizePercentage` of siblings.- if (containerToReplace is IResizable && replacementContainer is not IResizable)- {- // Get the freed up space after container is detached.- var availableSizePercentage = (containerToReplace as IResizable).SizePercentage;-- var resizableSiblings = containerToReplace.Siblings- .Where(container => container is IResizable);-- var sizePercentageIncrement = availableSizePercentage / resizableSiblings.Count();-- // Adjust `SizePercentage` of the siblings of the removed container.- foreach (var sibling in resizableSiblings)- (sibling as IResizable).SizePercentage += sizePercentageIncrement;- }-- // Replace the container at the given index.- targetParent.Children.Replace(containerToReplace, replacementContainer);- replacementContainer.Parent = targetParent;- targetParent.ChildFocusOrder.Replace(containerToReplace, replacementContainer);-- _containerService.ContainersToRedraw.Add(targetParent);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/ResizeContainerHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/ResizeContainerHandler.csdeleted file mode 100644index bc288642..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/ResizeContainerHandler.cs+++ /dev/null@@ -1,82 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class ResizeContainerHandler : ICommandHandler<ResizeContainerCommand>- {- private const double MIN_SIZE_PERCENTAGE = 0.01;-- public CommandResponse Handle(ResizeContainerCommand command)- {- var containerToResize = command.ContainerToResize;- var resizePercentage = command.ResizePercentage;-- var resizableSiblings = containerToResize.SiblingsOfType<IResizable>();-- // Ignore cases where the container to resize is a workspace or the only child.- if (!resizableSiblings.Any() || containerToResize is Workspace)- return CommandResponse.Ok;-- // Get available size percentage amongst siblings.- var availableSizePercentage = GetAvailableSizePercentage(- resizableSiblings- );-- // Prevent window from being smaller than the minimum and larger than space available from- // sibling containers.- var minResizeDelta = MIN_SIZE_PERCENTAGE - (containerToResize as IResizable).SizePercentage;- var clampedResizePercentage = Math.Clamp(- resizePercentage,- minResizeDelta,- availableSizePercentage- );-- // Resize the container.- (containerToResize as IResizable).SizePercentage += clampedResizePercentage;-- // Distribute the size percentage amongst its siblings.- foreach (var sibling in resizableSiblings)- {- (sibling as IResizable).SizePercentage -= GetSiblingResizePercentage(- sibling,- resizableSiblings.Count(),- clampedResizePercentage,- availableSizePercentage- );- }-- return CommandResponse.Ok;- }-- private static double GetAvailableSizePercentage(IEnumerable<Container> containers)- {- return containers.Aggregate(- 0.0,- (sum, container) => sum + (container as IResizable).SizePercentage - MIN_SIZE_PERCENTAGE- );- }-- private static double GetSiblingResizePercentage(- Container siblingToResize,- int siblingCount,- double sizePercentage,- double availableSizePercentage)- {- var conAvailableSizePercentage =- (siblingToResize as IResizable).SizePercentage - MIN_SIZE_PERCENTAGE;-- // Get percentage of resize that affects this container. `availableSizePercentage`- // can be 0 here when the main container to resize is shrunk from max size percentage.- var resizeFactor = availableSizePercentage == 0.0 || sizePercentage < 0- ? 1.0 / siblingCount- : conAvailableSizePercentage / availableSizePercentage;-- return resizeFactor * sizePercentage;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/SetActiveWindowBorderHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/SetActiveWindowBorderHandler.csdeleted file mode 100644index b458efef..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/SetActiveWindowBorderHandler.cs+++ /dev/null@@ -1,53 +0,0 @@-using System;-using System.Diagnostics;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class SetActiveWindowBorderHandler : ICommandHandler<SetActiveWindowBorderCommand>- {- private readonly UserConfigService _userConfigService;- private static Window _lastFocused;-- private uint rgbToUint(string rgb)- {- var c = rgb.ToCharArray();- var bgr = string.Concat(c[5], c[6], c[3], c[4], c[1], c[2]);- return Convert.ToUInt32(bgr, 16);- }-- public SetActiveWindowBorderHandler(UserConfigService userConfigService)- {- _userConfigService = userConfigService;- }-- public CommandResponse Handle(SetActiveWindowBorderCommand command)- {- uint BorderColorAttribute = 34;- if (_lastFocused is not null)- {- // Clear old window border- var inactiveColor = _userConfigService.FocusBorderConfig.Inactive.Enabled- ? rgbToUint(_userConfigService.FocusBorderConfig.Inactive.Color)- : 0xFFFFFFFF;- _ = DwmSetWindowAttribute(_lastFocused.Handle, BorderColorAttribute, ref inactiveColor, 4);- }-- var newWindowFocused = command.TargetWindow;- if (newWindowFocused is null)- return CommandResponse.Ok;-- _lastFocused = command.TargetWindow;- // Set new window border- var activeColor = _userConfigService.FocusBorderConfig.Active.Enabled- ? rgbToUint(_userConfigService.FocusBorderConfig.Active.Color)- : 0xFFFFFFFF;- _ = DwmSetWindowAttribute(_lastFocused.Handle, BorderColorAttribute, ref activeColor, 4);- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/SetFocusedDescendantHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/SetFocusedDescendantHandler.csdeleted file mode 100644index ca37347a..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/SetFocusedDescendantHandler.cs+++ /dev/null@@ -1,26 +0,0 @@-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class SetFocusedDescendantHandler : ICommandHandler<SetFocusedDescendantCommand>- {- public CommandResponse Handle(SetFocusedDescendantCommand command)- {- var focusedDescendant = command.FocusedDescendant;- var endAncestor = command.EndAncestor;-- // Traverse upwards, setting the container as the last focused until the root container- // or `endAncestor` (if provided) is reached.- var target = focusedDescendant;- while (target.Parent != null && target != endAncestor)- {- target.Parent.ChildFocusOrder.MoveToFront(target);- target = target.Parent;- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/SyncNativeFocusHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/SyncNativeFocusHandler.csdeleted file mode 100644index 8f8592b3..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/SyncNativeFocusHandler.cs+++ /dev/null@@ -1,52 +0,0 @@-using System;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class SyncNativeFocusHandler : ICommandHandler<SyncNativeFocusCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public SyncNativeFocusHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(SyncNativeFocusCommand command)- {- var hasPendingFocusSync = _containerService.HasPendingFocusSync;-- if (!hasPendingFocusSync)- return CommandResponse.Ok;-- // Container that the WM believes should have focus.- var focusedContainer = _containerService.FocusedContainer;-- var handleToFocus = focusedContainer switch- {- Window window => window.Handle,- Workspace => GetDesktopWindow(),- _ => throw new Exception("Invalid container type to focus. This is a bug."),- };-- // Set focus to the given window handle. If the container is a normal window, then this- // will trigger `EVENT_SYSTEM_FOREGROUND` window event and its handler.- KeybdEvent(0, 0, 0, 0);- SetForegroundWindow(handleToFocus);-- _bus.Emit(new NativeFocusSyncedEvent(focusedContainer));- _bus.Emit(new FocusChangedEvent(focusedContainer));-- _containerService.HasPendingFocusSync = false;-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/ToggleFocusModeHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/ToggleFocusModeHandler.csdeleted file mode 100644index a0e18b3d..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/ToggleFocusModeHandler.cs+++ /dev/null@@ -1,55 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class ToggleFocusModeHandler : ICommandHandler<ToggleFocusModeCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly WorkspaceService _workspaceService;-- public ToggleFocusModeHandler(- Bus bus,- ContainerService containerService,- WorkspaceService workspaceService)- {- _bus = bus;- _containerService = containerService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(ToggleFocusModeCommand command)- {- var currentFocusMode = _containerService.FocusMode;- var targetFocusMode = currentFocusMode == FocusMode.Tiling- ? FocusMode.Floating- : FocusMode.Tiling;-- var windowToFocus = GetWindowToFocus(targetFocusMode);-- if (windowToFocus is null)- return CommandResponse.Ok;-- _bus.Invoke(new SetFocusedDescendantCommand(windowToFocus));- _containerService.HasPendingFocusSync = true;-- return CommandResponse.Ok;- }-- private Window GetWindowToFocus(FocusMode targetFocusMode)- {- var focusedWorkspace = _workspaceService.GetFocusedWorkspace();-- if (targetFocusMode == FocusMode.Floating)- // Get the last focused tiling window within the workspace.- return focusedWorkspace.LastFocusedDescendantOfType<FloatingWindow>() as Window;-- // Get the last focused floating window within the workspace.- return focusedWorkspace.LastFocusedDescendantOfType<TilingWindow>() as Window;- }- }-}diff --git a/GlazeWM.Domain/Containers/CommandHandlers/ToggleTilingDirectionHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/ToggleTilingDirectionHandler.csdeleted file mode 100644index 3a80d6c9..00000000--- a/GlazeWM.Domain/Containers/CommandHandlers/ToggleTilingDirectionHandler.cs+++ /dev/null@@ -1,35 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.CommandHandlers-{- internal sealed class ToggleTilingDirectionHandler- : ICommandHandler<ToggleTilingDirectionCommand>- {- private readonly Bus _bus;-- public ToggleTilingDirectionHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(ToggleTilingDirectionCommand command)- {- var container = command.Container;-- var currentTilingDirection =- (container as SplitContainer)?.TilingDirection ??- (container.Parent as SplitContainer).TilingDirection;-- var newTilingDirection =- currentTilingDirection == TilingDirection.Horizontal- ? TilingDirection.Vertical- : TilingDirection.Horizontal;-- _bus.Invoke(new ChangeTilingDirectionCommand(container, newTilingDirection));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/AttachContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/AttachContainerCommand.csdeleted file mode 100644index 56fc6ae7..00000000--- a/GlazeWM.Domain/Containers/Commands/AttachContainerCommand.cs+++ /dev/null@@ -1,28 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class AttachContainerCommand : Command- {- public Container ChildToAdd { get; }- public Container TargetParent { get; }- public int TargetIndex { get; }-- /// <summary>- /// Insert child as end element if `targetIndex` is not provided.- /// </summary>- public AttachContainerCommand(Container childToAdd, Container targetParent)- {- ChildToAdd = childToAdd;- TargetParent = targetParent;- TargetIndex = targetParent.Children.Count;- }-- public AttachContainerCommand(Container childToAdd, Container targetParent, int targetIndex)- {- ChildToAdd = childToAdd;- TargetParent = targetParent;- TargetIndex = targetIndex;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/CenterCursorOnContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/CenterCursorOnContainerCommand.csdeleted file mode 100644index 12c6cb17..00000000--- a/GlazeWM.Domain/Containers/Commands/CenterCursorOnContainerCommand.cs+++ /dev/null@@ -1,18 +0,0 @@-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Containers.Commands-{- public class CenterCursorOnContainerCommand : Command- {- public Container TargetContainer { get; }-- /// <summary>- /// Center cursor in the middle of target container- /// </summary>- public CenterCursorOnContainerCommand(Container target)- {- TargetContainer = target;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/ChangeTilingDirectionCommand.cs b/GlazeWM.Domain/Containers/Commands/ChangeTilingDirectionCommand.csdeleted file mode 100644index 98b22bdc..00000000--- a/GlazeWM.Domain/Containers/Commands/ChangeTilingDirectionCommand.cs+++ /dev/null@@ -1,19 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class ChangeTilingDirectionCommand : Command- {- public Container Container { get; }- public TilingDirection TilingDirection { get; }-- public ChangeTilingDirectionCommand(- Container container,- TilingDirection tilingDirection)- {- Container = container;- TilingDirection = tilingDirection;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/DetachContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/DetachContainerCommand.csdeleted file mode 100644index a67a341b..00000000--- a/GlazeWM.Domain/Containers/Commands/DetachContainerCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class DetachContainerCommand : Command- {- public Container ChildToRemove { get; }-- public DetachContainerCommand(Container childToRemove)- {- ChildToRemove = childToRemove;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/FlattenSplitContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/FlattenSplitContainerCommand.csdeleted file mode 100644index 035e6aae..00000000--- a/GlazeWM.Domain/Containers/Commands/FlattenSplitContainerCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class FlattenSplitContainerCommand : Command- {- public SplitContainer ContainerToFlatten { get; }-- public FlattenSplitContainerCommand(SplitContainer parent)- {- ContainerToFlatten = parent;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.cs b/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.csdeleted file mode 100644index 104ca4cf..00000000--- a/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Containers.Commands-{- public class FocusContainerUnderCursorCommand : Command- {- public Point TargetPoint { get; }- public FocusContainerUnderCursorCommand(Point targetPoint)- {- TargetPoint = targetPoint;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/FocusInDirectionCommand.cs b/GlazeWM.Domain/Containers/Commands/FocusInDirectionCommand.csdeleted file mode 100644index d437caf5..00000000--- a/GlazeWM.Domain/Containers/Commands/FocusInDirectionCommand.cs+++ /dev/null@@ -1,15 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class FocusInDirectionCommand : Command- {- public Direction Direction { get; }-- public FocusInDirectionCommand(Direction direction)- {- Direction = direction;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/MoveContainerWithinTreeCommand.cs b/GlazeWM.Domain/Containers/Commands/MoveContainerWithinTreeCommand.csdeleted file mode 100644index 28a9426a..00000000--- a/GlazeWM.Domain/Containers/Commands/MoveContainerWithinTreeCommand.cs+++ /dev/null@@ -1,33 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class MoveContainerWithinTreeCommand : Command- {- public Container ContainerToMove { get; }- public Container TargetParent { get; }- public int TargetIndex { get; }-- /// <summary>- /// Insert child as end element if `targetIndex` is not provided.- /// </summary>- public MoveContainerWithinTreeCommand(- Container containerToMove,- Container targetParent)- {- ContainerToMove = containerToMove;- TargetParent = targetParent;- TargetIndex = targetParent.Children.Count;- }-- public MoveContainerWithinTreeCommand(- Container containerToMove,- Container targetParent,- int targetIndex)- {- ContainerToMove = containerToMove;- TargetParent = targetParent;- TargetIndex = targetIndex;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/RedrawContainersCommand.cs b/GlazeWM.Domain/Containers/Commands/RedrawContainersCommand.csdeleted file mode 100644index ebfd5d30..00000000--- a/GlazeWM.Domain/Containers/Commands/RedrawContainersCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class RedrawContainersCommand : Command- {- }-}diff --git a/GlazeWM.Domain/Containers/Commands/ReplaceContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/ReplaceContainerCommand.csdeleted file mode 100644index 9fd5db6e..00000000--- a/GlazeWM.Domain/Containers/Commands/ReplaceContainerCommand.cs+++ /dev/null@@ -1,21 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class ReplaceContainerCommand : Command- {- public Container ReplacementContainer { get; }- public Container TargetParent { get; }- public int TargetIndex { get; }-- public ReplaceContainerCommand(- Container replacementContainer,- Container targetParent,- int targetIndex)- {- ReplacementContainer = replacementContainer;- TargetParent = targetParent;- TargetIndex = targetIndex;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/ResizeContainerCommand.cs b/GlazeWM.Domain/Containers/Commands/ResizeContainerCommand.csdeleted file mode 100644index a49c9a51..00000000--- a/GlazeWM.Domain/Containers/Commands/ResizeContainerCommand.cs+++ /dev/null@@ -1,16 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class ResizeContainerCommand : Command- {- public Container ContainerToResize { get; }- public double ResizePercentage { get; }-- public ResizeContainerCommand(Container containerToResize, double resizePercentage)- {- ContainerToResize = containerToResize;- ResizePercentage = resizePercentage;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/SetActiveWindowBorderCommand.cs b/GlazeWM.Domain/Containers/Commands/SetActiveWindowBorderCommand.csdeleted file mode 100644index 92ea678f..00000000--- a/GlazeWM.Domain/Containers/Commands/SetActiveWindowBorderCommand.cs+++ /dev/null@@ -1,19 +0,0 @@-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Containers.Commands-{- public class SetActiveWindowBorderCommand : Command- {- public Window TargetWindow { get; }-- /// <summary>- /// Sets the newly focused window's border and removes border on older window.- /// </summary>- public SetActiveWindowBorderCommand(Window target)- {- TargetWindow = target;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/SetFocusedDescendantCommand.cs b/GlazeWM.Domain/Containers/Commands/SetFocusedDescendantCommand.csdeleted file mode 100644index ad839d14..00000000--- a/GlazeWM.Domain/Containers/Commands/SetFocusedDescendantCommand.cs+++ /dev/null@@ -1,16 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class SetFocusedDescendantCommand : Command- {- public Container FocusedDescendant { get; }- public Container EndAncestor { get; }-- public SetFocusedDescendantCommand(Container focusedDescendant, Container endAncestor = null)- {- FocusedDescendant = focusedDescendant;- EndAncestor = endAncestor;- }- }-}diff --git a/GlazeWM.Domain/Containers/Commands/SyncNativeFocusCommand.cs b/GlazeWM.Domain/Containers/Commands/SyncNativeFocusCommand.csdeleted file mode 100644index 7f52faf9..00000000--- a/GlazeWM.Domain/Containers/Commands/SyncNativeFocusCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class SyncNativeFocusCommand : Command- {- }-}diff --git a/GlazeWM.Domain/Containers/Commands/ToggleFocusModeCommand.cs b/GlazeWM.Domain/Containers/Commands/ToggleFocusModeCommand.csdeleted file mode 100644index 1fe2e2b7..00000000--- a/GlazeWM.Domain/Containers/Commands/ToggleFocusModeCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class ToggleFocusModeCommand : Command- {- }-}diff --git a/GlazeWM.Domain/Containers/Commands/ToggleTilingDirectionCommand.cs b/GlazeWM.Domain/Containers/Commands/ToggleTilingDirectionCommand.csdeleted file mode 100644index ed210064..00000000--- a/GlazeWM.Domain/Containers/Commands/ToggleTilingDirectionCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Commands-{- public class ToggleTilingDirectionCommand : Command- {- public Container Container { get; }-- public ToggleTilingDirectionCommand(Container container)- {- Container = container;- }- }-}diff --git a/GlazeWM.Domain/Containers/Container.cs b/GlazeWM.Domain/Containers/Container.csdeleted file mode 100644index bf72b248..00000000--- a/GlazeWM.Domain/Containers/Container.cs+++ /dev/null@@ -1,245 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Containers-{- public abstract class Container- {- /// <summary>- /// A unique identifier for the container.- /// </summary>- public Guid Id { get; set; } = Guid.NewGuid();-- /// <summary>- /// Derived container type (eg. `ContainerType.Monitor`).- /// </summary>- public abstract ContainerType Type { get; }-- public virtual int Height { get; set; }- public virtual int Width { get; set; }- public virtual int X { get; set; }- public virtual int Y { get; set; }-- public Container Parent { get; set; }- public List<Container> Children { get; set; } = new List<Container>();-- /// <summary>- /// The order of which child containers last had focus.- /// </summary>- public List<Container> ChildFocusOrder { get; set; } = new List<Container>();-- /// <summary>- /// The child container that last had focus.- /// </summary>- public Container LastFocusedChild => ChildFocusOrder.ElementAtOrDefault(0);-- /// <summary>- /// Index of this container in parent's child focus order.- /// </summary>- public int FocusIndex => this is RootContainer ? 0 : Parent.ChildFocusOrder.IndexOf(this);-- public List<Container> SelfAndSiblings =>- this is RootContainer ? new List<Container>() { this } : Parent.Children;-- public IEnumerable<Container> Siblings =>- this is RootContainer- ? Array.Empty<Container>()- : Parent.Children.Where(children => children != this);-- /// <summary>- /// Index of this container amongst its siblings.- /// </summary>- public int Index => this is RootContainer ? 0 : Parent.Children.IndexOf(this);-- /// <summary>- /// Get the last focused descendant by traversing downwards.- /// </summary>- public Container LastFocusedDescendant- {- get- {- var lastFocusedDescendant = LastFocusedChild;-- while (lastFocusedDescendant?.LastFocusedChild != null)- lastFocusedDescendant = lastFocusedDescendant.LastFocusedChild;-- return lastFocusedDescendant;- }- }-- /// <summary>- /// The sibling at the next index to this container.- /// </summary>- public Container NextSibling => SelfAndSiblings.ElementAtOrDefault(Index + 1);-- /// <summary>- /// The sibling at the previous index to this container.- /// </summary>- public Container PreviousSibling => SelfAndSiblings.ElementAtOrDefault(Index - 1);-- // TODO: Rename to SelfAndDescendants and change to getter.- public IEnumerable<Container> Flatten()- {- return new[] { this }.Concat(Children.SelectMany(children => children.Flatten()));- }-- public IEnumerable<Container> SelfAndAncestors => new[] { this }.Concat(Ancestors);-- public IEnumerable<Container> Ancestors- {- get- {- var parent = Parent;-- while (parent != null)- {- yield return parent;- parent = parent.Parent;- }- }- }-- public IEnumerable<Container> SelfAndDescendants => new[] { this }.Concat(Descendants);-- /// <summary>- /// Breadth-first downward traversal from a single container.- /// </summary>- public IEnumerable<Container> Descendants- {- get- {- var queue = new Queue<Container>();-- foreach (var child in Children)- queue.Enqueue(child);-- while (queue.Count > 0)- {- var current = queue.Dequeue();- yield return current;- foreach (var child in current.Children)- queue.Enqueue(child);- }- }- }-- /// <summary>- /// Leaf nodes (ie. windows and workspaces) in order of last focus.- /// </summary>- public IEnumerable<Container> DescendantFocusOrder- {- get- {- var stack = new Stack<Container>();- stack.Push(this);-- // Do a depth-first search using child focus order.- while (stack.Count > 0)- {- var current = stack.Pop();-- // Get containers that have no children. Descendant also cannot be the container itself.- if (current != this && !current.HasChildren())- yield return current;-- // Reverse the child focus order so that the first element is pushed last/popped first.- foreach (var focusChild in current.ChildFocusOrder.AsEnumerable().Reverse())- stack.Push(focusChild);- }- }- }-- public void InsertChild(int targetIndex, Container child)- {- Children.Insert(targetIndex, child);- ChildFocusOrder.Add(child);- child.Parent = this;- }-- public void RemoveChild(Container child)- {- child.Parent = null;- Children.Remove(child);- ChildFocusOrder.Remove(child);- }-- public bool IsDetached()- {- return Parent is null || Index == -1;- }-- public bool HasChildren()- {- return Children.Count > 0;- }-- public bool HasSiblings()- {- return Siblings.Any();- }-- public Rect ToRect()- {- return new Rect()- {- Left = X,- Right = X + Width,- Top = Y,- Bottom = Y + Height,- };- }-- public IEnumerable<Container> ChildrenOfType<T>()- {- return Children.Where(container => typeof(T).IsAssignableFrom(container.GetType()));- }-- public IEnumerable<Container> SiblingsOfType<T>()- {- return Siblings.Where(container => typeof(T).IsAssignableFrom(container.GetType()));- }-- public IEnumerable<Container> SelfAndSiblingsOfType<T>()- {- return SelfAndSiblings.Where(container => typeof(T).IsAssignableFrom(container.GetType()));- }-- public Container NextSiblingOfType<T>()- {- return SelfAndSiblings- .Skip(Index + 1)- .FirstOrDefault(container => typeof(T).IsAssignableFrom(container.GetType()));- }-- public Container PreviousSiblingOfType<T>()- {- return SelfAndSiblings- .Take(Index)- .Reverse()- .FirstOrDefault(container => typeof(T).IsAssignableFrom(container.GetType()));- }-- /// <summary>- /// Get the last focused child that matches the given type.- /// </summary>- public Container LastFocusedChildOfType<T>()- {- return ChildFocusOrder.Find(- container => typeof(T).IsAssignableFrom(container.GetType())- );- }-- /// <summary>- /// Get the last focused descendant that matches the given type.- /// </summary>- public Container LastFocusedDescendantOfType<T>()- {- return DescendantFocusOrder.FirstOrDefault(- container => typeof(T).IsAssignableFrom(container.GetType())- );- }- }-}diff --git a/GlazeWM.Domain/Containers/ContainerService.cs b/GlazeWM.Domain/Containers/ContainerService.csdeleted file mode 100644index 4a6c6a87..00000000--- a/GlazeWM.Domain/Containers/ContainerService.cs+++ /dev/null@@ -1,196 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.Containers-{- public class ContainerService- {- /// <summary>- /// The root node of the container tree. Monitors are the children of the root node, followed- /// by workspaces, then split containers/windows.- /// </summary>- public RootContainer ContainerTree = new();-- /// <summary>- /// Containers (and their descendants) to redraw on the next invocation of- /// `RedrawContainersCommand`.- /// </summary>- public List<Container> ContainersToRedraw = new();-- /// <summary>- /// The currently focused container. This can either be a `Window` or a- /// `Workspace` without any descendant windows.- /// </summary>- public Container FocusedContainer => ContainerTree.LastFocusedDescendant;-- /// <summary>- /// Whether native focus needs to be reassigned to `FocusedContainer`.- /// </summary>- public bool HasPendingFocusSync { get; set; }-- /// <summary>- /// Whether a tiling or floating container is currently focused.- /// </summary>- public FocusMode FocusMode => FocusedContainer is FloatingWindow ?- FocusMode.Floating : FocusMode.Tiling;-- /// <summary>- /// Name of the currently active binding mode (if one is active).- /// </summary>- public string ActiveBindingMode { get; set; }-- private readonly UserConfigService _userConfigService;-- public ContainerService(UserConfigService userConfigService)- {- _userConfigService = userConfigService;- }-- public Container GetContainerById(Guid id)- {- return ContainerTree.SelfAndDescendants.FirstOrDefault(container => container.Id == id);- }-- /// <summary>- /// Calculates the width of a container that can be resized programatically. This- /// calculation is shared by windows and split containers.- /// </summary>- public int GetWidthOfResizableContainer(Container container)- {- var parent = container.Parent as SplitContainer;-- if (parent.TilingDirection == TilingDirection.Vertical)- return parent.Width;-- var innerGap = UnitsHelper.TrimUnits(_userConfigService.GapsConfig.InnerGap);- var resizableSiblings = container.SelfAndSiblingsOfType<IResizable>();-- return (int)((container as IResizable).SizePercentage- * (parent.Width - (innerGap * (resizableSiblings.Count() - 1))));- }-- /// <summary>- /// Calculates the height of a container that can be resized programatically. This- /// calculation is shared by windows and split containers.- /// </summary>- public int GetHeightOfResizableContainer(Container container)- {- var parent = container.Parent as SplitContainer;-- if (parent.TilingDirection == TilingDirection.Horizontal)- return parent.Height;-- var innerGap = UnitsHelper.TrimUnits(_userConfigService.GapsConfig.InnerGap);- var resizableSiblings = container.SelfAndSiblingsOfType<IResizable>();-- return (int)((container as IResizable).SizePercentage- * (parent.Height - (innerGap * (resizableSiblings.Count() - 1))));- }-- /// <summary>- /// Calculates the X coordinate of a container that can be resized programatically. This- /// calculation is shared by windows and split containers.- /// </summary>- public int GetXOfResizableContainer(Container container)- {- var parent = container.Parent as SplitContainer;-- var isFirstOfType = container.SelfAndSiblingsOfType<IResizable>().First() == container;-- if (parent.TilingDirection == TilingDirection.Vertical || isFirstOfType)- return parent.X;-- var innerGap = UnitsHelper.TrimUnits(_userConfigService.GapsConfig.InnerGap);-- return container.PreviousSiblingOfType<IResizable>().X- + container.PreviousSiblingOfType<IResizable>().Width- + innerGap;- }-- /// <summary>- /// Calculates the Y coordinate of a container that can be resized programatically. This- /// calculation is shared by windows and split containers.- /// </summary>- public int GetYOfResizableContainer(Container container)- {- var parent = container.Parent as SplitContainer;-- var isFirstOfType = container.SelfAndSiblingsOfType<IResizable>().First() == container;-- if (parent.TilingDirection == TilingDirection.Horizontal || isFirstOfType)- return parent.Y;-- var innerGap = UnitsHelper.TrimUnits(_userConfigService.GapsConfig.InnerGap);-- return container.PreviousSiblingOfType<IResizable>().Y- + container.PreviousSiblingOfType<IResizable>().Height- + innerGap;- }-- /// <summary>- /// Traverse down a container in search of a descendant in the given direction. For example, get- /// the rightmost container for `Direction.RIGHT`. Returns the `originContainer` if no suitable- /// descendants are found. Any non-tiling containers are ignored.- /// </summary>- public Container GetDescendantInDirection(Container originContainer, Direction direction)- {- var isDescendable =- originContainer is SplitContainer &&- originContainer.ChildrenOfType<IResizable>().Any();-- if (!isDescendable)- return originContainer;-- var tilingDirection = (originContainer as SplitContainer).TilingDirection;-- if (tilingDirection != direction.GetTilingDirection())- return GetDescendantInDirection(- originContainer.LastFocusedChildOfType<IResizable>(),- direction- );- else if (direction is Direction.Up or Direction.Left)- return GetDescendantInDirection(- originContainer.ChildrenOfType<IResizable>().First(),- direction- );- else- return GetDescendantInDirection(- originContainer.ChildrenOfType<IResizable>().Last(),- direction- );- }-- /// <summary>- /// Get the lowest container in the tree that has both `containerA` and `containerB` as- /// descendants.- /// </summary>- public static Container GetLowestCommonAncestor(Container containerA, Container containerB)- {- var ancestorA = containerA;-- // Traverse upwards from container A.- while (ancestorA != null)- {- var ancestorB = containerB;-- // Traverse upwards from container B.- while (ancestorB != null)- {- if (ancestorA == ancestorB)- return ancestorA;-- ancestorB = ancestorB.Parent;- }-- ancestorA = ancestorA.Parent;- }-- throw new Exception("No common ancestor between containers. This is a bug.");- }- }-}diff --git a/GlazeWM.Domain/Containers/Events/FocusChangedEvent.cs b/GlazeWM.Domain/Containers/Events/FocusChangedEvent.csdeleted file mode 100644index 2bf7556a..00000000--- a/GlazeWM.Domain/Containers/Events/FocusChangedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Events-{- public record FocusChangedEvent(Container FocusedContainer)- : Event(DomainEvent.FocusChanged);-}diff --git a/GlazeWM.Domain/Containers/Events/FocusedContainerMovedEvent.cs b/GlazeWM.Domain/Containers/Events/FocusedContainerMovedEvent.csdeleted file mode 100644index a781a904..00000000--- a/GlazeWM.Domain/Containers/Events/FocusedContainerMovedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Events-{- public record FocusedContainerMovedEvent(Container FocusedContainer)- : Event(DomainEvent.FocusedContainerMoved);-}diff --git a/GlazeWM.Domain/Containers/Events/NativeFocusSyncedEvent.cs b/GlazeWM.Domain/Containers/Events/NativeFocusSyncedEvent.csdeleted file mode 100644index 7c59f9c4..00000000--- a/GlazeWM.Domain/Containers/Events/NativeFocusSyncedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Events-{- public record NativeFocusSyncedEvent(Container FocusedContainer)- : Event(DomainEvent.NativeFocusSynced);-}diff --git a/GlazeWM.Domain/Containers/Events/TilingDirectionChangedEvent.cs b/GlazeWM.Domain/Containers/Events/TilingDirectionChangedEvent.csdeleted file mode 100644index 86767c4a..00000000--- a/GlazeWM.Domain/Containers/Events/TilingDirectionChangedEvent.cs+++ /dev/null@@ -1,9 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Containers.Events-{- public record TilingDirectionChangedEvent(TilingDirection NewTilingDirection)- : Event(DomainEvent.TilingDirectionChanged);-}diff --git a/GlazeWM.Domain/Containers/IResizable.cs b/GlazeWM.Domain/Containers/IResizable.csdeleted file mode 100644index 4a3cd9b1..00000000--- a/GlazeWM.Domain/Containers/IResizable.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace GlazeWM.Domain.Containers-{- public interface IResizable- {- double SizePercentage { get; set; }- }-}diff --git a/GlazeWM.Domain/Containers/JsonContainerConverter.cs b/GlazeWM.Domain/Containers/JsonContainerConverter.csdeleted file mode 100644index f018fc47..00000000--- a/GlazeWM.Domain/Containers/JsonContainerConverter.cs+++ /dev/null@@ -1,160 +0,0 @@-using System;-using System.Text.Json;-using System.Text.Json.Serialization;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Serialization;--namespace GlazeWM.Domain.Containers-{- public class JsonContainerConverter : JsonConverter<Container>- {- public override bool CanConvert(Type typeToConvert)- {- return typeof(Container).IsAssignableFrom(typeToConvert);- }-- public override Container Read(- ref Utf8JsonReader reader,- Type typeToConvert,- JsonSerializerOptions options)- {- throw new NotSupportedException(- $"Deserializing {typeToConvert.Name} from JSON is not supported."- );- }-- public override void Write(- Utf8JsonWriter writer,- Container value,- JsonSerializerOptions options)- {- writer.WriteStartObject();-- switch (value)- {- case Monitor monitor:- WriteMonitorProperties(writer, monitor, options);- break;- case Workspace workspace:- WriteSplitContainerProperties(writer, workspace, options);- WriteWorkspaceProperties(writer, workspace, options);- break;- case SplitContainer splitContainer:- WriteSplitContainerProperties(writer, splitContainer, options);- break;- case MinimizedWindow minimizedWindow:- WriteWindowProperties(writer, minimizedWindow, options);- WriteMinimizedWindowProperties(writer, minimizedWindow, options);- break;- case FloatingWindow floatingWindow:- WriteWindowProperties(writer, floatingWindow, options);- break;- case TilingWindow tilingWindow:- WriteWindowProperties(writer, tilingWindow, options);- WriteTilingWindowProperties(writer, tilingWindow, options);- break;- }-- // The following properties are required for all container types.- WriteCommonProperties(writer, value, options);-- writer.WriteEndObject();- }-- private void WriteCommonProperties(- Utf8JsonWriter writer,- Container value,- JsonSerializerOptions options)- {- writer.WriteString(JsonParser.ChangeCasing("Id", options), value.Id);- writer.WriteNumber(JsonParser.ChangeCasing("X", options), value.X);- writer.WriteNumber(JsonParser.ChangeCasing("Y", options), value.Y);- writer.WriteNumber(JsonParser.ChangeCasing("Width", options), value.Width);- writer.WriteNumber(JsonParser.ChangeCasing("Height", options), value.Height);- writer.WritePropertyName(JsonParser.ChangeCasing("Type", options));- JsonSerializer.Serialize(writer, value.Type, options);- writer.WriteNumber(- JsonParser.ChangeCasing("FocusIndex", options),- value.FocusIndex- );-- // Recursively serialize child containers.- writer.WriteStartArray(JsonParser.ChangeCasing("Children", options));- foreach (var child in value.Children)- Write(writer, child, options);-- writer.WriteEndArray();- }-- private static void WriteMonitorProperties(- Utf8JsonWriter writer,- Monitor monitor,- JsonSerializerOptions options)- {- writer.WriteString(- JsonParser.ChangeCasing("DeviceName", options),- monitor.DeviceName- );- }-- private static void WriteWorkspaceProperties(- Utf8JsonWriter writer,- Workspace workspace,- JsonSerializerOptions options)- {- writer.WriteString(JsonParser.ChangeCasing("Name", options), workspace.Name);- }-- private static void WriteSplitContainerProperties(- Utf8JsonWriter writer,- SplitContainer splitContainer,- JsonSerializerOptions options)- {- writer.WritePropertyName(JsonParser.ChangeCasing("TilingDirection", options));- JsonSerializer.Serialize(writer, splitContainer.TilingDirection, options);-- writer.WriteNumber(- JsonParser.ChangeCasing("SizePercentage", options),- splitContainer.SizePercentage- );- }-- private static void WriteWindowProperties(- Utf8JsonWriter writer,- Window window,- JsonSerializerOptions options)- {- writer.WritePropertyName(JsonParser.ChangeCasing("FloatingPlacement", options));- JsonSerializer.Serialize(writer, window.FloatingPlacement, options);- writer.WritePropertyName(JsonParser.ChangeCasing("BorderDelta", options));- JsonSerializer.Serialize(writer, window.BorderDelta, options);- writer.WriteNumber(- JsonParser.ChangeCasing("Handle", options),- window.Handle.ToInt64()- );- }-- private static void WriteMinimizedWindowProperties(- Utf8JsonWriter writer,- MinimizedWindow minimizedWindow,- JsonSerializerOptions options)- {-- writer.WritePropertyName(JsonParser.ChangeCasing("PreviousState", options));- JsonSerializer.Serialize(writer, minimizedWindow.PreviousState, options);- }-- private static void WriteTilingWindowProperties(- Utf8JsonWriter writer,- TilingWindow tilingWindow,- JsonSerializerOptions options)- {- writer.WriteNumber(- JsonParser.ChangeCasing("SizePercentage", options),- tilingWindow.SizePercentage- );- }- }-}diff --git a/GlazeWM.Domain/Containers/RootContainer.cs b/GlazeWM.Domain/Containers/RootContainer.csdeleted file mode 100644index 8a3add5f..00000000--- a/GlazeWM.Domain/Containers/RootContainer.cs+++ /dev/null@@ -1,10 +0,0 @@-using GlazeWM.Domain.Common;--namespace GlazeWM.Domain.Containers-{- public sealed class RootContainer : Container- {- /// <inheritdoc />- public override ContainerType Type { get; } = ContainerType.Root;- }-}diff --git a/GlazeWM.Domain/Containers/SplitContainer.cs b/GlazeWM.Domain/Containers/SplitContainer.csdeleted file mode 100644index 6392d90c..00000000--- a/GlazeWM.Domain/Containers/SplitContainer.cs+++ /dev/null@@ -1,24 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure;--namespace GlazeWM.Domain.Containers-{- public class SplitContainer : Container, IResizable- {- /// <inheritdoc />- public override ContainerType Type { get; } = ContainerType.Split;-- public TilingDirection TilingDirection { get; set; } = TilingDirection.Horizontal;-- public double SizePercentage { get; set; } = 1;-- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();-- public override int Width => _containerService.GetWidthOfResizableContainer(this);- public override int Height => _containerService.GetHeightOfResizableContainer(this);- public override int X => _containerService.GetXOfResizableContainer(this);- public override int Y => _containerService.GetYOfResizableContainer(this);- }-}diff --git a/GlazeWM.Domain/DependencyInjection.cs b/GlazeWM.Domain/DependencyInjection.csdeleted file mode 100644index 6a1dfbe3..00000000--- a/GlazeWM.Domain/DependencyInjection.cs+++ /dev/null@@ -1,99 +0,0 @@-using GlazeWM.Domain.Common.CommandHandlers;-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.CommandHandlers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Monitors.CommandHandlers;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Monitors.EventHandlers;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.CommandHandlers;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Windows.CommandHandlers;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Windows.EventHandlers;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Domain.Workspaces.CommandHandlers;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.DependencyInjection;--namespace GlazeWM.Domain-{- public static class DependencyInjection- {- public static IServiceCollection AddDomainServices(this IServiceCollection services)- {- services.AddSingleton<ContainerService>();- services.AddSingleton<MonitorService>();- services.AddSingleton<CommandParsingService>();- services.AddSingleton<UserConfigService>();- services.AddSingleton<WindowService>();- services.AddSingleton<WorkspaceService>();-- services.AddSingleton<ICommandHandler<PopulateInitialStateCommand>, PopulateInitialStateHandler>();- services.AddSingleton<ICommandHandler<ExecProcessCommand>, ExecProcessHandler>();- services.AddSingleton<ICommandHandler<SetBindingModeCommand>, SetBindingModeHandler>();- services.AddSingleton<ICommandHandler<AttachContainerCommand>, AttachContainerHandler>();- services.AddSingleton<ICommandHandler<CenterCursorOnContainerCommand>, CenterCursorOnContainerHandler>();- services.AddSingleton<ICommandHandler<SetActiveWindowBorderCommand>, SetActiveWindowBorderHandler>();- services.AddSingleton<ICommandHandler<ChangeTilingDirectionCommand>, ChangeTilingDirectionHandler>();- services.AddSingleton<ICommandHandler<ToggleTilingDirectionCommand>, ToggleTilingDirectionHandler>();- services.AddSingleton<ICommandHandler<DetachContainerCommand>, DetachContainerHandler>();- services.AddSingleton<ICommandHandler<FlattenSplitContainerCommand>, FlattenSplitContainerHandler>();- services.AddSingleton<ICommandHandler<FocusInDirectionCommand>, FocusInDirectionHandler>();- services.AddSingleton<ICommandHandler<MoveContainerWithinTreeCommand>, MoveContainerWithinTreeHandler>();- services.AddSingleton<ICommandHandler<RedrawContainersCommand>, RedrawContainersHandler>();- services.AddSingleton<ICommandHandler<ReplaceContainerCommand>, ReplaceContainerHandler>();- services.AddSingleton<ICommandHandler<ResizeContainerCommand>, ResizeContainerHandler>();- services.AddSingleton<ICommandHandler<SetFocusedDescendantCommand>, SetFocusedDescendantHandler>();- services.AddSingleton<ICommandHandler<SyncNativeFocusCommand>, SyncNativeFocusHandler>();- services.AddSingleton<ICommandHandler<ToggleFocusModeCommand>, ToggleFocusModeHandler>();- services.AddSingleton<ICommandHandler<AddMonitorCommand>, AddMonitorHandler>();- services.AddSingleton<ICommandHandler<RefreshMonitorStateCommand>, RefreshMonitorStateHandler>();- services.AddSingleton<ICommandHandler<RemoveMonitorCommand>, RemoveMonitorHandler>();- services.AddSingleton<ICommandHandler<EvaluateUserConfigCommand>, EvaluateUserConfigHandler>();- services.AddSingleton<ICommandHandler<RegisterKeybindingsCommand>, RegisterKeybindingsHandler>();- services.AddSingleton<ICommandHandler<ReloadUserConfigCommand>, ReloadUserConfigHandler>();- services.AddSingleton<ICommandHandler<RunWithSubjectContainerCommand>, RunWithSubjectContainerHandler>();- services.AddSingleton<ICommandHandler<CloseWindowCommand>, CloseWindowHandler>();- services.AddSingleton<ICommandHandler<IgnoreWindowCommand>, IgnoreWindowHandler>();- services.AddSingleton<ICommandHandler<ManageWindowCommand>, ManageWindowHandler>();- services.AddSingleton<ICommandHandler<MoveWindowCommand>, MoveWindowHandler>();- services.AddSingleton<ICommandHandler<ResizeWindowCommand>, ResizeWindowHandler>();- services.AddSingleton<ICommandHandler<ResizeWindowBordersCommand>, ResizeWindowBordersHandler>();- services.AddSingleton<ICommandHandler<SetFloatingCommand>, SetFloatingHandler>();- services.AddSingleton<ICommandHandler<SetMaximizedCommand>, SetMaximizedHandler>();- services.AddSingleton<ICommandHandler<SetMinimizedCommand>, SetMinimizedHandler>();- services.AddSingleton<ICommandHandler<SetTilingCommand>, SetTilingHandler>();- services.AddSingleton<ICommandHandler<SetWindowSizeCommand>, SetWindowSizeHandler>();- services.AddSingleton<ICommandHandler<ToggleFloatingCommand>, ToggleFloatingHandler>();- services.AddSingleton<ICommandHandler<ToggleMaximizedCommand>, ToggleMaximizedHandler>();- services.AddSingleton<ICommandHandler<UnmanageWindowCommand>, UnmanageWindowHandler>();- services.AddSingleton<ICommandHandler<ActivateWorkspaceCommand>, ActivateWorkspaceHandler>();- services.AddSingleton<ICommandHandler<DeactivateWorkspaceCommand>, DeactivateWorkspaceHandler>();- services.AddSingleton<ICommandHandler<FocusWorkspaceCommand>, FocusWorkspaceHandler>();- services.AddSingleton<ICommandHandler<FocusWorkspaceRecentCommand>, FocusWorkspaceRecentHandler>();- services.AddSingleton<ICommandHandler<FocusWorkspaceSequenceCommand>, FocusWorkspaceSequenceHandler>();- services.AddSingleton<ICommandHandler<FocusContainerUnderCursorCommand>, FocusContainerUnderCursorHandler>();- services.AddSingleton<ICommandHandler<MoveWindowToWorkspaceCommand>, MoveWindowToWorkspaceHandler>();- services.AddSingleton<ICommandHandler<UpdateWorkspacesFromConfigCommand>, UpdateWorkspacesFromConfigHandler>();- services.AddSingleton<ICommandHandler<MoveWorkspaceInDirectionCommand>, MoveWorkspaceInDirectionHandler>();-- services.AddSingleton<IEventHandler<DisplaySettingsChangedEvent>, DisplaySettingsChangedHandler>();- services.AddSingleton<IEventHandler<WindowDestroyedEvent>, WindowDestroyedHandler>();- services.AddSingleton<IEventHandler<WindowFocusedEvent>, WindowFocusedHandler>();- services.AddSingleton<IEventHandler<WindowHiddenEvent>, WindowHiddenHandler>();- services.AddSingleton<IEventHandler<WindowLocationChangedEvent>, WindowLocationChangedHandler>();- services.AddSingleton<IEventHandler<WindowMinimizedEvent>, WindowMinimizedHandler>();- services.AddSingleton<IEventHandler<WindowMinimizeEndedEvent>, WindowMinimizeEndedHandler>();- services.AddSingleton<IEventHandler<WindowMovedOrResizedEvent>, WindowMovedOrResizedHandler>();- services.AddSingleton<IEventHandler<WindowShownEvent>, WindowShownHandler>();-- return services;- }- }-}diff --git a/GlazeWM.Domain/GlazeWM.Domain.csproj b/GlazeWM.Domain/GlazeWM.Domain.csprojdeleted file mode 100644index dc36b139..00000000--- a/GlazeWM.Domain/GlazeWM.Domain.csproj+++ /dev/null@@ -1,15 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <OutputType>Library</OutputType>- <TargetFramework>net7-windows10.0.17763.0</TargetFramework>- <UseWindowsForms>true</UseWindowsForms>- <ApplicationIcon />- <StartupObject />- <DebugType>embedded</DebugType>- </PropertyGroup>-- <ItemGroup>- <ProjectReference Include="..\GlazeWM.Infrastructure\GlazeWM.Infrastructure.csproj" />- </ItemGroup>-</Project>diff --git a/GlazeWM.Domain/Monitors/CommandHandlers/AddMonitorHandler.cs b/GlazeWM.Domain/Monitors/CommandHandlers/AddMonitorHandler.csdeleted file mode 100644index 48c3190d..00000000--- a/GlazeWM.Domain/Monitors/CommandHandlers/AddMonitorHandler.cs+++ /dev/null@@ -1,64 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Monitors.Events;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Exceptions;--namespace GlazeWM.Domain.Monitors.CommandHandlers-{- internal sealed class AddMonitorHandler : ICommandHandler<AddMonitorCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly WorkspaceService _workspaceService;-- public AddMonitorHandler(- Bus bus,- ContainerService containerService,- WorkspaceService workspaceService)- {- _bus = bus;- _containerService = containerService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(AddMonitorCommand command)- {- var screen = command.Screen;-- // Create a `Monitor` instance. Use the working area of the monitor instead of the bounds of- // the display. The working area excludes taskbars and other reserved display space.- var newMonitor = new Monitor(- screen.DeviceName,- screen.WorkingArea.Width,- screen.WorkingArea.Height,- screen.WorkingArea.X,- screen.WorkingArea.Y- );-- var rootContainer = _containerService.ContainerTree;- _bus.Invoke(new AttachContainerCommand(newMonitor, rootContainer));-- ActivateWorkspaceOnMonitor(newMonitor);-- _bus.Emit(new MonitorAddedEvent(newMonitor));-- return CommandResponse.Ok;- }-- private void ActivateWorkspaceOnMonitor(Monitor monitor)- {- // Get name of first workspace that is not active for that specified monitor or any.- var inactiveWorkspaceConfig = _workspaceService.GetWorkspaceConfigToActivate(monitor);-- if (inactiveWorkspaceConfig is null)- throw new FatalUserException("At least 1 workspace is required per monitor.");-- // Assign the workspace to the newly added monitor.- _bus.Invoke(new ActivateWorkspaceCommand(inactiveWorkspaceConfig.Name, monitor));- }- }-}diff --git a/GlazeWM.Domain/Monitors/CommandHandlers/RefreshMonitorStateHandler.cs b/GlazeWM.Domain/Monitors/CommandHandlers/RefreshMonitorStateHandler.csdeleted file mode 100644index c15d5946..00000000--- a/GlazeWM.Domain/Monitors/CommandHandlers/RefreshMonitorStateHandler.cs+++ /dev/null@@ -1,90 +0,0 @@-using System.Linq;-using System.Windows.Forms;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Monitors.Events;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.CommandHandlers-{- internal sealed class RefreshMonitorStateHandler : ICommandHandler<RefreshMonitorStateCommand>- {- private readonly Bus _bus;- private readonly MonitorService _monitorService;- private readonly ContainerService _containerService;- private readonly WindowService _windowService;-- public RefreshMonitorStateHandler(- Bus bus,- MonitorService monitorService,- ContainerService containerService,- WindowService windowService)- {- _bus = bus;- _monitorService = monitorService;- _containerService = containerService;- _windowService = windowService;- }-- public CommandResponse Handle(RefreshMonitorStateCommand command)- {- foreach (var screen in Screen.AllScreens)- {- var foundMonitor = _monitorService.GetMonitorByDeviceName(screen.DeviceName);-- // Add monitor if it doesn't exist in state.- if (foundMonitor == null)- {- _bus.Invoke(new AddMonitorCommand(screen));- continue;- }-- // Update monitor with changes to dimensions and positioning.- foundMonitor.Width = screen.WorkingArea.Width;- foundMonitor.Height = screen.WorkingArea.Height;- foundMonitor.X = screen.WorkingArea.X;- foundMonitor.Y = screen.WorkingArea.Y;-- _bus.Emit(new WorkingAreaResizedEvent(foundMonitor));- }-- // Verify that all monitors in state exist in `Screen.AllScreens`.- var monitorsToRemove = _monitorService.GetMonitors().Where(- monitor => !IsMonitorActive(monitor)- );-- // Remove any monitors that no longer exist and move their workspaces to other monitors.- // TODO: Verify that this works with "Duplicate these displays" or "Show only X" settings.- foreach (var monitor in monitorsToRemove.ToList())- {- _bus.Invoke(new RemoveMonitorCommand(monitor));- }-- foreach (var window in _windowService.GetWindows())- {- // Display setting changes can spread windows out sporadically, so mark all windows as- // needing a DPI adjustment (just in case).- window.HasPendingDpiAdjustment = true;-- // Need to update floating position of moved windows when a monitor is disconnected or if- // the primary display is changed. The primary display dictates the position of 0,0.- var parentWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(window);- window.FloatingPlacement =- window.FloatingPlacement.TranslateToCenter(parentWorkspace.ToRect());- }-- // Redraw full container tree.- _containerService.ContainersToRedraw.Add(_containerService.ContainerTree);-- return CommandResponse.Ok;- }-- private static bool IsMonitorActive(Monitor monitor)- {- return Screen.AllScreens.Any(screen => screen.DeviceName == monitor.DeviceName);- }- }-}diff --git a/GlazeWM.Domain/Monitors/CommandHandlers/RemoveMonitorHandler.cs b/GlazeWM.Domain/Monitors/CommandHandlers/RemoveMonitorHandler.csdeleted file mode 100644index aa97cd8a..00000000--- a/GlazeWM.Domain/Monitors/CommandHandlers/RemoveMonitorHandler.cs+++ /dev/null@@ -1,53 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Monitors.Events;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Domain.Workspaces.Events;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.CommandHandlers-{- internal sealed class RemoveMonitorHandler : ICommandHandler<RemoveMonitorCommand>- {- private readonly Bus _bus;- private readonly MonitorService _monitorService;-- public RemoveMonitorHandler(Bus bus, MonitorService monitorService)- {- _bus = bus;- _monitorService = monitorService;- }-- public CommandResponse Handle(RemoveMonitorCommand command)- {- var monitorToRemove = command.MonitorToRemove;- var targetMonitor = _monitorService.GetMonitors().First(- monitor => monitor != monitorToRemove- );-- // Keep reference to the focused monitor prior to moving workspaces around.- var focusedMonitor = _monitorService.GetFocusedMonitor();-- // Avoid moving empty workspaces.- var workspacesToMove = monitorToRemove.Children- .Cast<Workspace>()- .Where(workspace => workspace.HasChildren() || workspace.KeepAlive);-- foreach (var workspace in workspacesToMove.ToList())- {- // Move workspace to target monitor.- _bus.Invoke(new MoveContainerWithinTreeCommand(workspace, targetMonitor));-- // Update workspaces displayed in bar window.- // TODO: Consider creating separate event `WorkspaceMovedEvent`.- _bus.Emit(new WorkspaceActivatedEvent(workspace));- }-- _bus.Invoke(new DetachContainerCommand(monitorToRemove));- _bus.Emit(new MonitorRemovedEvent(monitorToRemove.Id, monitorToRemove.DeviceName));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Monitors/Commands/AddMonitorCommand.cs b/GlazeWM.Domain/Monitors/Commands/AddMonitorCommand.csdeleted file mode 100644index 496d0586..00000000--- a/GlazeWM.Domain/Monitors/Commands/AddMonitorCommand.cs+++ /dev/null@@ -1,15 +0,0 @@-using System.Windows.Forms;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Commands-{- public class AddMonitorCommand : Command- {- public Screen Screen { get; set; }-- public AddMonitorCommand(Screen screen)- {- Screen = screen;- }- }-}diff --git a/GlazeWM.Domain/Monitors/Commands/RefreshMonitorStateCommand.cs b/GlazeWM.Domain/Monitors/Commands/RefreshMonitorStateCommand.csdeleted file mode 100644index 6114db31..00000000--- a/GlazeWM.Domain/Monitors/Commands/RefreshMonitorStateCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Commands-{- public class RefreshMonitorStateCommand : Command- {- }-}diff --git a/GlazeWM.Domain/Monitors/Commands/RemoveMonitorCommand.cs b/GlazeWM.Domain/Monitors/Commands/RemoveMonitorCommand.csdeleted file mode 100644index 92094058..00000000--- a/GlazeWM.Domain/Monitors/Commands/RemoveMonitorCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Commands-{- public class RemoveMonitorCommand : Command- {- public Monitor MonitorToRemove { get; set; }-- public RemoveMonitorCommand(Monitor monitorToRemove)- {- MonitorToRemove = monitorToRemove;- }- }-}diff --git a/GlazeWM.Domain/Monitors/EventHandlers/DisplaySettingsChangedHandler.cs b/GlazeWM.Domain/Monitors/EventHandlers/DisplaySettingsChangedHandler.csdeleted file mode 100644index 26fc7684..00000000--- a/GlazeWM.Domain/Monitors/EventHandlers/DisplaySettingsChangedHandler.cs+++ /dev/null@@ -1,21 +0,0 @@-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;--namespace GlazeWM.Domain.Monitors.EventHandlers-{- internal sealed class DisplaySettingsChangedHandler : IEventHandler<DisplaySettingsChangedEvent>- {- private readonly Bus _bus;-- public DisplaySettingsChangedHandler(Bus bus)- {- _bus = bus;- }-- public void Handle(DisplaySettingsChangedEvent @event)- {- _bus.Invoke(new RefreshMonitorStateCommand());- }- }-}diff --git a/GlazeWM.Domain/Monitors/Events/MonitorAddedEvent.cs b/GlazeWM.Domain/Monitors/Events/MonitorAddedEvent.csdeleted file mode 100644index 15a3d8bb..00000000--- a/GlazeWM.Domain/Monitors/Events/MonitorAddedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Events-{- public record MonitorAddedEvent(Monitor AddedMonitor)- : Event(DomainEvent.MonitorAdded);-}diff --git a/GlazeWM.Domain/Monitors/Events/MonitorRemovedEvent.cs b/GlazeWM.Domain/Monitors/Events/MonitorRemovedEvent.csdeleted file mode 100644index c1db71c4..00000000--- a/GlazeWM.Domain/Monitors/Events/MonitorRemovedEvent.cs+++ /dev/null@@ -1,9 +0,0 @@-using System;-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Events-{- public record MonitorRemovedEvent(Guid RemovedId, string RemovedDeviceName)- : Event(DomainEvent.MonitorRemoved);-}diff --git a/GlazeWM.Domain/Monitors/Events/WorkingAreaResizedEvent.cs b/GlazeWM.Domain/Monitors/Events/WorkingAreaResizedEvent.csdeleted file mode 100644index 73f7f18e..00000000--- a/GlazeWM.Domain/Monitors/Events/WorkingAreaResizedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Monitors.Events-{- public record WorkingAreaResizedEvent(Monitor AffectedMonitor)- : Event(DomainEvent.WorkingAreaResized);-}diff --git a/GlazeWM.Domain/Monitors/Monitor.cs b/GlazeWM.Domain/Monitors/Monitor.csdeleted file mode 100644index 75b94020..00000000--- a/GlazeWM.Domain/Monitors/Monitor.cs+++ /dev/null@@ -1,31 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Workspaces;--namespace GlazeWM.Domain.Monitors-{- public sealed class Monitor : Container- {- /// <inheritdoc />- public override ContainerType Type { get; } = ContainerType.Monitor;-- public string DeviceName { get; set; }- public override int Width { get; set; }- public override int Height { get; set; }- public override int X { get; set; }- public override int Y { get; set; }-- public Workspace DisplayedWorkspace => LastFocusedChild as Workspace;- public uint Dpi => MonitorService.GetMonitorDpi(this);- public double ScaleFactor => Dpi / 96.0;-- public Monitor(string deviceName, int width, int height, int x, int y)- {- DeviceName = deviceName;- Width = width;- Height = height;- X = x;- Y = y;- }- }-}diff --git a/GlazeWM.Domain/Monitors/MonitorService.cs b/GlazeWM.Domain/Monitors/MonitorService.csdeleted file mode 100644index fd0e0bd4..00000000--- a/GlazeWM.Domain/Monitors/MonitorService.cs+++ /dev/null@@ -1,140 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Windows.Forms;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure.WindowsApi;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Monitors-{- public class MonitorService- {- private readonly ContainerService _containerService;-- public MonitorService(ContainerService containerService)- {- _containerService = containerService;- }-- /// <summary>- /// Get monitors by iterating over the children of the root container.- /// </summary>- public IEnumerable<Monitor> GetMonitors()- {- return _containerService.ContainerTree.Children.Cast<Monitor>();- }-- public Monitor GetMonitorByDeviceName(string deviceName)- {- return GetMonitors().FirstOrDefault(monitor => monitor.DeviceName == deviceName);- }-- public static Monitor GetMonitorFromChildContainer(Container container)- {- return container.SelfAndAncestors.OfType<Monitor>().First();- }-- /// <summary>- /// Get the monitor that encompasses the largest portion of the window handle.- /// </summary>- public Monitor GetMonitorFromHandleLocation(IntPtr windowHandle)- {- var screen = Screen.FromHandle(windowHandle);-- return GetMonitorByDeviceName(screen.DeviceName) ?? GetMonitors().First();- }-- public Monitor GetFocusedMonitor()- {- return GetMonitorFromChildContainer(_containerService.FocusedContainer);- }-- public static uint GetMonitorDpi(Monitor monitor)- {- // Create a point within the monitor's dimensions.- var point = new Point- {- X = monitor.X + 1,- Y = monitor.Y + 1- };-- // Get a handle to the monitor.- // TODO: Consider adding a `Monitor` getter for a monitor's handle.- var monitorHandle = MonitorFromPoint(point, MonitorFromPointFlags.DefaultToNearest);- _ = GetDpiForMonitor(monitorHandle, DpiType.Effective, out var dpiX, out _);-- // DPI X and Y should be equivalent, so it's arbitrary which to return.- return dpiX;- }-- /// <summary>- /// Whether there is a difference in DPI between two containers.- /// </summary>- public static bool HasDpiDifference(Container firstContainer, Container secondContainer)- {- var firstMonitor = firstContainer is Monitor ?- firstContainer as Monitor : GetMonitorFromChildContainer(firstContainer);-- var secondMonitor = secondContainer is Monitor ?- secondContainer as Monitor : GetMonitorFromChildContainer(secondContainer);-- return firstMonitor.Dpi != secondMonitor.Dpi;- }-- /// <summary>- /// Get monitor in a given direction. Use i3wm's algorithm for finding best guess.- /// </summary>- /// <param name="direction">Direction to search in.</param>- /// <param name="originMonitor">The monitor to search from.</param>- public Monitor GetMonitorInDirection(Direction direction, Monitor originMonitor)- {- Monitor monitorInDirection = null;-- foreach (var monitor in GetMonitors())- {- // Check whether the monitor is to the right/left of the origin monitor.- if (- (direction == Direction.Right && monitor.X > originMonitor.X) ||- (direction == Direction.Left && monitor.X < originMonitor.X))- {- // Check whether the y-coordinate overlaps with the y-coordinate of the origin monitor.- if (- monitor.Y + monitor.Height <= originMonitor.Y ||- originMonitor.Y + originMonitor.Height <= monitor.Y- )- continue;- }- // Check whether the monitor is below/above the origin monitor.- else if (- (direction == Direction.Down && monitor.Y > originMonitor.Y) ||- (direction == Direction.Up && monitor.Y < originMonitor.Y))- {- // Check whether the x-coordinate overlaps with the x-coordinate of the origin monitor.- if (- monitor.X + monitor.Width <= originMonitor.X ||- originMonitor.X + originMonitor.Width <= monitor.X- )- continue;- }- // Skip monitors that are not in the given direction.- else- continue;-- // Set `monitorInDirection` if no suitable monitors have been found yet or if the monitor- // is closer.- if (- monitorInDirection == null ||- (direction == Direction.Right && monitor.X < monitorInDirection.X) ||- (direction == Direction.Left && monitor.X > monitorInDirection.X) ||- (direction == Direction.Down && monitor.Y < monitorInDirection.Y) ||- (direction == Direction.Up && monitor.Y > monitorInDirection.Y)- )- monitorInDirection = monitor;- }-- return monitorInDirection;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/BarComponentConfig.cs b/GlazeWM.Domain/UserConfigs/BarComponentConfig.csdeleted file mode 100644index 59b7d9e1..00000000--- a/GlazeWM.Domain/UserConfigs/BarComponentConfig.cs+++ /dev/null@@ -1,57 +0,0 @@-using System.ComponentModel.DataAnnotations;--namespace GlazeWM.Domain.UserConfigs-{- public class BarComponentConfig- {- [Required]- public string Type { get; set; }-- public string Margin { get; set; } = "0";-- /// <summary>- /// Background of the bar component. Use transparent as a default, since falling back- /// to bar background config looks weird with nested semi-transparent backgrounds.- /// </summary>- public string Background { get; set; } = "transparent";-- /// <summary>- /// Fallback to bar foreground config if unset.- /// </summary>- public string Foreground { get; set; }-- /// <summary>- /// Fallback to bar font family config if unset.- /// </summary>- public string FontFamily { get; set; }-- /// <summary>- /// Fallback to bar font weight config if unset.- /// </summary>- public string FontWeight { get; set; }-- /// <summary>- /// Fallback to bar font size config if unset.- /// </summary>- public string FontSize { get; set; }-- public string BorderColor { get; set; } = "blue";-- /// <summary>- /// Radius of the border in pixels.- /// </summary>- public string BorderRadius { get; set; } = "0px";-- /// <summary>- /// Width of the border in pixels. To set a different border width for each side, specify four- /// values (eg. "5 0 5 0"). The borders widths apply to the top, right, bottom, and left in that- /// order.- /// </summary>- public string BorderWidth { get; set; } = "0";-- /// <summary>- /// Padding in pixels.- /// </summary>- public string Padding { get; set; } = "0";- }-}diff --git a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs b/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.csdeleted file mode 100644index c0e18f4f..00000000--- a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs+++ /dev/null@@ -1,120 +0,0 @@-using System;-using System.Text.Json;-using System.Text.Json.Serialization;--namespace GlazeWM.Domain.UserConfigs-{- public class BarComponentConfigConverter : JsonConverter<BarComponentConfig>- {- public override BarComponentConfig Read(- ref Utf8JsonReader reader,- Type typeToConvert,- JsonSerializerOptions options)- {- using var jsonObject = JsonDocument.ParseValue(ref reader);-- // Get the type of bar component (eg. "workspaces").- var typeDiscriminator = jsonObject.RootElement.GetProperty("type").ToString();-- return typeDiscriminator switch- {- "battery" =>- JsonSerializer.Deserialize<BatteryComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "binding mode" =>- JsonSerializer.Deserialize<BindingModeComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "clock" =>- JsonSerializer.Deserialize<ClockComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "text" =>- JsonSerializer.Deserialize<TextComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "network" =>- JsonSerializer.Deserialize<NetworkComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "volume" =>- JsonSerializer.Deserialize<VolumeComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "tiling direction" =>- JsonSerializer.Deserialize<TilingDirectionComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "window title" =>- JsonSerializer.Deserialize<WindowTitleComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "system tray" =>- JsonSerializer.Deserialize<SystemTrayComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "image" =>- JsonSerializer.Deserialize<ImageComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "weather" =>- JsonSerializer.Deserialize<WeatherComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "workspaces" =>- JsonSerializer.Deserialize<WorkspacesComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "cpu" =>- JsonSerializer.Deserialize<CpuComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "gpu" =>- JsonSerializer.Deserialize<GpuComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "memory" =>- JsonSerializer.Deserialize<MemoryComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "text file" => JsonSerializer.Deserialize<TextFileComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- "music" => JsonSerializer.Deserialize<MusicComponentConfig>(- jsonObject.RootElement.ToString(),- options- ),- _ => throw new ArgumentException($"Invalid component type '{typeDiscriminator}'."),- };- }-- /// <summary>- /// Serializing is not needed, so it's fine to leave it unimplemented.- /// </summary>- /// <exception cref="NotImplementedException"></exception>- public override void Write(- Utf8JsonWriter writer,- BarComponentConfig value,- JsonSerializerOptions options)- {- throw new NotImplementedException();- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/BarComponentSeparatorConfig.cs b/GlazeWM.Domain/UserConfigs/BarComponentSeparatorConfig.csdeleted file mode 100755index ab2e9360..00000000--- a/GlazeWM.Domain/UserConfigs/BarComponentSeparatorConfig.cs+++ /dev/null@@ -1,10 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class BarComponentSeparatorConfig- {- public string Label { get; set; } = "";- public string LabelLeft { get; set; }- public string LabelCenter { get; set; }- public string LabelRight { get; set; }- }-}diff --git a/GlazeWM.Domain/UserConfigs/BarConfig.cs b/GlazeWM.Domain/UserConfigs/BarConfig.csdeleted file mode 100644index e97407ef..00000000--- a/GlazeWM.Domain/UserConfigs/BarConfig.cs+++ /dev/null@@ -1,55 +0,0 @@-using System.Collections.Generic;--namespace GlazeWM.Domain.UserConfigs-{- public class BarConfig- {- public bool Enabled { get; set; } = true;-- public bool AlwaysOnTop { get; set; } = false;-- public string OffsetX { get; set; } = "0px";-- public string OffsetY { get; set; } = "0px";-- public string BorderRadius { get; set; } = "0px";-- public string Height { get; set; } = "30px";-- public BarPosition Position { get; set; } = BarPosition.Top;-- public double Opacity { get; set; } = 1.0;-- public string Background { get; set; } = "black";-- public string Foreground { get; set; } = "white";-- public string FontFamily { get; set; } = "Segoe UI";-- public string FontWeight { get; set; } = "Normal";-- public string FontSize { get; set; } = "13";-- public string BorderColor { get; set; } = "blue";-- public BarComponentSeparatorConfig ComponentSeparator { get; set; } = new();-- /// <summary>- /// Width of the border in pixels. To set a different border width for each side, specify four- /// values (eg. "5 0 5 0"). The borders widths apply to the top, right, bottom, and left in that- /// order.- /// </summary>- public string BorderWidth { get; set; } = "0";-- /// <summary>- /// Padding in pixels.- /// </summary>- public string Padding { get; set; } = "0";-- public List<BarComponentConfig> ComponentsLeft { get; set; } = new List<BarComponentConfig>();-- public List<BarComponentConfig> ComponentsCenter { get; set; } = new List<BarComponentConfig>();-- public List<BarComponentConfig> ComponentsRight { get; set; } = new List<BarComponentConfig>();- }-}diff --git a/GlazeWM.Domain/UserConfigs/BarPosition.cs b/GlazeWM.Domain/UserConfigs/BarPosition.csdeleted file mode 100644index f053fab1..00000000--- a/GlazeWM.Domain/UserConfigs/BarPosition.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public enum BarPosition- {- Top,- Bottom- }-}diff --git a/GlazeWM.Domain/UserConfigs/BatteryComponentConfig.cs b/GlazeWM.Domain/UserConfigs/BatteryComponentConfig.csdeleted file mode 100644index 9756be85..00000000--- a/GlazeWM.Domain/UserConfigs/BatteryComponentConfig.cs+++ /dev/null@@ -1,32 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- /// <summary>- /// <para>- /// A component to display information about the battery of the device, namely the battery level and- /// whether the device is connected to power or is in power saving mode.- /// </para>- /// <para>- /// There are 3 labels that are used depending on the situation, and the variable- /// <c>{battery_level}</c> is replaced with the current battery level of the device.- /// </para>- /// <para>- /// When the device does not have a dedicated battery, the battery level is displayed- /// as 100% at all times.- /// </para>- /// </summary>- public class BatteryComponentConfig : BarComponentConfig- {- /// <summary>- /// Formatted text to display when the device is draining battery power.- /// </summary>- public string LabelDraining { get; set; } = "{battery_level}%";- /// <summary>- /// Formatted text to display when the device is in power saving mode.- /// </summary>- public string LabelPowerSaver { get; set; } = "{battery_level}% (power saver)";- /// <summary>- /// Formatted text to display when the device is connected to power.- /// </summary>- public string LabelCharging { get; set; } = "{battery_level}% (charging)";- }-}diff --git a/GlazeWM.Domain/UserConfigs/BindingMode.cs b/GlazeWM.Domain/UserConfigs/BindingMode.csdeleted file mode 100644index b0256b44..00000000--- a/GlazeWM.Domain/UserConfigs/BindingMode.cs+++ /dev/null@@ -1,11 +0,0 @@-using System.Collections.Generic;--namespace GlazeWM.Domain.UserConfigs-{- public class BindingMode- {- public string Name { get; set; }-- public List<KeybindingConfig> Keybindings { get; set; } = new();- }-}diff --git a/GlazeWM.Domain/UserConfigs/BindingModeComponentConfig.cs b/GlazeWM.Domain/UserConfigs/BindingModeComponentConfig.csdeleted file mode 100644index 4d465d71..00000000--- a/GlazeWM.Domain/UserConfigs/BindingModeComponentConfig.cs+++ /dev/null@@ -1,10 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class BindingModeComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the binding mode component.- /// </summary>- public string Label { get; set; } = "{binding_mode}";- }-}diff --git a/GlazeWM.Domain/UserConfigs/ClockComponentConfig.cs b/GlazeWM.Domain/UserConfigs/ClockComponentConfig.csdeleted file mode 100644index 823a8e87..00000000--- a/GlazeWM.Domain/UserConfigs/ClockComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class ClockComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the clock component.- /// </summary>- public string Label { get; set; } = "{formatted_time}";-- /// <summary>- /// How to format the current time/date via `DateTime.ToString`.- /// </summary>- public string TimeFormatting { get; set; } = "hh:mm tt ddd MMM d";- }-}diff --git a/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs b/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.csdeleted file mode 100644index 0276c69f..00000000--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs+++ /dev/null@@ -1,228 +0,0 @@-using System;-using System.Collections.Generic;-using System.IO;-using System.Linq;-using System.Reflection;-using System.Text.Json;-using System.Windows.Forms;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Exceptions;-using GlazeWM.Infrastructure.Serialization;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.UserConfigs.CommandHandlers-{- internal sealed class EvaluateUserConfigHandler : ICommandHandler<EvaluateUserConfigCommand>- {- private readonly Bus _bus;- private readonly UserConfigService _userConfigService;- private readonly CommandParsingService _commandParsingService;-- /// <summary>- /// Keywords that cannot be used as workspace names.- /// </summary>- private static readonly HashSet<string> RESERVED_WORKSPACE_NAMES = new()- {- "prev",- "next",- "recent"- };-- public EvaluateUserConfigHandler(- Bus bus,- UserConfigService userConfigService,- CommandParsingService commandParsingService)- {- _bus = bus;- _userConfigService = userConfigService;- _commandParsingService = commandParsingService;- }-- public CommandResponse Handle(EvaluateUserConfigCommand command)- {- var userConfigPath = _userConfigService.UserConfigPath;-- if (!File.Exists(userConfigPath))- InitializeSampleUserConfig(userConfigPath);-- var deserializedConfig = DeserializeUserConfig(userConfigPath);-- // Merge default window rules with user-defined rules.- var defaultWindowRules = _userConfigService.DefaultWindowRules;- deserializedConfig.WindowRules.InsertRange(0, defaultWindowRules);-- _userConfigService.UserConfig = deserializedConfig;-- // Check for required properties and validate command strings.- ValidateDeserializedConfig(deserializedConfig);-- // Register keybindings.- _bus.Invoke(new RegisterKeybindingsCommand(deserializedConfig.Keybindings));-- return CommandResponse.Ok;- }-- private static void InitializeSampleUserConfig(string userConfigPath)- {- // Fix any inconsistencies in directory delimiters.- var normalizedUserConfigPath = new FileInfo(userConfigPath).FullName;-- var promptResult = MessageBox.Show(- $"No config file found at {normalizedUserConfigPath}. Create a new config file from the starter template?",- "No config file found",- MessageBoxButtons.OKCancel- );-- if (promptResult == DialogResult.Cancel)- throw new FatalUserException("Cannot start the app without a configuration file.");-- var assembly = Assembly.GetEntryAssembly();- const string sampleConfigResourceName = "GlazeWM.App.Resources.sample-config.yaml";-- // Create containing directory. Needs to be created before writing to the file.- Directory.CreateDirectory(Path.GetDirectoryName(userConfigPath));-- // Get the embedded sample user config from the entry assembly.- using var stream = assembly.GetManifestResourceStream(sampleConfigResourceName);-- // Write the sample user config to the appropriate destination.- using var fileStream = new FileStream(userConfigPath, FileMode.Create, FileAccess.Write);- stream.CopyTo(fileStream);- }-- private static UserConfig DeserializeUserConfig(string userConfigPath)- {- try- {- var userConfigLines = File.ReadAllLines(userConfigPath);- var input = string.Join(Environment.NewLine, userConfigLines);-- var deserializeOptions = JsonParser.OptionsFactory((options) =>- options.Converters.Add(new BarComponentConfigConverter())- );-- return YamlParser.ToInstance<UserConfig>(input, deserializeOptions);- }- catch (Exception exception)- {- throw new FatalUserException(FormatConfigError(exception));- }- }-- // TODO: Might be able to remove the required checks once nullable context is enabled.- private void ValidateDeserializedConfig(UserConfig deserializedConfig)- {- try- {- foreach (var workspaceConfig in deserializedConfig.Workspaces)- {- if (workspaceConfig.Name is null)- throw new FatalUserException("Property 'name' is required in workspace config.");-- if (RESERVED_WORKSPACE_NAMES.Contains(workspaceConfig.Name))- throw new FatalUserException(- $"Cannot use keyword '{workspaceConfig.Name}' as workspace name."- );- }-- var componentConfigs = deserializedConfig.Bar.ComponentsLeft- .Concat(deserializedConfig.Bar.ComponentsCenter)- .Concat(deserializedConfig.Bar.ComponentsRight);-- foreach (var componentConfig in componentConfigs)- {- if (componentConfig.Type is null)- throw new FatalUserException("Property 'type' is required in bar component config.");- }-- var keybindingsConfig = deserializedConfig.Keybindings;- var windowRulesConfig = deserializedConfig.WindowRules;-- foreach (var keybindingConfig in keybindingsConfig)- {- if (keybindingConfig.BindingList.Count == 0)- throw new FatalUserException(- "Property 'binding' or 'bindings' is required in keybinding config."- );-- // Check that all keybindings in the config can be cast to `Keys` enum.- foreach (var keybinding in keybindingConfig.BindingList)- {- try- {- var _ = KeybindingHelper.ParseKeybindingString(keybinding);- }- catch (ArgumentException exception)- {- throw new FatalUserException(- $"Invalid binding '{keybinding}' in keybinding config: {exception.Message}"- );- }- }-- if (keybindingConfig.CommandList.Count == 0)- throw new FatalUserException(- "Property 'command' or 'commands' is required in keybinding config."- );- }-- foreach (var windowRuleConfig in windowRulesConfig)- {- var hasMatchingRegex =- windowRuleConfig.MatchClassName is not null ||- windowRuleConfig.MatchProcessName is not null ||- windowRuleConfig.MatchTitle is not null;-- if (!hasMatchingRegex)- throw new FatalUserException(- "At least 1 matching regex (eg. 'match_process_name') is required in window rule config."- );-- if (windowRuleConfig.CommandList.Count == 0)- throw new FatalUserException(- "Property 'command' or 'commands' is required in window rule config."- );- }-- var textComponentCommands = componentConfigs- .OfType<TextComponentConfig>()- .SelectMany(- (componentConfig) => new List<string> {- componentConfig.LeftClickCommand,- componentConfig.RightClickCommand- }- )- .Where((commandString) => !string.IsNullOrEmpty(commandString));-- var allCommandStrings = new List<string>()- .Concat(keybindingsConfig.SelectMany((keybinding) => keybinding.CommandList))- .Concat(windowRulesConfig.SelectMany((windowRule) => windowRule.CommandList))- .Concat(textComponentCommands)- .Select((commandString) => CommandParsingService.FormatCommand(commandString));-- foreach (var commandString in allCommandStrings)- _commandParsingService.ValidateCommand(commandString);- }- catch (Exception exception)- {- throw new FatalUserException(FormatConfigError(exception));- }- }-- private static string FormatConfigError(Exception exception)- {- var errorMessage = "Failed to parse user config. ";-- // Add path to property for deserialization error messages.- if ((exception as JsonException)?.Path is not null)- {- errorMessage += $"Invalid value at property: '{(exception as JsonException).Path}'.";- return errorMessage;- }-- errorMessage += exception.Message;- return errorMessage;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/CommandHandlers/RegisterKeybindingsHandler.cs b/GlazeWM.Domain/UserConfigs/CommandHandlers/RegisterKeybindingsHandler.csdeleted file mode 100644index a6fc2f54..00000000--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/RegisterKeybindingsHandler.cs+++ /dev/null@@ -1,72 +0,0 @@-using System;-using System.Linq;-using System.Threading.Tasks;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.WindowsApi;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.UserConfigs.CommandHandlers-{- internal sealed class RegisterKeybindingsHandler : ICommandHandler<RegisterKeybindingsCommand>- {- private readonly Bus _bus;- private readonly KeybindingService _keybindingService;- private readonly WindowService _windowService;-- public RegisterKeybindingsHandler(- Bus bus,- KeybindingService keybindingService,- WindowService windowService)- {- _bus = bus;- _keybindingService = keybindingService;- _windowService = windowService;- }-- public CommandResponse Handle(RegisterKeybindingsCommand command)- {- _keybindingService.Reset();-- foreach (var keybindingConfig in command.Keybindings)- {- // Format command strings defined in keybinding config.- var commandStrings = keybindingConfig.CommandList.Select(- CommandParsingService.FormatCommand- );-- // Register all keybindings for a command sequence.- foreach (var binding in keybindingConfig.BindingList)- _keybindingService.AddGlobalKeybinding(binding, () =>- {- Task.Run(() =>- {- try- {- lock (_bus.LockObj)- {- // Avoid invoking keybinding if an ignored window currently has focus.- if (_windowService.IgnoredHandles.Contains(GetForegroundWindow()))- return;-- _bus.Invoke(new RunWithSubjectContainerCommand(commandStrings));- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- }- }- catch (Exception e)- {- _bus.Invoke(new HandleFatalExceptionCommand(e));- throw;- }- });- });- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/CommandHandlers/ReloadUserConfigHandler.cs b/GlazeWM.Domain/UserConfigs/CommandHandlers/ReloadUserConfigHandler.csdeleted file mode 100644index 53a989cf..00000000--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/ReloadUserConfigHandler.cs+++ /dev/null@@ -1,58 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.UserConfigs.Events;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.CommandHandlers-{- internal sealed class ReloadUserConfigHandler : ICommandHandler<ReloadUserConfigCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly UserConfigService _userConfigService;- private readonly WindowService _windowService;-- public ReloadUserConfigHandler(- Bus bus,- ContainerService containerService,- UserConfigService userConfigService,- WindowService windowService)- {- _bus = bus;- _containerService = containerService;- _userConfigService = userConfigService;- _windowService = windowService;- }-- public CommandResponse Handle(ReloadUserConfigCommand command)- {- // Re-evaluate user config file and set its values in state.- _bus.Invoke(new EvaluateUserConfigCommand());-- _bus.Invoke(new UpdateWorkspacesFromConfigCommand(_userConfigService.WorkspaceConfigs));-- foreach (var window in _windowService.GetWindows())- {- var windowRules = _userConfigService.GetMatchingWindowRules(window);- var windowRuleCommands = windowRules- .SelectMany(rule => rule.CommandList)- .Select(CommandParsingService.FormatCommand);-- // Run matching window rules.- _bus.Invoke(new RunWithSubjectContainerCommand(windowRuleCommands, window));- }-- // Redraw full container tree.- _containerService.ContainersToRedraw.Add(_containerService.ContainerTree);-- _bus.Emit(new UserConfigReloadedEvent());-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/CommandHandlers/RunWithSubjectContainerHandler.cs b/GlazeWM.Domain/UserConfigs/CommandHandlers/RunWithSubjectContainerHandler.csdeleted file mode 100644index 9a241902..00000000--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/RunWithSubjectContainerHandler.cs+++ /dev/null@@ -1,63 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Domain.UserConfigs.CommandHandlers-{- internal sealed class RunWithSubjectContainerHandler- : ICommandHandler<RunWithSubjectContainerCommand>- {- private readonly Bus _bus;- private readonly CommandParsingService _commandParsingService;- private readonly ContainerService _containerService;-- public RunWithSubjectContainerHandler(- Bus bus,- CommandParsingService commandParsingService,- ContainerService containerService)- {- _bus = bus;- _commandParsingService = commandParsingService;- _containerService = containerService;- }-- public CommandResponse Handle(RunWithSubjectContainerCommand command)- {- var commandStrings = command.CommandStrings.ToList();- var subjectContainer =- command.SubjectContainer ?? _containerService.FocusedContainer;-- var subjectContainerId = subjectContainer.Id;-- // Evaluate ignore rules first (avoids jitters if another rule triggers a redraw).- if (commandStrings.Any(command => command == "ignore"))- commandStrings.MoveToFront("ignore");-- // Invoke commands in sequence.- foreach (var commandString in commandStrings)- {- // Avoid calling command if container gets detached. This is to prevent crashes- // for edge cases like ["close", "move to workspace X"].- if (subjectContainer?.IsDetached() != false)- return CommandResponse.Ok;-- var parsedCommand = _commandParsingService.ParseCommand(- commandString,- subjectContainer- );-- // Use `dynamic` to resolve the command type at runtime and allow multiple- // dispatch.- _bus.Invoke((dynamic)parsedCommand);-- // Update subject container in case the reference changes (eg. when going from a- // tiling to a floating window).- subjectContainer = _containerService.GetContainerById(subjectContainerId);- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs b/GlazeWM.Domain/UserConfigs/CommandParsingService.csdeleted file mode 100644index 17c51094..00000000--- a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs+++ /dev/null@@ -1,353 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.RegularExpressions;-using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.Exceptions;-using GlazeWM.Infrastructure.Utils;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.UserConfigs-{- public class CommandParsingService- {- private readonly UserConfigService _userConfigService;-- public CommandParsingService(UserConfigService userConfigService)- {- _userConfigService = userConfigService;- }-- public static string FormatCommand(string commandString)- {- // Remove leading/trailing whitespace (if present).- commandString = commandString.Trim();-- // Remove leading/trailing single quotes.- if (commandString.StartsWith("'") && commandString.EndsWith("'"))- commandString = commandString.Trim('\'');-- // Remove leading/trailing double quotes.- if (commandString.StartsWith("\"") && commandString.EndsWith("\""))- commandString = commandString.Trim('"');-- var caseSensitiveCommandRegex = new List<Regex>- {- new Regex("^(exec).*", RegexOptions.IgnoreCase),- };-- // Some commands are partially case-sensitive (eg. `exec ...`). To handle such- // cases, only format part of the command string to be lowercase.- foreach (var regex in caseSensitiveCommandRegex)- {- if (regex.IsMatch(commandString))- {- return regex.Replace(commandString, (Match match) =>- match.Value.ToLowerInvariant()- );- }- }-- return commandString.ToLowerInvariant();- }-- public void ValidateCommand(string commandString)- {- ParseCommand(commandString, null);- }-- public Command ParseCommand(string commandString, Container subjectContainer)- {- try- {- var commandParts = commandString.Split(" ");-- return commandParts[0] switch- {- "tiling" => ParseTilingCommand(commandParts, subjectContainer),- // TODO: "layout <LAYOUT>" commands are deprecated. Remove in next major release.- "layout" => ParseLayoutCommand(commandParts, subjectContainer),- "focus" => ParseFocusCommand(commandParts),- "move" => ParseMoveCommand(commandParts, subjectContainer),- "resize" => ParseResizeCommand(commandParts, subjectContainer),- "set" => ParseSetCommand(commandParts, subjectContainer),- "toggle" => ParseToggleCommand(commandParts, subjectContainer),- "exit" => ParseExitCommand(commandParts),- "close" => subjectContainer is Window- ? new CloseWindowCommand(subjectContainer as Window)- : new NoopCommand(),- "reload" => ParseReloadCommand(commandParts),- "exec" => new ExecProcessCommand(- ExtractProcessName(string.Join(" ", commandParts[1..])),- ExtractProcessArgs(string.Join(" ", commandParts[1..]))- ),- "ignore" => subjectContainer is Window- ? new IgnoreWindowCommand(subjectContainer as Window)- : new NoopCommand(),- "binding" => ParseBindingCommand(commandParts),- _ => throw new ArgumentException(null, nameof(commandString)),- };- }- catch- {- throw new FatalUserException($"Invalid command '{commandString}'.");- }- }-- private static Command ParseTilingCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "direction" => commandParts[2] switch- {- "vertical" => new ChangeTilingDirectionCommand(subjectContainer, TilingDirection.Vertical),- "horizontal" => new ChangeTilingDirectionCommand(subjectContainer, TilingDirection.Horizontal),- "toggle" => new ToggleTilingDirectionCommand(subjectContainer),- _ => throw new ArgumentException(null, nameof(commandParts)),- },- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseLayoutCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "vertical" => new ChangeTilingDirectionCommand(subjectContainer, TilingDirection.Vertical),- "horizontal" => new ChangeTilingDirectionCommand(subjectContainer, TilingDirection.Horizontal),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private Command ParseFocusCommand(string[] commandParts)- {- return commandParts[1] switch- {- "left" => new FocusInDirectionCommand(Direction.Left),- "right" => new FocusInDirectionCommand(Direction.Right),- "up" => new FocusInDirectionCommand(Direction.Up),- "down" => new FocusInDirectionCommand(Direction.Down),- "workspace" => ParseFocusWorkspaceCommand(commandParts),- "mode" => commandParts[2] switch- {- "toggle" => new ToggleFocusModeCommand(),- _ => throw new ArgumentException(null, nameof(commandParts)),- },- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private Command ParseFocusWorkspaceCommand(string[] commandParts)- {- return commandParts[2] switch- {- "recent" => new FocusWorkspaceRecentCommand(),- "prev" => new FocusWorkspaceSequenceCommand(Sequence.Previous),- "next" => new FocusWorkspaceSequenceCommand(Sequence.Next),- _ when IsValidWorkspace(commandParts[2]) => new FocusWorkspaceCommand(commandParts[2]),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private Command ParseMoveCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "left" => subjectContainer is Window- ? new MoveWindowCommand(subjectContainer as Window, Direction.Left)- : new NoopCommand(),- "right" => subjectContainer is Window- ? new MoveWindowCommand(subjectContainer as Window, Direction.Right)- : new NoopCommand(),- "up" => subjectContainer is Window- ? new MoveWindowCommand(subjectContainer as Window, Direction.Up)- : new NoopCommand(),- "down" => subjectContainer is Window- ? new MoveWindowCommand(subjectContainer as Window, Direction.Down)- : new NoopCommand(),- "to" when IsValidWorkspace(commandParts[3]) => subjectContainer is Window- ? new MoveWindowToWorkspaceCommand(subjectContainer as Window, commandParts[3])- : new NoopCommand(),- "workspace" => ParseMoveWorkspaceCommand(commandParts),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseMoveWorkspaceCommand(string[] commandParts)- {- return commandParts[2] switch- {- "left" => new MoveWorkspaceInDirectionCommand(Direction.Left),- "right" => new MoveWorkspaceInDirectionCommand(Direction.Right),- "up" => new MoveWorkspaceInDirectionCommand(Direction.Up),- "down" => new MoveWorkspaceInDirectionCommand(Direction.Down),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseResizeCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "height" => subjectContainer is Window- ? new ResizeWindowCommand(subjectContainer as Window, ResizeDimension.Height, commandParts[2])- : new NoopCommand(),- "width" => subjectContainer is Window- ? new ResizeWindowCommand(subjectContainer as Window, ResizeDimension.Width, commandParts[2])- : new NoopCommand(),- "borders" => subjectContainer is Window- ? new ResizeWindowBordersCommand(- subjectContainer as Window,- ShorthandToRectDelta(string.Join(" ", commandParts[2..]))- )- : new NoopCommand(),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseSetCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "floating" => subjectContainer is Window- ? new SetFloatingCommand(subjectContainer as Window)- : new NoopCommand(),- "minimized" => subjectContainer is Window- ? new SetMinimizedCommand(subjectContainer as Window)- : new NoopCommand(),- "maximized" => subjectContainer is Window- ? new SetMaximizedCommand(subjectContainer as Window)- : new NoopCommand(),- "tiling" => subjectContainer is Window- ? new SetTilingCommand(subjectContainer as Window)- : new NoopCommand(),- "width" => subjectContainer is Window- ? new SetWindowSizeCommand(subjectContainer as Window, ResizeDimension.Width, commandParts[2])- : new NoopCommand(),- "height" => subjectContainer is Window- ? new SetWindowSizeCommand(subjectContainer as Window, ResizeDimension.Height, commandParts[2])- : new NoopCommand(),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseToggleCommand(string[] commandParts, Container subjectContainer)- {- return commandParts[1] switch- {- "floating" => subjectContainer is Window- ? new ToggleFloatingCommand(subjectContainer as Window)- : new NoopCommand(),- "maximized" => subjectContainer is Window- ? new ToggleMaximizedCommand(subjectContainer as Window)- : new NoopCommand(),- // TODO: "toggle focus mode" command is deprecated. Remove in next major release.- "focus" => commandParts[2] switch- {- "mode" => new ToggleFocusModeCommand(),- _ => throw new ArgumentException(null, nameof(commandParts)),- },- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseExitCommand(string[] commandParts)- {- return commandParts[1] switch- {- "wm" => new ExitApplicationCommand(false),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private Command ParseBindingCommand(string[] commandParts)- {- return commandParts[1] switch- {- "mode" when IsValidBindingMode(commandParts[2]) =>- new SetBindingModeCommand(commandParts[2]),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- private static Command ParseReloadCommand(string[] commandParts)- {- return commandParts[1] switch- {- "config" => new ReloadUserConfigCommand(),- _ => throw new ArgumentException(null, nameof(commandParts)),- };- }-- /// <summary>- /// Whether a workspace exists with the given name.- /// </summary>- private bool IsValidWorkspace(string workspaceName)- {- var workspaceConfig = _userConfigService.GetWorkspaceConfigByName(workspaceName);-- return workspaceConfig is not null;- }-- /// <summary>- /// Whether a binding mode exists with the given name.- /// </summary>- private bool IsValidBindingMode(string bindingModeName)- {- var bindingMode = _userConfigService.GetBindingModeByName(bindingModeName);-- return bindingMode is not null || bindingModeName == "none";- }-- public static string ExtractProcessName(string processNameAndArgs)- {- var hasSingleQuotes = processNameAndArgs.StartsWith(- "'",- StringComparison.InvariantCulture- );-- return hasSingleQuotes- ? processNameAndArgs.Split("'")[1]- : processNameAndArgs.Split(" ")[0];- }-- public static List<string> ExtractProcessArgs(string processNameAndArgs)- {- var hasSingleQuotes = processNameAndArgs.StartsWith(- "'",- StringComparison.InvariantCulture- );-- var args = hasSingleQuotes- ? processNameAndArgs.Split("'")[2..]- : processNameAndArgs.Split(" ")[1..];-- return args.Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();- }-- public static RectDelta ShorthandToRectDelta(string shorthand)- {- var shorthandParts = shorthand.Split(" ")- .Select(shorthandPart => UnitsHelper.TrimUnits(shorthandPart))- .ToList();-- return shorthandParts.Count switch- {- 1 => new RectDelta(shorthandParts[0], shorthandParts[0], shorthandParts[0], shorthandParts[0]),- 2 => new RectDelta(shorthandParts[1], shorthandParts[0], shorthandParts[1], shorthandParts[0]),- 3 => new RectDelta(shorthandParts[1], shorthandParts[0], shorthandParts[1], shorthandParts[2]),- 4 => new RectDelta(shorthandParts[3], shorthandParts[0], shorthandParts[1], shorthandParts[2]),- _ => throw new ArgumentException(null, nameof(shorthand)),- };- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/Commands/EvaluateUserConfigCommand.cs b/GlazeWM.Domain/UserConfigs/Commands/EvaluateUserConfigCommand.csdeleted file mode 100644index bbce7177..00000000--- a/GlazeWM.Domain/UserConfigs/Commands/EvaluateUserConfigCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.Commands-{- public class EvaluateUserConfigCommand : Command- {- }-}diff --git a/GlazeWM.Domain/UserConfigs/Commands/RegisterKeybindingsCommand.cs b/GlazeWM.Domain/UserConfigs/Commands/RegisterKeybindingsCommand.csdeleted file mode 100644index 0bfedcf6..00000000--- a/GlazeWM.Domain/UserConfigs/Commands/RegisterKeybindingsCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using System.Collections.Generic;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.Commands-{- // TODO: Consider renaming to `RegisterUserKeybindingsCommand`.- // TODO: Perhaps call command for each keybinding config.- public class RegisterKeybindingsCommand : Command- {- public List<KeybindingConfig> Keybindings { get; }-- public RegisterKeybindingsCommand(List<KeybindingConfig> keybindings)- {- Keybindings = keybindings;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/Commands/ReloadUserConfigCommand.cs b/GlazeWM.Domain/UserConfigs/Commands/ReloadUserConfigCommand.csdeleted file mode 100644index f9dd71c2..00000000--- a/GlazeWM.Domain/UserConfigs/Commands/ReloadUserConfigCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.Commands-{- public class ReloadUserConfigCommand : Command- {- }-}diff --git a/GlazeWM.Domain/UserConfigs/Commands/RunWithSubjectContainerCommand.cs b/GlazeWM.Domain/UserConfigs/Commands/RunWithSubjectContainerCommand.csdeleted file mode 100644index b1592302..00000000--- a/GlazeWM.Domain/UserConfigs/Commands/RunWithSubjectContainerCommand.cs+++ /dev/null@@ -1,25 +0,0 @@-using System.Collections.Generic;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.Commands-{- public class RunWithSubjectContainerCommand : Command- {- public IEnumerable<string> CommandStrings { get; }- public Container SubjectContainer { get; }-- public RunWithSubjectContainerCommand(- IEnumerable<string> commandStrings,- Container subjectContainer)- {- CommandStrings = commandStrings;- SubjectContainer = subjectContainer;- }-- public RunWithSubjectContainerCommand(IEnumerable<string> commandStrings)- {- CommandStrings = commandStrings;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/CpuComponentConfig.cs b/GlazeWM.Domain/UserConfigs/CpuComponentConfig.csdeleted file mode 100644index c9c4569f..00000000--- a/GlazeWM.Domain/UserConfigs/CpuComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class CpuComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the CPU component.- /// </summary>- public string Label { get; set; } = "CPU: {percent_usage}%";-- /// <summary>- /// How often this component refreshes in milliseconds.- /// </summary>- public int RefreshIntervalMs { get; set; } = 1000;- }-}diff --git a/GlazeWM.Domain/UserConfigs/Events/UserConfigReloadedEvent.cs b/GlazeWM.Domain/UserConfigs/Events/UserConfigReloadedEvent.csdeleted file mode 100644index 6b65fcdc..00000000--- a/GlazeWM.Domain/UserConfigs/Events/UserConfigReloadedEvent.cs+++ /dev/null@@ -1,7 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.UserConfigs.Events-{- public record UserConfigReloadedEvent() : Event(DomainEvent.UserConfigReloaded);-}diff --git a/GlazeWM.Domain/UserConfigs/FocusBorderConfig.cs b/GlazeWM.Domain/UserConfigs/FocusBorderConfig.csdeleted file mode 100644index ec0f1570..00000000--- a/GlazeWM.Domain/UserConfigs/FocusBorderConfig.cs+++ /dev/null@@ -1,28 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class FocusBordersConfig- {- /// <summary>- /// Border of the focused window.- /// </summary>- public FocusBorder Active { get; set; } = new() { Enabled = false, Color = "#0000ff" };-- /// <summary>- /// Border of non-focused windows.- /// </summary>- public FocusBorder Inactive { get; set; } = new() { Enabled = false, Color = "#ff0000" };- }-- public class FocusBorder- {- /// <summary>- /// Should the default transparent border be used.- /// </summary>- public bool Enabled;-- /// <summary>- /// Border color of window.- /// </summary>- public string Color;- }-}diff --git a/GlazeWM.Domain/UserConfigs/GapsConfig.cs b/GlazeWM.Domain/UserConfigs/GapsConfig.csdeleted file mode 100644index d7f4308d..00000000--- a/GlazeWM.Domain/UserConfigs/GapsConfig.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class GapsConfig- {- public string InnerGap { get; set; } = "20px";- public string OuterGap { get; set; } = "20px";- }-}diff --git a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs b/GlazeWM.Domain/UserConfigs/GeneralConfig.csdeleted file mode 100644index 8d892469..00000000--- a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs+++ /dev/null@@ -1,34 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class GeneralConfig- {- /// <summary>- /// Whether to show floating windows as always on top.- /// </summary>- public bool ShowFloatingOnTop { get; set; }- /// <summary>- /// Center the cursor in the middle of a newly focused window- /// </summary>- public bool CursorFollowsFocus { get; set; }- /// <summary>- /// Focus the window directly under the cursor at all times- /// </summary>- public bool FocusFollowsCursor { get; set; }- /// <summary>- /// Amount by which to move floating windows- /// </summary>- public string FloatingWindowMoveAmount { get; set; } = "5%";- /// <summary>- /// If activated, by switching to the current workspace the previous focused workspace is activated.- /// </summary>- public bool ToggleWorkspaceOnRefocus { get; set; }- /// <summary>- /// Whether to enable window transition animations (on minimize, close, etc).- /// </summary>- public WindowAnimations WindowAnimations { get; set; } = WindowAnimations.Unchanged;- /// <summary>- /// Whether to center new floating windows- /// </summary>- public bool CenterNewFloatingWindows { get; set; } = true;- }-}diff --git a/GlazeWM.Domain/UserConfigs/GpuComponentConfig.cs b/GlazeWM.Domain/UserConfigs/GpuComponentConfig.csdeleted file mode 100644index df9906a7..00000000--- a/GlazeWM.Domain/UserConfigs/GpuComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class GpuComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the GPU component.- /// </summary>- public string Label { get; set; } = "GPU: {percent_usage}%";-- /// <summary>- /// How often this component refreshes in milliseconds.- /// </summary>- public int RefreshIntervalMs { get; set; } = 1000;- }-}diff --git a/GlazeWM.Domain/UserConfigs/ImageComponentConfig.cs b/GlazeWM.Domain/UserConfigs/ImageComponentConfig.csdeleted file mode 100644index b053dad4..00000000--- a/GlazeWM.Domain/UserConfigs/ImageComponentConfig.cs+++ /dev/null@@ -1,10 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class ImageComponentConfig : BarComponentConfig- {- /// <summary>- /// Path to image- /// </summary>- public string Source { get; set; }- }-}diff --git a/GlazeWM.Domain/UserConfigs/KeybindingConfig.cs b/GlazeWM.Domain/UserConfigs/KeybindingConfig.csdeleted file mode 100644index 5052076a..00000000--- a/GlazeWM.Domain/UserConfigs/KeybindingConfig.cs+++ /dev/null@@ -1,21 +0,0 @@-using System.Collections.Generic;--namespace GlazeWM.Domain.UserConfigs-{- public class KeybindingConfig- {- public string Binding { get; set; }-- public List<string> Bindings { get; set; }-- public List<string> BindingList =>- Binding != null ? new List<string> { Binding } : Bindings;-- public string Command { get; set; }-- public List<string> Commands { get; set; }-- public List<string> CommandList =>- Command != null ? new List<string> { Command } : Commands;- }-}diff --git a/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.cs b/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.csdeleted file mode 100644index 0ceda207..00000000--- a/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class MemoryComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the memory component.- /// </summary>- public string Label { get; set; } = "RAM: {percent_usage}%";-- /// <summary>- /// How often this component refreshes in milliseconds.- /// </summary>- public int RefreshIntervalMs { get; set; } = 1000;- }-}diff --git a/GlazeWM.Domain/UserConfigs/MultiBarConfig.cs b/GlazeWM.Domain/UserConfigs/MultiBarConfig.csdeleted file mode 100644index 265c1ba1..00000000--- a/GlazeWM.Domain/UserConfigs/MultiBarConfig.cs+++ /dev/null@@ -1,16 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class MultiBarConfig : BarConfig- {- // TODO: Put this logic somewhere shared, so that it's not repeated in- // `WorkspaceConfig.BindToMonitor`.- private string _bindToMonitor;- public string BindToMonitor- {- get => _bindToMonitor;- set => _bindToMonitor = int.TryParse(value, out var monitorIndex)- ? $@"\\.\DISPLAY{monitorIndex}"- : value;- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/MusicComponentConfig.cs b/GlazeWM.Domain/UserConfigs/MusicComponentConfig.csdeleted file mode 100644index c7164ebe..00000000--- a/GlazeWM.Domain/UserConfigs/MusicComponentConfig.cs+++ /dev/null@@ -1,26 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class MusicComponentConfig : BarComponentConfig- {- /// <summary>- /// Formatted text to display when music is not playing.- /// </summary>- public string LabelNotPlaying { get; set; } = "";- /// <summary>- /// Formatted text to display when music is not paused.- /// </summary>- public string LabelPaused { get; set; } = "";- /// <summary>- /// Formatted text to display when music is playing.- /// </summary>- public string LabelPlaying { get; set; } = "{song_title} - {artist_name}";- /// <summary>- /// The maximum length after which the song title will be truncated; if set to -1, the title will not be truncated.- /// </summary>- public int MaxTitleLength { get; set; } = -1;- /// <summary>- /// The maximum length after which the artist name will be truncated; if set to -1, the name will not be truncated.- /// </summary>- public int MaxArtistLength { get; set; } = -1;- }-}diff --git a/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.cs b/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.csdeleted file mode 100644index cc04eb28..00000000--- a/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.cs+++ /dev/null@@ -1,34 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class NetworkComponentConfig : BarComponentConfig- {- /// <summary>- /// Label for wifi at 0% RSSI.- /// </summary>- public string LabelWifiStrength0 { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for wifi at 25% RSSI.- /// </summary>- public string LabelWifiStrength25 { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for wifi at 50% RSSI.- /// </summary>- public string LabelWifiStrength50 { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for wifi at 75% RSSI.- /// </summary>- public string LabelWifiStrength75 { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for wifi at 100% RSSI.- /// </summary>- public string LabelWifiStrength100 { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for ethernet connection.- /// </summary>- public string LabelEthernet { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- /// <summary>- /// Label for connection to the internet.- /// </summary>- public string LabelNoInternet { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- }-}diff --git a/GlazeWM.Domain/UserConfigs/SystemTrayComponentConfig.cs b/GlazeWM.Domain/UserConfigs/SystemTrayComponentConfig.csdeleted file mode 100644index 7d8a8e00..00000000--- a/GlazeWM.Domain/UserConfigs/SystemTrayComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class SystemTrayComponentConfig : BarComponentConfig- {- /// <summary>- /// Expands to show both pinned and unppined icons.- /// </summary>- public string LabelExpandText { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";-- /// <summary>- /// Collapse to show only pinned icons.- /// </summary>- public string LabelCollapseText { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>";- }-}diff --git a/GlazeWM.Domain/UserConfigs/TextComponentConfig.cs b/GlazeWM.Domain/UserConfigs/TextComponentConfig.csdeleted file mode 100644index 9097595d..00000000--- a/GlazeWM.Domain/UserConfigs/TextComponentConfig.cs+++ /dev/null@@ -1,20 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class TextComponentConfig : BarComponentConfig- {- /// <summary>- /// Text to display.- /// </summary>- public string Text { get; set; } = "Hello world!";-- /// <summary>- /// Command to invoke on left-click.- /// </summary>- public string LeftClickCommand { get; set; }-- /// <summary>- /// Command to invoke on right-click.- /// </summary>- public string RightClickCommand { get; set; }- }-}diff --git a/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.cs b/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.csdeleted file mode 100644index 13ee20bc..00000000--- a/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class TextFileComponentConfig : BarComponentConfig- {- public string FilePath { get; set; }- }-}diff --git a/GlazeWM.Domain/UserConfigs/TilingDirectionComponentConfig.cs b/GlazeWM.Domain/UserConfigs/TilingDirectionComponentConfig.csdeleted file mode 100644index 4376b0fb..00000000--- a/GlazeWM.Domain/UserConfigs/TilingDirectionComponentConfig.cs+++ /dev/null@@ -1,15 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class TilingDirectionComponentConfig : BarComponentConfig- {- /// <summary>- /// Text to display in vertical mode.- /// </summary>- public string LabelVertical { get; set; } = "vertical";-- /// <summary>- /// Text to display horizontal mode.- /// </summary>- public string LabelHorizontal { get; set; } = "horizontal";- }-}diff --git a/GlazeWM.Domain/UserConfigs/UserConfig.cs b/GlazeWM.Domain/UserConfigs/UserConfig.csdeleted file mode 100644index 25324a9f..00000000--- a/GlazeWM.Domain/UserConfigs/UserConfig.cs+++ /dev/null@@ -1,30 +0,0 @@-using System.Collections.Generic;-using System.Linq;--namespace GlazeWM.Domain.UserConfigs-{- public class UserConfig- {- public GapsConfig Gaps { get; set; } = new();-- public FocusBordersConfig FocusBorders { get; set; } = new();-- public GeneralConfig General { get; set; } = new();-- public BarConfig Bar { get; set; } = new();-- public List<MultiBarConfig> Bars { get; set; } = new();-- public List<BarConfig> BarConfigs => Bars.Count == 0- ? new() { Bar }- : Bars.Cast<BarConfig>().ToList();-- public List<WorkspaceConfig> Workspaces { get; set; } = new();-- public List<WindowRuleConfig> WindowRules { get; set; } = new();-- public List<KeybindingConfig> Keybindings { get; set; } = new();-- public List<BindingMode> BindingModes { get; set; } = new();- }-}diff --git a/GlazeWM.Domain/UserConfigs/UserConfigService.cs b/GlazeWM.Domain/UserConfigs/UserConfigService.csdeleted file mode 100644index 203edd7d..00000000--- a/GlazeWM.Domain/UserConfigs/UserConfigService.cs+++ /dev/null@@ -1,141 +0,0 @@-using System;-using System.Collections.Generic;-using System.IO;-using System.Linq;-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows;--namespace GlazeWM.Domain.UserConfigs-{- public class UserConfigService- {- /// <summary>- /// The deserialized user config. Sections of the config can be accessed via getters.- /// </summary>- public UserConfig UserConfig { private get; set; }-- public GapsConfig GapsConfig => UserConfig.Gaps;- public FocusBordersConfig FocusBorderConfig => UserConfig.FocusBorders;- public GeneralConfig GeneralConfig => UserConfig.General;- public List<BarConfig> BarConfigs => UserConfig.BarConfigs;- public List<WorkspaceConfig> WorkspaceConfigs => UserConfig.Workspaces;- public List<WindowRuleConfig> WindowRules => UserConfig.WindowRules;- public List<KeybindingConfig> Keybindings => UserConfig.Keybindings;- public List<BindingMode> BindingModes => UserConfig.BindingModes;-- /// <summary>- /// Path to the user's config file.- /// </summary>- public string UserConfigPath =>- _startupOptions.ConfigPath ?? _defaultUserConfigPath;-- private readonly string _defaultUserConfigPath = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),- "./.glaze-wm/config.yaml"- );-- private readonly WmStartupOptions _startupOptions;-- public UserConfigService(WmStartupOptions startupOptions)- {- _startupOptions = startupOptions;- }-- public readonly List<WindowRuleConfig> DefaultWindowRules = GetDefaultWindowRules();-- private static List<WindowRuleConfig> GetDefaultWindowRules()- {- var windowRules = new List<WindowRuleConfig>();-- var classNamesToFloat = new List<string> {- // Windows 10 dialog shown when moving and deleting files.- "OperationStatusWindow",- };-- foreach (var className in classNamesToFloat)- {- var windowRule = new WindowRuleConfig()- {- MatchClassName = className,- Command = "set floating",- };-- windowRules.Add(windowRule);- }-- var chromiumBrowserProcessNames = new List<string> {- "chrome",- "msedge",- "opera",- "vivaldi",- "brave",- };-- // Electron apps do not have invisible borders and are thus over-corrected by the default- // border fix. To match these apps, get windows with the class name 'Chrome_WidgetWin_1' that- // are not Chromium-based browsers (since the browser windows do have invisble borders).- var resizeElectronBorderWindowRule = new WindowRuleConfig()- {- MatchProcessName = $"/^(?!({string.Join("|", chromiumBrowserProcessNames)})$)/",- MatchClassName = "/Chrome_WidgetWin_*/",- Command = "resize borders 0px -7px -7px -7px",- };-- windowRules.Add(resizeElectronBorderWindowRule);-- var processNamesToIgnore = new List<string> {- "SearchApp",- "SearchHost",- "ShellExperienceHost",- "StartMenuExperienceHost",- };-- foreach (var processName in processNamesToIgnore)- {- var windowRule = new WindowRuleConfig()- {- MatchProcessName = processName,- Command = "ignore",- };-- windowRules.Add(windowRule);- }-- return windowRules;- }-- public WorkspaceConfig GetWorkspaceConfigByName(string workspaceName)- {- return WorkspaceConfigs.Find(- (workspaceConfig) => workspaceConfig.Name == workspaceName- );- }-- public BindingMode GetBindingModeByName(string bindingModeName)- {- return BindingModes.Find(- (bindingMode) => bindingMode.Name == bindingModeName- );- }-- public BarConfig GetBarConfigForMonitor(Monitor monitor)- {- var boundMonitor = BarConfigs- .OfType<MultiBarConfig>()- .FirstOrDefault(config => config.BindToMonitor == monitor.DeviceName);-- return boundMonitor ?? BarConfigs[0];- }-- public List<WindowRuleConfig> GetMatchingWindowRules(Window window)- {- return WindowRules.Where(rule =>- {- return rule.ProcessNameRegex?.IsMatch(window.ProcessName) != false &&- rule.ClassNameRegex?.IsMatch(window.ClassName) != false &&- rule.TitleRegex?.IsMatch(window.Title) != false;- }).ToList();- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/VolumeComponentConfig.cs b/GlazeWM.Domain/UserConfigs/VolumeComponentConfig.csdeleted file mode 100644index 744df85c..00000000--- a/GlazeWM.Domain/UserConfigs/VolumeComponentConfig.cs+++ /dev/null@@ -1,27 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class VolumeComponentConfig : BarComponentConfig- {- /// <summary>- /// Default label.- /// </summary>- public string Label { get; set; } = "{volume_level}%";- /// <summary>- /// Label for low volume.- /// </summary>- public string LabelLow { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>{volume_level}%";- /// <summary>- /// Label for medium volume.- /// </summary>- public string LabelMedium { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>{volume_level}%";- /// <summary>- /// Label for high volume.- /// </summary>- public string LabelHigh { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>{volume_level}%";- /// <summary>- /// Label for volume mute.- /// </summary>- public string LabelMute { get; set; } = "<attr ff='pack://application:,,,/Resources/#Material Icons'></attr>{volume_level}%";- }--}diff --git a/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.cs b/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.csdeleted file mode 100644index 8c41c77d..00000000--- a/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.cs+++ /dev/null@@ -1,75 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class WeatherComponentConfig : BarComponentConfig- {- /// <summary>- /// Latitude to retreive weather.- /// </summary>- public float Latitude { get; set; }-- /// <summary>- /// Longitude to retrieve weather.- /// </summary>- public float Longitude { get; set; }-- /// <summary>- /// How often this component refreshes in milliseconds.- /// </summary>- public int RefreshIntervalMs { get; set; } = 60 * 60 * 1000;-- /// <summary>- /// Default label.- /// </summary>- public string Label { get; set; } = "{temperature_celsius}°C";-- /// <summary>- /// Label to represent sunny weather.- /// </summary>- public string LabelSun { get; set; } = "☀️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent clear weather at night.- /// </summary>- public string LabelMoon { get; set; } = "🌙 {temperature_celsius}°C";-- /// <summary>- /// Label to represent partly cloudy at night.- /// </summary>- public string LabelCloudMoon { get; set; } = "🌙☁️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent partly cloudy.- /// </summary>- public string LabelCloudSun { get; set; } = "⛅ {temperature_celsius}°C";-- /// <summary>- /// Label to represent light rain at night.- /// </summary>- public string LabelCloudMoonRain { get; set; } = "🌙🌧️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent light rain.- /// </summary>- public string LabelCloudSunRain { get; set; } = "🌦️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent heavy rain.- /// </summary>- public string LabelCloudRain { get; set; } = "🌧️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent snow.- /// </summary>- public string LabelSnowflake { get; set; } = "❄️ {temperature_celsius}°C";-- /// <summary>- /// Label to represent a thunderstorm.- /// </summary>- public string LabelThunderstorm { get; set; } = "⚡ {temperature_celsius}°C";-- /// <summary>- /// Label to represent heavy clouds.- /// </summary>- public string LabelCloud { get; set; } = "☁️ {temperature_celsius}°C";- }-}diff --git a/GlazeWM.Domain/UserConfigs/WindowAnimations.cs b/GlazeWM.Domain/UserConfigs/WindowAnimations.csdeleted file mode 100644index 319672b1..00000000--- a/GlazeWM.Domain/UserConfigs/WindowAnimations.cs+++ /dev/null@@ -1,9 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public enum WindowAnimations- {- Unchanged,- True,- False- }-}diff --git a/GlazeWM.Domain/UserConfigs/WindowRuleConfig.cs b/GlazeWM.Domain/UserConfigs/WindowRuleConfig.csdeleted file mode 100644index b36c9078..00000000--- a/GlazeWM.Domain/UserConfigs/WindowRuleConfig.cs+++ /dev/null@@ -1,49 +0,0 @@-using System;-using System.Collections.Generic;-using System.Text.RegularExpressions;--namespace GlazeWM.Domain.UserConfigs-{- public class WindowRuleConfig- {- public string MatchProcessName { get; set; }-- public Regex ProcessNameRegex => CreateRegex(MatchProcessName);-- public string MatchClassName { get; set; }-- public Regex ClassNameRegex => CreateRegex(MatchClassName);-- public string MatchTitle { get; set; }-- public Regex TitleRegex => CreateRegex(MatchTitle);-- public string Command { get; set; }-- public List<string> Commands { get; set; } = new List<string>();-- public List<string> CommandList =>- Command != null ? new List<string> { Command } : Commands;-- /// <summary>- /// Creates an exact match regex for the given string.- /// </summary>- /// <returns>The corresponding regex, or null if input is invalid.</returns>- private static Regex CreateRegex(string input)- {- if (string.IsNullOrWhiteSpace(input))- return null;-- var isRegexLiteral =- input.StartsWith("/", StringComparison.InvariantCulture) &&- input.EndsWith("/", StringComparison.InvariantCulture);-- // Allow user to pass a string that should be interpreted as regex (eg. "/steam/").- if (isRegexLiteral)- return new Regex(input[1..^1]);-- // Otherwise, create an exact match regex.- return new Regex($"^{input}$");- }- }-}diff --git a/GlazeWM.Domain/UserConfigs/WindowTitleComponentConfig.cs b/GlazeWM.Domain/UserConfigs/WindowTitleComponentConfig.csdeleted file mode 100644index 66132ed1..00000000--- a/GlazeWM.Domain/UserConfigs/WindowTitleComponentConfig.cs+++ /dev/null@@ -1,10 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class WindowTitleComponentConfig : BarComponentConfig- {- /// <summary>- /// Label assigned to the window title component.- /// </summary>- public string Label { get; set; } = "{window_title}";- }-}diff --git a/GlazeWM.Domain/UserConfigs/WorkspaceConfig.cs b/GlazeWM.Domain/UserConfigs/WorkspaceConfig.csdeleted file mode 100644index 93c3d476..00000000--- a/GlazeWM.Domain/UserConfigs/WorkspaceConfig.cs+++ /dev/null@@ -1,22 +0,0 @@-using System.ComponentModel.DataAnnotations;--namespace GlazeWM.Domain.UserConfigs-{- public class WorkspaceConfig- {- [Required]- public string Name { get; set; }-- private string _bindToMonitor;- public string BindToMonitor- {- get => _bindToMonitor;- set => _bindToMonitor = int.TryParse(value, out var monitorIndex)- ? $@"\\.\DISPLAY{monitorIndex}"- : value;- }-- public string DisplayName { get; set; }- public bool KeepAlive { get; set; }- }-}diff --git a/GlazeWM.Domain/UserConfigs/WorkspacesComponentConfig.cs b/GlazeWM.Domain/UserConfigs/WorkspacesComponentConfig.csdeleted file mode 100644index e3d10bbb..00000000--- a/GlazeWM.Domain/UserConfigs/WorkspacesComponentConfig.cs+++ /dev/null@@ -1,37 +0,0 @@-namespace GlazeWM.Domain.UserConfigs-{- public class WorkspacesComponentConfig : BarComponentConfig- {- public string FocusedWorkspaceBorderWidth { get; set; } = "0";- public string FocusedWorkspaceBorderColor { get; set; } = "blue";- public string FocusedWorkspaceBackground { get; set; } = "#8192B3";-- /// <summary>- /// Fallback to component foreground config if unset.- /// </summary>- public string FocusedWorkspaceForeground { get; set; }-- public string DisplayedWorkspaceBorderWidth { get; set; } = "0";- public string DisplayedWorkspaceBorderColor { get; set; } = "blue";- public string DisplayedWorkspaceBackground { get; set; } = "#42403e";-- /// <summary>- /// Fallback to component foreground config if unset.- /// </summary>- public string DisplayedWorkspaceForeground { get; set; }-- public string DefaultWorkspaceBorderWidth { get; set; } = "0";- public string DefaultWorkspaceBorderColor { get; set; } = "blue";-- /// <summary>- /// Use transparent as a default, since falling back to bar background config looks- /// weird with nested semi-transparent backgrounds.- /// </summary>- public string DefaultWorkspaceBackground { get; set; } = "transparent";-- /// <summary>- /// Fallback to component foreground config if unset.- /// </summary>- public string DefaultWorkspaceForeground { get; set; }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/CloseWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/CloseWindowHandler.csdeleted file mode 100644index 104c43fa..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/CloseWindowHandler.cs+++ /dev/null@@ -1,19 +0,0 @@-using System;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class CloseWindowHandler : ICommandHandler<CloseWindowCommand>- {- public CommandResponse Handle(CloseWindowCommand command)- {- var windowToClose = command.WindowToClose;-- SendNotifyMessage(windowToClose.Handle, SendMessageType.Close, IntPtr.Zero, IntPtr.Zero);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/IgnoreWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/IgnoreWindowHandler.csdeleted file mode 100644index 0d0d8afc..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/IgnoreWindowHandler.cs+++ /dev/null@@ -1,31 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class IgnoreWindowHandler : ICommandHandler<IgnoreWindowCommand>- {- private readonly Bus _bus;- private readonly WindowService _windowService;-- public IgnoreWindowHandler(Bus bus, WindowService windowService)- {- _bus = bus;- _windowService = windowService;- }-- public CommandResponse Handle(IgnoreWindowCommand command)- {- var windowToIgnore = command.WindowToIgnore;-- // Store handle to ignored window.- _windowService.IgnoredHandles.Add(windowToIgnore.Handle);-- _bus.Invoke(new DetachContainerCommand(windowToIgnore));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.csdeleted file mode 100644index 217a7bcd..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/ManageWindowHandler.cs+++ /dev/null@@ -1,158 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.UserConfigs.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Windows.Events;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;-using Microsoft.Extensions.Logging;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class ManageWindowHandler : ICommandHandler<ManageWindowCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly ILogger<ManageWindowHandler> _logger;- private readonly MonitorService _monitorService;- private readonly WindowService _windowService;- private readonly UserConfigService _userConfigService;-- public ManageWindowHandler(- Bus bus,- ContainerService containerService,- ILogger<ManageWindowHandler> logger,- MonitorService monitorService,- WindowService windowService,- UserConfigService userConfigService)- {- _bus = bus;- _containerService = containerService;- _logger = logger;- _monitorService = monitorService;- _windowService = windowService;- _userConfigService = userConfigService;- }-- public CommandResponse Handle(ManageWindowCommand command)- {- var windowHandle = command.WindowHandle;-- // Attach the new window as first child of the target parent (if provided), otherwise, add as- // a sibling of the focused container.- var (targetParent, targetIndex) = command.TargetParent != null- ? (command.TargetParent, 0)- : GetInsertionTarget();-- // Create the window instance.- var window = CreateWindow(windowHandle, targetParent);- _bus.Invoke(new AttachContainerCommand(window, targetParent, targetIndex));-- // The OS might spawn the window on a different monitor to the target parent, so adjustments- // might need to be made because of DPI.- var monitor = _monitorService.GetMonitorFromHandleLocation(windowHandle);- if (MonitorService.HasDpiDifference(monitor, window.Parent))- window.HasPendingDpiAdjustment = true;-- var windowRules = _userConfigService.GetMatchingWindowRules(window);- var windowRuleCommands = windowRules- .SelectMany(rule => rule.CommandList)- .Select(CommandParsingService.FormatCommand);-- // Set the newly added window as focus descendant. This means the window rules will be run as- // if the window is focused.- _bus.Invoke(new SetFocusedDescendantCommand(window));- _bus.Invoke(new RunWithSubjectContainerCommand(windowRuleCommands, window));-- // Update window in case the reference changes.- window = _windowService.GetWindowByHandle(window.Handle);-- // Window might be detached if 'ignore' command has been invoked.- if (window?.IsDetached() != false)- return CommandResponse.Ok;-- _logger.LogWindowEvent("New window managed", window);- _bus.Emit(new WindowManagedEvent(window));-- // OS focus should be set to the newly added window in case it's not already focused.- _containerService.HasPendingFocusSync = true;-- return CommandResponse.Ok;- }-- private Window CreateWindow(IntPtr windowHandle, Container targetParent)- {- var originalPlacement = WindowService.GetPlacementOfHandle(windowHandle).NormalPosition;-- var targetWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(targetParent);- var handleWorkspace = _monitorService- .GetMonitorFromHandleLocation(windowHandle)- .DisplayedWorkspace;-- // Calculate where window should be placed when floating is enabled. Use the original- // width/height of the window and optionally position it in the center of the workspace.- var centerNewFloatingWindows = _userConfigService.GeneralConfig.CenterNewFloatingWindows;- var floatingPlacement = handleWorkspace == targetWorkspace && !centerNewFloatingWindows- ? originalPlacement- : originalPlacement.TranslateToCenter(targetWorkspace.ToRect());-- var defaultBorderDelta = new RectDelta(7, 0, 7, 7);-- var windowType = GetWindowTypeToCreate(windowHandle);- var isResizable = WindowService.HandleHasWindowStyle(windowHandle, WindowStyles.ThickFrame);-- // TODO: Handle initialization of maximized and fullscreen windows.- return windowType switch- {- WindowType.Minimized => new MinimizedWindow(- windowHandle,- floatingPlacement,- defaultBorderDelta,- isResizable ? WindowType.Tiling : WindowType.Floating- ),- WindowType.Floating => new FloatingWindow(- windowHandle,- floatingPlacement,- defaultBorderDelta- ),- WindowType.Tiling => new TilingWindow(- windowHandle,- floatingPlacement,- defaultBorderDelta- ),- WindowType.Maximized => throw new ArgumentException(null, nameof(windowHandle)),- WindowType.Fullscreen => throw new ArgumentException(null, nameof(windowHandle)),- _ => throw new ArgumentException(null, nameof(windowHandle)),- };- }-- private static WindowType GetWindowTypeToCreate(IntPtr windowHandle)- {- if (WindowService.HandleHasWindowStyle(windowHandle, WindowStyles.Minimize))- return WindowType.Minimized;-- // Initialize windows that can't be resized as floating.- if (!WindowService.HandleHasWindowStyle(windowHandle, WindowStyles.ThickFrame))- return WindowType.Floating;-- return WindowType.Tiling;- }-- private (SplitContainer targetParent, int targetIndex) GetInsertionTarget()- {- var focusedContainer = _containerService.FocusedContainer;-- if (focusedContainer is Workspace)- return (focusedContainer as Workspace, 0);-- return (focusedContainer.Parent as SplitContainer, focusedContainer.Index + 1);- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/MoveWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/MoveWindowHandler.csdeleted file mode 100644index ceb3562a..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/MoveWindowHandler.cs+++ /dev/null@@ -1,293 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Utils;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class MoveWindowHandler : ICommandHandler<MoveWindowCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;- private readonly UserConfigService _userConfigService;-- public MoveWindowHandler(- Bus bus,- ContainerService containerService,- MonitorService monitorService,- UserConfigService userConfigService)- {- _bus = bus;- _containerService = containerService;- _monitorService = monitorService;- _userConfigService = userConfigService;- }-- public CommandResponse Handle(MoveWindowCommand command)- {- var windowToMove = command.WindowToMove;- var direction = command.Direction;-- if (windowToMove is FloatingWindow)- {- MoveFloatingWindow(windowToMove as FloatingWindow, direction);- return CommandResponse.Ok;- }-- if (windowToMove is TilingWindow)- {- MoveTilingWindow(windowToMove as TilingWindow, direction);- return CommandResponse.Ok;- }-- return CommandResponse.Fail;- }-- /// <summary>- /// Whether the window has a tiling sibling in the given direction.- /// </summary>- private static bool HasSiblingInDirection(Window windowToMove, Direction direction)- {- if (direction is Direction.Up or Direction.Left)- return windowToMove != windowToMove.SelfAndSiblingsOfType<IResizable>().First();-- return windowToMove != windowToMove.SelfAndSiblingsOfType<IResizable>().Last();- }-- private void SwapSiblingContainers(Window windowToMove, Direction direction)- {- var siblingInDirection = direction is Direction.Up or Direction.Left- ? windowToMove.PreviousSiblingOfType<IResizable>()- : windowToMove.NextSiblingOfType<IResizable>();-- // Swap the window with sibling in given direction.- if (siblingInDirection is Window)- {- windowToMove.Parent.Children.ShiftToIndex(- siblingInDirection.Index,- windowToMove- );-- _containerService.ContainersToRedraw.Add(windowToMove);- _containerService.ContainersToRedraw.Add(siblingInDirection);- return;- }-- // Move the window into the sibling split container.- var targetDescendant = _containerService.GetDescendantInDirection(- siblingInDirection,- direction.Inverse()- );- var targetParent = targetDescendant.Parent as SplitContainer;-- var shouldInsertAfter =- targetParent.TilingDirection != direction.GetTilingDirection() ||- direction == Direction.Up ||- direction == Direction.Left;- var insertionIndex = shouldInsertAfter ? targetDescendant.Index + 1 : targetDescendant.Index;-- _bus.Invoke(- new MoveContainerWithinTreeCommand(windowToMove, targetParent, insertionIndex)- );- }-- private void MoveToWorkspaceInDirection(Window windowToMove, Direction direction)- {- var monitor = MonitorService.GetMonitorFromChildContainer(windowToMove);- var monitorInDirection = _monitorService.GetMonitorInDirection(direction, monitor);- var workspaceInDirection = monitorInDirection?.DisplayedWorkspace;-- if (workspaceInDirection == null)- return;-- // Since window is crossing monitors, adjustments might need to be made because of DPI.- if (MonitorService.HasDpiDifference(windowToMove, workspaceInDirection))- windowToMove.HasPendingDpiAdjustment = true;-- // Update floating placement since the window has to cross monitors.- windowToMove.FloatingPlacement =- windowToMove.FloatingPlacement.TranslateToCenter(workspaceInDirection.ToRect());-- // TODO: Descend into container if possible.- if (direction is Direction.Up or Direction.Left)- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, workspaceInDirection));- else- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, workspaceInDirection, 0));- }-- private void ChangeWorkspaceTilingDirection(Window windowToMove, Direction direction)- {- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(windowToMove);-- _bus.Invoke(new ChangeTilingDirectionCommand(workspace, direction.GetTilingDirection()));-- // TODO: Should probably descend into sibling if possible.- if (HasSiblingInDirection(windowToMove, direction))- SwapSiblingContainers(windowToMove, direction);- }-- private void InsertIntoAncestor(- TilingWindow windowToMove,- Direction direction,- Container ancestorWithTilingDirection)- {- // Traverse up from `windowToMove` to find container where the parent is- // `ancestorWithTilingDirection`. Then, depending on the direction, insert before- // or after that container.- var insertionReference = windowToMove.Ancestors- .FirstOrDefault(container => container.Parent == ancestorWithTilingDirection);-- var insertionReferenceSibling = direction is Direction.Up or Direction.Left- ? insertionReference.PreviousSiblingOfType<IResizable>()- : insertionReference.NextSiblingOfType<IResizable>();-- if (insertionReferenceSibling is SplitContainer)- {- // Move the window into the adjacent split container.- var targetDescendant = _containerService.GetDescendantInDirection(- insertionReferenceSibling,- direction.Inverse()- );- var targetParent = targetDescendant.Parent as SplitContainer;-- var shouldInsertAfter =- targetParent.TilingDirection != direction.GetTilingDirection() ||- direction == Direction.Up ||- direction == Direction.Left;-- var insertionIndex = shouldInsertAfter- ? targetDescendant.Index + 1- : targetDescendant.Index;-- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, targetParent, insertionIndex));- }- else- {- // Move the window into the container above.- var insertionIndex = (direction is Direction.Up or Direction.Left) ?- insertionReference.Index : insertionReference.Index + 1;-- _bus.Invoke(- new MoveContainerWithinTreeCommand(- windowToMove,- ancestorWithTilingDirection,- insertionIndex- )- );- }- }-- private void MoveTilingWindow(TilingWindow windowToMove, Direction direction)- {- var parentHasTilingDirection =- (windowToMove.Parent as SplitContainer).TilingDirection == direction.GetTilingDirection();-- if (parentHasTilingDirection && HasSiblingInDirection(windowToMove, direction))- {- SwapSiblingContainers(windowToMove, direction);- return;- }-- // Attempt to the move window to workspace in given direction.- if (parentHasTilingDirection && windowToMove.Parent is Workspace)- {- MoveToWorkspaceInDirection(windowToMove, direction);- return;- }-- // The window cannot be moved within the parent container, so traverse upwards to find a- // suitable ancestor to move to.- var ancestorWithTilingDirection = windowToMove.Parent.Ancestors.FirstOrDefault(- (container) =>- (container as SplitContainer)?.TilingDirection == direction.GetTilingDirection()- ) as SplitContainer;-- // Change the tiling direction of the workspace to tiling direction for direction.- if (ancestorWithTilingDirection == null)- {- ChangeWorkspaceTilingDirection(windowToMove, direction);- return;- }-- InsertIntoAncestor(windowToMove, direction, ancestorWithTilingDirection);- }-- private void MoveFloatingWindow(Window windowToMove, Direction direction)- {- var valueFromConfig = _userConfigService.GeneralConfig.FloatingWindowMoveAmount;-- var amount = UnitsHelper.TrimUnits(valueFromConfig);- var units = UnitsHelper.GetUnits(valueFromConfig);- var currentMonitor = MonitorService.GetMonitorFromChildContainer(windowToMove);-- amount = units switch- {- "%" => amount * currentMonitor.Width / 100,- "ppt" => amount * currentMonitor.Width / 100,- "px" => amount,- // in case user only provided a number in the config;- // TODO: somehow validate floating_window_move_amount in config on startup- _ => amount- // _ => throw new ArgumentException(null, nameof(amount)),- };-- var x = windowToMove.FloatingPlacement.X;- var y = windowToMove.FloatingPlacement.Y;-- _ = direction switch- {- Direction.Left => x -= amount,- Direction.Right => x += amount,- Direction.Up => y -= amount,- Direction.Down => y += amount,- _ => throw new ArgumentException(null, nameof(direction))- };-- // Make sure grabbable space on top is always visible- var monitorAbove = _monitorService.GetMonitorInDirection(Direction.Up, currentMonitor);- if (y < currentMonitor.Y && monitorAbove == null)- {- y = currentMonitor.Y;- }-- var newPlacement = Rect.FromXYCoordinates(x, y, windowToMove.FloatingPlacement.Width, windowToMove.FloatingPlacement.Height);- var center = newPlacement.GetCenterPoint();-- // If new placement wants to cross monitors- // && direction == ... is for edge case when user places window center outside a monitor with a mouse- if ((center.X >= currentMonitor.Width + currentMonitor.X && direction == Direction.Right) ||- (center.X < currentMonitor.X && direction == Direction.Left) ||- (center.Y < currentMonitor.Y && direction == Direction.Up) ||- (center.Y >= currentMonitor.Height + currentMonitor.Y && direction == Direction.Down))- {- var monitorInDirection = _monitorService.GetMonitorInDirection(direction, currentMonitor);- var workspaceInDirection = monitorInDirection?.DisplayedWorkspace;-- if (workspaceInDirection == null)- {- return;- }-- // Change the window's parent workspace.- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, workspaceInDirection));-- // Redrawing twice to fix weird WindowsOS dpi behaviour- windowToMove.HasPendingDpiAdjustment = true;- }-- windowToMove.FloatingPlacement = newPlacement;-- _containerService.ContainersToRedraw.Add(windowToMove);- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowBordersHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowBordersHandler.csdeleted file mode 100644index 3fe452d6..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowBordersHandler.cs+++ /dev/null@@ -1,44 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class ResizeWindowBordersHandler : ICommandHandler<ResizeWindowBordersCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;-- public ResizeWindowBordersHandler(Bus bus, ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- }-- public CommandResponse Handle(ResizeWindowBordersCommand command)- {- var borderDelta = command.BorderDelta;- var windowToResize = command.WindowToResize;-- // Set the new border delta of the window.- // TODO: Move default border delta into some sort of shared state.- var defaultBorderDelta = new RectDelta(7, 0, 7, 7);- windowToResize.BorderDelta = new RectDelta(- defaultBorderDelta.Left + borderDelta.Left,- defaultBorderDelta.Top + borderDelta.Top,- defaultBorderDelta.Right + borderDelta.Right,- defaultBorderDelta.Bottom + borderDelta.Bottom- );-- // No need to redraw if window isn't tiling.- if (windowToResize is not TilingWindow)- return CommandResponse.Ok;-- _containerService.ContainersToRedraw.Add(windowToResize);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowHandler.csdeleted file mode 100644index e7887b58..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/ResizeWindowHandler.cs+++ /dev/null@@ -1,138 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class ResizeWindowHandler : ICommandHandler<ResizeWindowCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;-- public ResizeWindowHandler(Bus bus, ContainerService containerService, MonitorService monitorService)- {- _bus = bus;- _containerService = containerService;- _monitorService = monitorService;- }-- public CommandResponse Handle(ResizeWindowCommand command)- {- var dimensionToResize = command.DimensionToResize;- var resizeAmount = command.ResizeAmount;- var windowToResize = command.WindowToResize;-- if (windowToResize is FloatingWindow)- {- ResizeFloatingWindow(windowToResize, dimensionToResize, resizeAmount);- return CommandResponse.Ok;- }- // Ignore cases where window is not tiling.- if (windowToResize is not TilingWindow)- return CommandResponse.Ok;-- // Get container and its siblings to resize.- var containerToResize = GetContainerToResize(windowToResize, dimensionToResize);- var resizableSiblings = containerToResize.SiblingsOfType<IResizable>();-- // Ignore cases where the container to resize is a workspace or the only child.- if (!resizableSiblings.Any() || containerToResize is Workspace)- return CommandResponse.Ok;-- // Convert `resizeAmount` to a percentage to increase/decrease the window size by.- var resizePercentage = ResizeParsingService.ParseResizePercentage(- containerToResize,- dimensionToResize,- resizeAmount- );-- _bus.Invoke(new ResizeContainerCommand(containerToResize, resizePercentage));-- // TODO: Return early if `clampedResizePercentage` is 0 to avoid unnecessary redraws.- _containerService.ContainersToRedraw.Add(containerToResize.Parent);-- return CommandResponse.Ok;- }-- private static Container GetContainerToResize(- Window windowToResize,- ResizeDimension dimensionToResize)- {- var parent = windowToResize.Parent;- var grandparent = parent.Parent;- var tilingDirection = (parent as SplitContainer).TilingDirection;-- // Whether the resize is in the inverse direction of its tiling direction.- var isInverseResize =- (tilingDirection == TilingDirection.Horizontal &&- dimensionToResize == ResizeDimension.Height) ||- (tilingDirection == TilingDirection.Vertical &&- dimensionToResize == ResizeDimension.Width);-- var hasResizableSiblings = windowToResize.SiblingsOfType<IResizable>().Any();-- if (!isInverseResize && !hasResizableSiblings && grandparent is IResizable)- return grandparent;-- return isInverseResize ? parent : windowToResize;- }-- private void ResizeFloatingWindow(Window windowToResize, ResizeDimension dimensionToResize, string resizeAmount)- {- const int MIN_WIDTH = 250;- const int MIN_HEIGHT = 140;-- var resizePercentage = ResizeParsingService.ParseResizePercentage(windowToResize, dimensionToResize, resizeAmount);- var currentMonitor = MonitorService.GetMonitorFromChildContainer(windowToResize);-- var amount = (int)(currentMonitor.Width * resizePercentage);-- var width = windowToResize.FloatingPlacement.Width;- var height = windowToResize.FloatingPlacement.Height;-- _ = dimensionToResize switch- {- ResizeDimension.Width => width += amount,- ResizeDimension.Height => height += amount,- _ => throw new ArgumentException(null, nameof(dimensionToResize))- };-- //Return if resize gonna make window smaller than allowed- //but allow increasing size (for situations if user made the window smaller- // than MIN_WIDHT or MIN_HEIGHT with the mouse)- if ((width < MIN_WIDTH || height < MIN_HEIGHT) && amount < 0)- return;-- windowToResize.FloatingPlacement = Rect.FromXYCoordinates(windowToResize.FloatingPlacement.X, windowToResize.FloatingPlacement.Y, width, height);-- _containerService.ContainersToRedraw.Add(windowToResize);-- // Check if window now takes up more of another screen after moving- var currentWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(windowToResize);-- // Get workspace that encompasses most of the window after moving- var targetMonitor = _monitorService.GetMonitorFromHandleLocation(windowToResize.Handle);- var targetWorkspace = targetMonitor.DisplayedWorkspace;-- // Ignore if window is still within the bounds of its current workspace.- if (currentWorkspace == targetWorkspace)- {- return;- }-- // Change the window's parent workspace.- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToResize, targetWorkspace));-- windowToResize.HasPendingDpiAdjustment = true;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/SetFloatingHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/SetFloatingHandler.csdeleted file mode 100644index 48842d8d..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/SetFloatingHandler.cs+++ /dev/null@@ -1,45 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class SetFloatingHandler : ICommandHandler<SetFloatingCommand>- {- private readonly Bus _bus;-- public SetFloatingHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(SetFloatingCommand command)- {- var window = command.Window;-- if (window is FloatingWindow)- return CommandResponse.Ok;-- // Keep reference to the window's ancestor workspace prior to detaching.- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(window);-- _bus.Invoke(new MoveContainerWithinTreeCommand(window, workspace));-- // Create a floating window and place it in the center of the workspace.- var floatingWindow = new FloatingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta- )- {- Id = window.Id- };-- _bus.Invoke(new ReplaceContainerCommand(floatingWindow, window.Parent, window.Index));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/SetMaximizedHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/SetMaximizedHandler.csdeleted file mode 100644index 0200c60e..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/SetMaximizedHandler.cs+++ /dev/null@@ -1,18 +0,0 @@-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class SetMaximizedHandler : ICommandHandler<SetMaximizedCommand>- {- public CommandResponse Handle(SetMaximizedCommand command)- {- var window = command.Window;-- ShowWindowAsync(window.Handle, ShowWindowFlags.Maximize);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/SetMinimizedHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/SetMinimizedHandler.csdeleted file mode 100644index d8c2b732..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/SetMinimizedHandler.cs+++ /dev/null@@ -1,18 +0,0 @@-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class SetMinimizedHandler : ICommandHandler<SetMinimizedCommand>- {- public CommandResponse Handle(SetMinimizedCommand command)- {- var window = command.Window;-- ShowWindowAsync(window.Handle, ShowWindowFlags.Minimize);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/SetTilingHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/SetTilingHandler.csdeleted file mode 100644index eceac73c..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/SetTilingHandler.cs+++ /dev/null@@ -1,58 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class SetTilingHandler : ICommandHandler<SetTilingCommand>- {- private readonly Bus _bus;-- public SetTilingHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(SetTilingCommand command)- {- var window = command.Window;-- if (window is TilingWindow)- return CommandResponse.Ok;-- // Keep reference to the window's ancestor workspace prior to detaching.- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(window);-- var insertionTarget = workspace.LastFocusedDescendantOfType<IResizable>();-- var tilingWindow = new TilingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- 0- )- {- Id = window.Id- };-- // Replace the original window with the created tiling window.- _bus.Invoke(new ReplaceContainerCommand(tilingWindow, window.Parent, window.Index));-- // Insert the created tiling window after the last focused descendant of the workspace.- if (insertionTarget is null)- _bus.Invoke(new MoveContainerWithinTreeCommand(tilingWindow, workspace, 0));- else- _bus.Invoke(- new MoveContainerWithinTreeCommand(- tilingWindow,- insertionTarget.Parent,- insertionTarget.Index + 1- )- );-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/SetWindowSizeHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/SetWindowSizeHandler.csdeleted file mode 100644index 9769c1fa..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/SetWindowSizeHandler.cs+++ /dev/null@@ -1,58 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class SetWindowSizeHandler : ICommandHandler<SetWindowSizeCommand>- {- private readonly Bus _bus;-- public SetWindowSizeHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(SetWindowSizeCommand command)- {- // calculate the delta required to achivee the desired window size- var resizeAmount = CalculateResizeAmount(command);-- // invoke the resize command with the calculated delta- _bus.Invoke(new ResizeWindowCommand(command.WindowToResize, command.DimensionToResize, resizeAmount));-- return CommandResponse.Ok;- }-- private static string CalculateResizeAmount(SetWindowSizeCommand command)- {- // get the parent dimension (width or height)- var parentSize = command.DimensionToResize switch- {- ResizeDimension.Width => command.WindowToResize.Parent.Width,- ResizeDimension.Height => command.WindowToResize.Parent.Height,- _ => 0,- };-- // get the current window dimension (width or height)- var actualSize = command.DimensionToResize switch- {- ResizeDimension.Width => command.WindowToResize.Width,- ResizeDimension.Height => command.WindowToResize.Height,- _ => 0,- };-- // calculate the desired size (based on parent size)- var desiredSize = parentSize * ResizeParsingService.ParseResizePercentage(- command.WindowToResize,- command.DimensionToResize,- command.ResizeAmount);-- // calculate the delta required to achieve the desired size- var resizeDelta = desiredSize - actualSize;-- // return delta (in px)- return resizeDelta > 0 ? $"+{resizeDelta}px" : $"{resizeDelta}px";- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ToggleFloatingHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ToggleFloatingHandler.csdeleted file mode 100644index 4f2e55aa..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/ToggleFloatingHandler.cs+++ /dev/null@@ -1,27 +0,0 @@-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class ToggleFloatingHandler : ICommandHandler<ToggleFloatingCommand>- {- private readonly Bus _bus;-- public ToggleFloatingHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(ToggleFloatingCommand command)- {- var window = command.Window;-- if (window is FloatingWindow)- _bus.Invoke(new SetTilingCommand(window));- else- _bus.Invoke(new SetFloatingCommand(window));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/ToggleMaximizedHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/ToggleMaximizedHandler.csdeleted file mode 100644index 1a758b70..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/ToggleMaximizedHandler.cs+++ /dev/null@@ -1,21 +0,0 @@-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.CommandHandlers-{- internal sealed class ToggleMaximizedHandler : ICommandHandler<ToggleMaximizedCommand>- {- public CommandResponse Handle(ToggleMaximizedCommand command)- {- var window = command.Window;-- if (window.HasWindowStyle(WindowStyles.Maximize))- ShowWindowAsync(window.Handle, ShowWindowFlags.Restore);- else- ShowWindowAsync(window.Handle, ShowWindowFlags.Maximize);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.cs b/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.csdeleted file mode 100644index 6b7428a1..00000000--- a/GlazeWM.Domain/Windows/CommandHandlers/UnmanageWindowHandler.cs+++ /dev/null@@ -1,48 +0,0 @@-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-{- internal sealed class UnmanageWindowHandler : ICommandHandler<UnmanageWindowCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly WindowService _windowService;-- public UnmanageWindowHandler(- Bus bus,- ContainerService containerService,- WindowService windowService)- {- _bus = bus;- _containerService = containerService;- _windowService = windowService;- }-- public CommandResponse Handle(UnmanageWindowCommand command)- {- var window = command.Window;-- // Get container to switch focus to after the window has been removed.- var focusedContainer = _containerService.FocusedContainer;- var focusTarget = window == focusedContainer- ? WindowService.GetFocusTargetAfterRemoval(window)- : null;-- _bus.Invoke(new DetachContainerCommand(window));- _bus.Emit(new WindowUnmanagedEvent(window.Id, window.Handle));-- if (focusTarget is null)- return CommandResponse.Ok;-- _bus.Invoke(new SetFocusedDescendantCommand(focusTarget));- _containerService.HasPendingFocusSync = true;- _windowService.UnmanagedOrMinimizedStopwatch.Restart();-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/CloseWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/CloseWindowCommand.csdeleted file mode 100644index 72e90248..00000000--- a/GlazeWM.Domain/Windows/Commands/CloseWindowCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class CloseWindowCommand : Command- {- public Window WindowToClose { get; }-- public CloseWindowCommand(Window windowToClose)- {- WindowToClose = windowToClose;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/IgnoreWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/IgnoreWindowCommand.csdeleted file mode 100644index ab3d784e..00000000--- a/GlazeWM.Domain/Windows/Commands/IgnoreWindowCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class IgnoreWindowCommand : Command- {- public Window WindowToIgnore { get; }-- public IgnoreWindowCommand(Window windowToIgnore)- {- WindowToIgnore = windowToIgnore;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/ManageWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/ManageWindowCommand.csdeleted file mode 100644index 263f1eb4..00000000--- a/GlazeWM.Domain/Windows/Commands/ManageWindowCommand.cs+++ /dev/null@@ -1,20 +0,0 @@-using System;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class ManageWindowCommand : Command- {- public IntPtr WindowHandle { get; }- public SplitContainer TargetParent { get; }-- public ManageWindowCommand(- IntPtr windowHandle,- SplitContainer targetParent = null)- {- WindowHandle = windowHandle;- TargetParent = targetParent;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/MoveWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/MoveWindowCommand.csdeleted file mode 100644index 64c49f5b..00000000--- a/GlazeWM.Domain/Windows/Commands/MoveWindowCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class MoveWindowCommand : Command- {- public Window WindowToMove { get; }- public Direction Direction { get; }-- public MoveWindowCommand(Window windowToMove, Direction direction)- {- WindowToMove = windowToMove;- Direction = direction;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/ResizeWindowBordersCommand.cs b/GlazeWM.Domain/Windows/Commands/ResizeWindowBordersCommand.csdeleted file mode 100644index e31ba898..00000000--- a/GlazeWM.Domain/Windows/Commands/ResizeWindowBordersCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows.Commands-{- public class ResizeWindowBordersCommand : Command- {- public Window WindowToResize { get; }- public RectDelta BorderDelta { get; }-- public ResizeWindowBordersCommand(Window windowToResize, RectDelta borderDelta)- {- WindowToResize = windowToResize;- BorderDelta = borderDelta;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/ResizeWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/ResizeWindowCommand.csdeleted file mode 100644index dc279f1b..00000000--- a/GlazeWM.Domain/Windows/Commands/ResizeWindowCommand.cs+++ /dev/null@@ -1,22 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class ResizeWindowCommand : Command- {- public Window WindowToResize { get; }- public ResizeDimension DimensionToResize { get; }- public string ResizeAmount { get; }-- public ResizeWindowCommand(- Window windowToResize,- ResizeDimension dimensionToResize,- string resizeAmount)- {- WindowToResize = windowToResize;- DimensionToResize = dimensionToResize;- ResizeAmount = resizeAmount;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/SetFloatingCommand.cs b/GlazeWM.Domain/Windows/Commands/SetFloatingCommand.csdeleted file mode 100644index 0504f86e..00000000--- a/GlazeWM.Domain/Windows/Commands/SetFloatingCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class SetFloatingCommand : Command- {- public Window Window { get; }-- public SetFloatingCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/SetMaximizedCommand.cs b/GlazeWM.Domain/Windows/Commands/SetMaximizedCommand.csdeleted file mode 100644index 768c0bc9..00000000--- a/GlazeWM.Domain/Windows/Commands/SetMaximizedCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class SetMaximizedCommand : Command- {- public Window Window { get; }-- public SetMaximizedCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/SetMinimizedCommand.cs b/GlazeWM.Domain/Windows/Commands/SetMinimizedCommand.csdeleted file mode 100644index 22640e14..00000000--- a/GlazeWM.Domain/Windows/Commands/SetMinimizedCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class SetMinimizedCommand : Command- {- public Window Window { get; }-- public SetMinimizedCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/SetTilingCommand.cs b/GlazeWM.Domain/Windows/Commands/SetTilingCommand.csdeleted file mode 100644index a7670843..00000000--- a/GlazeWM.Domain/Windows/Commands/SetTilingCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class SetTilingCommand : Command- {- public Window Window { get; }-- public SetTilingCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/SetWindowSizeCommand.cs b/GlazeWM.Domain/Windows/Commands/SetWindowSizeCommand.csdeleted file mode 100644index 1d0dadd6..00000000--- a/GlazeWM.Domain/Windows/Commands/SetWindowSizeCommand.cs+++ /dev/null@@ -1,22 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class SetWindowSizeCommand : Command- {- public Window WindowToResize { get; }- public ResizeDimension DimensionToResize { get; }- public string ResizeAmount { get; }-- public SetWindowSizeCommand(- Window windowToResize,- ResizeDimension dimensionToResize,- string resizeAmount)- {- WindowToResize = windowToResize;- DimensionToResize = dimensionToResize;- ResizeAmount = resizeAmount;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/ToggleFloatingCommand.cs b/GlazeWM.Domain/Windows/Commands/ToggleFloatingCommand.csdeleted file mode 100644index 4c36e188..00000000--- a/GlazeWM.Domain/Windows/Commands/ToggleFloatingCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class ToggleFloatingCommand : Command- {- public Window Window { get; }-- public ToggleFloatingCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/ToggleMaximizedCommand.cs b/GlazeWM.Domain/Windows/Commands/ToggleMaximizedCommand.csdeleted file mode 100644index ae012b4c..00000000--- a/GlazeWM.Domain/Windows/Commands/ToggleMaximizedCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class ToggleMaximizedCommand : Command- {- public Window Window { get; }-- public ToggleMaximizedCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/Commands/UnmanageWindowCommand.cs b/GlazeWM.Domain/Windows/Commands/UnmanageWindowCommand.csdeleted file mode 100644index bf9d3026..00000000--- a/GlazeWM.Domain/Windows/Commands/UnmanageWindowCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Commands-{- public class UnmanageWindowCommand : Command- {- public Window Window { get; }-- public UnmanageWindowCommand(Window window)- {- Window = window;- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowDestroyedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowDestroyedHandler.csdeleted file mode 100644index 63cc3857..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowDestroyedHandler.cs+++ /dev/null@@ -1,53 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowDestroyedHandler : IEventHandler<WindowDestroyedEvent>- {- private readonly Bus _bus;- private readonly WindowService _windowService;- private readonly ILogger<WindowDestroyedHandler> _logger;-- public WindowDestroyedHandler(- Bus bus,- WindowService windowService,- ILogger<WindowDestroyedHandler> logger)- {- _bus = bus;- _windowService = windowService;- _logger = logger;- }-- public void Handle(WindowDestroyedEvent @event)- {- var windowHandle = @event.WindowHandle;-- if (_windowService.AppBarHandles.Contains(windowHandle))- {- _windowService.AppBarHandles.Remove(windowHandle);- _bus.Invoke(new RefreshMonitorStateCommand());- return;- }-- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == windowHandle);-- if (window == null)- return;-- _logger.LogWindowEvent("Window closed", window);-- // If window is in tree, detach the removed window from its parent.- _bus.Invoke(new UnmanageWindowCommand(window));- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowFocusedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowFocusedHandler.csdeleted file mode 100644index 6c778d81..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowFocusedHandler.cs+++ /dev/null@@ -1,87 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowFocusedHandler : IEventHandler<WindowFocusedEvent>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly ILogger<WindowFocusedHandler> _logger;- private readonly WindowService _windowService;-- public WindowFocusedHandler(- Bus bus,- ContainerService containerService,- ILogger<WindowFocusedHandler> logger,- WindowService windowService)- {- _bus = bus;- _containerService = containerService;- _logger = logger;- _windowService = windowService;- }-- public void Handle(WindowFocusedEvent @event)- {- var windowHandle = @event.WindowHandle;-- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == @event.WindowHandle);-- // Ignore event if window is unmanaged or being hidden by the WM.- if (window is null || window.DisplayState is DisplayState.Hiding)- return;-- _logger.LogWindowEvent("Native focus event", window);-- var focusedContainer = _containerService.FocusedContainer;-- // Focus is already set to the WM's focused container.- if (window == focusedContainer)- return;-- var unmanagedStopwatch = _windowService.UnmanagedOrMinimizedStopwatch;-- // Handle overriding focus on close/minimize. After a window is closed or minimized,- // the OS or the closed application might automatically switch focus to a different- // window. To force focus to go to the WM's target focus container, we reassign any- // focus events 100ms after close/minimize. This will cause focus to briefly flicker- // to the OS focus target and then to the WM's focus target.- if (unmanagedStopwatch.IsRunning && unmanagedStopwatch.ElapsedMilliseconds < 100)- {- _logger.LogDebug("Overriding native focus.");- _bus.Invoke(new SyncNativeFocusCommand());- return;- }-- // Handle focus events from windows on hidden workspaces. For example, if Discord- // is forcefully shown by the OS when it's on a hidden workspace, switch focus to- // Discord's workspace.- if (window.DisplayState is DisplayState.Hidden)- {- _logger.LogWindowEvent("Focusing off-screen window", window);-- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(window);- _bus.Invoke(new FocusWorkspaceCommand(workspace.Name));- _bus.Invoke(new SetFocusedDescendantCommand(window));- _bus.Invoke(new RedrawContainersCommand());- _bus.Emit(new FocusChangedEvent(window));- return;- }-- // Update the WM's focus state.- _bus.Invoke(new SetFocusedDescendantCommand(window));- _bus.Emit(new FocusChangedEvent(window));- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowHiddenHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowHiddenHandler.csdeleted file mode 100644index 36911c1c..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowHiddenHandler.cs+++ /dev/null@@ -1,67 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowHiddenHandler : IEventHandler<WindowHiddenEvent>- {- private readonly Bus _bus;- private readonly WindowService _windowService;- private readonly ILogger<WindowHiddenHandler> _logger;-- public WindowHiddenHandler(- Bus bus,- WindowService windowService,- ILogger<WindowHiddenHandler> logger)- {- _bus = bus;- _windowService = windowService;- _logger = logger;- }-- public void Handle(WindowHiddenEvent @event)- {- var windowHandle = @event.WindowHandle;-- if (_windowService.AppBarHandles.Contains(windowHandle))- {- _windowService.AppBarHandles.Remove(windowHandle);- _bus.Invoke(new RefreshMonitorStateCommand());- return;- }-- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == windowHandle);-- // Ignore event if window is unmanaged.- if (window is null)- return;-- _logger.LogWindowEvent("Window hidden", window);-- // Update the display state.- if (window.DisplayState is DisplayState.Hiding)- {- window.DisplayState = DisplayState.Hidden;- return;- }-- // Unmanage the window if it's not in a display state transition. Also, since window- // events are not 100% guaranteed to be in correct order, we need to ignore events- // where the window is not actually hidden.- if (window.DisplayState is DisplayState.Shown && !WindowService.IsHandleVisible(window.Handle))- {- _bus.Invoke(new UnmanageWindowCommand(window));- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- }- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowLocationChangedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowLocationChangedHandler.csdeleted file mode 100644index 558bdd33..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowLocationChangedHandler.cs+++ /dev/null@@ -1,138 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowLocationChangedHandler : IEventHandler<WindowLocationChangedEvent>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly WindowService _windowService;-- public WindowLocationChangedHandler(Bus bus,- WindowService windowService,- ContainerService containerService)- {- _bus = bus;- _containerService = containerService;- _windowService = windowService;- }-- public void Handle(WindowLocationChangedEvent @event)- {- var windowHandle = @event.WindowHandle;-- HandleMaximizedWindow(windowHandle);-- if (!_windowService.AppBarHandles.Contains(windowHandle))- return;-- _bus.Invoke(new RefreshMonitorStateCommand());- _bus.Invoke(new RedrawContainersCommand());- }-- private void HandleMaximizedWindow(IntPtr windowHandle)- {- var window = _windowService.GetWindowByHandle(windowHandle);- if (window is null)- return;-- var windowPlacement = WindowService.GetPlacementOfHandle(windowHandle);- var isMaximized = windowPlacement.ShowCommand == ShowWindowFlags.Maximize;-- // Window is being maximized.- if (isMaximized && window is not MaximizedWindow)- {- var previousState = WindowService.GetWindowType(window);- var maximizedWindow = new MaximizedWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- previousState- )- {- Id = window.Id- };-- if (!window.HasSiblings() && window.Parent is not Workspace)- _bus.Invoke(new FlattenSplitContainerCommand(window.Parent as SplitContainer));-- _bus.Invoke(new ReplaceContainerCommand(maximizedWindow, window.Parent, window.Index));-- _containerService.ContainersToRedraw.Concat(window.Siblings);- _bus.Invoke(new RedrawContainersCommand());- }-- // Maximized window is being restored.- if (!isMaximized && window is MaximizedWindow)- {- var restoredWindow = CreateWindowFromPreviousState(window as MaximizedWindow);- _bus.Invoke(new ReplaceContainerCommand(restoredWindow, window.Parent, window.Index));-- // Non-tiling window expect to be direct children of workspace.- if (restoredWindow is not TilingWindow)- {- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(restoredWindow);- _bus.Invoke(new MoveContainerWithinTreeCommand(restoredWindow, workspace));- }- else- {- // TODO: Temporary hack to resize restored tiling window.- _bus.Invoke(- new MoveContainerWithinTreeCommand(- restoredWindow,- restoredWindow.Parent,- restoredWindow.Index- )- );- }-- _containerService.ContainersToRedraw.Add(restoredWindow);- _bus.Invoke(new RedrawContainersCommand());- }- }-- // TODO: Share logic with `WindowMinimizedHandler`.- private static Window CreateWindowFromPreviousState(MaximizedWindow window)- {- Window restoredWindow = window.PreviousState switch- {- WindowType.Floating => new FloatingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta- ),- WindowType.Fullscreen => new FullscreenWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta- ),- // Set `SizePercentage` to 0 to correctly resize the container when moved within tree.- WindowType.Tiling => new TilingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- 0- ),- WindowType.Minimized => new MinimizedWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- WindowType.Tiling- ),- WindowType.Maximized => throw new ArgumentException(null, nameof(window)),- _ => throw new ArgumentException(null, nameof(window)),- };-- restoredWindow.Id = window.Id;- return restoredWindow;- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizeEndedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizeEndedHandler.csdeleted file mode 100644index e99ce1e6..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizeEndedHandler.cs+++ /dev/null@@ -1,103 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowMinimizeEndedHandler : IEventHandler<WindowMinimizeEndedEvent>- {- private readonly Bus _bus;- private readonly WindowService _windowService;- private readonly ContainerService _containerService;- private readonly ILogger<WindowMinimizeEndedHandler> _logger;-- public WindowMinimizeEndedHandler(- Bus bus,- WindowService windowService,- ContainerService containerService,- ILogger<WindowMinimizeEndedHandler> logger)- {- _bus = bus;- _windowService = windowService;- _containerService = containerService;- _logger = logger;- }-- public void Handle(WindowMinimizeEndedEvent @event)- {- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == @event.WindowHandle) as MinimizedWindow;-- if (window == null)- return;-- _logger.LogWindowEvent("Window minimize ended", window);-- var restoredWindow = CreateWindowFromPreviousState(window);-- _bus.Invoke(new ReplaceContainerCommand(restoredWindow, window.Parent, window.Index));-- if (restoredWindow is not TilingWindow)- return;-- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(window);- var insertionTarget = workspace.LastFocusedDescendantOfType<IResizable>();-- // Insert the created tiling window after the last focused descendant of the workspace.- if (insertionTarget == null)- _bus.Invoke(new MoveContainerWithinTreeCommand(restoredWindow, workspace, 0));- else- _bus.Invoke(- new MoveContainerWithinTreeCommand(- restoredWindow,- insertionTarget.Parent,- insertionTarget.Index + 1- )- );-- _containerService.ContainersToRedraw.Add(workspace);- _bus.Invoke(new RedrawContainersCommand());- }-- private static Window CreateWindowFromPreviousState(MinimizedWindow window)- {- Window restoredWindow = window.PreviousState switch- {- WindowType.Floating => new FloatingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta- ),- WindowType.Maximized => new MaximizedWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- WindowType.Tiling- ),- WindowType.Fullscreen => new FullscreenWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta- ),- // Set `SizePercentage` to 0 to correctly resize the container when moved within tree.- WindowType.Tiling => new TilingWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- 0- ),- WindowType.Minimized => throw new ArgumentException(null, nameof(window)),- _ => throw new ArgumentException(null, nameof(window)),- };-- restoredWindow.Id = window.Id;- return restoredWindow;- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizedHandler.csdeleted file mode 100644index 479e638f..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowMinimizedHandler.cs+++ /dev/null@@ -1,80 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowMinimizedHandler : IEventHandler<WindowMinimizedEvent>- {- private readonly Bus _bus;- private readonly WindowService _windowService;- private readonly ContainerService _containerService;- private readonly ILogger<WindowMinimizedHandler> _logger;-- public WindowMinimizedHandler(- Bus bus,- WindowService windowService,- ContainerService containerService,- ILogger<WindowMinimizedHandler> logger)- {- _bus = bus;- _windowService = windowService;- _containerService = containerService;- _logger = logger;- }-- public void Handle(WindowMinimizedEvent @event)- {- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == @event.WindowHandle);-- if (window is null or MinimizedWindow)- return;-- _logger.LogWindowEvent("Window minimized", window);-- var workspace = WorkspaceService.GetWorkspaceFromChildContainer(window);-- // Move tiling windows to be direct children of workspace (in case they aren't already).- if (window is TilingWindow)- _bus.Invoke(new MoveContainerWithinTreeCommand(window, workspace));-- var previousState = WindowService.GetWindowType(window);- var minimizedWindow = new MinimizedWindow(- window.Handle,- window.FloatingPlacement,- window.BorderDelta,- previousState- )- {- Id = window.Id- };-- // Get container to switch focus to after the window has been minimized. Need to- // get focus target prior to calling `ReplaceContainerCommand`.- var focusedContainer = _containerService.FocusedContainer;- var focusTarget = window == focusedContainer- ? WindowService.GetFocusTargetAfterRemoval(window)- : null;-- _bus.Invoke(new ReplaceContainerCommand(minimizedWindow, window.Parent, window.Index));-- // Focus should be reassigned to appropriate container.- if (focusTarget is not null)- {- _bus.Invoke(new SetFocusedDescendantCommand(focusTarget));- _containerService.HasPendingFocusSync = true;- _windowService.UnmanagedOrMinimizedStopwatch.Restart();- }-- _containerService.ContainersToRedraw.Add(workspace);- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowMovedOrResizedHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowMovedOrResizedHandler.csdeleted file mode 100644index 58078196..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowMovedOrResizedHandler.cs+++ /dev/null@@ -1,115 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using GlazeWM.Infrastructure.WindowsApi;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowMovedOrResizedHandler : IEventHandler<WindowMovedOrResizedEvent>- {- private readonly Bus _bus;- private readonly WindowService _windowService;- private readonly MonitorService _monitorService;- private readonly ContainerService _containerService;- private readonly ILogger<WindowMovedOrResizedHandler> _logger;-- public WindowMovedOrResizedHandler(- Bus bus,- WindowService windowService,- MonitorService monitorService,- ILogger<WindowMovedOrResizedHandler> logger,- ContainerService containerService)- {- _bus = bus;- _windowService = windowService;- _monitorService = monitorService;- _logger = logger;- _containerService = containerService;- }-- public void Handle(WindowMovedOrResizedEvent @event)- {- var window = _windowService.GetWindows().FirstOrDefault(window => window.Handle == @event.WindowHandle);-- if (window is null)- return;-- _logger.LogWindowEvent("Window moved/resized", window);-- if (window is TilingWindow)- {- UpdateTilingWindow(window as TilingWindow);- return;- }-- if (window is FloatingWindow)- UpdateFloatingWindow(window as FloatingWindow);- }-- private void UpdateTilingWindow(TilingWindow window)- {- // Snap window to its original position even if it's not being resized.- var hasNoResizableSiblings = window.Parent is Workspace- && !window.SiblingsOfType<IResizable>().Any();-- if (hasNoResizableSiblings)- {- _containerService.ContainersToRedraw.Add(window);- _bus.Invoke(new RedrawContainersCommand());- return;- }-- // Remove invisible borders from current placement to be able to compare window width/height.- var currentPlacement = WindowService.GetPlacementOfHandle(window.Handle).NormalPosition;- var adjustedPlacement = new Rect- {- Left = currentPlacement.Left + window.BorderDelta.Left,- Right = currentPlacement.Right - window.BorderDelta.Right,- Top = currentPlacement.Top + window.BorderDelta.Top,- Bottom = currentPlacement.Bottom - window.BorderDelta.Bottom,- };-- var deltaWidth = adjustedPlacement.Width - window.Width;- var deltaHeight = adjustedPlacement.Height - window.Height;-- _bus.Invoke(new ResizeWindowCommand(window, ResizeDimension.Width, $"{deltaWidth}px"));- _bus.Invoke(new ResizeWindowCommand(window, ResizeDimension.Height, $"{deltaHeight}px"));- _bus.Invoke(new RedrawContainersCommand());- }-- private void UpdateFloatingWindow(FloatingWindow window)- {- // Update state with new location of the floating window.- window.FloatingPlacement = WindowService.GetPlacementOfHandle(window.Handle).NormalPosition;-- // Change floating window's parent workspace if out of its bounds.- UpdateParentWorkspace(window);- }-- private void UpdateParentWorkspace(Window window)- {- var currentWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(window);-- // Get workspace that encompasses most of the window.- var targetMonitor = _monitorService.GetMonitorFromHandleLocation(window.Handle);- var targetWorkspace = targetMonitor.DisplayedWorkspace;-- // Ignore if window is still within the bounds of its current workspace.- if (currentWorkspace == targetWorkspace)- return;-- // Change the window's parent workspace.- _bus.Invoke(new MoveContainerWithinTreeCommand(window, targetWorkspace));- _bus.Emit(new FocusChangedEvent(window));- }- }-}diff --git a/GlazeWM.Domain/Windows/EventHandlers/WindowShownHandler.cs b/GlazeWM.Domain/Windows/EventHandlers/WindowShownHandler.csdeleted file mode 100644index a64c2e67..00000000--- a/GlazeWM.Domain/Windows/EventHandlers/WindowShownHandler.cs+++ /dev/null@@ -1,60 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Common.Utils;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors.Commands;-using GlazeWM.Domain.Windows.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Windows.EventHandlers-{- internal sealed class WindowShownHandler : IEventHandler<WindowShownEvent>- {- private readonly Bus _bus;- private readonly ILogger<WindowShownHandler> _logger;- private readonly WindowService _windowService;-- public WindowShownHandler(- Bus bus,- ILogger<WindowShownHandler> logger,- WindowService windowService)- {- _bus = bus;- _logger = logger;- _windowService = windowService;- }-- public void Handle(WindowShownEvent @event)- {- var windowHandle = @event.WindowHandle;-- if (_windowService.IsHandleAppBar(windowHandle))- {- _windowService.AppBarHandles.Add(windowHandle);- _bus.Invoke(new RefreshMonitorStateCommand());- return;- }-- var window = _windowService.GetWindows()- .FirstOrDefault(window => window.Handle == windowHandle);-- // Manage the window if it's manageable.- if (window is null && WindowService.IsHandleManageable(windowHandle))- {- _bus.Invoke(new ManageWindowCommand(windowHandle));- _bus.Invoke(new RedrawContainersCommand());- _bus.Invoke(new SyncNativeFocusCommand());- return;- }-- if (window is not null)- _logger.LogWindowEvent("Showing window", window);-- // Update display state if window is already managed.- if (window?.DisplayState == DisplayState.Showing)- window.DisplayState = DisplayState.Shown;- }- }-}diff --git a/GlazeWM.Domain/Windows/Events/WindowManagedEvent.cs b/GlazeWM.Domain/Windows/Events/WindowManagedEvent.csdeleted file mode 100644index c8fc9739..00000000--- a/GlazeWM.Domain/Windows/Events/WindowManagedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Events-{- public record WindowManagedEvent(Window ManagedWindow)- : Event(DomainEvent.WindowManaged);-}diff --git a/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.cs b/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.csdeleted file mode 100644index 4ca8bc4a..00000000--- a/GlazeWM.Domain/Windows/Events/WindowUnmanagedEvent.cs+++ /dev/null@@ -1,9 +0,0 @@-using System;-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Windows.Events-{- public record WindowUnmanagedEvent(Guid UnmanagedId, IntPtr UnmanagedHandle)- : Event(DomainEvent.WindowUnmanaged);-}diff --git a/GlazeWM.Domain/Windows/FloatingWindow.cs b/GlazeWM.Domain/Windows/FloatingWindow.csdeleted file mode 100644index b6988174..00000000--- a/GlazeWM.Domain/Windows/FloatingWindow.cs+++ /dev/null@@ -1,24 +0,0 @@-using System;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows-{- public sealed class FloatingWindow : Window- {- public override int Width => FloatingPlacement.Width;-- public override int Height => FloatingPlacement.Height;-- public override int X => FloatingPlacement.X;-- public override int Y => FloatingPlacement.Y;-- public FloatingWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta- ) : base(handle, floatingPlacement, borderDelta)- {- }- }-}diff --git a/GlazeWM.Domain/Windows/FullscreenWindow.cs b/GlazeWM.Domain/Windows/FullscreenWindow.csdeleted file mode 100644index 522cfd08..00000000--- a/GlazeWM.Domain/Windows/FullscreenWindow.cs+++ /dev/null@@ -1,16 +0,0 @@-using System;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows-{- public sealed class FullscreenWindow : Window- {- public FullscreenWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta- ) : base(handle, floatingPlacement, borderDelta)- {- }- }-}diff --git a/GlazeWM.Domain/Windows/MaximizedWindow.cs b/GlazeWM.Domain/Windows/MaximizedWindow.csdeleted file mode 100644index 4e5532eb..00000000--- a/GlazeWM.Domain/Windows/MaximizedWindow.cs+++ /dev/null@@ -1,20 +0,0 @@-using System;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows-{- public sealed class MaximizedWindow : Window- {- public WindowType PreviousState;-- public MaximizedWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta,- WindowType previousState- ) : base(handle, floatingPlacement, borderDelta)- {- PreviousState = previousState;- }- }-}diff --git a/GlazeWM.Domain/Windows/MinimizedWindow.cs b/GlazeWM.Domain/Windows/MinimizedWindow.csdeleted file mode 100644index ae6c52d7..00000000--- a/GlazeWM.Domain/Windows/MinimizedWindow.cs+++ /dev/null@@ -1,20 +0,0 @@-using System;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows-{- public sealed class MinimizedWindow : Window- {- public WindowType PreviousState;-- public MinimizedWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta,- WindowType previousState- ) : base(handle, floatingPlacement, borderDelta)- {- PreviousState = previousState;- }- }-}diff --git a/GlazeWM.Domain/Windows/ResizeParsingService.cs b/GlazeWM.Domain/Windows/ResizeParsingService.csdeleted file mode 100644index e0c45bff..00000000--- a/GlazeWM.Domain/Windows/ResizeParsingService.cs+++ /dev/null@@ -1,55 +0,0 @@-using System;-using System.Globalization;-using System.Linq;-using System.Text.RegularExpressions;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure.Exceptions;--namespace GlazeWM.Domain.Windows-{- public class ResizeParsingService- {- public static double ParseResizePercentage(- Container containerToResize,- ResizeDimension dimensionToResize,- string resizeAmount)- {- try- {- var matchedResizeAmount = new Regex("(.*)(%|ppt|px)").Match(resizeAmount);- var amount = matchedResizeAmount.Groups[1].Value;- var unit = matchedResizeAmount.Groups[2].Value;- var floatAmount = Convert.ToDouble(amount, CultureInfo.InvariantCulture);-- return unit switch- {- "%" => floatAmount / 100,- "ppt" => floatAmount / 100,- "px" => floatAmount * GetPixelScaleFactor(containerToResize, dimensionToResize),- _ => throw new ArgumentException(null, nameof(resizeAmount)),- };- }- catch- {- throw new FatalUserException($"Invalid resize amount {resizeAmount}.");- }- }-- private static double GetPixelScaleFactor(- Container containerToResize,- ResizeDimension dimensionToResize)- {- // Get available width/height that can be resized (ie. exclude inner gaps).- var resizableLength = containerToResize.SelfAndSiblingsOfType<IResizable>().Aggregate(- 1.0,- (sum, container) =>- dimensionToResize == ResizeDimension.Width- ? sum + container.Width- : sum + container.Height- );-- return 1.0 / resizableLength;- }- }-}diff --git a/GlazeWM.Domain/Windows/TilingWindow.cs b/GlazeWM.Domain/Windows/TilingWindow.csdeleted file mode 100644index d6be9da9..00000000--- a/GlazeWM.Domain/Windows/TilingWindow.cs+++ /dev/null@@ -1,38 +0,0 @@-using System;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Windows-{- public sealed class TilingWindow : Window, IResizable- {- public double SizePercentage { get; set; } = 1;-- private readonly ContainerService _containerService =- ServiceLocator.GetRequiredService<ContainerService>();-- public override int Width => _containerService.GetWidthOfResizableContainer(this);- public override int Height => _containerService.GetHeightOfResizableContainer(this);- public override int X => _containerService.GetXOfResizableContainer(this);- public override int Y => _containerService.GetYOfResizableContainer(this);-- public TilingWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta- ) : base(handle, floatingPlacement, borderDelta)- {- }-- public TilingWindow(- IntPtr handle,- Rect floatingPlacement,- RectDelta borderDelta,- double sizePercentage- ) : base(handle, floatingPlacement, borderDelta)- {- SizePercentage = sizePercentage;- }- }-}diff --git a/GlazeWM.Domain/Windows/Window.cs b/GlazeWM.Domain/Windows/Window.csdeleted file mode 100644index 8a4792d8..00000000--- a/GlazeWM.Domain/Windows/Window.cs+++ /dev/null@@ -1,73 +0,0 @@-using System;-using System.Diagnostics;-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Infrastructure.WindowsApi;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows-{- public abstract class Window : Container- {- /// <inheritdoc />- public override ContainerType Type { get; } = ContainerType.Window;-- public IntPtr Handle { get; }-- /// <summary>- /// Whether window is shown, hidden, or in an intermediary state.- /// </summary>- public DisplayState DisplayState { get; set; } = DisplayState.Shown;-- /// <summary>- /// The placement of the window when floating. Initialized with window's placement on launch- /// and updated on resize/move whilst floating.- /// </summary>- public Rect FloatingPlacement { get; set; }-- /// <summary>- /// The difference in window dimensions to adjust for invisible borders. This is typically 7px- /// on the left, right, and bottom edges. This needs to be adjusted for to draw a window with- /// exact dimensions.- /// </summary>- public RectDelta BorderDelta { get; set; } = new RectDelta(7, 0, 7, 7);-- /// <summary>- /// Whether adjustments need to be made because of DPI (eg. when moving between monitors).- /// </summary>- public bool HasPendingDpiAdjustment { get; set; }-- protected Window(IntPtr handle, Rect floatingPlacement, RectDelta borderDelta)- {- Handle = handle;- FloatingPlacement = floatingPlacement;- BorderDelta = borderDelta;- }-- public string ProcessName =>- WindowService.GetProcessOfHandle(Handle)?.ProcessName ?? string.Empty;-- public string ClassName => WindowService.GetClassNameOfHandle(Handle);-- public Rect Location => WindowService.GetLocationOfHandle(Handle);-- public string Title => WindowService.GetTitleOfHandle(Handle);-- public bool IsManageable => WindowService.IsHandleManageable(Handle);-- public WindowStyles WindowStyles => WindowService.GetWindowStyles(Handle);-- public WindowStylesEx WindowStylesEx => WindowService.GetWindowStylesEx(Handle);-- public bool HasWindowStyle(WindowStyles style)- {- return WindowService.HandleHasWindowStyle(Handle, style);- }-- public bool HasWindowExStyle(WindowStylesEx style)- {- return WindowService.HandleHasWindowExStyle(Handle, style);- }- }-}diff --git a/GlazeWM.Domain/Windows/WindowService.cs b/GlazeWM.Domain/Windows/WindowService.csdeleted file mode 100644index de5a311e..00000000--- a/GlazeWM.Domain/Windows/WindowService.cs+++ /dev/null@@ -1,283 +0,0 @@-using System;-using System.Collections.Generic;-using System.Diagnostics;-using System.Linq;-using System.Runtime.InteropServices;-using System.Text;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Workspaces;-using GlazeWM.Infrastructure.WindowsApi;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Domain.Windows-{- public class WindowService- {- /// <summary>- /// Window handles to appbars (application desktop toolbars). Positioning changes of appbars- /// can affect the working area of the parent monitor and requires windows to be redrawn.- /// </summary>- public List<IntPtr> AppBarHandles { get; set; } = new();-- /// <summary>- /// Window handles to ignored windows (ie. windows where 'ignore' command has been invoked).- /// </summary>- public List<IntPtr> IgnoredHandles { get; set; } = new();-- /// <summary>- /// Time since a previously focused window was unmanaged or minimized. Used to- /// decide whether to override incoming focus events.- /// </summary>- public Stopwatch UnmanagedOrMinimizedStopwatch { get; } = new();-- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;-- public WindowService(ContainerService containerService, MonitorService monitorService)- {- _containerService = containerService;- _monitorService = monitorService;- }-- /// <summary>- /// Get all windows by traversing down container tree.- /// </summary>- public IEnumerable<Window> GetWindows()- {- return _containerService.ContainerTree.Descendants.OfType<Window>();- }-- public Window GetWindowByHandle(IntPtr handle)- {- return GetWindows().FirstOrDefault(window => window.Handle == handle);- }-- /// <summary>- /// Get the id of the process that created the window.- /// </summary>- public static Process GetProcessOfHandle(IntPtr handle)- {- try- {- _ = GetWindowThreadProcessId(handle, out var processId);- return Process.GetProcessById((int)processId);- }- catch (Exception)- {- return null;- }- }-- /// <summary>- /// Get the class name of the specified window.- /// </summary>- public static string GetClassNameOfHandle(IntPtr handle)- {- // Class name is limited to 256 characters, so it's fine to use a fixed size buffer.- var buffer = new StringBuilder(256);- _ = GetClassName(handle, buffer, buffer.Capacity);- return buffer.ToString();- }-- /// <summary>- /// Get dimensions of the bounding rectangle of the specified window.- /// </summary>- public static Rect GetLocationOfHandle(IntPtr handle)- {- var rect = new Rect();- GetWindowRect(handle, ref rect);- return rect;- }-- /// <summary>- /// Get info about the placement of the specified window.- /// </summary>- public static WindowPlacement GetPlacementOfHandle(IntPtr handle)- {- var windowPlacement = new WindowPlacement();- GetWindowPlacement(handle, ref windowPlacement);- return windowPlacement;- }-- /// <summary>- /// Get title bar text of the specified window.- /// </summary>- public static string GetTitleOfHandle(IntPtr handle)- {- var titleLength = GetWindowTextLength(handle);-- if (titleLength == 0)- return string.Empty;-- var buffer = new StringBuilder(titleLength + 1);- _ = GetWindowText(handle, buffer, buffer.Capacity);- return buffer.ToString();- }-- public static List<IntPtr> GetAllWindowHandles()- {- var windowHandles = new List<IntPtr>();-- EnumWindows((IntPtr handle, int _) =>- {- windowHandles.Add(handle);- return true;- }, IntPtr.Zero);-- return windowHandles;- }-- public static WindowStylesEx GetWindowStylesEx(IntPtr handle)- {- return unchecked((WindowStylesEx)GetWindowLongPtr(handle, GWLEXSTYLE).ToInt64());- }-- public static WindowStyles GetWindowStyles(IntPtr handle)- {- return unchecked((WindowStyles)GetWindowLongPtr(handle, GWLSTYLE).ToInt64());- }-- public static bool HandleHasWindowStyle(IntPtr handle, WindowStyles style)- {- return (GetWindowStyles(handle) & style) != 0;- }-- public static bool HandleHasWindowExStyle(IntPtr handle, WindowStylesEx style)- {- return (GetWindowStylesEx(handle) & style) != 0;- }-- /// <summary>- /// Whether the given handle is cloaked. For some UWP apps, `WS_VISIBLE` will be true even if- /// the window isn't actually visible. The `DWMWA_CLOAKED` attribute is used to check whether- /// these apps are visible.- /// </summary>- public static bool IsHandleCloaked(IntPtr handle)- {- _ = DwmGetWindowAttribute(- handle,- DwmWindowAttribute.Cloaked,- out var isCloaked,- Marshal.SizeOf(typeof(bool))- );-- return isCloaked;- }-- /// <summary>- /// Whether the given handle is actually visible.- /// </summary>- public static bool IsHandleVisible(IntPtr handle)- {- return IsWindowVisible(handle) && !IsHandleCloaked(handle);- }-- public static bool IsHandleManageable(IntPtr handle)- {- if (GetProcessOfHandle(handle) is not null)- {- var processName = GetProcessOfHandle(handle)?.ProcessName;- var title = GetTitleOfHandle(handle);-- // TODO: Temporary fix for managing Flow Launcher until a force manage command is added.- if (processName == "Flow.Launcher" && title == "Flow.Launcher")- return true;- }-- // Ignore windows that are hidden.- if (!IsHandleVisible(handle))- return false;-- // Ensure window is top-level (ie. not a child window). Ignore windows that cannot be focused- // or if they're unavailable in task switcher (alt+tab menu).- var isApplicationWindow = !HandleHasWindowStyle(handle, WindowStyles.Child)- && !HandleHasWindowExStyle(handle, WindowStylesEx.NoActivate | WindowStylesEx.ToolWindow);-- if (!isApplicationWindow)- return false;-- /// Some applications spawn top-level windows for menus that should be ignored. This includes- /// the autocomplete popup in Notepad++ and title bar menu in Keepass. Although not- /// foolproof, these can typically be identified by having an owner window and no title bar.- var isMenuWindow = GetWindow(handle, GW.Owner) != IntPtr.Zero- && !HandleHasWindowStyle(handle, WindowStyles.Capion);-- return !isMenuWindow;- }-- /// <summary>- /// Whether the given handle is an appbar window (application desktop toolbar).- /// </summary>- public bool IsHandleAppBar(IntPtr handle)- {- // Appbar window has to be visible.- if (!IsHandleVisible(handle))- return false;-- var monitor = _monitorService.GetMonitorFromHandleLocation(handle);- var location = GetLocationOfHandle(handle);-- var isFullWidth = location.Width == monitor.Width;- var isFullHeight = location.Height == monitor.Height;-- if (!(isFullWidth || isFullHeight))- return false;-- // Whether window is below or above the monitor's working area.- var isHorizontalBar = (isFullWidth && location.Y + location.Height <= monitor.Y)- || (isFullWidth && location.Y >= monitor.Y + monitor.Height);-- // Whether window is to the left or right of the monitor's working area.- var isVerticalBar = (isFullHeight && location.X + location.Width <= monitor.X)- || (isFullHeight && location.X >= monitor.X + monitor.Width);-- return isHorizontalBar || isVerticalBar;- }-- public static WindowType GetWindowType(Window window)- {- return window switch- {- TilingWindow => WindowType.Tiling,- FloatingWindow => WindowType.Floating,- MinimizedWindow => WindowType.Minimized,- MaximizedWindow => WindowType.Maximized,- FullscreenWindow => WindowType.Fullscreen,- _ => throw new ArgumentException(null, nameof(window)),- };- }-- /// <summary>- /// Get container to focus after the given window is unmanaged, minimized, or moved to another- /// workspace.- /// </summary>- public static Container GetFocusTargetAfterRemoval(Window removedWindow)- {- var parentWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(removedWindow);-- // Get descendant focus order excluding the removed container.- var descendantFocusOrder = parentWorkspace.DescendantFocusOrder.Where(- descendant => descendant != removedWindow- );-- // Get focus target that matches the removed window type (only for tiling/floating windows).- var focusTargetOfType = descendantFocusOrder.FirstOrDefault(- (descendant) =>- (removedWindow is FloatingWindow && descendant is FloatingWindow) ||- (removedWindow is TilingWindow && descendant is TilingWindow)- );-- if (focusTargetOfType is not null)- return focusTargetOfType;-- var nonMinimizedFocusTarget = descendantFocusOrder.FirstOrDefault(- (descendant) => descendant is not MinimizedWindow- );-- return nonMinimizedFocusTarget ??- descendantFocusOrder.FirstOrDefault() ??- parentWorkspace;- }- }-}diff --git a/GlazeWM.Domain/Windows/WindowType.cs b/GlazeWM.Domain/Windows/WindowType.csdeleted file mode 100644index 1823abe9..00000000--- a/GlazeWM.Domain/Windows/WindowType.cs+++ /dev/null@@ -1,11 +0,0 @@-namespace GlazeWM.Domain.Windows-{- public enum WindowType- {- Tiling,- Floating,- Minimized,- Maximized,- Fullscreen,- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/ActivateWorkspaceHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/ActivateWorkspaceHandler.csdeleted file mode 100644index c90a4bdb..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/ActivateWorkspaceHandler.cs+++ /dev/null@@ -1,36 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Domain.Workspaces.Events;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class ActivateWorkspaceHandler : ICommandHandler<ActivateWorkspaceCommand>- {- private readonly Bus _bus;-- public ActivateWorkspaceHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(ActivateWorkspaceCommand command)- {- var workspaceName = command.WorkspaceName;- var targetMonitor = command.TargetMonitor;-- var tilingDirection = targetMonitor.Height > targetMonitor.Width- ? TilingDirection.Vertical- : TilingDirection.Horizontal;-- var newWorkspace = new Workspace(workspaceName, tilingDirection);-- // Attach the created workspace to the specified monitor.- _bus.Invoke(new AttachContainerCommand(newWorkspace, targetMonitor));- _bus.Emit(new WorkspaceActivatedEvent(newWorkspace));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/DeactivateWorkspaceHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/DeactivateWorkspaceHandler.csdeleted file mode 100644index d2c67459..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/DeactivateWorkspaceHandler.cs+++ /dev/null@@ -1,27 +0,0 @@-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Domain.Workspaces.Events;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class DeactivateWorkspaceHandler : ICommandHandler<DeactivateWorkspaceCommand>- {- public Bus _bus { get; }-- public DeactivateWorkspaceHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(DeactivateWorkspaceCommand command)- {- var workspace = command.Workspace;-- _bus.Invoke(new DetachContainerCommand(workspace));- _bus.Emit(new WorkspaceDeactivatedEvent(workspace.Id, workspace.Name));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceHandler.csdeleted file mode 100644index acf03fb9..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceHandler.cs+++ /dev/null@@ -1,108 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Containers.Events;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class FocusWorkspaceHandler : ICommandHandler<FocusWorkspaceCommand>- {- private readonly Bus _bus;- private readonly ILogger<FocusWorkspaceHandler> _logger;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;- private readonly UserConfigService _userConfigService;- private readonly WorkspaceService _workspaceService;-- public FocusWorkspaceHandler(- Bus bus,- ILogger<FocusWorkspaceHandler> logger,- ContainerService containerService,- MonitorService monitorService,- UserConfigService userConfigService,- WorkspaceService workspaceService)- {- _bus = bus;- _logger = logger;- _containerService = containerService;- _monitorService = monitorService;- _userConfigService = userConfigService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(FocusWorkspaceCommand command)- {- var workspaceName = "";- var focusedWorkspace = _workspaceService.GetFocusedWorkspace();- if (focusedWorkspace.Name == command.WorkspaceName)- {- if (!_userConfigService.GeneralConfig.ToggleWorkspaceOnRefocus || _workspaceService.MostRecentWorkspace == null)- return CommandResponse.Ok;- workspaceName = _workspaceService.MostRecentWorkspace.Name;- }- else- {- workspaceName = command.WorkspaceName;- }-- // Get workspace to focus. If it's currently inactive, then activate it.- var workspaceToFocus = _workspaceService.GetActiveWorkspaceByName(workspaceName)- ?? ActivateWorkspace(workspaceName);-- var displayedWorkspace = (workspaceToFocus.Parent as Monitor).DisplayedWorkspace;-- // Save currently focused workspace as recent for command "recent"- _workspaceService.MostRecentWorkspace = focusedWorkspace;-- _logger.LogDebug("WorkspaceToFocus: {WorkspaceToFocusName}", workspaceToFocus.Name);-- // Set focus to the last focused window in workspace. If the workspace has no descendant- // windows, then set focus to the workspace itself.- var containerToFocus = workspaceToFocus.HasChildren()- ? workspaceToFocus.LastFocusedDescendant- : workspaceToFocus;-- _bus.Invoke(new SetFocusedDescendantCommand(containerToFocus));- _containerService.HasPendingFocusSync = true;-- // Display the workspace to switch focus to.- _containerService.ContainersToRedraw.Add(displayedWorkspace);- _containerService.ContainersToRedraw.Add(workspaceToFocus);-- // Get empty workspace to destroy (if any are found). Cannot destroy empty workspaces if- // they're the only workspace on the monitor or are pending focus.- var workspaceToDestroy = _workspaceService- .GetActiveWorkspaces()- .FirstOrDefault(- (workspace) =>- !workspace.KeepAlive && !workspace.HasChildren() && !workspace.IsDisplayed- );-- if (workspaceToDestroy != null)- _bus.Invoke(new DeactivateWorkspaceCommand(workspaceToDestroy));-- return CommandResponse.Ok;- }-- /// <summary>- /// Activate a given workspace on the currently focused monitor.- /// </summary>- private Workspace ActivateWorkspace(string workspaceName)- {- // Get the monitor that the workspace should be bound to (if it exists).- var workspaceConfig = _userConfigService.GetWorkspaceConfigByName(workspaceName);- var boundMonitor =- _monitorService.GetMonitorByDeviceName(workspaceConfig.BindToMonitor);-- var targetMonitor = boundMonitor ?? _monitorService.GetFocusedMonitor();- _bus.Invoke(new ActivateWorkspaceCommand(workspaceName, targetMonitor));-- return _workspaceService.GetActiveWorkspaceByName(workspaceName);- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceRecentHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceRecentHandler.csdeleted file mode 100644index 37da5177..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceRecentHandler.cs+++ /dev/null@@ -1,47 +0,0 @@-using System.Linq;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class FocusWorkspaceRecentHandler : ICommandHandler<FocusWorkspaceRecentCommand>- {- private readonly Bus _bus;- private readonly UserConfigService _userConfigService;- private readonly WorkspaceService _workspaceService;-- public FocusWorkspaceRecentHandler(- Bus bus,- UserConfigService userConfigService,- WorkspaceService workspaceService)- {- _bus = bus;- _userConfigService = userConfigService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(FocusWorkspaceRecentCommand command)- {- var mostRecentWorkspace = _workspaceService.MostRecentWorkspace;- var currentWorkspace = _workspaceService.GetFocusedWorkspace();- var workspaceConfigs = _userConfigService.WorkspaceConfigs;-- if (mostRecentWorkspace != null)- {- // Validate that workspace are still available- if (workspaceConfigs.Any(workspace => workspace.Name == mostRecentWorkspace.Name))- {- // Focus workspace- _bus.Invoke(new FocusWorkspaceCommand(mostRecentWorkspace.Name));- // Update most recent workspace- _workspaceService.MostRecentWorkspace = currentWorkspace;-- return CommandResponse.Ok;- }- }-- return CommandResponse.Fail;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceSequenceHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceSequenceHandler.csdeleted file mode 100644index 30bf9ead..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/FocusWorkspaceSequenceHandler.cs+++ /dev/null@@ -1,61 +0,0 @@-using System;-using System.Linq;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class FocusWorkspaceSequenceHandler : ICommandHandler<FocusWorkspaceSequenceCommand>- {- private readonly Bus _bus;- private readonly UserConfigService _userConfigService;- private readonly WorkspaceService _workspaceService;-- public FocusWorkspaceSequenceHandler(- Bus bus,- UserConfigService userConfigService,- WorkspaceService workspaceService)- {- _bus = bus;- _userConfigService = userConfigService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(FocusWorkspaceSequenceCommand command)- {- var direction = command.Direction;- var workspacesConfigs = _userConfigService.WorkspaceConfigs;-- // Get active workspaces in order of their config index.- var activeWorkspaces = _workspaceService.GetActiveWorkspaces();- var sortedWorkspaces = activeWorkspaces- .OrderBy((workspace) =>- workspacesConfigs.FindIndex((config) => config.Name == workspace.Name)- )- .ToList();-- // Get config index of the currently focused workspace.- var focusedWorkspace = _workspaceService.GetFocusedWorkspace();- var configIndex = sortedWorkspaces.IndexOf(focusedWorkspace);-- // Get index in `sortedWorkspaces` of target workspace to focus. Wrap around to start if- // there is no previous/next workspace.- var indexToFocus = direction switch- {- Sequence.Previous => configIndex == 0 ? sortedWorkspaces.Count - 1 : configIndex - 1,- Sequence.Next => configIndex == sortedWorkspaces.Count - 1 ? 0 : configIndex + 1,- _ => throw new ArgumentException(nameof(direction)),- };-- var workspaceToFocus = sortedWorkspaces.ElementAtOrDefault(indexToFocus);-- // Set focus to the previous/next workspace if found.- if (workspaceToFocus is not null && workspaceToFocus != focusedWorkspace)- _bus.Invoke(new FocusWorkspaceCommand(workspaceToFocus.Name));-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWindowToWorkspaceHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWindowToWorkspaceHandler.csdeleted file mode 100644index 4c0e923e..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWindowToWorkspaceHandler.cs+++ /dev/null@@ -1,116 +0,0 @@-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class MoveWindowToWorkspaceHandler : ICommandHandler<MoveWindowToWorkspaceCommand>- {- private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly MonitorService _monitorService;- private readonly UserConfigService _userConfigService;- private readonly WorkspaceService _workspaceService;-- public MoveWindowToWorkspaceHandler(- Bus bus,- ContainerService containerService,- MonitorService monitorService,- UserConfigService userConfigService,- WorkspaceService workspaceService)- {- _bus = bus;- _containerService = containerService;- _monitorService = monitorService;- _userConfigService = userConfigService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(MoveWindowToWorkspaceCommand command)- {- var windowToMove = command.WindowToMove;- var workspaceName = command.WorkspaceName;-- var currentWorkspace = WorkspaceService.GetWorkspaceFromChildContainer(windowToMove);- var targetWorkspace = _workspaceService.GetActiveWorkspaceByName(workspaceName)- ?? ActivateWorkspace(workspaceName, windowToMove);-- if (currentWorkspace == targetWorkspace)- return CommandResponse.Ok;-- // Since target workspace could be on a different monitor, adjustments might need to be made- // because of DPI.- if (MonitorService.HasDpiDifference(currentWorkspace, targetWorkspace))- windowToMove.HasPendingDpiAdjustment = true;-- // Update floating placement if the window has to cross monitors.- if (targetWorkspace.Parent != currentWorkspace.Parent)- windowToMove.FloatingPlacement =- windowToMove.FloatingPlacement.TranslateToCenter(targetWorkspace.ToRect());-- var focusTarget = WindowService.GetFocusTargetAfterRemoval(windowToMove);-- // Since the workspace that gets displayed is the last focused child, focus needs to be- // reassigned to the displayed workspace.- var targetMonitor = targetWorkspace.Parent as Monitor;- var focusResetTarget = targetWorkspace.IsDisplayed ? null : targetMonitor.LastFocusedDescendant;-- if (windowToMove is TilingWindow)- MoveTilingWindowToWorkspace(windowToMove as TilingWindow, targetWorkspace);- else- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, targetWorkspace));-- if (focusResetTarget is not null)- _bus.Invoke(new SetFocusedDescendantCommand(focusResetTarget));-- // Reassign focus to descendant within the current workspace. Need to call- // `SetFocusedDescendantCommand` for when commands like `FocusWorkspaceCommand` are called- // immediately afterwards and they should behave as if `focusTarget` is the focused- // descendant.- _bus.Invoke(new SetFocusedDescendantCommand(focusTarget));- _containerService.HasPendingFocusSync = true;-- _containerService.ContainersToRedraw.Add(currentWorkspace);- _containerService.ContainersToRedraw.Add(windowToMove);-- return CommandResponse.Ok;- }-- private Workspace ActivateWorkspace(string workspaceName, Window windowToMove)- {- var currentMonitor = MonitorService.GetMonitorFromChildContainer(windowToMove);-- // Get the monitor that the workspace should be bound to (if it exists).- var workspaceConfig = _userConfigService.GetWorkspaceConfigByName(workspaceName);- var boundMonitor =- _monitorService.GetMonitorByDeviceName(workspaceConfig.BindToMonitor);-- // Activate the workspace on the target monitor.- var targetMonitor = boundMonitor ?? currentMonitor;- _bus.Invoke(new ActivateWorkspaceCommand(workspaceName, targetMonitor));-- return _workspaceService.GetActiveWorkspaceByName(workspaceName);- }-- private void MoveTilingWindowToWorkspace(TilingWindow windowToMove, Workspace targetWorkspace)- {- var insertionTarget = targetWorkspace.LastFocusedDescendantOfType<IResizable>();-- // Insert the window into the target workspace.- if (insertionTarget == null)- _bus.Invoke(new MoveContainerWithinTreeCommand(windowToMove, targetWorkspace));- else- _bus.Invoke(- new MoveContainerWithinTreeCommand(- windowToMove,- insertionTarget.Parent,- insertionTarget.Index + 1- )- );- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWorkspaceInDirectionHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWorkspaceInDirectionHandler.csdeleted file mode 100644index 3b37ead9..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/MoveWorkspaceInDirectionHandler.cs+++ /dev/null@@ -1,83 +0,0 @@-using System.Linq;-using GlazeWM.Domain.Containers.Commands;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Windows;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Domain.Workspaces.Events;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Exceptions;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class MoveWorkspaceInDirectionHandler :- ICommandHandler<MoveWorkspaceInDirectionCommand>- {- private readonly Bus _bus;- private readonly MonitorService _monitorService;- private readonly WorkspaceService _workspaceService;-- public MoveWorkspaceInDirectionHandler(- Bus bus,- MonitorService monitorService,- WorkspaceService workspaceService)- {- _bus = bus;- _monitorService = monitorService;- _workspaceService = workspaceService;- }-- public CommandResponse Handle(MoveWorkspaceInDirectionCommand command)- {- var direction = command.Direction;-- // Get focused workspace + monitor.- var focusedWorkspace = _workspaceService.GetFocusedWorkspace();- var focusedMonitor = MonitorService.GetMonitorFromChildContainer(focusedWorkspace);-- // Get monitor in the given direction from the focused workspace.- var targetMonitor = _monitorService.GetMonitorInDirection(- direction,- focusedMonitor- );-- if (targetMonitor is null)- return CommandResponse.Ok;-- // Move workspace to target monitor.- _bus.Invoke(- new MoveContainerWithinTreeCommand(focusedWorkspace, targetMonitor)- );-- // Update floating placement since the windows have to cross monitors.- foreach (var window in focusedWorkspace.Descendants.OfType<Window>())- {- window.FloatingPlacement = window.FloatingPlacement.TranslateToCenter(- targetMonitor.DisplayedWorkspace.ToRect()- );- }-- // Prevent original monitor from having no workspaces.- if (focusedMonitor.Children.Count == 0)- ActivateWorkspaceOnMonitor(focusedMonitor);-- // Update workspaces displayed in bar window.- // TODO: Consider creating separate event `WorkspaceMovedEvent`.- _bus.Emit(new WorkspaceActivatedEvent(focusedWorkspace));-- return CommandResponse.Ok;- }-- private void ActivateWorkspaceOnMonitor(Monitor monitor)- {- // Get name of first workspace that is not active for that specified monitor or any.- var inactiveWorkspaceConfig =- _workspaceService.GetWorkspaceConfigToActivate(monitor);-- if (inactiveWorkspaceConfig is null)- throw new FatalUserException("At least 1 workspace is required per monitor.");-- // Assign the workspace to the empty monitor.- _bus.Invoke(new ActivateWorkspaceCommand(inactiveWorkspaceConfig.Name, monitor));- }- }-}diff --git a/GlazeWM.Domain/Workspaces/CommandHandlers/UpdateWorkspacesFromConfigHandler.cs b/GlazeWM.Domain/Workspaces/CommandHandlers/UpdateWorkspacesFromConfigHandler.csdeleted file mode 100644index 9490df0b..00000000--- a/GlazeWM.Domain/Workspaces/CommandHandlers/UpdateWorkspacesFromConfigHandler.cs+++ /dev/null@@ -1,43 +0,0 @@-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.Workspaces.Commands;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Exceptions;--namespace GlazeWM.Domain.Workspaces.CommandHandlers-{- internal sealed class UpdateWorkspacesFromConfigHandler :- ICommandHandler<UpdateWorkspacesFromConfigCommand>- {- private readonly WorkspaceService _workspaceService;-- public UpdateWorkspacesFromConfigHandler(WorkspaceService workspaceService)- {- _workspaceService = workspaceService;- }-- public CommandResponse Handle(UpdateWorkspacesFromConfigCommand command)- {- var workspaceConfigs = command.WorkspaceConfigs;-- foreach (var workspace in _workspaceService.GetActiveWorkspaces())- {- var workspaceConfig = workspaceConfigs.Find(config => config.Name == workspace.Name);-- if (workspaceConfig is null)- {- var monitor = workspace.Parent as Monitor;- var inactiveWorkspaceConfig = _workspaceService.GetWorkspaceConfigToActivate(monitor);-- if (inactiveWorkspaceConfig is null)- throw new FatalUserException("At least 1 workspace is required per monitor.");-- workspace.Name = inactiveWorkspaceConfig.Name;- }-- // TODO: Update `DisplayName` and `KeepAlive` once they are changed to properties.- }-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/ActivateWorkspaceCommand.cs b/GlazeWM.Domain/Workspaces/Commands/ActivateWorkspaceCommand.csdeleted file mode 100644index 21d02822..00000000--- a/GlazeWM.Domain/Workspaces/Commands/ActivateWorkspaceCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using GlazeWM.Domain.Monitors;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- internal sealed class ActivateWorkspaceCommand : Command- {- public string WorkspaceName { get; }- public Monitor TargetMonitor { get; }-- public ActivateWorkspaceCommand(string workspaceName, Monitor targetMonitor)- {- WorkspaceName = workspaceName;- TargetMonitor = targetMonitor;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/DeactivateWorkspaceCommand.cs b/GlazeWM.Domain/Workspaces/Commands/DeactivateWorkspaceCommand.csdeleted file mode 100644index 81b05256..00000000--- a/GlazeWM.Domain/Workspaces/Commands/DeactivateWorkspaceCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- internal sealed class DeactivateWorkspaceCommand : Command- {- public Workspace Workspace { get; }-- public DeactivateWorkspaceCommand(Workspace workspace)- {- Workspace = workspace;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceCommand.cs b/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceCommand.csdeleted file mode 100644index 88a31a97..00000000--- a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- public class FocusWorkspaceCommand : Command- {- public string WorkspaceName { get; }-- public FocusWorkspaceCommand(string workspaceName)- {- WorkspaceName = workspaceName;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceRecentCommand.cs b/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceRecentCommand.csdeleted file mode 100644index dce6c575..00000000--- a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceRecentCommand.cs+++ /dev/null@@ -1,6 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- public class FocusWorkspaceRecentCommand : Command { }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceSequenceCommand.cs b/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceSequenceCommand.csdeleted file mode 100644index f0936462..00000000--- a/GlazeWM.Domain/Workspaces/Commands/FocusWorkspaceSequenceCommand.cs+++ /dev/null@@ -1,15 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- public class FocusWorkspaceSequenceCommand : Command- {- public Sequence Direction { get; }-- public FocusWorkspaceSequenceCommand(Sequence direction)- {- Direction = direction;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/MoveWindowToWorkspaceCommand.cs b/GlazeWM.Domain/Workspaces/Commands/MoveWindowToWorkspaceCommand.csdeleted file mode 100644index 1b2f6f14..00000000--- a/GlazeWM.Domain/Workspaces/Commands/MoveWindowToWorkspaceCommand.cs+++ /dev/null@@ -1,17 +0,0 @@-using GlazeWM.Domain.Windows;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- internal sealed class MoveWindowToWorkspaceCommand : Command- {- public Window WindowToMove { get; }- public string WorkspaceName { get; }-- public MoveWindowToWorkspaceCommand(Window windowToMove, string workspaceName)- {- WindowToMove = windowToMove;- WorkspaceName = workspaceName;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/MoveWorkspaceInDirectionCommand.cs b/GlazeWM.Domain/Workspaces/Commands/MoveWorkspaceInDirectionCommand.csdeleted file mode 100644index cadb3c70..00000000--- a/GlazeWM.Domain/Workspaces/Commands/MoveWorkspaceInDirectionCommand.cs+++ /dev/null@@ -1,16 +0,0 @@-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- internal sealed class MoveWorkspaceInDirectionCommand : Command- {- // TODO: Add argument for workspace to move instead of assuming the focused workspace.- public Direction Direction { get; }-- public MoveWorkspaceInDirectionCommand(Direction direction)- {- Direction = direction;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Commands/UpdateWorkspacesFromConfigCommand.cs b/GlazeWM.Domain/Workspaces/Commands/UpdateWorkspacesFromConfigCommand.csdeleted file mode 100644index 78f24c55..00000000--- a/GlazeWM.Domain/Workspaces/Commands/UpdateWorkspacesFromConfigCommand.cs+++ /dev/null@@ -1,16 +0,0 @@-using System.Collections.Generic;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Commands-{- internal sealed class UpdateWorkspacesFromConfigCommand : Command- {- public List<WorkspaceConfig> WorkspaceConfigs { get; }-- public UpdateWorkspacesFromConfigCommand(List<WorkspaceConfig> workspaceConfigs)- {- WorkspaceConfigs = workspaceConfigs;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/Events/WorkspaceActivatedEvent.cs b/GlazeWM.Domain/Workspaces/Events/WorkspaceActivatedEvent.csdeleted file mode 100644index df070876..00000000--- a/GlazeWM.Domain/Workspaces/Events/WorkspaceActivatedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Events-{- public record WorkspaceActivatedEvent(Workspace ActivatedWorkspace)- : Event(DomainEvent.WorkspaceActivated);-}diff --git a/GlazeWM.Domain/Workspaces/Events/WorkspaceDeactivatedEvent.cs b/GlazeWM.Domain/Workspaces/Events/WorkspaceDeactivatedEvent.csdeleted file mode 100644index 20306e26..00000000--- a/GlazeWM.Domain/Workspaces/Events/WorkspaceDeactivatedEvent.cs+++ /dev/null@@ -1,9 +0,0 @@-using System;-using GlazeWM.Domain.Common;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Domain.Workspaces.Events-{- public record WorkspaceDeactivatedEvent(Guid DeactivatedId, string DeactivatedName)- : Event(DomainEvent.WorkspaceDeactivated);-}diff --git a/GlazeWM.Domain/Workspaces/Workspace.cs b/GlazeWM.Domain/Workspaces/Workspace.csdeleted file mode 100644index bff0cdea..00000000--- a/GlazeWM.Domain/Workspaces/Workspace.cs+++ /dev/null@@ -1,102 +0,0 @@-using System;-using GlazeWM.Domain.Common;-using GlazeWM.Domain.Common.Enums;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;-using GlazeWM.Infrastructure;-using GlazeWM.Infrastructure.Utils;-using GlazeWM.Infrastructure.WindowsApi;--namespace GlazeWM.Domain.Workspaces-{- public sealed class Workspace : SplitContainer- {- /// <inheritdoc />- public override ContainerType Type { get; } = ContainerType.Workspace;-- public string Name { get; set; }-- private readonly UserConfigService _userConfigService =- ServiceLocator.GetRequiredService<UserConfigService>();-- private readonly WorkspaceService _workspaceService =- ServiceLocator.GetRequiredService<WorkspaceService>();-- public string DisplayName =>- _userConfigService.GetWorkspaceConfigByName(Name).DisplayName ?? Name;-- public bool KeepAlive =>- _userConfigService.GetWorkspaceConfigByName(Name).KeepAlive;-- /// <summary>- /// Get height of bar after it's been automatically adjusted by DPI scaling.- /// </summary>- private int _logicalBarHeight- {- get- {- var barHeight = UnitsHelper.TrimUnits(_userConfigService.GetBarConfigForMonitor(Parent as Monitor).Height);- return Convert.ToInt32(barHeight * (Parent as Monitor).ScaleFactor);- }- }-- private int _yOffset- {- get- {- var barPosition = _userConfigService.GetBarConfigForMonitor(Parent as Monitor).Position;- return barPosition == BarPosition.Top ? _logicalBarHeight : 0;- }- }-- private RectDelta _outerGaps => CommandParsingService.ShorthandToRectDelta(_userConfigService.GapsConfig.OuterGap);-- private BarConfig barForMonitor => _userConfigService.GetBarConfigForMonitor(Parent as Monitor);- private int floatBarOffsetY => UnitsHelper.TrimUnits(barForMonitor.OffsetY);-- public override int Height- {- get- {- if (!_userConfigService.GetBarConfigForMonitor(Parent as Monitor).Enabled)- {- return Parent.Height - _outerGaps.Top - _outerGaps.Bottom;- }-- return Parent.Height - _outerGaps.Top - _outerGaps.Bottom - (barForMonitor.Position == BarPosition.Top ? floatBarOffsetY : -floatBarOffsetY) - _logicalBarHeight;- }- }-- public override int Width => Parent.Width - _outerGaps.Left - _outerGaps.Right;- public override int X => Parent.X + _outerGaps.Left;- public override int Y- {- get- {- if (!_userConfigService.GetBarConfigForMonitor(Parent as Monitor).Enabled || barForMonitor.Position == BarPosition.Bottom)- {- return Parent.Y + _outerGaps.Top;- }-- return Parent.Y + _outerGaps.Top + _yOffset + floatBarOffsetY;- }- }-- /// <summary>- /// Whether the workspace itself or a descendant container has focus.- /// </summary>- public bool HasFocus => _workspaceService.GetFocusedWorkspace() == this;-- /// <summary>- /// Whether the workspace is currently displayed by the parent monitor.- /// </summary>- public bool IsDisplayed => (Parent as Monitor)?.DisplayedWorkspace == this;-- public Workspace(string name, TilingDirection tilingDirection)- {- Name = name;- TilingDirection = tilingDirection;- }- }-}diff --git a/GlazeWM.Domain/Workspaces/WorkspaceService.cs b/GlazeWM.Domain/Workspaces/WorkspaceService.csdeleted file mode 100644index 27aec95f..00000000--- a/GlazeWM.Domain/Workspaces/WorkspaceService.cs+++ /dev/null@@ -1,71 +0,0 @@-using System.Collections.Generic;-using System.Linq;-using GlazeWM.Domain.Containers;-using GlazeWM.Domain.Monitors;-using GlazeWM.Domain.UserConfigs;--namespace GlazeWM.Domain.Workspaces-{- public class WorkspaceService- {- private readonly ContainerService _containerService;- private readonly UserConfigService _userConfigService;-- public Workspace MostRecentWorkspace { get; set; }-- public WorkspaceService(ContainerService containerService, UserConfigService userConfigService)- {- _containerService = containerService;- _userConfigService = userConfigService;- }-- /// <summary>- /// Get active workspaces by iterating over the 2nd level of container tree.- /// </summary>- public IEnumerable<Workspace> GetActiveWorkspaces()- {- return _containerService.ContainerTree.Children- .SelectMany(monitor => monitor.Children)- .Cast<Workspace>();- }-- public Workspace GetActiveWorkspaceByName(string name)- {- return GetActiveWorkspaces().FirstOrDefault(workspace => workspace.Name == name);- }-- public IEnumerable<WorkspaceConfig> GetInactiveWorkspaceConfigs()- {- var activeWorkspaces = GetActiveWorkspaces();-- return _userConfigService.WorkspaceConfigs.Where(- (config) => !activeWorkspaces.Any((workspace) => workspace.Name == config.Name)- );- }-- public WorkspaceConfig GetWorkspaceConfigToActivate(Monitor monitor)- {- var inactiveWorkspaceConfigs = GetInactiveWorkspaceConfigs();- var boundWorkspaceConfig = inactiveWorkspaceConfigs- .FirstOrDefault(config => config.BindToMonitor == monitor.DeviceName);-- if (boundWorkspaceConfig is not null)- return boundWorkspaceConfig;-- var unreservedWorkspaceConfig = inactiveWorkspaceConfigs- .FirstOrDefault(config => string.IsNullOrWhiteSpace(config.BindToMonitor));-- return unreservedWorkspaceConfig ?? inactiveWorkspaceConfigs.ElementAtOrDefault(0);- }-- public static Workspace GetWorkspaceFromChildContainer(Container container)- {- return container.SelfAndAncestors.OfType<Workspace>().FirstOrDefault();- }-- public Workspace GetFocusedWorkspace()- {- return GetWorkspaceFromChildContainer(_containerService.FocusedContainer);- }- }-}diff --git a/GlazeWM.Infrastructure/Bussing/Bus.cs b/GlazeWM.Infrastructure/Bussing/Bus.csdeleted file mode 100644index 46eba713..00000000--- a/GlazeWM.Infrastructure/Bussing/Bus.cs+++ /dev/null@@ -1,104 +0,0 @@-using System;-using System.Collections.Generic;-using System.Reactive.Subjects;-using System.Threading.Tasks;-using GlazeWM.Infrastructure.Common.Commands;-using Microsoft.Extensions.Logging;--namespace GlazeWM.Infrastructure.Bussing-{- /// <summary>- /// Bus facilitates communication to command and event handlers.- /// </summary>- public sealed class Bus- {- public readonly Subject<Event> Events = new();- public readonly Queue<Command> CommandHistory = new();- public readonly object LockObj = new();- private readonly ILogger<Bus> _logger;-- public Bus(ILogger<Bus> logger)- {- _logger = logger;- }-- /// <summary>- /// Sends command to appropriate command handler.- /// </summary>- public CommandResponse Invoke<T>(T command) where T : Command- {- lock (LockObj)- {- _logger.LogDebug("Command {CommandName} invoked.", command.Name);-- CommandHistory.Enqueue(command);-- // Maintain a history of the last 15 command invocations for debugging.- if (CommandHistory.Count > 15)- CommandHistory.Dequeue();-- // Create a `Type` object representing the constructed `ICommandHandler` generic.- var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());-- var handlerInstance = ServiceLocator.GetRequiredService(handlerType)- as ICommandHandler<T>;-- return handlerInstance.Handle(command);- }- }-- public Task<CommandResponse> InvokeAsync<T>(T command) where T : Command- {- return Task.Run(() =>- {- try- {- return Invoke(command);- }- catch (Exception e)- {- Invoke(new HandleFatalExceptionCommand(e));- throw;- }- });- }-- /// <summary>- /// Sends event to appropriate event handlers.- /// </summary>- public void Emit<T>(T @event) where T : Event- {- lock (LockObj)- {- // Create a `Type` object representing the constructed `IEventHandler` generic.- var handlerType = typeof(IEventHandler<>).MakeGenericType(@event.GetType());-- var handlerInstances = ServiceLocator.GetServices(handlerType)- as IEnumerable<IEventHandler<T>>;-- foreach (var handler in handlerInstances)- {- handler.Handle(@event);- }-- // Emit event through subject.- Events.OnNext(@event);- }- }-- public Task EmitAsync<T>(T @event) where T : Event- {- return Task.Run(() =>- {- try- {- Emit(@event);- }- catch (Exception e)- {- Invoke(new HandleFatalExceptionCommand(e));- }- });- }- }-}diff --git a/GlazeWM.Infrastructure/Bussing/Command.cs b/GlazeWM.Infrastructure/Bussing/Command.csdeleted file mode 100644index b57ff738..00000000--- a/GlazeWM.Infrastructure/Bussing/Command.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace GlazeWM.Infrastructure.Bussing-{- public class Command- {- public string Name => GetType().Name;- }-}diff --git a/GlazeWM.Infrastructure/Bussing/CommandResponse.cs b/GlazeWM.Infrastructure/Bussing/CommandResponse.csdeleted file mode 100644index 0c483755..00000000--- a/GlazeWM.Infrastructure/Bussing/CommandResponse.cs+++ /dev/null@@ -1,14 +0,0 @@-namespace GlazeWM.Infrastructure.Bussing-{- public class CommandResponse- {- public bool Success { get; private set; }- public static readonly CommandResponse Ok = new() { Success = true };- public static readonly CommandResponse Fail = new() { Success = false };-- public CommandResponse(bool success = false)- {- Success = success;- }- }-}diff --git a/GlazeWM.Infrastructure/Bussing/Event.cs b/GlazeWM.Infrastructure/Bussing/Event.csdeleted file mode 100644index d1453a1f..00000000--- a/GlazeWM.Infrastructure/Bussing/Event.cs+++ /dev/null@@ -1,13 +0,0 @@-using GlazeWM.Infrastructure.Utils;--namespace GlazeWM.Infrastructure.Bussing-{- /// <summary>- /// An event emitted on the bus.- /// </summary>- /// <param name="Type">- /// Identifier for the type of event. For CLI and IPC usage when subscribing to a- /// given event type.- /// </param>- public abstract record Event(string Type);-}diff --git a/GlazeWM.Infrastructure/Bussing/ICommandHandler.cs b/GlazeWM.Infrastructure/Bussing/ICommandHandler.csdeleted file mode 100644index 5f44e460..00000000--- a/GlazeWM.Infrastructure/Bussing/ICommandHandler.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace GlazeWM.Infrastructure.Bussing-{- public interface ICommandHandler<TCommand> where TCommand : Command- {- CommandResponse Handle(TCommand command);- }-}diff --git a/GlazeWM.Infrastructure/Bussing/IEventHandler.cs b/GlazeWM.Infrastructure/Bussing/IEventHandler.csdeleted file mode 100644index 6b8f6a65..00000000--- a/GlazeWM.Infrastructure/Bussing/IEventHandler.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace GlazeWM.Infrastructure.Bussing-{- public interface IEventHandler<TEvent> where TEvent : Event- {- void Handle(TEvent @event);- }-}diff --git a/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.cs b/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.csdeleted file mode 100644index 5af54dd3..00000000--- a/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.cs+++ /dev/null@@ -1,30 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.Common.Events;--namespace GlazeWM.Infrastructure.Common.CommandHandlers-{- internal class ExitApplicationHandler : ICommandHandler<ExitApplicationCommand>- {- private readonly Bus _bus;-- public ExitApplicationHandler(Bus bus)- {- _bus = bus;- }-- public CommandResponse Handle(ExitApplicationCommand command)- {- var withErrorCode = command.WithErrorCode;-- // Signal that application is about to exit (to perform cleanup).- _bus.Emit(new ApplicationExitingEvent());-- // Use exit code 1 if exiting due to an exception.- Environment.Exit(withErrorCode ? 1 : 0);-- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Infrastructure/Common/CommandHandlers/HandleFatalExceptionHandler.cs b/GlazeWM.Infrastructure/Common/CommandHandlers/HandleFatalExceptionHandler.csdeleted file mode 100644index b4166040..00000000--- a/GlazeWM.Infrastructure/Common/CommandHandlers/HandleFatalExceptionHandler.cs+++ /dev/null@@ -1,66 +0,0 @@-using System;-using System.IO;-using System.Windows.Forms;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.Exceptions;-using Microsoft.Extensions.Options;--namespace GlazeWM.Infrastructure.Common.CommandHandlers-{- internal class HandleFatalExceptionHandler : ICommandHandler<HandleFatalExceptionCommand>- {- private readonly Bus _bus;- private readonly IOptions<ExceptionHandlingOptions> _options;-- public HandleFatalExceptionHandler(Bus bus, IOptions<ExceptionHandlingOptions> options)- {- _bus = bus;- _options = options;- }-- public CommandResponse Handle(HandleFatalExceptionCommand command)- {- var exception = command.Exception;-- var dialogButtons = exception is FatalUserException- ? MessageBoxButtons.OK- : MessageBoxButtons.OKCancel;-- var dialogMesssage = exception is FatalUserException- ? exception.Message- : $"Unhandled exception: {exception.Message}\n\nContinue without exiting?";-- // Alert the user of the error.- var dialogResult = MessageBox.Show(- dialogMesssage,- "Encountered a problem",- dialogButtons,- MessageBoxIcon.Warning,- MessageBoxDefaultButton.Button1,- MessageBoxOptions.DefaultDesktopOnly- );-- WriteToErrorLog(exception);-- // Always exit on `FatalUserException`.- if (dialogResult == DialogResult.Cancel || exception is FatalUserException)- _bus.Invoke(new ExitApplicationCommand(true));-- return CommandResponse.Ok;- }-- private void WriteToErrorLog(Exception exception)- {- var errorLogPath = _options.Value.ErrorLogPath;-- // Create containing directory. Needs to be created before writing to the file.- Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));-- File.AppendAllText(- errorLogPath,- _options.Value.ErrorLogMessageDelegate(exception)- );- }- }-}diff --git a/GlazeWM.Infrastructure/Common/CommandHandlers/NoopHandler.cs b/GlazeWM.Infrastructure/Common/CommandHandlers/NoopHandler.csdeleted file mode 100644index 38600368..00000000--- a/GlazeWM.Infrastructure/Common/CommandHandlers/NoopHandler.cs+++ /dev/null@@ -1,13 +0,0 @@-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Commands;--namespace GlazeWM.Infrastructure.Common.CommandHandlers-{- internal class NoopHandler : ICommandHandler<NoopCommand>- {- public CommandResponse Handle(NoopCommand command)- {- return CommandResponse.Ok;- }- }-}diff --git a/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.cs b/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.csdeleted file mode 100644index 14ea790c..00000000--- a/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.cs+++ /dev/null@@ -1,14 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Commands-{- public class ExitApplicationCommand : Command- {- public bool WithErrorCode { get; }-- public ExitApplicationCommand(bool withErrorCode)- {- WithErrorCode = withErrorCode;- }- }-}diff --git a/GlazeWM.Infrastructure/Common/Commands/HandleFatalExceptionCommand.cs b/GlazeWM.Infrastructure/Common/Commands/HandleFatalExceptionCommand.csdeleted file mode 100644index 26d09b6a..00000000--- a/GlazeWM.Infrastructure/Common/Commands/HandleFatalExceptionCommand.cs+++ /dev/null@@ -1,15 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Commands-{- public class HandleFatalExceptionCommand : Command- {- public Exception Exception { get; }-- public HandleFatalExceptionCommand(Exception exception)- {- Exception = exception;- }- }-}diff --git a/GlazeWM.Infrastructure/Common/Commands/NoopCommand.cs b/GlazeWM.Infrastructure/Common/Commands/NoopCommand.csdeleted file mode 100644index d9f9960f..00000000--- a/GlazeWM.Infrastructure/Common/Commands/NoopCommand.cs+++ /dev/null@@ -1,8 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Commands-{- public class NoopCommand : Command- {- }-}diff --git a/GlazeWM.Infrastructure/Common/Events/ApplicationExitingEvent.cs b/GlazeWM.Infrastructure/Common/Events/ApplicationExitingEvent.csdeleted file mode 100644index a855920e..00000000--- a/GlazeWM.Infrastructure/Common/Events/ApplicationExitingEvent.cs+++ /dev/null@@ -1,6 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record ApplicationExitingEvent() : Event(InfraEvent.ApplicationExiting);-}diff --git a/GlazeWM.Infrastructure/Common/Events/DisplaySettingsChangedEvent.cs b/GlazeWM.Infrastructure/Common/Events/DisplaySettingsChangedEvent.csdeleted file mode 100644index 8a7c8a6e..00000000--- a/GlazeWM.Infrastructure/Common/Events/DisplaySettingsChangedEvent.cs+++ /dev/null@@ -1,6 +0,0 @@-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record DisplaySettingsChangedEvent() : Event(InfraEvent.DisplaySettingsChanged);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowDestroyedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowDestroyedEvent.csdeleted file mode 100644index 7a3234bb..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowDestroyedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowDestroyedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowDestroyed);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowFocusedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowFocusedEvent.csdeleted file mode 100644index ee111306..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowFocusedEvent.cs+++ /dev/null@@ -1,7 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowFocusedEvent(IntPtr WindowHandle) : Event(InfraEvent.WindowFocused);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowHiddenEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowHiddenEvent.csdeleted file mode 100644index 90228df1..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowHiddenEvent.cs+++ /dev/null@@ -1,7 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowHiddenEvent(IntPtr WindowHandle) : Event(InfraEvent.WindowHidden);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowLocationChangedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowLocationChangedEvent.csdeleted file mode 100644index 1b415f7f..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowLocationChangedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowLocationChangedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowLocationChanged);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowMinimizeEndedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowMinimizeEndedEvent.csdeleted file mode 100644index d9b9bb5f..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowMinimizeEndedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowMinimizeEndedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowMinimizeEnded);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowMinimizedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowMinimizedEvent.csdeleted file mode 100644index a51eb996..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowMinimizedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowMinimizedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowMinimized);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowMovedOrResizedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowMovedOrResizedEvent.csdeleted file mode 100644index 63d077ef..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowMovedOrResizedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowMovedOrResizedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowMovedOrResized);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowShownEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowShownEvent.csdeleted file mode 100644index d056238e..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowShownEvent.cs+++ /dev/null@@ -1,7 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowShownEvent(IntPtr WindowHandle) : Event(InfraEvent.WindowShown);-}diff --git a/GlazeWM.Infrastructure/Common/Events/WindowTitleChangedEvent.cs b/GlazeWM.Infrastructure/Common/Events/WindowTitleChangedEvent.csdeleted file mode 100644index d1a63182..00000000--- a/GlazeWM.Infrastructure/Common/Events/WindowTitleChangedEvent.cs+++ /dev/null@@ -1,8 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;--namespace GlazeWM.Infrastructure.Common.Events-{- public record WindowTitleChangedEvent(IntPtr WindowHandle)- : Event(InfraEvent.WindowTitleChanged);-}diff --git a/GlazeWM.Infrastructure/Common/ExitCode.cs b/GlazeWM.Infrastructure/Common/ExitCode.csdeleted file mode 100644index 44f4ff5e..00000000--- a/GlazeWM.Infrastructure/Common/ExitCode.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Infrastructure.Common-{- public enum ExitCode- {- Success = 0,- Error = 1,- }-}diff --git a/GlazeWM.Infrastructure/Common/InfraEvent.cs b/GlazeWM.Infrastructure/Common/InfraEvent.csdeleted file mode 100644index a6f01abe..00000000--- a/GlazeWM.Infrastructure/Common/InfraEvent.cs+++ /dev/null@@ -1,18 +0,0 @@-namespace GlazeWM.Infrastructure.Common-{- public static class InfraEvent- {- public const string ApplicationExiting = "application_exiting";- public const string DisplaySettingsChanged = "display_settings_changed";- public const string MouseMove = "mouse_move";- public const string WindowDestroyed = "window_destroyed";- public const string WindowFocused = "window_focused";- public const string WindowHidden = "window_hidden";- public const string WindowLocationChanged = "window_location_changed";- public const string WindowMinimizeEnded = "window_minimize_ended";- public const string WindowMinimized = "window_minimized";- public const string WindowMovedOrResized = "window_moved_or_resized";- public const string WindowShown = "window_shown";- public const string WindowTitleChanged = "window_title_changed";- }-}diff --git a/GlazeWM.Infrastructure/DependencyInjection.cs b/GlazeWM.Infrastructure/DependencyInjection.csdeleted file mode 100644index 26f09407..00000000--- a/GlazeWM.Infrastructure/DependencyInjection.cs+++ /dev/null@@ -1,30 +0,0 @@-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.CommandHandlers;-using GlazeWM.Infrastructure.Common.Commands;-using GlazeWM.Infrastructure.WindowsApi;-using Microsoft.Extensions.DependencyInjection;--namespace GlazeWM.Infrastructure-{- public static class DependencyInjection- {- public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)- {- services.AddSingleton<Bus>();- services.AddSingleton<KeybindingService>();- services.AddSingleton<WindowEventService>();- services.AddSingleton<CpuStatsService>();- services.AddSingleton<GpuStatsService>();- services.AddSingleton<MemoryStatsService>();- services.AddSingleton<SystemVolumeInformation>();-- services.AddSingleton<ICommandHandler<ExitApplicationCommand>, ExitApplicationHandler>();- services.AddSingleton<ICommandHandler<HandleFatalExceptionCommand>, HandleFatalExceptionHandler>();- services.AddSingleton<ICommandHandler<NoopCommand>, NoopHandler>();-- // TODO: Change WindowsApiService to be compatible with DI.-- return services;- }- }-}diff --git a/GlazeWM.Infrastructure/Exceptions/ExceptionHandlingOptions.cs b/GlazeWM.Infrastructure/Exceptions/ExceptionHandlingOptions.csdeleted file mode 100644index e888fea0..00000000--- a/GlazeWM.Infrastructure/Exceptions/ExceptionHandlingOptions.cs+++ /dev/null@@ -1,10 +0,0 @@-using System;--namespace GlazeWM.Infrastructure.Exceptions-{- public class ExceptionHandlingOptions- {- public string ErrorLogPath { get; set; }- public Func<Exception, string> ErrorLogMessageDelegate { get; set; }- }-}diff --git a/GlazeWM.Infrastructure/Exceptions/FatalUserException.cs b/GlazeWM.Infrastructure/Exceptions/FatalUserException.csdeleted file mode 100644index 3dbcf21f..00000000--- a/GlazeWM.Infrastructure/Exceptions/FatalUserException.cs+++ /dev/null@@ -1,21 +0,0 @@-using System;--namespace GlazeWM.Infrastructure.Exceptions-{- public class FatalUserException : Exception- {- public FatalUserException()- {- }-- public FatalUserException(string message) : base(message)- {- }-- public FatalUserException(- string message,- Exception innerException) : base(message, innerException)- {- }- }-}diff --git a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csprojdeleted file mode 100644index fe39f419..00000000--- a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj+++ /dev/null@@ -1,59 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <TargetFramework>net7-windows10.0.17763.0</TargetFramework>- <UseWindowsForms>true</UseWindowsForms>- <DebugType>embedded</DebugType>- </PropertyGroup>-- <ItemGroup>- <PackageReference- Include="CommandLineParser"- Version="2.9.1" />- <PackageReference- Include="System.Reactive"- Version="5.0.0" />- <PackageReference- Include="Vanara.Core"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.CoreAudio"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.DwmApi"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.Kernel32"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.SHCore"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.User32"- Version="3.4.13" />- <PackageReference- Include="Vanara.PInvoke.WlanApi"- Version="3.4.12" />- <PackageReference- Include="Vanara.PInvoke.IpHlpApi"- Version="3.4.12" />- <PackageReference- Include="Vostok.Sys.Metrics.PerfCounters"- Version="0.0.6" />- <PackageReference- Include="YamlDotNet"- Version="8.1.0" />- <PackageReference- Include="Roslynator.Analyzers"- Version="4.2.0" />- <PackageReference- Include="Microsoft.CodeAnalysis.NetAnalyzers"- Version="7.0.0" />- <PackageReference- Include="Microsoft.Extensions.Hosting"- Version="6.0.1" />- <PackageReference- Include="ManagedShell"- Version="0.0.198" />- </ItemGroup>-</Project>diff --git a/GlazeWM.Infrastructure/Logging/LogFormatter.cs b/GlazeWM.Infrastructure/Logging/LogFormatter.csdeleted file mode 100644index 20777bae..00000000--- a/GlazeWM.Infrastructure/Logging/LogFormatter.cs+++ /dev/null@@ -1,65 +0,0 @@-using System;-using System.Globalization;-using System.IO;-using Microsoft.Extensions.Logging;-using Microsoft.Extensions.Logging.Abstractions;-using Microsoft.Extensions.Logging.Console;-using Microsoft.Extensions.Options;--namespace GlazeWM.Infrastructure.Logging-{- public sealed class LogFormatter : ConsoleFormatter, IDisposable- {- public new const string Name = "customFormatter";-- private readonly IDisposable _optionsReloadToken;- private ConsoleFormatterOptions _formatterOptions;-- public LogFormatter(IOptionsMonitor<ConsoleFormatterOptions> options) : base(Name)- {- (_optionsReloadToken, _formatterOptions)- = (options.OnChange(ReloadLoggerOptions), options.CurrentValue);- }-- private void ReloadLoggerOptions(ConsoleFormatterOptions options)- {- _formatterOptions = options;- }-- public override void Write<T>(- in LogEntry<T> logEntry,- IExternalScopeProvider scopeProvider,- TextWriter textWriter)- {- var message = logEntry.Formatter?.Invoke(logEntry.State, logEntry.Exception);-- if (message is null)- return;-- AddTimestampPrefix(textWriter);- AddTrimmedCategoryPrefix(textWriter, logEntry);- textWriter.WriteLine(message);- }-- private void AddTimestampPrefix(TextWriter textWriter)- {- var timestamp = _formatterOptions.UseUtcTimestamp- ? DateTime.UtcNow- : DateTime.Now;-- textWriter.Write(- $"{timestamp.ToString(_formatterOptions.TimestampFormat, CultureInfo.InvariantCulture)}"- );- }-- private static void AddTrimmedCategoryPrefix<T>(TextWriter textWriter, LogEntry<T> logEntry)- {- textWriter.Write($"[{logEntry.Category.Split(".")[^1]}] ");- }-- public void Dispose()- {- _optionsReloadToken?.Dispose();- }- }-}diff --git a/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.cs b/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.csdeleted file mode 100644index 92f9a241..00000000--- a/GlazeWM.Infrastructure/Serialization/JsonIntPtrConverter.cs+++ /dev/null@@ -1,25 +0,0 @@-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.csdeleted file mode 100644index 92db84ef..00000000--- a/GlazeWM.Infrastructure/Serialization/JsonParser.cs+++ /dev/null@@ -1,64 +0,0 @@-using System;-using System.Text.Json;-using System.Text.Json.Serialization;--namespace GlazeWM.Infrastructure.Serialization-{- public static class JsonParser- {- private static readonly JsonSerializerOptions _defaultOptions = new()- {- // TODO: Use built-in snake case policy once support is added.- // Ref: https://github.com/dotnet/runtime/issues/782- PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance,- NumberHandling = JsonNumberHandling.AllowReadingFromString,- IncludeFields = true,- Converters = {- // Enable strings to be mapped to a C# enum (eg. `BarPosition` enum).- new 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(),- }- };-- public static string ToString<T>(T value)- {- return JsonSerializer.Serialize(value, _defaultOptions);- }-- public static string ToString<T>(T value, JsonSerializerOptions options)- {- return JsonSerializer.Serialize(value, options);- }-- public static T ToInstance<T>(string json)- {- return JsonSerializer.Deserialize<T>(json, _defaultOptions);- }-- public static T ToInstance<T>(string json, JsonSerializerOptions options)- {- return JsonSerializer.Deserialize<T>(json, options);- }-- public static JsonSerializerOptions OptionsFactory(- Action<JsonSerializerOptions> callback)- {- var options = new JsonSerializerOptions(_defaultOptions);- callback(options);- return options;- }-- /// <summary>- /// Convert property name according to naming policy.- /// </summary>- public static string ChangeCasing(- string propertyName,- JsonSerializerOptions options)- {- return options.PropertyNamingPolicy?.ConvertName(propertyName) ?? propertyName;- }- }-}diff --git a/GlazeWM.Infrastructure/Serialization/JsonStringBoolConverter.cs b/GlazeWM.Infrastructure/Serialization/JsonStringBoolConverter.csdeleted file mode 100644index 46781051..00000000--- a/GlazeWM.Infrastructure/Serialization/JsonStringBoolConverter.cs+++ /dev/null@@ -1,34 +0,0 @@-using System;-using System.Text.Json;-using System.Text.Json.Serialization;--namespace GlazeWM.Infrastructure.Serialization-{- public class JsonStringBoolConverter : JsonConverter<bool>- {- /// <summary>- /// Allow boolean strings when deserializing to a bool (eg. "true" -> true).- /// </summary>- /// <exception cref="JsonException"></exception>- public override bool Read(- ref Utf8JsonReader reader,- Type typeToConvert,- JsonSerializerOptions options)- {- return reader.TokenType switch- {- JsonTokenType.True => true,- JsonTokenType.False => false,- JsonTokenType.String => bool.TryParse(reader.GetString(), out var parsedBool)- ? parsedBool- : throw new JsonException(),- _ => throw new JsonException(),- };- }-- public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)- {- writer.WriteBooleanValue(value);- }- }-}diff --git a/GlazeWM.Infrastructure/Serialization/SnakeCaseNamingPolicy.cs b/GlazeWM.Infrastructure/Serialization/SnakeCaseNamingPolicy.csdeleted file mode 100644index b57be1e6..00000000--- a/GlazeWM.Infrastructure/Serialization/SnakeCaseNamingPolicy.cs+++ /dev/null@@ -1,27 +0,0 @@-using System.Globalization;-using System.Linq;-using System.Text.Json;--namespace GlazeWM.Infrastructure.Serialization-{- public class SnakeCaseNamingPolicy : JsonNamingPolicy- {- public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();-- public override string ConvertName(string name)- {- return ToSnakeCase(name);- }-- public static string ToSnakeCase(string input)- {- var snakeCaseLetters = input.Select((letter, index) =>- index > 0 && char.IsUpper(letter)- ? "_" + letter.ToString()- : letter.ToString()- );-- return string.Concat(snakeCaseLetters).ToLower(CultureInfo.InvariantCulture);- }- }-}diff --git a/GlazeWM.Infrastructure/Serialization/YamlParser.cs b/GlazeWM.Infrastructure/Serialization/YamlParser.csdeleted file mode 100644index 83962c86..00000000--- a/GlazeWM.Infrastructure/Serialization/YamlParser.cs+++ /dev/null@@ -1,27 +0,0 @@-using System.IO;-using System.Text.Json;-using YamlDotNet.Core;-using YamlDotNet.Serialization;--namespace GlazeWM.Infrastructure.Serialization-{- public static class YamlParser- {- /// <summary>- /// The YAML deserialization library doesn't have support for polymorphic objects. Because of- /// this, the YAML is first converted into JSON and then deserialized via `System.Text.Json`.- /// </summary>- public static T ToInstance<T>(string input, JsonSerializerOptions deserializeOptions)- {- // Deserializes YAML into key-value pairs (ie. not an object of type `T`). Merging parser is- // used to enable the use of merge keys.- var reader = new MergingParser(new Parser(new StringReader(input)));- var yamlObject = new DeserializerBuilder().Build().Deserialize(reader);-- // Convert key-value pairs into a JSON string.- var jsonString = JsonParser.ToString(yamlObject);-- return JsonParser.ToInstance<T>(jsonString, deserializeOptions);- }- }-}diff --git a/GlazeWM.Infrastructure/ServiceLocator.cs b/GlazeWM.Infrastructure/ServiceLocator.csdeleted file mode 100644index a845ab15..00000000--- a/GlazeWM.Infrastructure/ServiceLocator.cs+++ /dev/null@@ -1,41 +0,0 @@-using System;-using System.Collections.Generic;-using Microsoft.Extensions.DependencyInjection;--namespace GlazeWM.Infrastructure-{- public static class ServiceLocator- {- public static IServiceProvider Provider { private get; set; }-- public static T GetRequiredService<T>()- {- return Provider.GetRequiredService<T>();- }-- public static object GetRequiredService(Type type)- {- return Provider.GetRequiredService(type);- }-- public static IEnumerable<object> GetServices(Type type)- {- return Provider.GetServices(type);- }-- public static (T1, T2) GetRequiredServices<T1, T2>()- {- var service1 = Provider.GetRequiredService<T1>();- var service2 = Provider.GetRequiredService<T2>();- return (service1, service2);- }-- public static (T1, T2, T3) GetRequiredServices<T1, T2, T3>()- {- var service1 = Provider.GetRequiredService<T1>();- var service2 = Provider.GetRequiredService<T2>();- var service3 = Provider.GetRequiredService<T3>();- return (service1, service2, service3);- }- }-}diff --git a/GlazeWM.Infrastructure/Services/WeatherService.cs b/GlazeWM.Infrastructure/Services/WeatherService.csdeleted file mode 100644index 328d9a81..00000000--- a/GlazeWM.Infrastructure/Services/WeatherService.cs+++ /dev/null@@ -1,151 +0,0 @@-using System;-using System.Collections.Generic;-using System.Globalization;-using System.Net.Http;-using System.Text.Json;-using System.Text.Json.Serialization;-using System.Threading.Tasks;-using static GlazeWM.Infrastructure.Services.WeatherStatus;--namespace GlazeWM.Infrastructure.Services-{- /// <summary>- /// Service that queries current weather status using the OpenMeteo API.- /// </summary>- public static class WeatherService- {- /// <summary>- /// Retrieves the current weather status asynchronously.- /// </summary>- /// <param name="latitude">Current latitude.</param>- /// <param name="longitude">Current longitude.</param>- public static async Task<WeatherServiceResult> GetWeatherAsync(float latitude, float longitude)- {- var lat = latitude.ToString(CultureInfo.InvariantCulture);- var lng = longitude.ToString(CultureInfo.InvariantCulture);-- using var client = new HttpClient();-- var res = await client.GetStringAsync(- "https://api.open-meteo.com/v1/forecast?latitude=" +- lat +- "&longitude=" +- lng +- "&temperature_unit=celsius¤t_weather=true&daily=sunset,sunrise&timezone=auto"- );-- var weather = JsonSerializer.Deserialize<MeteoWeatherResult>(res);- var isDaylight = IsDaytime(weather.Daily);- var status = GetWeatherStatus(weather.CurrentWeather.WeatherCode, isDaylight);-- return new WeatherServiceResult(status, weather);- }-- private static bool IsDaytime(MeteoDailyResult times)- {- var now = DateTime.Now;- var sunsetToday = times.Sunset.Find(t => t.Day == now.Day);- var sunriseToday = times.Sunrise.Find(t => t.Day == now.Day);- return now > sunriseToday && now < sunsetToday;- }-- public static double ToFahrenheit(double celsius)- {- return (celsius * 1.8) + 32;- }-- private static WeatherStatus GetWeatherStatus(int code, bool isDaytime)- {- return code switch- {- // https://open-meteo.com/en/docs- 0 => isDaytime ? Sun : Moon,- < 3 => isDaytime ? CloudSun : CloudMoon,- < 50 => Cloud,- < 60 => isDaytime ? CloudSunRain : CloudMoonRain,- < 70 => CloudRain,- < 80 => Snowflake,- < 83 => CloudRain,- < 87 => Snowflake,- < 99 => Thunder,- _ => Sun- };- }- }-- /// <summary>- /// Result of individual weather service query.- /// </summary>- /// <param name="Status">Weather status.</param>- /// <param name="Result">Result of the weather lookup.</param>- public record WeatherServiceResult(WeatherStatus Status, MeteoWeatherResult Result);-- /// <summary>- /// Describes the icon to use for a given returned weather code.- /// </summary>- public enum WeatherStatus- {- Sun,- Moon,- CloudSun,- CloudMoon,- Cloud,- CloudSunRain,- CloudMoonRain,- CloudRain,- Snowflake,- Thunder- }-- /// <summary>- /// Temperature Unit returned from the API.- /// </summary>- public enum TemperatureUnit- {- /// <summary>- /// Temperature is returned in Celsius (C).- /// </summary>- Celsius,-- /// <summary>- /// Temperature is returned in Fahrenheit (F).- /// </summary>- Fahrenheit- }-- public record MeteoWeatherResult- {- [JsonPropertyName("latitude")]- public float Latitude { get; set; }-- [JsonPropertyName("longitude")]- public float Longitude { get; set; }-- [JsonPropertyName("current_weather")]- public MeteoCurrentWeatherResult CurrentWeather { get; set; }-- [JsonPropertyName("daily")]- public MeteoDailyResult Daily { get; set; }- }-- public record MeteoDailyResult- {- [JsonPropertyName("sunset")]- public List<DateTime> Sunset { get; set; }-- [JsonPropertyName("sunrise")]- public List<DateTime> Sunrise { get; set; }- }-- public record MeteoCurrentWeatherResult- {- [JsonPropertyName("temperature")]- public float Temperature { get; set; }-- [JsonPropertyName("weathercode")]- public int WeatherCode { get; set; }-- [JsonPropertyName("time")]- public DateTime Time { get; set; }- }-}diff --git a/GlazeWM.Infrastructure/Utils/CasingUtil.cs b/GlazeWM.Infrastructure/Utils/CasingUtil.csdeleted file mode 100644index 6b659f63..00000000--- a/GlazeWM.Infrastructure/Utils/CasingUtil.cs+++ /dev/null@@ -1,20 +0,0 @@-using System.Globalization;-using System.Text.RegularExpressions;--namespace GlazeWM.Infrastructure.Utils-{- public static class CasingUtil- {- private static readonly Regex _regex = new("([a-z])([A-Z])");-- /// <summary>- /// Converts pascal case to snake case (eg. `FirstName` -> `first_name`).- /// </summary>- public static string PascalToSnake(string input)- {- return _regex.Replace(input, "$1_$2").ToLower(- CultureInfo.InvariantCulture- );- }- }-}diff --git a/GlazeWM.Infrastructure/Utils/EnumerableExtensions.cs b/GlazeWM.Infrastructure/Utils/EnumerableExtensions.csdeleted file mode 100644index cfdae1d4..00000000--- a/GlazeWM.Infrastructure/Utils/EnumerableExtensions.cs+++ /dev/null@@ -1,16 +0,0 @@-using System.Collections.Generic;-using System.Linq;--namespace GlazeWM.Infrastructure.Utils-{- public static class EnumerableExtensions- {- /// <summary>- /// Create an enumerable of tuples with index and item at index. Can be used with foreach loops.- /// </summary>- public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)- {- return source?.Select((item, index) => (item, index)) ?? new List<(T, int)>();- }- }-}diff --git a/GlazeWM.Infrastructure/Utils/KeybindingHelper.cs b/GlazeWM.Infrastructure/Utils/KeybindingHelper.csdeleted file mode 100644index 408f6695..00000000--- a/GlazeWM.Infrastructure/Utils/KeybindingHelper.cs+++ /dev/null@@ -1,42 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Windows.Forms;--namespace GlazeWM.Infrastructure.Utils-{- public static class KeybindingHelper- {- public static List<Keys> ParseKeybindingString(string keybindingString)- {- return keybindingString- .Split('+')- .Select(keyString => FormatKeyString(keyString))- .Select(keyString => ParseKeyString(keyString))- .ToList();- }-- private static string FormatKeyString(string keyString)- {- var isNumeric = int.TryParse(keyString, out var _);-- return isNumeric ? $"D{keyString}" : keyString;- }-- private static Keys ParseKeyString(string keyString)- {- try- {- return Enum.Parse<Keys>(keyString);- }- catch (ArgumentException)- {- return keyString switch- {- "Ctrl" => Keys.Control,- _ => throw new ArgumentException($"Unknown key '{keyString}'"),- };- }- }- }-}diff --git a/GlazeWM.Infrastructure/Utils/ListExtensions.cs b/GlazeWM.Infrastructure/Utils/ListExtensions.csdeleted file mode 100644index 762d6982..00000000--- a/GlazeWM.Infrastructure/Utils/ListExtensions.cs+++ /dev/null@@ -1,50 +0,0 @@-using System.Collections.Generic;--namespace GlazeWM.Infrastructure.Utils-{- public static class ListExtensions- {- /// <summary>- /// Replace the first occurrence of a value with a new value in a list.- /// </summary>- public static void Replace<T>(this IList<T> source, T oldValue, T newValue)- {- var index = source.IndexOf(oldValue);-- if (index != -1)- source[index] = newValue;- }-- /// <summary>- /// Shift a value to a specified index in a list. Insert at index if it doesn't already exist.- /// </summary>- public static void ShiftToIndex<T>(this IList<T> source, int index, T value)- {- var initialIndex = source.IndexOf(value);-- if (initialIndex != -1)- source.Remove(value);-- source.Insert(index, value);- }-- /// <summary>- /// Shift a value to the first index of a list. Insert at start if it doesn't already exist.- /// </summary>- public static void MoveToFront<T>(this IList<T> source, T value)- {- ShiftToIndex(source, 0, value);- }-- /// <summary>- /// Insert a value between each element of a list.- /// </summary>- public static void Intersperse<T>(this IList<T> source, T value)- {- for (var i = 1; i < source.Count; i += 2)- {- source.Insert(i, value);- }- }- }-}diff --git a/GlazeWM.Infrastructure/Utils/ThreadUtils.cs b/GlazeWM.Infrastructure/Utils/ThreadUtils.csdeleted file mode 100644index bb5d0122..00000000--- a/GlazeWM.Infrastructure/Utils/ThreadUtils.cs+++ /dev/null@@ -1,29 +0,0 @@-using System;-using System.Threading;--namespace GlazeWM.Infrastructure.Utils-{- public static class ThreadUtils- {- public static void CreateSTA(string threadName, Action threadAction)- {- var thread = new Thread(() => threadAction())- {- Name = threadName- };-- thread.SetApartmentState(ApartmentState.STA);- thread.Start();- }-- public static void Create(string threadName, Action threadAction)- {- var thread = new Thread(() => threadAction())- {- Name = threadName- };-- thread.Start();- }- }-}diff --git a/GlazeWM.Infrastructure/Utils/UnitsHelper.cs b/GlazeWM.Infrastructure/Utils/UnitsHelper.csdeleted file mode 100644index 67204959..00000000--- a/GlazeWM.Infrastructure/Utils/UnitsHelper.cs+++ /dev/null@@ -1,28 +0,0 @@-using System;-using System.Globalization;-using System.Text.RegularExpressions;--namespace GlazeWM.Infrastructure.Utils-{- public static class UnitsHelper- {- /// <summary>- /// Returns the number part of amount with units as signed integer- /// </summary>- public static int TrimUnits(string amountWithUnits)- {- var unitsRegex = new Regex("(%|ppt|px)");- var amount = unitsRegex.Replace(amountWithUnits, "").Trim();- return Convert.ToInt32(amount, CultureInfo.InvariantCulture);- }- /// <summary>- /// Returns the unit part of amount with units as a string- /// </summary>- public static string GetUnits(string amountWithUnits)- {- var unitsRegex = new Regex("(%|ppt|px)");- var match = unitsRegex.Match(amountWithUnits);- return match.Value;- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.csdeleted file mode 100644index eabedaff..00000000--- a/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.cs+++ /dev/null@@ -1,43 +0,0 @@-using System;-using Vostok.Sys.Metrics.PerfCounters;--namespace GlazeWM.Infrastructure.WindowsApi-{- /// <summary>- /// Provides access to current CPU statistics.- /// </summary>- public class CpuStatsService : IDisposable- {- private readonly IPerformanceCounter<double> _cpuCounter =- PerformanceCounterFactory.Default.CreateCounter(- "Processor Information",- "% Processor Utility",- "_Total"- );-- /// <inheritdoc />- ~CpuStatsService() => Dispose();-- /// <inheritdoc />- public void Dispose()- {- _cpuCounter.Dispose();- GC.SuppressFinalize(this);- }-- /// <summary>- /// Returns the current CPU utilization as a percentage.- /// </summary>- public double GetCpuUsage()- {- try- {- return _cpuCounter.Observe();- }- catch- {- return 0;- }- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/CurrentMediaChangedArgsEvent.cs b/GlazeWM.Infrastructure/WindowsApi/CurrentMediaChangedArgsEvent.csdeleted file mode 100755index fb1006a0..00000000--- a/GlazeWM.Infrastructure/WindowsApi/CurrentMediaChangedArgsEvent.cs+++ /dev/null@@ -1,9 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi-{- public class CurrentMediaChangedEventArgs- {- public string AlbumTitle { get; set; }- public string Artist { get; set; }- public string Title { get; set; }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/CurrentMediaPlaybackChangedEventArgs.cs b/GlazeWM.Infrastructure/WindowsApi/CurrentMediaPlaybackChangedEventArgs.csdeleted file mode 100755index cbc5d89d..00000000--- a/GlazeWM.Infrastructure/WindowsApi/CurrentMediaPlaybackChangedEventArgs.cs+++ /dev/null@@ -1,9 +0,0 @@-using Windows.Media.Control;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class CurrentMediaPlaybackChangedEventArgs- {- public GlobalSystemMediaTransportControlsSessionPlaybackStatus PlaybackState { get; set; }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/Enums/EventConstant.cs b/GlazeWM.Infrastructure/WindowsApi/Enums/EventConstant.csdeleted file mode 100644index 1b1999a0..00000000--- a/GlazeWM.Infrastructure/WindowsApi/Enums/EventConstant.cs+++ /dev/null@@ -1,20 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi.Enums-{- /// <summary>- /// Only the subset of event constants relevant to this application are included.- /// </summary>- public enum EventConstant : uint- {- Foreground = 0x0003,- MoveSizeEnd = 0x000B,- MinimizeStart = 0x0016,- MinimizeEnd = 0x0017,- Destroy = 0x8001,- Show = 0x8002,- Hide = 0x8003,- LocationChange = 0x800B,- NameChange = 0x800C,- Cloaked = 0x8017,- Uncloaked = 0x8018- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/Enums/ObjectIdentifier.cs b/GlazeWM.Infrastructure/WindowsApi/Enums/ObjectIdentifier.csdeleted file mode 100644index 8791ad09..00000000--- a/GlazeWM.Infrastructure/WindowsApi/Enums/ObjectIdentifier.cs+++ /dev/null@@ -1,11 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi.Enums-{- /// <summary>- /// Identifies categories of accessible objects within a window (including the window object itself).- /// Only the subset of object indentifiers relevant to this application are included.- /// </summary>- public enum ObjectIdentifier- {- Window = 0,- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.csdeleted file mode 100644index 964728e5..00000000--- a/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.cs+++ /dev/null@@ -1,286 +0,0 @@-using System;-using System.Collections.Generic;-using System.Diagnostics;-using System.Linq;-using System.Runtime.CompilerServices;-using Vostok.Sys.Metrics.PerfCounters;--namespace GlazeWM.Infrastructure.WindowsApi-{- /// <summary>- /// Provides access to current GPU statistics.- /// </summary>- public class GpuStatsService : IDisposable- {- private readonly PerformanceCounterCategory GpuEngineCategory = new("GPU Engine");-- /// <summary>- /// Stats for individual GPU performance counters indexed by GpuPerformanceCategory.- /// </summary>- private readonly GpuStatsForType[] StatsForTypes =- {- new("engtype_3D"),- new("engtype_LegacyOverlay"),- new("engtype_VideoDecode"),- new("engtype_Security"),- new("engtype_Copy"),- new("engtype_VideoEncode"),- new("engtype_VR")- };-- public void Dispose()- {- GC.SuppressFinalize(this);- foreach (var stat in StatsForTypes)- stat.Dispose();- }-- ~GpuStatsService()- {- Dispose();- }-- /// <summary>- /// Returns the current GPU utilization (average of all GPUs) for a given set of categories.- /// </summary>- /// <param name="categories">Categories to fetch info for.</param>- /// <returns>Average load.</returns>- public float GetAverageLoadPercent(GpuPerformanceCategoryFlags categories)- {- var instanceNames = GpuEngineCategory.GetInstanceNames();- var numCategories = 0;- var totalValue = 0f;-- QueryCategory(categories, GpuPerformanceCategoryFlags.Copy, GpuPerformanceCategory.Copy, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.VideoDecode, GpuPerformanceCategory.VideoDecode, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.VideoEncode, GpuPerformanceCategory.VideoEncode, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.LegacyOverlay, GpuPerformanceCategory.LegacyOverlay, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.Graphics, GpuPerformanceCategory.Graphics, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.Security, GpuPerformanceCategory.Security, instanceNames, ref numCategories, ref totalValue);- QueryCategory(categories, GpuPerformanceCategoryFlags.Vr, GpuPerformanceCategory.Vr, instanceNames, ref numCategories, ref totalValue);-- if (numCategories == 0)- numCategories = 1;-- return totalValue / numCategories;- }-- /// <summary>- /// Returns the current GPU utilization (average of all GPUs) for a given category.- /// </summary>- /// <param name="category">Category to fetch info for.</param>- /// <param name="instanceNames">Names of all available counter instances.</param>- /// <returns>Average load.</returns>- public float GetAverageLoadPercent(GpuPerformanceCategory category, string[] instanceNames = null)- {- try- {- instanceNames ??= GpuEngineCategory.GetInstanceNames();- var totalUtilization = 0f;-- var statsForType = StatsForTypes[(int)category];- foreach (var counterForProcess in statsForType.Update(instanceNames))- {- var processUtilization = 0f;-- // Try/catch here isn't ideal, but this appears to throw on- // own PID after a reload; I don't exactly know why.- foreach (var counter in counterForProcess.Value)- {- try { processUtilization += (float)counter.Observe(); }- catch { /* ignored */ }- }-- totalUtilization += processUtilization / counterForProcess.Value.Count;- }-- return totalUtilization;- }- catch (Exception)- {- // TODO: Some decent way of logging error here; this has no instance state.- return -1;- }- }-- [MethodImpl(MethodImplOptions.AggressiveInlining)]- private void QueryCategory(GpuPerformanceCategoryFlags requestedCategories, GpuPerformanceCategoryFlags flags, GpuPerformanceCategory category, string[] instanceNames, ref int numCategories, ref float totalValue)- {- if ((requestedCategories & flags) != flags)- return;-- totalValue += GetAverageLoadPercent(category, instanceNames);- numCategories++;- }-- private class GpuStatsForType : IDisposable- {- /// <summary>- /// Name of the counter, e.g. engtype_VR.- /// </summary>- private readonly string _counter;-- /// <summary>- /// Counters for each given instance of this counter.- /// </summary>- private readonly Dictionary<string, IPerformanceCounter<double>> _counters = new();-- public GpuStatsForType(string counter)- {- _counter = counter;- }-- /// <summary>- /// Updates the state of this counter.- /// </summary>- /// <param name="instanceNames">Name of all counter instances.</param>- public Dictionary<int, List<IPerformanceCounter<double>>> Update(string[] instanceNames)- {- // Problem, process can have multiple eng of 1 type; in that case, value should be averaged.- var filteredInstances = new HashSet<string>(instanceNames.Length);- foreach (var name in instanceNames)- {- if (name.Contains(_counter, StringComparison.Ordinal))- filteredInstances.Add(name);- }-- // Remove dead items from counters.- foreach (var key in _counters.Keys.ToArray())- {- if (filteredInstances.Contains(key))- continue;-- if (_counters.Remove(key, out var value))- value.Dispose();- }-- // Add items not present in dictionary.- foreach (var name in filteredInstances)- {- if (!_counters.ContainsKey(name))- _counters[name] = PerformanceCounterFactory.Default.CreateCounter(- "GPU Engine",- "Utilization Percentage",- name- );- }-- // Copy remaining results.- var byProcessId = new Dictionary<int, List<IPerformanceCounter<double>>>();- const string searchString = "pid_";- var stringLength = searchString.Length;- foreach (var counter in _counters)- {- var pidIndex = counter.Key.IndexOf(searchString, StringComparison.Ordinal);- if (pidIndex == -1)- continue;-- var processId = ExtractNumber(counter.Key.AsSpan(pidIndex + stringLength));- if (!byProcessId.TryGetValue(processId, out var value))- {- value = new List<IPerformanceCounter<double>>();- byProcessId[processId] = value;- }-- value.Add(counter.Value);- }-- return byProcessId;- }-- /// <summary>- /// Extracts a number from a string which begins with a number.- /// </summary>- /// <param name="input">Input string.</param>- /// <returns>Number starting at input.</returns>- private static int ExtractNumber(ReadOnlySpan<char> input)- {- var result = 0;- foreach (var c in input)- {- if (char.IsDigit(c))- result = (result * 10) + (c - '0');- else- break;- }-- return result;- }-- public void Dispose()- {- foreach (var counter in _counters)- counter.Value.Dispose();- }- }- }-- // DO NOT REARRANGE ITEMS BELOW, ENUM USED AS INDEXER.-- /// <summary>- /// Category used for fetching GPU performance data.- /// </summary>- [Flags]- public enum GpuPerformanceCategoryFlags- {- /// <summary>- /// 3D GPU Engine usage. i.e. engtype_3D- /// </summary>- Graphics = 1 << 0,-- /// <summary>- /// Legacy API for displaying items over other items. i.e. engtype_LegacyOverlay- /// </summary>- LegacyOverlay = 1 << 1,-- /// <summary>- /// Dedicated video decoding silicon. i.e. engtype_VideoDecode- /// </summary>- VideoDecode = 1 << 2,-- /// <summary>- /// Workloads related to cryptography, such as encryption, decryption, and secure video processing. i.e. engtype_Security- /// </summary>- Security = 1 << 3,-- /// <summary>- /// Copying data without intervention of CPU e.g. copying framebuffer across screens in multi GPU setup or uploading textures. engtype_Copy- /// </summary>- Copy = 1 << 4,-- /// <summary>- /// Dedicated video encoding silicon load, i.e. NVENC/AMD AMF/QuickSync. engtype_VideoEncode- /// </summary>- VideoEncode = 1 << 5,-- /// <summary>- /// Virtual Reality Related Stuff (don't know exact work, probably space reproduction stuff). engtype_VR- /// </summary>- Vr = 1 << 6,-- /// <summary>- /// All supported categories.- /// </summary>- All = Graphics | LegacyOverlay | VideoDecode | Security | Copy | VideoEncode | Vr- }-- /// <inheritdoc cref="GpuPerformanceCategoryFlags"/>- [Flags]- public enum GpuPerformanceCategory- {- /// <inheritdoc cref="GpuPerformanceCategoryFlags.Graphics"/>- Graphics,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.LegacyOverlay"/>- LegacyOverlay,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.VideoDecode"/>- VideoDecode,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.Security"/>- Security,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.Copy"/>- Copy,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.VideoEncode"/>- VideoEncode,- /// <inheritdoc cref="GpuPerformanceCategoryFlags.Vr"/>- Vr- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs b/GlazeWM.Infrastructure/WindowsApi/KeybindingService.csdeleted file mode 100644index 1d14f7bd..00000000--- a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs+++ /dev/null@@ -1,191 +0,0 @@-using System;-using System.Collections.Generic;-using System.Diagnostics;-using System.Linq;-using System.Runtime.InteropServices;-using System.Windows.Forms;-using GlazeWM.Infrastructure.Utils;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Infrastructure.WindowsApi-{- internal class Keybinding- {- public List<Keys> KeyCombination { get; }- public Action KeybindingProc { get; }-- public Keybinding(List<Keys> keyCombination, Action keybindingProc)- {- KeyCombination = keyCombination;- KeybindingProc = keybindingProc;- }- }-- public class KeybindingService- {- private const uint WM_KEYDOWN = 0x100;- private const uint WM_SYSKEYDOWN = 0x104;-- /// <summary>- /// Registered keybindings grouped by trigger key (ie. the final key in a key combination).- /// </summary>- private readonly Dictionary<Keys, List<Keybinding>> _keybindingsByTriggerKey = new();-- private readonly Keys[] _modifierKeys = new Keys[] {- Keys.LControlKey,- Keys.RControlKey,- Keys.LMenu,- Keys.RMenu,- Keys.LShiftKey,- Keys.RShiftKey- };-- /// <summary>- /// Store a reference to the hook delegate to prevent its garbage collection.- /// </summary>- private readonly HookProc _hookProc;-- public KeybindingService()- {- _hookProc = new HookProc(KeybindingHookProc);- }-- public void Start()- {- // Create low-level keyboard hook.- _ = SetWindowsHookEx(- HookType.KeyboardLowLevel,- _hookProc,- Process.GetCurrentProcess().MainModule.BaseAddress,- 0- );- }-- public void AddGlobalKeybinding(string keybindingString, Action callback)- {- var keybindingKeys = KeybindingHelper.ParseKeybindingString(keybindingString);-- var triggerKey = keybindingKeys.Last();- var keybinding = new Keybinding(keybindingKeys, callback);-- if (_keybindingsByTriggerKey.ContainsKey(triggerKey))- {- _keybindingsByTriggerKey[triggerKey].Add(keybinding);- return;- }-- _keybindingsByTriggerKey.Add(triggerKey, new List<Keybinding>() { keybinding });- }-- public void Reset()- {- _keybindingsByTriggerKey.Clear();- }-- private IntPtr KeybindingHookProc(int nCode, IntPtr wParam, IntPtr lParam)- {- var shouldPassThrough =- nCode != 0 || !((uint)wParam == WM_KEYDOWN || (uint)wParam == WM_SYSKEYDOWN);-- // If nCode is less than zero, the hook procedure must pass the hook notification to other- // applications via `CallNextHookEx`.- if (shouldPassThrough)- return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);-- // Get struct with details about keyboard input event.- var inputEvent = (LowLevelKeyboardInputEvent)Marshal.PtrToStructure(- lParam,- typeof(LowLevelKeyboardInputEvent)- );-- var pressedKey = inputEvent.Key;- var registeredKeybindings = _keybindingsByTriggerKey.GetValueOrDefault(pressedKey);-- // Forward the hook notification if no keybindings exist for the trigger key.- if (registeredKeybindings == null)- return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);-- var cachedKeyStates = new Dictionary<Keys, bool>();-- var matchedKeybindings = registeredKeybindings.Where(keybinding =>- {- return keybinding.KeyCombination.All(key =>- {- if (key == pressedKey)- return true;-- if (cachedKeyStates.ContainsKey(key))- return cachedKeyStates[key];-- return cachedKeyStates[key] = IsKeyDown(key);- });- });-- // If multiple keybindings match the user input, call the longest key combination.- var longestKeybinding = matchedKeybindings- .OrderByDescending(keybinding => keybinding.KeyCombination.Count)- .FirstOrDefault();-- if (longestKeybinding == null)- return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);-- // Get modifier keys that aren't part of the key combination.- var modifierKeysToReject = _modifierKeys.Where(- (modifierKey) =>- !longestKeybinding.KeyCombination.Contains(modifierKey) &&- !longestKeybinding.KeyCombination.Contains(GetGenericKey(modifierKey))- );-- var hasModifierKeysToReject = modifierKeysToReject.Any((modifierKey) =>- cachedKeyStates.ContainsKey(modifierKey)- ? cachedKeyStates[modifierKey]- : IsKeyDown(modifierKey)- );-- // This makes sure that if you press Control+Alt+1, and you have a keybinding of Alt+1, that- // it doesn't fire. Even though that all the keys satisfy it, the event has too many keys,- // so it shouldn't fire.- if (hasModifierKeysToReject)- return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);-- // Invoke the matched keybinding.- longestKeybinding.KeybindingProc();-- // Avoid forwarding the key input to other applications.- return new IntPtr(1);- }-- private static Keys GetGenericKey(Keys key)- {- return key switch- {- Keys.LMenu or Keys.RMenu => Keys.Alt,- Keys.LShiftKey or Keys.RShiftKey => Keys.Shift,- Keys.LControlKey or Keys.RControlKey => Keys.Control,- _ => key,- };- }-- /// <summary>- /// Get whether the given key is down. Check alternate versions of modifier keys.- /// </summary>- private static bool IsKeyDown(Keys key)- {- return key switch- {- Keys.Alt => IsKeyDownRaw(Keys.LMenu) || IsKeyDownRaw(Keys.RMenu),- Keys.Shift => IsKeyDownRaw(Keys.LShiftKey) || IsKeyDownRaw(Keys.RShiftKey),- Keys.Control => IsKeyDownRaw(Keys.LControlKey) || IsKeyDownRaw(Keys.RControlKey),- _ => IsKeyDownRaw(key),- };- }-- /// <summary>- /// Get whether the given key is down. If the high-order bit is 1, the key is down; otherwise, it is up.- /// </summary>- private static bool IsKeyDownRaw(Keys key)- {- return (GetKeyState(key) & 0x8000) == 0x8000;- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.csdeleted file mode 100644index 27fabe7a..00000000--- a/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.cs+++ /dev/null@@ -1,43 +0,0 @@-using System;-using Microsoft.VisualBasic.Devices;-using Vostok.Sys.Metrics.PerfCounters;--namespace GlazeWM.Infrastructure.WindowsApi-{- /// <summary>- /// Provides access to current memory statistics.- /// </summary>- public class MemoryStatsService : IDisposable- {- private readonly IPerformanceCounter<double> _availableBytes =- PerformanceCounterFactory.Default.CreateCounter("Memory", "Available Bytes");-- private readonly long _physicalBytes = (long)new ComputerInfo().TotalPhysicalMemory;-- /// <inheritdoc />- ~MemoryStatsService() => Dispose();-- /// <inheritdoc />- public void Dispose()- {- GC.SuppressFinalize(this);- _availableBytes.Dispose();- }-- /// <summary>- /// Returns the current memory utilization as a percentage.- /// </summary>- public double GetMemoryUsage()- {- try- {- var percent = (_physicalBytes - _availableBytes.Observe()) / _physicalBytes;- return percent * 100;- }- catch- {- return 0;- }- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/MouseEvents.cs b/GlazeWM.Infrastructure/WindowsApi/MouseEvents.csdeleted file mode 100644index 202b3009..00000000--- a/GlazeWM.Infrastructure/WindowsApi/MouseEvents.cs+++ /dev/null@@ -1,83 +0,0 @@-using System;-using System.Diagnostics;-using System.Reactive.Disposables;-using System.Reactive.Linq;-using System.Reactive.Subjects;-using System.Runtime.InteropServices;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Infrastructure.WindowsApi-{- public static class MouseEvents- {- public static IObservable<MouseMoveEvent> MouseMoves- {- get- {- var mouseEvents = new Subject<MouseMoveEvent>();-- var isRMouseDown = false;- var isLMouseDown = false;- var hookProc = new HookProc((nCode, wParam, lParam) =>- {- var details = (LowLevelMouseInputEventDetails)Marshal.PtrToStructure(- lParam,- typeof(LowLevelMouseInputEventDetails)- );-- // Check if mouse click is being held.- switch ((WMessages)wParam)- {- case WMessages.WM_RBUTTONUP:- isRMouseDown = false;- break;- case WMessages.WM_RBUTTONDOWN:- isRMouseDown = true;- break;- case WMessages.WM_LBUTTONUP:- isLMouseDown = false;- break;- case WMessages.WM_LBUTTONDOWN:- isLMouseDown = true;- break;- }-- var filteredEvent = new MouseMoveEvent(details.pt, isRMouseDown, isLMouseDown, details.TimeStamp);- mouseEvents.OnNext(filteredEvent);-- return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);- });-- var hookId = CreateHook(hookProc);-- return Observable.Create<MouseMoveEvent>(observer =>- {- var subscription = mouseEvents.Subscribe(- mouseEvent => observer.OnNext(mouseEvent)- );-- return Disposable.Create(() =>- {- // Unregister mouse hook on observable completion.- subscription.Dispose();- UnhookWindowsHookEx(hookId);- GC.KeepAlive(hookProc);- });- });- }- }-- /// <summary>- /// Create a low-level mouse hook.- /// </summary>- private static IntPtr CreateHook(HookProc proc)- {- return SetWindowsHookEx(- HookType.MouseLowLevel,- proc,- Process.GetCurrentProcess().MainModule.BaseAddress,- 0- );- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.cs b/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.csdeleted file mode 100644index 1aa0d0a2..00000000--- a/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.cs+++ /dev/null@@ -1,88 +0,0 @@-using System;-using System.Runtime.InteropServices;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common;-using GlazeWM.Infrastructure.WindowsApi;--public record MouseMoveEvent(- /// <summary>- /// (X,Y) location of mouse with 0,0 being the top-left corner of the main monitor- /// </summary>- Point Point,-- /// <summary>- /// Whether left-click is currently pressed.- /// </summary>- bool IsLMouseDown,-- /// <summary>- /// Whether right-click is currently pressed.- /// </summary>- bool IsRMouseDown,-- /// <summary>- /// The time stamp for this message, equivalent to what `GetMessageTime` would- /// return.- /// </summary>- int TimeStamp-) : Event(InfraEvent.MouseMove);--public enum WMessages-{- WM_MOUSEMOVE = 0x0200,- WM_LBUTTONDOWN = 0x201,- WM_LBUTTONUP = 0x202,- WM_RBUTTONDOWN = 0x0204,- WM_RBUTTONUP = 0x0205,- WM_KEYDOWN = 0x100,- WM_KEYUP = 0x101,- WH_KEYBOARD_LL = 13,- WH_MOUSE_LL = 14,-}-[StructLayout(LayoutKind.Sequential)]-public struct LowLevelMouseInputEvent-{- /// <summary>- /// Mouse event details.- /// </summary>- public LowLevelMouseInputEventDetails lParam;-- /// <summary>- /// Determines how to process the event.- /// </summary>- public int nCode;-- /// <summary>- /// Identify type of event.- /// </summary>- public WMessages wParam;-}--[StructLayout(LayoutKind.Sequential)]-public struct LowLevelMouseInputEventDetails-{- /// <summary>- /// (X,Y) location of mouse with 0,0 being the top-left corner of the main monitor- /// </summary>- public Point pt;-- /// <summary>- /// Mouse data.- /// </summary>- public int mouseData;-- /// <summary>- /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.- /// </summary>- public int Flags;-- /// <summary>- /// The time stamp for this message, equivalent to what GetMessageTime would return for this message.- /// </summary>- public int TimeStamp;-- /// <summary>- /// Additional information associated with the message.- /// </summary>- public IntPtr dwExtraInfo;-}diff --git a/GlazeWM.Infrastructure/WindowsApi/NetworkService.cs b/GlazeWM.Infrastructure/WindowsApi/NetworkService.csdeleted file mode 100644index c51e7b63..00000000--- a/GlazeWM.Infrastructure/WindowsApi/NetworkService.cs+++ /dev/null@@ -1,65 +0,0 @@-using System;-using System.Linq;-using System.Net.NetworkInformation;-using System.Text;-using Vanara.InteropServices;-using static Vanara.PInvoke.IpHlpApi;-using static Vanara.PInvoke.WlanApi;--namespace GlazeWM.Infrastructure.WindowsApi-{- public static class NetworkService- {- public static int GetWlanRSSI()- {- var hWlan = WlanOpenHandle();- WlanEnumInterfaces(hWlan, default, out var list);- if (list == null || list.dwNumberOfItems < 1)- return -1;- var primaryIntfGuid = list.InterfaceInfo[0].InterfaceGuid;-- // Get wireless connection details.- var getType = CorrespondingTypeAttribute.GetCorrespondingTypes(WLAN_INTF_OPCODE.wlan_intf_opcode_current_connection, CorrespondingAction.Get).FirstOrDefault();- var interfaceDetails = WlanQueryInterface(hWlan, primaryIntfGuid, WLAN_INTF_OPCODE.wlan_intf_opcode_current_connection, default, out var dataSize, out var data, out _);- if (interfaceDetails.Failed)- return -1;-- // Get RSSI signal strength of connection.- var connectionAttributes = (WLAN_CONNECTION_ATTRIBUTES)data.DangerousGetHandle().Convert(dataSize, getType);- return (int)connectionAttributes.wlanAssociationAttributes.wlanSignalQuality;- }-- public static bool PingTest()- {- try- {- // Use Google DNS servers to check if online.- var reply = new Ping().Send("8.8.8.8");- return reply.Status == IPStatus.Success;- }- catch (Exception)- {- return false;- }- }-- public static uint GetPrimaryAdapterID()- {- // Using Google DNS as example IP for IP to check against.- var dwDestAddr = BitConverter.ToUInt32(Encoding.ASCII.GetBytes("8.8.8.8"));- GetBestInterface(dwDestAddr, out var dwBestIfIndex);- return dwBestIfIndex;- }-- public static IP_ADAPTER_ADDRESSES GetPrimaryAdapter()- {- // Filter out active tunnels and VPNS.- return GetAdaptersAddresses(GetAdaptersAddressesFlags.GAA_FLAG_INCLUDE_GATEWAYS).FirstOrDefault(- r => r.OperStatus == IF_OPER_STATUS.IfOperStatusUp- && r.TunnelType == TUNNEL_TYPE.TUNNEL_TYPE_NONE- && r.FirstGatewayAddress != IntPtr.Zero- && r.IfIndex == GetPrimaryAdapterID()- );- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/Point.cs b/GlazeWM.Infrastructure/WindowsApi/Point.csdeleted file mode 100644index 93d8bd7f..00000000--- a/GlazeWM.Infrastructure/WindowsApi/Point.cs+++ /dev/null@@ -1,11 +0,0 @@-using System.Runtime.InteropServices;--namespace GlazeWM.Infrastructure.WindowsApi-{- [StructLayout(LayoutKind.Sequential)]- public struct Point- {- public int X;- public int Y;- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/RectDelta.cs b/GlazeWM.Infrastructure/WindowsApi/RectDelta.csdeleted file mode 100644index 6aef8540..00000000--- a/GlazeWM.Infrastructure/WindowsApi/RectDelta.cs+++ /dev/null@@ -1,33 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi-{- public class RectDelta- {- /// <summary>- /// The difference in x-coordinates of the upper-left corner of the rectangle.- /// </summary>- public int Left { get; }-- /// <summary>- /// The difference in y-coordinates of the upper-left corner of the rectangle.- /// </summary>- public int Top { get; }-- /// <summary>- /// The difference in x-coordinates of the lower-right corner of the rectangle.- /// </summary>- public int Right { get; }-- /// <summary>- /// The difference in y-coordinates of the lower-right corner of the rectangle.- /// </summary>- public int Bottom { get; }-- public RectDelta(int left, int top, int right, int bottom)- {- Left = left;- Right = right;- Top = top;- Bottom = bottom;- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SetWindowPosFlags.cs b/GlazeWM.Infrastructure/WindowsApi/SetWindowPosFlags.csdeleted file mode 100644index c4bfe10a..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SetWindowPosFlags.cs+++ /dev/null@@ -1,68 +0,0 @@-using System;--namespace GlazeWM.Infrastructure.WindowsApi-{- /// <summary>- /// Window sizing and positioning flags- /// </summary>- [Flags]- public enum SetWindowPosFlags : uint- {- /// <summary>Retains the current size (ignores the cx and cy parameters).</summary>- /// <remarks>SWP_NOSIZE</remarks>- IgnoreResize = 0x0001,- /// <summary>Retains the current position (ignores X and Y parameters).</summary>- /// <remarks>SWP_NOMOVE</remarks>- IgnoreMove = 0x0002,- /// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary>- /// <remarks>SWP_NOZORDER</remarks>- IgnoreZOrder = 0x0004,- /// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to- /// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent- /// window uncovered as a result of the window being moved. When this flag is set, the application must- /// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary>- /// <remarks>SWP_NOREDRAW</remarks>- DoNotRedraw = 0x0008,- /// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the- /// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter- /// parameter).</summary>- /// <remarks>SWP_NOACTIVATE</remarks>- DoNotActivate = 0x0010,- /// <summary>Draws a frame (defined in the window's class description) around the window.</summary>- /// <remarks>SWP_DRAWFRAME</remarks>- DrawFrame = 0x0020,- /// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to- /// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE- /// is sent only when the window's size is being changed.</summary>- /// <remarks>SWP_FRAMECHANGED</remarks>- FrameChanged = 0x0020,- /// <summary>Displays the window.</summary>- /// <remarks>SWP_SHOWWINDOW</remarks>- ShowWindow = 0x0040,- /// <summary>Hides the window.</summary>- /// <remarks>SWP_HIDEWINDOW</remarks>- HideWindow = 0x0080,- /// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid- /// contents of the client area are saved and copied back into the client area after the window is sized or- /// repositioned.</summary>- /// <remarks>SWP_NOCOPYBITS</remarks>- DoNotCopyBits = 0x0100,- /// <summary>Does not change the owner window's position in the Z order.</summary>- /// <remarks>SWP_NOOWNERZORDER</remarks>- DoNotChangeOwnerZOrder = 0x0200,- /// <summary>Same as the SWP_NOOWNERZORDER flag.</summary>- /// <remarks>SWP_NOREPOSITION</remarks>- DoNotReposition = 0x0200,- /// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary>- /// <remarks>SWP_NOSENDCHANGING</remarks>- DoNotSendChangingEvent = 0x0400,- /// <summary>Prevents generation of the WM_SYNCPAINT message.</summary>- /// <remarks>SWP_DEFERERASE</remarks>- DeferErase = 0x2000,- /// <summary>If the calling thread and the thread that owns the window are attached to different input queues,- /// the system posts the request to the thread that owns the window. This prevents the calling thread from- /// blocking its execution while other threads process the request.</summary>- /// <remarks>SWP_ASYNCWINDOWPOS</remarks>- AsynchronousWindowPosition = 0x4000,- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemEvents.cs b/GlazeWM.Infrastructure/WindowsApi/SystemEvents.csdeleted file mode 100644index 12325fb8..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemEvents.cs+++ /dev/null@@ -1,15 +0,0 @@-using System;-using System.Reactive.Linq;-using GlazeWM.Infrastructure.Common.Events;--namespace GlazeWM.Infrastructure.WindowsApi-{- public static class SystemEvents- {- public static IObservable<DisplaySettingsChangedEvent> DisplaySettingsChanged =>- Observable.FromEventPattern<EventHandler, EventArgs>(- handler => Microsoft.Win32.SystemEvents.DisplaySettingsChanged += handler,- handler => Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= handler- ).Select((_) => new DisplaySettingsChangedEvent());- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemMediaInformation.cs b/GlazeWM.Infrastructure/WindowsApi/SystemMediaInformation.csdeleted file mode 100755index da1a41e0..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemMediaInformation.cs+++ /dev/null@@ -1,69 +0,0 @@--using System;-using Windows.Media.Control;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class SystemMediaInformation- {- private readonly GlobalSystemMediaTransportControlsSessionManager _gsmtcsManager;- private GlobalSystemMediaTransportControlsSession _currentSession;-- public event EventHandler<CurrentMediaPlaybackChangedEventArgs> CurrentMediaPlaybackChanged;- public event EventHandler<CurrentMediaChangedEventArgs> CurrentMediaChanged;-- public SystemMediaInformation()- {- _gsmtcsManager = GlobalSystemMediaTransportControlsSessionManager- .RequestAsync()- .GetAwaiter()- .GetResult();- _gsmtcsManager.CurrentSessionChanged += OnCurrentSessionChanged;- _currentSession = _gsmtcsManager.GetCurrentSession();- _currentSession.MediaPropertiesChanged += OnMediaPropertiesChanged;- var mediaProps = _currentSession- .TryGetMediaPropertiesAsync()- .GetAwaiter()- .GetResult();- CurrentMediaChanged?.Invoke(- this, new CurrentMediaChangedEventArgs- {- Title = mediaProps.Title,- AlbumTitle = mediaProps.AlbumTitle,- Artist = mediaProps.Artist- }- );- var currentState = _currentSession.GetPlaybackInfo().PlaybackStatus;- CurrentMediaPlaybackChanged?.Invoke(- this, new CurrentMediaPlaybackChangedEventArgs { PlaybackState = currentState }- );- }-- private void OnCurrentSessionChanged(GlobalSystemMediaTransportControlsSessionManager sender, CurrentSessionChangedEventArgs args)- {- _currentSession.MediaPropertiesChanged -= OnMediaPropertiesChanged;- _currentSession = _gsmtcsManager.GetCurrentSession();- _currentSession.MediaPropertiesChanged += OnMediaPropertiesChanged;- var mediaProps = _currentSession- .TryGetMediaPropertiesAsync()- .GetAwaiter()- .GetResult();- CurrentMediaChanged?.Invoke(- this, new CurrentMediaChangedEventArgs- {- Title = mediaProps.Title,- AlbumTitle = mediaProps.AlbumTitle,- Artist = mediaProps.Artist- }- );- }-- private void OnMediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args)- {- var newState = _currentSession.GetPlaybackInfo().PlaybackStatus;- CurrentMediaPlaybackChanged?.Invoke(- this, new CurrentMediaPlaybackChangedEventArgs { PlaybackState = newState }- );- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemSettings.cs b/GlazeWM.Infrastructure/WindowsApi/SystemSettings.csdeleted file mode 100644index a908e6ad..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemSettings.cs+++ /dev/null@@ -1,22 +0,0 @@-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Infrastructure.WindowsApi-{- public static class SystemSettings- {- /// <summary>- /// Modify global setting for whether window transition animations are enabled.- /// </summary>- public static void SetWindowAnimationsEnabled(bool enabled)- {- var animationInfo = AnimationInfo.Create(enabled);-- SystemParametersInfo(- SystemParametersInfoFlags.SetAnimation,- animationInfo.CallbackSize,- ref animationInfo,- 0- );- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemTrayIcon.cs b/GlazeWM.Infrastructure/WindowsApi/SystemTrayIcon.csdeleted file mode 100644index ef2e6524..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemTrayIcon.cs+++ /dev/null@@ -1,54 +0,0 @@-using System;-using System.Drawing;-using System.Reflection;-using System.Windows.Forms;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class SystemTrayIcon- {- private readonly SystemTrayIconConfig _config;- private NotifyIcon _notifyIcon { get; set; }-- public SystemTrayIcon(SystemTrayIconConfig config)- {- _config = config;- }-- public void Show()- {- var contextMenuStrip = new ContextMenuStrip();-- foreach (var action in _config.Actions)- {- // Create an entry in the context menu that is shown on click.- contextMenuStrip.Items.Add(- action.Key,- null,- (object sender, EventArgs e) => action.Value()- );- }-- // Get the embedded icon resource from the entry assembly.- var assembly = Assembly.GetEntryAssembly();- using var stream = assembly.GetManifestResourceStream(_config.IconResourceName);-- _notifyIcon = new NotifyIcon- {- Icon = new Icon(stream),- ContextMenuStrip = contextMenuStrip,- Text = _config.HoverText,- Visible = true- };- }-- public void Remove()- {- if (_notifyIcon is null)- return;-- _notifyIcon.Visible = false;- _notifyIcon.Dispose();- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemTrayIconConfig.cs b/GlazeWM.Infrastructure/WindowsApi/SystemTrayIconConfig.csdeleted file mode 100644index 3330e951..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemTrayIconConfig.cs+++ /dev/null@@ -1,12 +0,0 @@-using System;-using System.Collections.Generic;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class SystemTrayIconConfig- {- public string HoverText { get; init; }- public string IconResourceName { get; init; }- public Dictionary<string, Action> Actions { get; init; }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemVolumeInformation.cs b/GlazeWM.Infrastructure/WindowsApi/SystemVolumeInformation.csdeleted file mode 100755index e9990ec9..00000000--- a/GlazeWM.Infrastructure/WindowsApi/SystemVolumeInformation.cs+++ /dev/null@@ -1,98 +0,0 @@-using System;-using System.Runtime.InteropServices;-using Vanara.PInvoke;-using static Vanara.PInvoke.CoreAudio;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class SystemVolumeInformation : IAudioEndpointVolumeCallback, IMMNotificationClient- {- private readonly IMMDeviceEnumerator _deviceEnum = new();- private IMMDevice _defaultDevice;- private IAudioEndpointVolume _endPointVolume;-- public event EventHandler<VolumeInformation> VolumeChanged;-- public SystemVolumeInformation()- {- _deviceEnum.RegisterEndpointNotificationCallback(this);- _defaultDevice = _deviceEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);-- _defaultDevice.Activate(typeof(IAudioEndpointVolume).GUID, 0, null, out var epVol);- _endPointVolume = epVol as IAudioEndpointVolume;- _endPointVolume.RegisterControlChangeNotify(this);-- VolumeChanged?.Invoke(this, new VolumeInformation- {- Volume = (int)(_endPointVolume.GetMasterVolumeLevelScalar() * 100),- Muted = _endPointVolume.GetMute()- });- }- public VolumeInformation GetVolumeInformation()- {- return new()- {- Volume = (int)(_endPointVolume.GetMasterVolumeLevelScalar() * 100),- Muted = _endPointVolume.GetMute()- };- }-- public HRESULT OnNotify(IntPtr pNotify)- {- var notificationData = Marshal.PtrToStructure<AUDIO_VOLUME_NOTIFICATION_DATA>(pNotify);-- var channelVolumesOffset = Marshal.OffsetOf<AUDIO_VOLUME_NOTIFICATION_DATA>("afChannelVolumes");- var firstChannelVolumesMember = (IntPtr)((long)pNotify + (long)channelVolumesOffset);-- var channelVolumes = new float[notificationData.nChannels];-- for (var i = 0; i < notificationData.nChannels; i++)- {- channelVolumes[i] = Marshal.PtrToStructure<float>(firstChannelVolumesMember);- }-- VolumeChanged?.Invoke(this, new VolumeInformation- {- Volume = (int)(notificationData.fMasterVolume * 100),- Muted = notificationData.bMuted- });-- return HRESULT.S_OK;- }-- public HRESULT OnDefaultDeviceChanged(EDataFlow flow, ERole role, string pwstrDefaultDeviceId)- {- if (role.Equals(ERole.eMultimedia))- {- _endPointVolume.UnregisterControlChangeNotify(this);-- _defaultDevice = _deviceEnum.GetDevice(pwstrDefaultDeviceId);- _defaultDevice.Activate(typeof(IAudioEndpointVolume).GUID, 0, null, out var epVol);-- _endPointVolume = epVol as IAudioEndpointVolume;- _endPointVolume.RegisterControlChangeNotify(this);- }- return HRESULT.S_OK;- }-- public HRESULT OnDeviceStateChanged(string pwstrDeviceId, DEVICE_STATE dwNewState)- {- return HRESULT.S_OK;- }-- public HRESULT OnDeviceAdded(string pwstrDeviceId)- {- return HRESULT.S_OK;- }-- public HRESULT OnDeviceRemoved(string pwstrDeviceId)- {- return HRESULT.S_OK;- }-- public HRESULT OnPropertyValueChanged(string pwstrDeviceId, Ole32.PROPERTYKEY key)- {- return HRESULT.S_OK;- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/VolumeChangedEventArgs.cs b/GlazeWM.Infrastructure/WindowsApi/VolumeChangedEventArgs.csdeleted file mode 100755index b804b25e..00000000--- a/GlazeWM.Infrastructure/WindowsApi/VolumeChangedEventArgs.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi-{- public class VolumeInformation- {- public int Volume { get; set; }- public bool Muted { get; set; }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowEventService.cs b/GlazeWM.Infrastructure/WindowsApi/WindowEventService.csdeleted file mode 100644index 53423178..00000000--- a/GlazeWM.Infrastructure/WindowsApi/WindowEventService.cs+++ /dev/null@@ -1,73 +0,0 @@-using System;-using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Common.Events;-using GlazeWM.Infrastructure.WindowsApi.Enums;-using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;--namespace GlazeWM.Infrastructure.WindowsApi-{- public class WindowEventService- {- private readonly Bus _bus;-- /// <summary>- /// Store a reference to the hook delegate to prevent its garbage collection.- /// </summary>- private readonly WindowEventProc _hookProc;- private const int CHILDID_SELF = 0;-- public WindowEventService(Bus bus)- {- _bus = bus;- _hookProc = new WindowEventProc(WindowEventHookProc);- }-- public void Start()- {- SetWinEventHook(EventConstant.LocationChange, EventConstant.LocationChange, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.Destroy, EventConstant.Hide, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.MinimizeStart, EventConstant.MinimizeEnd, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.MoveSizeEnd, EventConstant.MoveSizeEnd, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.Foreground, EventConstant.Foreground, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.LocationChange, EventConstant.NameChange, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.Cloaked, EventConstant.Uncloaked, IntPtr.Zero, _hookProc, 0, 0, 0);- SetWinEventHook(EventConstant.Uncloaked, EventConstant.Uncloaked, IntPtr.Zero, _hookProc, 0, 0, 0);- }-- private void WindowEventHookProc(- IntPtr hWinEventHook,- EventConstant eventType,- IntPtr hwnd,- ObjectIdentifier idObject,- int idChild,- uint dwEventThread,- uint dwmsEventTime)- {- // Whether the event is actually associated with a window object (instead of a UI control).- var isWindowEvent = idChild == CHILDID_SELF && idObject == ObjectIdentifier.Window- && hwnd != IntPtr.Zero;-- if (!isWindowEvent)- return;-- Event eventToRaise = eventType switch- {- EventConstant.LocationChange => new WindowLocationChangedEvent(hwnd),- EventConstant.Foreground => new WindowFocusedEvent(hwnd),- EventConstant.MinimizeStart => new WindowMinimizedEvent(hwnd),- EventConstant.MinimizeEnd => new WindowMinimizeEndedEvent(hwnd),- EventConstant.MoveSizeEnd => new WindowMovedOrResizedEvent(hwnd),- EventConstant.Destroy => new WindowDestroyedEvent(hwnd),- EventConstant.Show => new WindowShownEvent(hwnd),- EventConstant.NameChange => new WindowTitleChangedEvent(hwnd),- EventConstant.Hide => new WindowHiddenEvent(hwnd),- EventConstant.Cloaked => new WindowHiddenEvent(hwnd),- EventConstant.Uncloaked => new WindowShownEvent(hwnd),- _ => null,- };-- if (eventToRaise is not null)- _bus.EmitAsync((dynamic)eventToRaise);- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowRect.cs b/GlazeWM.Infrastructure/WindowsApi/WindowRect.csdeleted file mode 100644index 8fd04a61..00000000--- a/GlazeWM.Infrastructure/WindowsApi/WindowRect.cs+++ /dev/null@@ -1,90 +0,0 @@-namespace GlazeWM.Infrastructure.WindowsApi-{- public struct Rect- {- /// <summary>- /// The x-coordinate of the upper-left corner of the rectangle.- /// </summary>- public int Left { get; set; }-- /// <summary>- /// The y-coordinate of the upper-left corner of the rectangle.- /// </summary>- public int Top { get; set; }-- /// <summary>- /// The x-coordinate of the lower-right corner of the rectangle.- /// </summary>- public int Right { get; set; }-- /// <summary>- /// The y-coordinate of the lower-right corner of the rectangle.- /// </summary>- public int Bottom { get; set; }-- public int X => Left;-- public int Y => Top;-- public int Width => Right - Left;-- public int Height => Bottom - Top;-- /// <summary>- /// Creates a new `WindowRect` from coordinates of its upper-left and lower-right corners.- /// </summary>- public static Rect FromLTRB(int left, int top, int right, int bottom)- {- return new Rect()- {- Left = left,- Right = right,- Top = top,- Bottom = bottom,- };- }-- /// <summary>- /// Creates a new `WindowRect` from its X/Y coordinates and size.- /// </summary>- public static Rect FromXYCoordinates(int x, int y, int width, int height)- {- return new Rect()- {- Left = x,- Right = x + width,- Top = y,- Bottom = y + height,- };- }-- public Rect TranslateToCoordinates(int x, int y)- {- return FromXYCoordinates(x, y, Width, Height);- }-- public Rect TranslateToCenter(Rect outerRect)- {- return TranslateToCoordinates(- outerRect.X + (outerRect.Width / 2) - (Width / 2),- outerRect.Y + (outerRect.Height / 2) - (Height / 2)- );- }- public Point GetCenterPoint()- {- return new Point- {- X = X + (Width / 2),- Y = Y + (Height / 2),- };- }- public Point GetCenterPoint(Rect rect)- {- return new Point- {- X = rect.X + (rect.Width / 2),- Y = rect.Y + (rect.Height / 2),- };- }- }-}diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs b/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.csdeleted file mode 100644index 781bf002..00000000--- a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs+++ /dev/null@@ -1,517 +0,0 @@-using System;-using System.IO;-using System.Runtime.InteropServices;-using System.Text;-using System.Windows.Forms;-using GlazeWM.Infrastructure.WindowsApi.Enums;--namespace GlazeWM.Infrastructure.WindowsApi-{- public static class WindowsApiService- {- [Flags]- public enum SetWindowPosFlags : uint- {- NoSize = 0x0001,- NoMove = 0x0002,- NoZOrder = 0x0004,- NoRedraw = 0x0008,- NoActivate = 0x0010,- FrameChanged = 0x0020,- ShowWindow = 0x0040,- HideWindow = 0x0080,- NoCopyBits = 0x0100,- NoOwnerZOrder = 0x0200,- NoSendChanging = 0x0400,- DeferErase = 0x2000,- AsyncWindowPos = 0x4000- }-- /// <summary>- /// Flags that can be passed as `hWndInsertAfter` to `SetWindowPos`.- /// </summary>- public enum ZOrderFlags- {- /// <summary>- /// Places the window above all non-topmost windows (that is, behind all topmost- /// windows). This flag has no effect if the window is already a non-topmost window.- /// </summary>- NoTopMost = -2,- /// <summary>- /// Places the window above all non-topmost windows. The window maintains its- /// topmost position even when it is deactivated.- /// </summary>- TopMost = -1,- /// <summary>- /// Places the window at the top of the Z order.- /// </summary>- Top = 0,- /// <summary>- /// Places the window at the bottom of the Z order.- /// </summary>- Bottom = 1,- }-- /// <summary>- /// Window styles- /// </summary>- [Flags]- public enum WindowStyles : uint- {- Overlapped = 0x00000000,- Tiled = Overlapped,- TabStop = 0x00010000,- MaximizeBox = 0x00010000,- Group = 0x00020000,- MinimizeBox = 0x00020000,- ThickFrame = 0x00040000,- SizeBox = ThickFrame,- SysMenu = 0x00080000,- HScroll = 0x00100000,- VScroll = 0x00200000,- DlgFrame = 0x00400000,- Border = 0x00800000,- Capion = Border | DlgFrame,- TiledWindow = OverlappedWindow,- OverlappedWindow = Overlapped | Capion | SysMenu | ThickFrame | MinimizeBox | MaximizeBox,- Maximize = 0x01000000,- ClipChildren = 0x02000000,- ClipSiblings = 0x04000000,- Disabled = 0x08000000,- Visible = 0x10000000,- Minimize = 0x20000000,- Iconic = Minimize,- Child = 0x40000000,- ChildWindow = Child,- Popup = 0x80000000,- PopupWindow = Popup | Border | SysMenu- }-- /// <summary>- /// Extended window styles- /// </summary>- [Flags]- public enum WindowStylesEx : uint- {- Left = 0x0000,- LtrReading = 0x0000,- RightScrollbar = 0x0000,- DlgModalFrame = 0x0001,- NoParentNotify = 0x0004,- TopMost = 0x0008,- AcceptFiles = 0x0010,- Transparent = 0x0020,- MdiChild = 0x0040,- ToolWindow = 0x0080,- WindowEdge = 0x0100,- PaletteWindow = WindowEdge | ToolWindow | TopMost,- ClientEdge = 0x0200,- OverlappedWindow = WindowEdge | ClientEdge,- ContextHelp = 0x0400,- Right = 0x1000,- RtlReading = 0x2000,- LeftScrollbar = 0x4000,- ControlParent = 0x10000,- StaticEdge = 0x20000,- AppWindow = 0x40000,- Layered = 0x00080000,- NoInheritLayout = 0x00100000,- LayoutRtl = 0x00400000,- Composited = 0x02000000,- NoActivate = 0x08000000- }-- [Flags]- public enum DwmWindowAttribute : uint- {- NcRenderingEnabled = 1,- NcRenderingPolicy,- TransitionsForceDisabled,- AllowNcPaint,- CaptionButtonBounds,- NonClientRtlLayout,- ForceIconicRepresentation,- Flip3DPolicy,- ExtendedFrameBounds,- HasIconicBitmap,- DisallowPeek,- ExcludedFromPeek,- Cloak,- Cloaked,- FreezeRepresentation,- Last- }-- public const int GWLSTYLE = -16;- public const int GWLEXSTYLE = -20;-- public enum GW : uint- {- Owner = 4,- }-- public delegate bool EnumWindowsDelegate(IntPtr hWnd, int lParam);-- [DllImport("user32.dll", EntryPoint = "EnumWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]- public static extern bool EnumWindows(EnumWindowsDelegate enumCallback, IntPtr lParam);-- [DllImport("user32.dll")]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool IsWindowVisible(IntPtr hWnd);-- [DllImport("user32.dll", EntryPoint = "GetWindowLong")]- private static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int index);-- [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]- private static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int index);-- public static IntPtr GetWindowLongPtr(IntPtr hWnd, int index)- {- return Environment.Is64BitProcess- ? GetWindowLongPtr64(hWnd, index)- : GetWindowLongPtr32(hWnd, index);- }-- [DllImport("user32.dll", EntryPoint = "SetWindowLong")]- private static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int index, IntPtr newLong);-- [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]- private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int index, IntPtr newLong);-- public static IntPtr SetWindowLongPtr(IntPtr hWnd, int index, IntPtr newLong)- {- return Environment.Is64BitProcess- ? SetWindowLongPtr64(hWnd, index, newLong)- : SetWindowLongPtr32(hWnd, index, newLong);- }-- [DllImport("user32.dll", SetLastError = true)]- public static extern bool SetWindowPos(- IntPtr hWnd,- IntPtr hWndInsertAfter,- int x,- int y,- int cx,- int cy,- SetWindowPosFlags uFlags);-- [DllImport("user32.dll")]- public static extern IntPtr BeginDeferWindowPos(int nNumWindows);-- [DllImport("user32.dll")]- public static extern IntPtr DeferWindowPos(- IntPtr hWinPosInfo,- IntPtr hWnd,- [Optional] IntPtr hWndInsertAfter,- int x,- int y,- int cx,- int cy,- SetWindowPosFlags uFlags);-- [DllImport("user32.dll")]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool EndDeferWindowPos(IntPtr hWinPosInfo);-- [DllImport("user32.dll")]- public static extern IntPtr GetDesktopWindow();-- [DllImport("user32.dll")]- public static extern IntPtr GetForegroundWindow();-- [DllImport("user32.dll")]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool SetForegroundWindow(IntPtr hWnd);-- [DllImport("user32.dll")]- public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint);-- [DllImport("user32.dll")]- public static extern bool SetFocus(IntPtr hWnd);-- [DllImport("user32.dll")]- public static extern IntPtr WindowFromPoint(Point Point);-- [DllImport("user32.dll")]- public static extern IntPtr GetParent(IntPtr hWnd);-- [DllImport("user32.dll")]- public static extern bool SetCursorPos(int x, int y);-- /// <summary>- /// Params that can be passed to `ShowWindow`. Only the subset of flags relevant to- /// this application are included.- /// </summary>- public enum ShowWindowFlags : uint- {- Minimize = 2,- Maximize = 3,- ShowNoActivate = 8,- Restore = 9,- ShowDefault = 10,- }-- [DllImport("user32.dll")]- public static extern bool ShowWindowAsync(IntPtr hWnd, ShowWindowFlags flags);-- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]- public static extern int GetWindowTextLength(IntPtr hWnd);-- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]- public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);-- [DllImport("user32.dll", SetLastError = true)]- public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);-- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]- public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);-- [DllImport("user32.dll")]- public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);-- /// <summary>- /// Contains information about the placement of a window on the screen.- /// </summary>- [StructLayout(LayoutKind.Sequential)]- public struct WindowPlacement- {- /// <summary>- /// The length of the structure, in bytes. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).- /// </summary>- public int Length;-- /// <summary>- /// Specifies flags that control the position of the minimized window and the method by which the window is restored.- /// </summary>- public int Flags;-- /// <summary>- /// The current show state of the window.- /// </summary>- public ShowWindowFlags ShowCommand;-- /// <summary>- /// The coordinates of the window's upper-left corner when the window is minimized.- /// </summary>- public Point MinPosition;-- /// <summary>- /// The coordinates of the window's upper-left corner when the window is maximized.- /// </summary>- public Point MaxPosition;-- /// <summary>- /// The window's coordinates when the window is in the restored position.- /// </summary>- public Rect NormalPosition;- }-- [DllImport("user32.dll", SetLastError = true)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement windowPlacement);-- [DllImport("user32.dll")]- public static extern IntPtr GetWindow(IntPtr hWnd, GW uCmd);-- [DllImport("dwmapi.dll")]- public static extern int DwmGetWindowAttribute(IntPtr hwnd, DwmWindowAttribute dwAttribute, out bool pvAttribute, int cbAttribute);-- [DllImport("user32.dll")]- public static extern IntPtr GetShellWindow();-- public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);-- public enum HookType- {- KeyboardLowLevel = 13,- MouseLowLevel = 14- }-- /// <summary>- /// Contains information about a low-level keyboard input event.- /// </summary>- [StructLayout(LayoutKind.Sequential)]- public struct LowLevelKeyboardInputEvent- {- /// <summary>- /// A virtual-key code. The code must be a value in the range 1 to 254.- /// </summary>- public int VirtualCode;-- /// <summary>- /// The `VirtualCode` converted to `Keys` for better usability.- /// </summary>- public Keys Key => (Keys)VirtualCode;-- /// <summary>- /// A hardware scan code for the key.- /// </summary>- public int HardwareScanCode;-- /// <summary>- /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.- /// </summary>- public int Flags;-- /// <summary>- /// The time stamp for this message, equivalent to what GetMessageTime would return for this message.- /// </summary>- public int TimeStamp;-- /// <summary>- /// Additional information associated with the message.- /// </summary>- public IntPtr AdditionalInformation;- }-- [DllImport("user32.dll")]- public static extern IntPtr SetWindowsHookEx(HookType hookType, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hMod, int dwThreadId);-- [DllImport("user32.dll")]- public static extern IntPtr CallNextHookEx([Optional] IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);-- [DllImport("user32.dll")]- public static extern bool UnhookWindowsHookEx(IntPtr hhk);-- [DllImport("user32.dll")]- public static extern int GetKeyboardState(byte[] pbKeyState);-- [DllImport("user32.dll")]- public static extern short GetKeyState(Keys nVirtKey);-- [DllImport("user32.dll", EntryPoint = "keybd_event")]- public static extern void KeybdEvent(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);-- [DllImport("User32.dll")]- public static extern short GetAsyncKeyState(Keys key);-- public delegate void WindowEventProc(IntPtr hWinEventHook, EventConstant eventType, IntPtr hwnd, ObjectIdentifier idObject, int idChild, uint dwEventThread, uint dwmsEventTime);-- [DllImport("user32.dll")]- public static extern IntPtr SetWinEventHook(EventConstant eventMin, EventConstant eventMax, IntPtr hmodWinEventProc, WindowEventProc lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);-- /// <summary>- /// Message types that can be passed to `SendMessage`. Only the subset of types relevant to- /// this application are included.- /// </summary>- public enum SendMessageType : uint- {- Close = 0x0010,- }-- [DllImport("user32.dll", CharSet = CharSet.Auto)]- public static extern IntPtr SendNotifyMessage(IntPtr hWnd, SendMessageType msg, IntPtr wParam, IntPtr lParam);-- [DllImport("user32.dll", SetLastError = true)]- public static extern bool IsProcessDPIAware();-- public enum DpiAwarenessContext- {- UnawareGdiScaled = -5,- PerMonitorAwareV2 = -4,- PerMonitorAware = -3,- SystemAware = -2,- Unaware = -1,- Undefined = 0- }-- [DllImport("user32.dll", SetLastError = true)]- public static extern int SetProcessDpiAwarenessContext(DpiAwarenessContext value);-- [DllImport("user32.dll", SetLastError = true)]- public static extern uint GetDpiForWindow(IntPtr hWnd);-- [DllImport("user32.dll", SetLastError = true)]- public static extern bool AdjustWindowRectEx(ref Rect lpRect, WindowStyles dwStyle, [MarshalAs(UnmanagedType.Bool)] bool bMenu, WindowStylesEx dwExStyle);-- [DllImport("user32.dll", SetLastError = true)]- public static extern bool AdjustWindowRect(ref Rect lpRect, WindowStyles dwStyle, [MarshalAs(UnmanagedType.Bool)] bool bMenu);-- [DllImport("user32.dll", SetLastError = true)]- public static extern bool AdjustWindowRectExForDpi(ref Rect lpRect, WindowStyles dwStyle, [MarshalAs(UnmanagedType.Bool)] bool bMenu, WindowStylesEx dwExStyle, uint dpi);-- public enum DpiType- {- Effective = 0,- Angular = 1,- Raw = 2,- }-- [DllImport("Shcore.dll")]- public static extern IntPtr GetDpiForMonitor(IntPtr hmonitor, DpiType dpiType, out uint dpiX, out uint dpiY);-- public enum MonitorFromPointFlags : uint- {- DefaultToNearest = 2,- }-- [DllImport("User32.dll")]- public static extern IntPtr MonitorFromPoint(Point pt, MonitorFromPointFlags dwFlags);-- [DllImport("kernel32.dll")]- public static extern bool GetSystemPowerStatus(out SystemPowerStatus lpSystemPowerStatus);-- [StructLayout(LayoutKind.Sequential)]- public struct SystemPowerStatus- {- public byte ACLineStatus;- public byte BatteryFlag;- public byte BatteryLifePercent;- public byte SystemStatusFlag;- public uint BatteryLifeTime;- public uint BatteryFullLifeTime;- }-- [DllImport("dwmapi.dll")]- public static extern int DwmSetWindowAttribute(IntPtr handle, uint attribute, ref uint value, uint size);-- [StructLayout(LayoutKind.Sequential)]- public struct AnimationInfo- {- public uint CallbackSize;- public int MinAnimate;-- public bool IsEnabled- {- readonly get => MinAnimate != 0;- set => MinAnimate = value ? 1 : 0;- }-- public static AnimationInfo Create(bool isEnabled)- {- return new()- {- IsEnabled = isEnabled,- CallbackSize = (uint)Marshal.SizeOf(typeof(AnimationInfo))- };- }- }-- public enum SystemParametersInfoFlags : uint- {- GetAnimation = 72,- SetAnimation = 73,- }-- [DllImport("User32.dll", SetLastError = true)]- public static extern bool SystemParametersInfo(SystemParametersInfoFlags uiAction, uint uiParam, ref AnimationInfo pvParam, uint fWinIni);-- [DllImport("kernel32.dll")]- internal static extern bool AttachConsole(uint dwProcessId);-- public static bool AttachConsoleToParentProcess()- {- const uint AttachParentProcess = 0x0ffffffff;- var result = AttachConsole(AttachParentProcess);-- var streamWriter = new StreamWriter(Console.OpenStandardOutput())- {- AutoFlush = true- };- Console.SetOut(streamWriter);- Console.SetError(streamWriter);-- return result;- }- }-}diff --git a/GlazeWM.sln b/GlazeWM.slndeleted file mode 100644index 7e09f53a..00000000--- a/GlazeWM.sln+++ /dev/null@@ -1,71 +0,0 @@-Microsoft Visual Studio Solution File, Format Version 12.00-# Visual Studio Version 17-VisualStudioVersion = 17.3.32922.545-MinimumVisualStudioVersion = 10.0.40219.1-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.Domain", "GlazeWM.Domain\GlazeWM.Domain.csproj", "{D7741551-9A1D-4357-9571-991C6FDB1906}"-EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.Bar", "GlazeWM.Bar\GlazeWM.Bar.csproj", "{F038C06D-2085-40EA-AEE9-A517231656FC}"-EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.Infrastructure", "GlazeWM.Infrastructure\GlazeWM.Infrastructure.csproj", "{9FA1F058-7ED2-4BC3-B3BC-C8C43B3C62C5}"-EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.App", "GlazeWM.App\GlazeWM.App.csproj", "{86A11BD4-B17A-4422-9D3A-D2516A730BFE}"-EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.App.IpcServer", "GlazeWM.App.IpcServer\GlazeWM.App.IpcServer.csproj", "{BBD11CB5-FDF2-4BD5-B3F6-8B75BC3AFD79}"-EndProject-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{877CCE5C-94A9-4CE4-8A29-164179ADE9D3}"- ProjectSection(SolutionItems) = preProject- .editorconfig = .editorconfig- EndProjectSection-EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlazeWM.App.WindowManager", "GlazeWM.App.WindowManager\GlazeWM.App.WindowManager.csproj", "{D160D151-C030-4A0E-A805-6E28B533F03F}"-EndProject-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}"-EndProject-Global- GlobalSection(SolutionConfigurationPlatforms) = preSolution- Debug|Any CPU = Debug|Any CPU- Release|Any CPU = Release|Any CPU- EndGlobalSection- GlobalSection(ProjectConfigurationPlatforms) = postSolution- {D7741551-9A1D-4357-9571-991C6FDB1906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {D7741551-9A1D-4357-9571-991C6FDB1906}.Debug|Any CPU.Build.0 = Debug|Any CPU- {D7741551-9A1D-4357-9571-991C6FDB1906}.Release|Any CPU.ActiveCfg = Release|Any CPU- {D7741551-9A1D-4357-9571-991C6FDB1906}.Release|Any CPU.Build.0 = Release|Any CPU- {F038C06D-2085-40EA-AEE9-A517231656FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {F038C06D-2085-40EA-AEE9-A517231656FC}.Debug|Any CPU.Build.0 = Debug|Any CPU- {F038C06D-2085-40EA-AEE9-A517231656FC}.Release|Any CPU.ActiveCfg = Release|Any CPU- {F038C06D-2085-40EA-AEE9-A517231656FC}.Release|Any CPU.Build.0 = Release|Any CPU- {9FA1F058-7ED2-4BC3-B3BC-C8C43B3C62C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {9FA1F058-7ED2-4BC3-B3BC-C8C43B3C62C5}.Debug|Any CPU.Build.0 = Debug|Any CPU- {9FA1F058-7ED2-4BC3-B3BC-C8C43B3C62C5}.Release|Any CPU.ActiveCfg = Release|Any CPU- {9FA1F058-7ED2-4BC3-B3BC-C8C43B3C62C5}.Release|Any CPU.Build.0 = Release|Any CPU- {86A11BD4-B17A-4422-9D3A-D2516A730BFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {86A11BD4-B17A-4422-9D3A-D2516A730BFE}.Debug|Any CPU.Build.0 = Debug|Any CPU- {86A11BD4-B17A-4422-9D3A-D2516A730BFE}.Release|Any CPU.ActiveCfg = Release|Any CPU- {86A11BD4-B17A-4422-9D3A-D2516A730BFE}.Release|Any CPU.Build.0 = Release|Any CPU- {BBD11CB5-FDF2-4BD5-B3F6-8B75BC3AFD79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {BBD11CB5-FDF2-4BD5-B3F6-8B75BC3AFD79}.Debug|Any CPU.Build.0 = Debug|Any CPU- {BBD11CB5-FDF2-4BD5-B3F6-8B75BC3AFD79}.Release|Any CPU.ActiveCfg = Release|Any CPU- {BBD11CB5-FDF2-4BD5-B3F6-8B75BC3AFD79}.Release|Any CPU.Build.0 = Release|Any CPU- {D160D151-C030-4A0E-A805-6E28B533F03F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {D160D151-C030-4A0E-A805-6E28B533F03F}.Debug|Any CPU.Build.0 = Debug|Any CPU- {D160D151-C030-4A0E-A805-6E28B533F03F}.Release|Any CPU.ActiveCfg = Release|Any CPU- {D160D151-C030-4A0E-A805-6E28B533F03F}.Release|Any CPU.Build.0 = Release|Any CPU- {BC6D71E7-8D01-4627-A3C9-2B6B9186A36E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {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 CPU- EndGlobalSection- GlobalSection(SolutionProperties) = preSolution- HideSolutionNode = FALSE- EndGlobalSection- GlobalSection(ExtensibilityGlobals) = postSolution- SolutionGuid = {90AFACCD-B199-4A1E-B14E-5DA783E09D17}- EndGlobalSection-EndGlobaldiff --git a/docs/contributing-new-components.md b/docs/contributing-new-components.mddeleted file mode 100644index b4fbaa7e..00000000--- a/docs/contributing-new-components.md+++ /dev/null@@ -1,152 +0,0 @@-# Adding Components--Adding a new component is relatively trivial and involves a few simple steps; though requires some upfront plumbing. This document should hopefully help make this process easier.--## Adding a Config--First add a config to the `GlazeWM.Domain.UserConfigs` namespace; here is an example:--```csharp-public class CpuComponentConfig : BarComponentConfig-{- /// <summary>- /// Label assigned to the CPU component.- /// </summary>- public string Label { get; set; } = "CPU: {percent_usage}%";-}-```--Once this is done, you should register this config in `BarComponentConfigConverter.Read`:--```csharp-"cpu" =>- JsonSerializer.Deserialize<CpuComponentConfig>(- jsonObject.RootElement.ToString(),- options- )-```--This will map directly to the config using the YAML naming rules, i.e.--```yaml-components_right:- - type: "cpu"- label: "CPU: {percent_usage}%"-```--Each capital letter is prefixed by a space delimited by `_`.--## Adding a Service [Optional]--In some cases to add a component, you might want to register a `'Service'`; this will allow your logic to be reused across multiple locations in the program.--To do so, first create the raw service in `GlazeWM.Infrastructure`.--```csharp-/// <summary>-/// Provides access to current CPU statistics.-/// </summary>-public class CpuStatsService-{ ... }-```--And register it in the DI container in `GlazeWM.Infrastructure.DependencyInjection`:--```csharp-services.AddSingleton<CpuStatsService>();-```--## Adding a ViewModel--This contains the main logic used to fetch the data to be displayed in the UI.-You add this file to `GlazeWM.Bar.Components`.--Example:--```csharp-public class CpuComponentViewModel : ComponentViewModel-{- public CpuComponentViewModel(- BarViewModel parentViewModel,- CpuComponentConfig config) : base(parentViewModel, config)- {- _config = config;- _cpuStatsService = ServiceLocator.GetRequiredService<CpuStatsService>();-- Observable.Timer(- TimeSpan.Zero,- TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)- )- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe((_) => Label = CreateLabel());- }-}-```--Note the line `.TakeUntil(_parentViewModel.WindowClosing)`. This is necessary to correctly clean up after config reloads; otherwise your component will remain alive; wasting CPU and RAM.--Then register your ViewModel to `BarViewModel.CreateComponentViewModels`--```csharp-CpuComponentConfig cpupc => new CpuComponentViewModel(this, cpupc),-```--## Adding a Component XAML--Each individual component has its own custom XAML WPF UserControl.-Most of these don't require much customization; so it's usually easier to just copy an existing component; for example.--### Copy Existing Component--CTRL+C & CTRL+V existing Xaml file----### Fix Class Name--Fix the class name to correspond to your new class in the XAML, i.e.--```xaml-<UserControl- x:Class="GlazeWM.Bar.Components.CpuComponent"-```--(first line)--And corresponding `xaml.cs` file.--```csharp-public partial class CpuComponent : UserControl-{- public CpuComponent() => InitializeComponent();-}-```--### Fix Item Name--Change following line in the XAML--```xaml-<!-- Or whichever property is here -->-Text="{Binding TilingDirectionString}" />-```--To match your property from the `ViewModel`, i.e. `FormattedText`, so the XAML reads.--```xaml-Text="{Binding FormattedText}" />-```--## Register Component XAML--Add your component to `ComponentPortal.xaml` beside all the other components.--```xaml-<DataTemplate DataType="{x:Type components:CpuComponentViewModel}">- <components:CpuComponent Padding="{Binding Padding}" Background="{Binding Background}" />-</DataTemplate>-```--After doing this, add the component to your config, see if it works.--diff --git a/docs/images/duplicate_xaml.png b/docs/images/duplicate_xaml.pngdeleted file mode 100644index e933bed8..00000000Binary files a/docs/images/duplicate_xaml.png and /dev/null differdiff --git a/docs/images/working_cpu_indicator.png b/docs/images/working_cpu_indicator.pngdeleted file mode 100644index 72ff4168..00000000Binary files a/docs/images/working_cpu_indicator.png and /dev/null differ