From 080377fd790cdb76b01bb770d1938f8acd391a8f Mon Sep 17 00:00:00 2001 From: nandithebull Date: Tue, 24 Nov 2026 22:08:34 -0800 Subject: [PATCH] =?UTF-8?q?Wayland:=20decode=20UTF-8=20strings=20from=20cl?= =?UTF-8?q?ients=20(titles=20like=20'Session=20Chooser=20=E2=80=94=20Kate'?= =?UTF-8?q?=20showed=20as=20mojibake)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- compositor/wayland/wire.mbt | 43 ++++++++++++++++++++++++++++---- compositor/wayland/wire_test.mbt | 8 ++++++ 2 files changed, 46 insertions(+), 5 deletions(-) create mode 100644 compositor/wayland/wire_test.mbt diff --git a/compositor/wayland/wire.mbt b/compositor/wayland/wire.mbt index 9602c75..1f6efcf 100644 --- a/compositor/wayland/wire.mbt +++ b/compositor/wayland/wire.mbt @@ -105,12 +105,45 @@ pub fn WireReader::str(self : WireReader) -> String { return "" } let buf = StringBuilder::new() - // Exclude trailing NUL + // Exclude trailing NUL; decode UTF-8 (invalid bytes become U+FFFD). let str_len = if len > 0 { len - 1 } else { 0 } - for i = 0; i < str_len; i = i + 1 { - let b = self.data[self.pos + i].to_int() - if b != 0 { - buf.write_char(Int::unsafe_to_char(b)) + let d = self.data + let base = self.pos + let mut i = 0 + while i < str_len { + let b = d[base + i].to_int() + let (n, init) = if b < 0x80 { + (1, b) + } else if b >= 0xF0 && b < 0xF8 { + (4, b & 0x07) + } else if b >= 0xE0 { + (3, b & 0x0F) + } else if b >= 0xC0 { + (2, b & 0x1F) + } else { + (0, 0) + } + if n == 0 || i + n > str_len { + buf.write_char('\u{FFFD}') + i = i + 1 + continue + } + let mut cp = init + let mut ok = true + for k = 1; k < n; k = k + 1 { + let c = d[base + i + k].to_int() + if (c & 0xC0) != 0x80 { + ok = false + break + } + cp = (cp << 6) | (c & 0x3F) + } + if ok && cp != 0 && cp <= 0x10FFFF && !(cp >= 0xD800 && cp < 0xE000) { + buf.write_char(Int::unsafe_to_char(cp)) + i = i + n + } else { + buf.write_char('\u{FFFD}') + i = i + 1 } } let padded = (len + 3) / 4 * 4 diff --git a/compositor/wayland/wire_test.mbt b/compositor/wayland/wire_test.mbt new file mode 100644 index 0000000..c64447c --- /dev/null +++ b/compositor/wayland/wire_test.mbt @@ -0,0 +1,8 @@ + +///| +test "WireReader::str decodes UTF-8" { + let w = WireWriter::new() + w.str("Session Chooser — Kate é😀") + let r = WireReader::from_array(w.finish_msg(1U, 0U).to_array(), 8) + inspect(r.str(), content="Session Chooser — Kate é😀") +}