Skip to content

Commit 20b6afc

Browse files
authored
[Windows] Update HidDeviceReportEvent() (#447)
1 parent 8909d6c commit 20b6afc

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

windows/QMK Toolbox/HidConsole/HidConsoleDevice.cs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using HidLibrary;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Text;
45
using System.Threading.Tasks;
@@ -54,29 +55,34 @@ private async Task<HidReport> ReadReportAsync()
5455
return await Task.Run(() => HidDevice.ReadReport());
5556
}
5657

57-
private string currentLine = "";
58+
private List<byte> currentLine = new();
5859

5960
private void HidDeviceReportEvent(HidReport report)
6061
{
6162
if (HidDevice.IsConnected)
6263
{
6364
// Check if we have a completed line queued
64-
int lineEnd = currentLine.IndexOf('\n');
65+
int lineEnd = currentLine.IndexOf((byte)'\n');
6566
if (lineEnd == -1)
6667
{
6768
// Partial line or nothing - append incoming report to current line
68-
string reportString = Encoding.UTF8.GetString(report.Data).Trim('\0');
69-
currentLine += reportString;
69+
foreach (byte b in report.Data)
70+
{
71+
// Trim trailing null bytes
72+
if (b == 0) break;
73+
currentLine.Add(b);
74+
}
7075
}
7176

7277
// Check again for a completed line
73-
lineEnd = currentLine.IndexOf('\n');
78+
lineEnd = currentLine.IndexOf((byte)'\n');
7479
while (lineEnd >= 0)
7580
{
7681
// Fire delegate with completed lines until we have none left
77-
string completedLine = currentLine[..lineEnd];
78-
currentLine = currentLine[(lineEnd + 1)..];
79-
lineEnd = currentLine.IndexOf('\n');
82+
// Only convert to string at the last possible moment in case there is a UTF-8 sequence split across reports
83+
string completedLine = Encoding.UTF8.GetString(currentLine.GetRange(0, lineEnd).ToArray());
84+
currentLine = currentLine.Skip(lineEnd + 1).ToList();
85+
lineEnd = currentLine.IndexOf((byte)'\n');
8086
consoleReportReceived?.Invoke(this, completedLine);
8187
}
8288

0 commit comments

Comments
 (0)