Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix KeyCombination throwing when duplicates are fed in #6130

Merged
merged 3 commits into from Jan 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -7,7 +7,7 @@
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationModifierTest
public class KeyCombinationTest
{
private static readonly object[][] key_combination_display_test_cases =
{
Expand Down Expand Up @@ -50,5 +50,23 @@ public class KeyCombinationModifierTest
[TestCaseSource(nameof(key_combination_display_test_cases))]
public void TestLeftRightModifierHandling(KeyCombination candidate, KeyCombination pressed, KeyCombinationMatchingMode matchingMode, bool shouldContain)
=> Assert.AreEqual(shouldContain, KeyCombination.ContainsAll(candidate.Keys, pressed.Keys, matchingMode));

[Test]
public void TestCreationNoDuplicates()
{
var keyCombination = new KeyCombination(InputKey.A, InputKey.Control);

Assert.That(keyCombination.Keys[0], Is.EqualTo(InputKey.Control));
Assert.That(keyCombination.Keys[1], Is.EqualTo(InputKey.A));
}

[Test]
public void TestCreationWithDuplicates()
{
var keyCombination = new KeyCombination(InputKey.A, InputKey.Control, InputKey.A);

Assert.That(keyCombination.Keys[0], Is.EqualTo(InputKey.Control));
Assert.That(keyCombination.Keys[1], Is.EqualTo(InputKey.A));
}
}
}
14 changes: 11 additions & 3 deletions osu.Framework/Input/Bindings/KeyCombination.cs
Expand Up @@ -39,15 +39,23 @@ public KeyCombination(ICollection<InputKey>? keys)

var keyBuilder = ImmutableArray.CreateBuilder<InputKey>(keys.Count);

bool hadDuplicates = false;

foreach (var key in keys)
{
if (!keyBuilder.Contains(key))
keyBuilder.Add(key);
if (keyBuilder.Contains(key))
{
// This changes the expected count meaning we can't use the optimised MoveToImmutable() method.
hadDuplicates = true;
continue;
}

keyBuilder.Add(key);
}

keyBuilder.Sort();

Keys = keyBuilder.MoveToImmutable();
Keys = hadDuplicates ? keyBuilder.ToImmutableArray() : keyBuilder.MoveToImmutable();
}

/// <summary>
Expand Down