From 33ef9a612d31b07531196247ba17e6d4ef4ca7ea Mon Sep 17 00:00:00 2001 From: leo Date: Tue, 10 Dec 2024 12:06:36 +0800 Subject: [PATCH] fix: avoid crash if fontfamily contains consecutive whitespace (#799) --- src/ViewModels/Preference.cs | 38 ++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/ViewModels/Preference.cs b/src/ViewModels/Preference.cs index a02df359..04f0fa91 100644 --- a/src/ViewModels/Preference.cs +++ b/src/ViewModels/Preference.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using Avalonia.Collections; @@ -65,8 +66,8 @@ namespace SourceGit.ViewModels get => _defaultFontFamily; set { - var trimmed = value.Trim(); - if (SetProperty(ref _defaultFontFamily, trimmed) && !_isLoading) + var name = FixFontFamilyName(value); + if (SetProperty(ref _defaultFontFamily, name) && !_isLoading) App.SetFonts(_defaultFontFamily, _monospaceFontFamily, _onlyUseMonoFontInEditor); } } @@ -76,8 +77,8 @@ namespace SourceGit.ViewModels get => _monospaceFontFamily; set { - var trimmed = value.Trim(); - if (SetProperty(ref _monospaceFontFamily, trimmed) && !_isLoading) + var name = FixFontFamilyName(value); + if (SetProperty(ref _monospaceFontFamily, name) && !_isLoading) App.SetFonts(_defaultFontFamily, _monospaceFontFamily, _onlyUseMonoFontInEditor); } } @@ -588,6 +589,35 @@ namespace SourceGit.ViewModels return changed; } + private string FixFontFamilyName(string name) + { + var trimmed = name.Trim(); + if (string.IsNullOrEmpty(trimmed)) + return string.Empty; + + var builder = new StringBuilder(); + var lastIsSpace = false; + for (int i = 0; i < trimmed.Length; i++) + { + var c = trimmed[i]; + if (char.IsWhiteSpace(c)) + { + if (lastIsSpace) + continue; + + lastIsSpace = true; + } + else + { + lastIsSpace = false; + } + + builder.Append(c); + } + + return builder.ToString(); + } + private static Preference _instance = null; private static bool _isLoading = false;