// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! X11 keysyms, the numbers harrier names keys by above the platform: zig-xkb //! where there is a keyboard it describes, and on Windows the little of it //! harrier needs. const std = @import("std"); const builtin = @import("builtin"); const xkb = if (builtin.os.tag == .linux) @import("xkb") else struct {}; /// The keysym for a character: itself for Latin-1, and Unicode's block of /// keysyms for the rest, as xkbcommon makes them. pub fn fromUtf32(cp: u21) u32 { if (builtin.os.tag == .linux) return @backingInt(xkb.Keysym.fromUtf32(cp)); return fromUtf32Plain(cp); } fn fromUtf32Plain(cp: u21) u32 { return switch (cp) { 0x20...0x7e, 0xa0...0xff => cp, else => 0x0100_0000 | @as(u32, cp), }; } /// The keysym's name, as xkbcommon spells it — `Return`, `a` — in `buf`. /// Without xkbcommon's table, a character's keysym is named by the /// character and anything else by its number. pub fn name(sym: u32, buf: *[64]u8) []const u8 { if (builtin.os.tag == .linux) { const ks: xkb.Keysym = @fromBackingInt(sym); return ks.getName(buf); } var w: std.Io.Writer = .fixed(buf); const cp: ?u21 = switch (sym) { 0x20...0x7e, 0xa0...0xff => @intCast(sym), 0x0100_0000...0x0110_ffff => @intCast(sym & 0x1f_ffff), else => null, }; if (cp) |c| { var enc: [4]u8 = undefined; const n = std.unicode.utf8Encode(c, &enc) catch return ""; w.writeAll(enc[0..n]) catch return ""; } else w.print("0x{x:0>4}", .{sym}) catch return ""; return w.buffered(); } test "characters' keysyms" { try std.testing.expectEqual(@as(u32, 'a'), fromUtf32Plain('a')); try std.testing.expectEqual(@as(u32, 0xe9), fromUtf32Plain(0xe9)); try std.testing.expectEqual(@as(u32, 0x0100_20ac), fromUtf32Plain(0x20ac)); }