Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

refactor: migrate from `Newtonsoft.Json` package (#103)

lars-berger3f6eef568211
diff --git a/GlazeWM.Domain/GlazeWM.Domain.csproj b/GlazeWM.Domain/GlazeWM.Domain.csproj
index 9b2b7b56..e66809cb 100644
--- a/GlazeWM.Domain/GlazeWM.Domain.csproj
+++ b/GlazeWM.Domain/GlazeWM.Domain.csproj
@@ -10,18 +10,9 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference
- Include="Microsoft.Extensions.Hosting"
- Version="6.0.1" />
- <PackageReference
- Include="Newtonsoft.Json"
- Version="13.0.1" />
- <PackageReference
- Include="System.Reactive"
- Version="5.0.0" />
- <PackageReference
- Include="YamlDotNet"
- Version="8.1.0" />
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
+ <PackageReference Include="System.Reactive" Version="5.0.0" />
+ <PackageReference Include="YamlDotNet" Version="8.1.0" />
</ItemGroup>
<ItemGroup>
diff --git a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs b/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs
index 895b1831..f9c59222 100644
--- a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs
+++ b/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs
@@ -1,40 +1,39 @@
using System;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
+using System.Text.Json;
+using System.Text.Json.Serialization;
namespace GlazeWM.Domain.UserConfigs
{
- public class BarComponentConfigConverter : JsonConverter
+ public class BarComponentConfigConverter : JsonConverter<BarComponentConfig>
{
- public override bool CanConvert(Type objectType)
+ public override BarComponentConfig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
- return objectType.IsAssignableFrom(typeof(BarComponentConfig));
- }
-
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
- {
- var jObject = JObject.Load(reader);
+ using var jsonObject = JsonDocument.ParseValue(ref reader);
- // Get the type of workspace component config.
- var type = jObject["type"].Value<string>();
+ // Get the type of bar component (eg. "workspaces").
+ var typeDiscriminator = jsonObject.RootElement.GetProperty("type").ToString();
- object target = type switch
+ return typeDiscriminator switch
{
- "workspaces" => new WorkspacesComponentConfig(),
- "clock" => new ClockComponentConfig(),
- _ => throw new ArgumentException($"Invalid workspace type '{type}'."),
+ "workspaces" =>
+ JsonSerializer.Deserialize<WorkspacesComponentConfig>(
+ jsonObject.RootElement.ToString(),
+ options
+ ),
+ "clock" =>
+ JsonSerializer.Deserialize<ClockComponentConfig>(
+ jsonObject.RootElement.ToString(),
+ options
+ ),
+ _ => throw new ArgumentException($"Invalid component type '{typeDiscriminator}'."),
};
-
- serializer.Populate(jObject.CreateReader(), target);
-
- return target;
}
/// <summary>
/// Serializing is not needed, so it's fine to leave it unimplemented.
/// </summary>
/// <exception cref="NotImplementedException"></exception>
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void Write(Utf8JsonWriter writer, BarComponentConfig value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
diff --git a/GlazeWM.Domain/UserConfigs/BarConfig.cs b/GlazeWM.Domain/UserConfigs/BarConfig.cs
index a1afd862..c395b5a2 100644
--- a/GlazeWM.Domain/UserConfigs/BarConfig.cs
+++ b/GlazeWM.Domain/UserConfigs/BarConfig.cs
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-using Newtonsoft.Json;
namespace GlazeWM.Domain.UserConfigs
{
@@ -35,13 +34,10 @@ namespace GlazeWM.Domain.UserConfigs
/// </summary>
public string Padding { get; set; } = "0";
- [JsonProperty(ItemConverterType = typeof(BarComponentConfigConverter))]
public List<BarComponentConfig> ComponentsLeft { get; set; } = new List<BarComponentConfig>();
- [JsonProperty(ItemConverterType = typeof(BarComponentConfigConverter))]
public List<BarComponentConfig> ComponentsCenter { get; set; } = new List<BarComponentConfig>();
- [JsonProperty(ItemConverterType = typeof(BarComponentConfigConverter))]
public List<BarComponentConfig> ComponentsRight { get; set; } = new List<BarComponentConfig>();
}
}
diff --git a/GlazeWM.Domain/UserConfigs/BarPosition.cs b/GlazeWM.Domain/UserConfigs/BarPosition.cs
index 447470ff..50cf7cd4 100644
--- a/GlazeWM.Domain/UserConfigs/BarPosition.cs
+++ b/GlazeWM.Domain/UserConfigs/BarPosition.cs
@@ -2,6 +2,7 @@
{
public enum BarPosition
{
- Top, Bottom
+ Top,
+ Bottom
}
}
diff --git a/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs b/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs
index 6c9a6fe9..aa9b536d 100644
--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs
+++ b/GlazeWM.Domain/UserConfigs/CommandHandlers/EvaluateUserConfigHandler.cs
@@ -2,11 +2,13 @@
using GlazeWM.Infrastructure.Bussing;
using GlazeWM.Infrastructure.Exceptions;
using GlazeWM.Infrastructure.Yaml;
-using Newtonsoft.Json;
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Reflection;
-using System.Text.RegularExpressions;
+using System.Text.Json;
+using System.Text.Json.Serialization;
using System.Windows.Forms;
namespace GlazeWM.Domain.UserConfigs.CommandHandlers
@@ -16,36 +18,29 @@ namespace GlazeWM.Domain.UserConfigs.CommandHandlers
private readonly Bus _bus;
private readonly UserConfigService _userConfigService;
private readonly YamlDeserializationService _yamlDeserializationService;
+ private readonly CommandParsingService _commandParsingService;
public EvaluateUserConfigHandler(
Bus bus,
UserConfigService userConfigService,
- YamlDeserializationService yamlDeserializationService
+ YamlDeserializationService yamlDeserializationService,
+ CommandParsingService commandParsingService
)
{
_bus = bus;
_userConfigService = userConfigService;
_yamlDeserializationService = yamlDeserializationService;
+ _commandParsingService = commandParsingService;
}
public CommandResponse Handle(EvaluateUserConfigCommand command)
{
- UserConfig deserializedConfig;
+ var userConfigPath = _userConfigService.UserConfigPath;
- try
- {
- var userConfigPath = _userConfigService.UserConfigPath;
+ if (!File.Exists(userConfigPath))
+ InitializeSampleUserConfig(userConfigPath);
- if (!File.Exists(userConfigPath))
- InitializeSampleUserConfig(userConfigPath);
-
- deserializedConfig = DeserializeUserConfig(userConfigPath);
- }
- catch (Exception exception)
- {
- var errorMessage = FormatErrorMessage(exception);
- throw new FatalUserException(errorMessage);
- }
+ var deserializedConfig = DeserializeUserConfig(userConfigPath);
// Merge default window rules with user-defined rules.
var defaultWindowRules = _userConfigService.DefaultWindowRules;
@@ -53,6 +48,9 @@ namespace GlazeWM.Domain.UserConfigs.CommandHandlers
_userConfigService.UserConfig = deserializedConfig;
+ // Check for required properties and validate command strings.
+ ValidateDeserializedConfig(deserializedConfig);
+
// Register keybindings.
_bus.Invoke(new RegisterKeybindingsCommand(deserializedConfig.Keybindings));
@@ -89,29 +87,103 @@ namespace GlazeWM.Domain.UserConfigs.CommandHandlers
private UserConfig DeserializeUserConfig(string userConfigPath)
{
- var userConfigLines = File.ReadAllLines(userConfigPath);
- var input = new StringReader(string.Join(Environment.NewLine, userConfigLines));
+ try
+ {
+ var userConfigLines = File.ReadAllLines(userConfigPath);
+ var input = new StringReader(string.Join(Environment.NewLine, userConfigLines));
- return _yamlDeserializationService.Deserialize<UserConfig>(input);
+ return _yamlDeserializationService.Deserialize<UserConfig>(
+ input,
+ new List<JsonConverter>() { new BarComponentConfigConverter() }
+ );
+ }
+ catch (Exception exception)
+ {
+ throw new FatalUserException(FormatConfigError(exception));
+ }
}
- private static string FormatErrorMessage(Exception exception)
+ // TODO: Might be able to remove the required checks once nullable context is enabled.
+ private void ValidateDeserializedConfig(UserConfig deserializedConfig)
{
- var errorMessage = "Failed to parse user config. ";
-
- var unknownPropertyRegex = new Regex("Could not find member '(?<property>.*?)' on object");
- var unknownPropertyMatch = unknownPropertyRegex.Match(exception.Message);
+ try
+ {
+ foreach (var workspaceConfig in deserializedConfig.Workspaces)
+ {
+ if (workspaceConfig.Name is null)
+ throw new FatalUserException("Property 'name' is required in workspace config.");
+ }
+
+ 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."
+ );
+
+ 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 allCommandStrings = new List<string>()
+ .Concat(keybindingsConfig.SelectMany(keybinding => keybinding.CommandList))
+ .Concat(windowRulesConfig.SelectMany(windowRule => windowRule.CommandList))
+ .Select(commandString => CommandParsingService.FormatCommand(commandString));
+
+ foreach (var commandString in allCommandStrings)
+ _commandParsingService.ValidateCommand(commandString);
+ }
+ catch (Exception exception)
+ {
+ throw new FatalUserException(FormatConfigError(exception));
+ }
+ }
- // Improve error message in case of unknown property errors.
- if (unknownPropertyMatch.Success)
- errorMessage += $"Unknown property: '{unknownPropertyMatch.Groups["property"]}'.";
+ private static string FormatConfigError(Exception exception)
+ {
+ var errorMessage = "Failed to parse user config. ";
- // Improve error message of generic deserialization errors.
- else if (exception is JsonReaderException)
- errorMessage += $"Invalid value at property: '{(exception as JsonReaderException).Path}'.";
- else
- errorMessage += exception.Message;
+ // 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.cs
index 1161e025..a36ed6d6 100644
--- a/GlazeWM.Domain/UserConfigs/CommandHandlers/RegisterKeybindingsHandler.cs
+++ b/GlazeWM.Domain/UserConfigs/CommandHandlers/RegisterKeybindingsHandler.cs
@@ -35,9 +35,6 @@ namespace GlazeWM.Domain.UserConfigs.CommandHandlers
commandString => CommandParsingService.FormatCommand(commandString)
);
- foreach (var commandString in formattedCommandStrings)
- _commandParsingService.ValidateCommand(commandString);
-
// Register all keybindings for a command sequence.
foreach (var binding in keybindingConfig.BindingList)
_keybindingService.AddGlobalKeybinding(binding, () =>
diff --git a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs b/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
index 5769f472..0d1f0a30 100644
--- a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
+++ b/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
@@ -60,6 +60,8 @@ namespace GlazeWM.Domain.UserConfigs
"close" => subjectContainer is Window
? new CloseWindowCommand(subjectContainer as Window)
: new NoopCommand(),
+ // TODO: Temporary hack to avoid errors during `ValidateCommand`.
+ "ignore" => new NoopCommand(),
_ => throw new ArgumentException(null, nameof(commandString)),
};
}
diff --git a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
index b1bdecb6..559210fd 100644
--- a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
+++ b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
@@ -7,17 +7,8 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference
- Include="Microsoft.Extensions.Hosting"
- Version="6.0.1" />
- <PackageReference
- Include="Newtonsoft.Json"
- Version="13.0.1" />
- <PackageReference
- Include="System.Reactive"
- Version="5.0.0" />
- <PackageReference
- Include="YamlDotNet"
- Version="8.1.0" />
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
+ <PackageReference Include="System.Reactive" Version="5.0.0" />
+ <PackageReference Include="YamlDotNet" Version="8.1.0" />
</ItemGroup>
</Project>
diff --git a/GlazeWM.Infrastructure/Yaml/SnakeCaseNamingPolicy.cs b/GlazeWM.Infrastructure/Yaml/SnakeCaseNamingPolicy.cs
new file mode 100644
index 00000000..165c7248
--- /dev/null
+++ b/GlazeWM.Infrastructure/Yaml/SnakeCaseNamingPolicy.cs
@@ -0,0 +1,26 @@
+using System.Linq;
+using System.Text.Json;
+
+namespace GlazeWM.Infrastructure.Yaml
+{
+ 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();
+ }
+ }
+}
diff --git a/GlazeWM.Infrastructure/Yaml/ValidatingDeserializer.cs b/GlazeWM.Infrastructure/Yaml/ValidatingDeserializer.cs
deleted file mode 100644
index 3a417448..00000000
--- a/GlazeWM.Infrastructure/Yaml/ValidatingDeserializer.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using System.ComponentModel.DataAnnotations;
-using YamlDotNet.Core;
-using YamlDotNet.Serialization;
-
-namespace GlazeWM.Infrastructure.Yaml
-{
- public class ValidatingDeserializer : INodeDeserializer
- {
- private readonly INodeDeserializer _nodeDeserializer;
-
- public ValidatingDeserializer(INodeDeserializer nodeDeserializer)
- {
- _nodeDeserializer = nodeDeserializer;
- }
-
- public bool Deserialize(IParser reader, Type expectedType,
- Func<IParser, Type, object> nestedObjectDeserializer, out object value)
- {
- if (!_nodeDeserializer.Deserialize(reader, expectedType, nestedObjectDeserializer, out value))
- return false;
-
- // Validate using the provided data annotations (eg. `[Required]`).
- var context = new ValidationContext(value, null, null);
- Validator.ValidateObject(value, context, true);
-
- return true;
- }
- }
-}
diff --git a/GlazeWM.Infrastructure/Yaml/YamlDeserializationService.cs b/GlazeWM.Infrastructure/Yaml/YamlDeserializationService.cs
index 95e6a7c7..eaabf787 100644
--- a/GlazeWM.Infrastructure/Yaml/YamlDeserializationService.cs
+++ b/GlazeWM.Infrastructure/Yaml/YamlDeserializationService.cs
@@ -1,40 +1,53 @@
+using System.Collections.Generic;
using System.IO;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Serialization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
using YamlDotNet.Serialization;
-using YamlDotNet.Serialization.NamingConventions;
namespace GlazeWM.Infrastructure.Yaml
{
public class YamlDeserializationService
{
private readonly IDeserializer _yamlDeserializer = new DeserializerBuilder()
- .WithNamingConvention(UnderscoredNamingConvention.Instance)
.Build();
private readonly ISerializer _jsonSerializer = new SerializerBuilder()
.JsonCompatible()
.Build();
- private readonly JsonSerializerSettings _jsonDeserializerSettings = new()
- {
- MissingMemberHandling = MissingMemberHandling.Error,
- ContractResolver = new DefaultContractResolver
- {
- NamingStrategy = new SnakeCaseNamingStrategy()
- },
- };
-
/// <summary>
/// The YAML deserializing library doesn't have support for polymorphic objects. Because of
- /// this, the YAML is first converted into JSON and then deserialized via `Newtonsoft.Json`.
+ /// this, the YAML is first converted into JSON and then deserialized via `System.Text.Json`.
/// </summary>
- public T Deserialize<T>(TextReader input)
+ public T Deserialize<T>(TextReader input, List<JsonConverter> converters)
{
var yamlObject = _yamlDeserializer.Deserialize(input);
var jsonString = _jsonSerializer.Serialize(yamlObject);
- return JsonConvert.DeserializeObject<T>(jsonString, _jsonDeserializerSettings);
+ var jsonDeserializerSettings = GetJsonDeserializerOptions(converters);
+ return JsonSerializer.Deserialize<T>(jsonString, jsonDeserializerSettings);
+ }
+
+ private static JsonSerializerOptions GetJsonDeserializerOptions(
+ List<JsonConverter> converters
+ )
+ {
+ var jsonDeserializerOptions = new JsonSerializerOptions()
+ {
+ // TODO: Use built-in snake case policy once support is added.
+ // Ref: https://github.com/dotnet/runtime/issues/782
+ PropertyNamingPolicy = new SnakeCaseNamingPolicy(),
+ NumberHandling = JsonNumberHandling.AllowReadingFromString,
+ IncludeFields = true,
+ };
+
+ foreach (var converter in converters)
+ jsonDeserializerOptions.Converters.Add(converter);
+
+ // Enable strings to be mapped to a C# enum (eg. `BarPosition` enum).
+ jsonDeserializerOptions.Converters.Add(new JsonStringEnumConverter());
+
+ return jsonDeserializerOptions;
}
}
}