From 3343d87b5ff56938422438c268beb3839c14c5b0 Mon Sep 17 00:00:00 2001
From: sago35 <sago35@gmail.com>
Date: Tue, 24 Dec 2024 20:19:54 +0900
Subject: [PATCH] Fix the press order when cancelling Combos

---
 keyboard.go | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/keyboard.go b/keyboard.go
index 398ce24..a31c7a7 100644
--- a/keyboard.go
+++ b/keyboard.go
@@ -284,10 +284,18 @@ func (d *Device) Tick() error {
 			noneToPress = noneToPress[:0]
 		} else {
 			// Cancel the Combos waiting state if a key unrelated to Combos is pressed.
+			// Sort `d.combosPressed` so that the ones pressed earlier are triggered first.
 			d.combosTimer = time.Time{}
+			ofs := len(noneToPress)
+			noneToPress = d.noneToPressBuf[:ofs+len(d.combosPressed)]
+			for i := range noneToPress[:ofs] {
+				noneToPress[len(noneToPress)-1-i] = noneToPress[ofs-1-i]
+			}
+			idx := 0
 			for xx := range d.combosPressed {
-				noneToPress = append(noneToPress, xx)
+				noneToPress[idx] = xx
 				delete(d.combosPressed, xx)
+				idx++
 			}
 			pressToRelease = append(d.combosReleased, pressToRelease...)
 			d.combosReleased = d.combosReleased[:0]