diff --git a/src/Avalonia.Base/Input/KeyGesture.cs b/src/Avalonia.Base/Input/KeyGesture.cs index 122176a1272..83d99bf7a97 100644 --- a/src/Avalonia.Base/Input/KeyGesture.cs +++ b/src/Avalonia.Base/Input/KeyGesture.cs @@ -79,15 +79,10 @@ public static KeyGesture Parse(string gesture) { var partSpan = gesture.AsSpan(cstart, c - cstart).Trim(); - if (isLast) - { - key = ParseKey(partSpan.ToString()); - } - else + if (!TryParseKey(partSpan.ToString(), out key)) { keyModifiers |= ParseModifier(partSpan); } - cstart = c + 1; } } @@ -151,8 +146,11 @@ static void Plus(StringBuilder s) s.Append(formatInfo.Meta); } - Plus(s); - s.Append(formatInfo.FormatKey(Key)); + if ((Key != Key.None) || (KeyModifiers == KeyModifiers.None)) + { + Plus(s); + s.Append(formatInfo.FormatKey(Key)); + } return StringBuilderCache.GetStringAndRelease(s); } @@ -163,12 +161,16 @@ public bool Matches(KeyEventArgs? keyEvent) => ResolveNumPadOperationKey(keyEvent.Key) == ResolveNumPadOperationKey(Key); // TODO: Move that to external key parser - private static Key ParseKey(string key) + private static bool TryParseKey(string keyStr, out Key key) { - if (s_keySynonyms.TryGetValue(key.ToLower(CultureInfo.InvariantCulture), out Key rv)) - return rv; + key = Key.None; + if (s_keySynonyms.TryGetValue(keyStr.ToLower(CultureInfo.InvariantCulture), out key)) + return true; + + if (EnumHelper.TryParse(keyStr, true, out key)) + return true; - return EnumHelper.Parse(key, true); + return false; } private static KeyModifiers ParseModifier(ReadOnlySpan modifier) diff --git a/tests/Avalonia.Base.UnitTests/Input/KeyGestureTests.cs b/tests/Avalonia.Base.UnitTests/Input/KeyGestureTests.cs index 33cd94ec98b..790d1f9c49d 100644 --- a/tests/Avalonia.Base.UnitTests/Input/KeyGestureTests.cs +++ b/tests/Avalonia.Base.UnitTests/Input/KeyGestureTests.cs @@ -13,6 +13,9 @@ public class KeyGestureTests new object[]{"Control++", new KeyGesture(Key.OemPlus, KeyModifiers.Control) }, new object[]{ "Shift+⌘+A", new KeyGesture(Key.A, KeyModifiers.Meta | KeyModifiers.Shift) }, new object[]{ "Shift+Cmd+A", new KeyGesture(Key.A, KeyModifiers.Meta | KeyModifiers.Shift) }, + new object[]{"None", new KeyGesture(Key.None)}, + new object[]{"Alt+Shift", new KeyGesture(Key.None, KeyModifiers.Alt | KeyModifiers.Shift)}, + }; public static readonly IEnumerable ToStringData = new object[][] @@ -23,6 +26,8 @@ public class KeyGestureTests new object[]{new KeyGesture(Key.A, KeyModifiers.Alt | KeyModifiers.Shift), "Shift+Alt+A"}, new object[]{new KeyGesture(Key.A, KeyModifiers.Control | KeyModifiers.Alt | KeyModifiers.Shift), "Ctrl+Shift+Alt+A"}, new object[]{new KeyGesture(Key.A, KeyModifiers.Meta | KeyModifiers.Shift), "Shift+Cmd+A"}, + new object[]{new KeyGesture(Key.None), "None"}, + new object[]{new KeyGesture(Key.None, KeyModifiers.Alt | KeyModifiers.Shift), "Shift+Alt"}, }; [Theory]