//! Terminal input event types. //! //! Port of ultraviolet's `event.go` (and the small color helpers from //! `decoder.go`: `XParseColor`, `rgbToHSL`, `isDarkColor`). Where Go models //! events as separate types behind an `Event` interface, Zig uses a single //! tagged union `Event`. String/slice payloads borrow from the input buffer //! the decoder received, unless otherwise noted. const std = @import("std"); const ir = @import("root.zig"); const Key = ir.Key; const Mouse = ir.Mouse; const t = std.testing; /// The maximum number of events a `MultiEvent` can hold inline. pub const max_multi_events: usize = 4; /// Maximum number of parameters in device-attribute events. pub const max_device_attrs: usize = 32; /// An RGB color (used by color events). pub const Rgb = struct { r: u8, g: u8, b: u8, a: u8 = 255, }; /// The size of the terminal window in a given unit. pub const Size = struct { width: usize, height: usize, }; /// Clipboard selection byte. pub const ClipboardSelection = u8; pub const system_clipboard: ClipboardSelection = 'c'; pub const primary_clipboard: ClipboardSelection = 'p'; /// A mode report value (DECRPM). Mirrors `ansi.ModeSetting`. pub const ModeSetting = enum(u8) { not_recognized = 0, set = 1, reset = 2, permanently_set = 3, permanently_reset = 4, pub fn isSet(self: ModeSetting) bool { return self == .set or self == .permanently_set; } pub fn isReset(self: ModeSetting) bool { return self == .reset or self == .permanently_reset; } }; /// Modes as ints (DECMode/ANSIMode collapse to plain ints). pub const Mode = i32; /// A terminal input event. pub const Event = union(enum) { unknown: []const u8, unknown_csi: []const u8, unknown_ss3: []const u8, unknown_osc: []const u8, unknown_dcs: []const u8, unknown_sos: []const u8, unknown_pm: []const u8, unknown_apc: []const u8, /// An internally-ignored sequence. ignored: []const u8, /// Multiple events reported together. Points at a decoder-owned scratch /// array of exactly `max_multi_events` slots (see `multiLen`). multi: *const [max_multi_events]Event, key_press: Key, key_release: Key, mouse_click: Mouse, mouse_release: Mouse, mouse_wheel: Mouse, mouse_motion: Mouse, window_size: Size, pixel_size: Size, cell_size: Size, cursor_position: struct { x: i32, y: i32 }, focus: void, blur: void, dark_color_scheme: void, light_color_scheme: void, paste: []const u8, paste_start: void, paste_end: void, terminal_version: []const u8, modify_other_keys: struct { mode: i32 }, kitty_graphics: struct { /// Options query string (borrowed). options: [:0]const u8 = "", /// Payload (borrowed). payload: []const u8 = "", }, keyboard_enhancements: struct { flags: i32 }, primary_device_attrs: [max_device_attrs]i32, secondary_device_attrs: [max_device_attrs]i32, tertiary_device_attrs: []const u8, mode_report: struct { mode: Mode, value: ModeSetting, }, foreground_color: Rgb, background_color: Rgb, cursor_color: Rgb, window_op: struct { op: i32, /// Arg count + values. args: [max_window_op_args]i32, }, capability: []const u8, clipboard: struct { content: []const u8 = "", selection: ClipboardSelection = 0, }, pub fn toString(self: Event, out: []u8) []const u8 { switch (self) { .unknown, .unknown_csi, .unknown_ss3, .unknown_osc, .unknown_dcs, .unknown_sos, .unknown_pm, .unknown_apc, => |s| return s, .paste, .terminal_version, .capability => |s| return s, .key_press, .key_release => |k| return k.string(out), .mouse_click, .mouse_release, .mouse_wheel => |m| return m.string(), .mouse_motion => |m| { if (m.button != .none) return m.string(); @memcpy(out[0..6], "motion"); return out[0..6]; }, else => return "", } } }; /// Maximum number of args in a `WindowOpEvent`. pub const max_window_op_args: usize = 32; /// The number of events in a `multi` payload (unused slots are `.unknown` /// with empty data). pub fn multiLen(arr: *const [max_multi_events]Event) usize { var n: usize = 0; for (arr) |e| { if (e == .unknown and e.unknown.len == 0) break; n += 1; } return n; } fn shiftChannel(v: u32) u8 { if (v > 0xff) return @intCast(v >> 8); return @intCast(v); } fn hexVal(c: u8) ?u4 { return switch (c) { '0'...'9' => @intCast(c - '0'), 'a'...'f' => @intCast(c - 'a' + 10), 'A'...'F' => @intCast(c - 'A' + 10), else => null, }; } /// Parses a color string into `Rgb`. Supports `#RGB`, `#RRGGBB`, `rgb:RRRR/GGGG/BBBB` /// and `rgba:RRRR/GGGG/BBBB/AAAA`. `null` on failure (mirrors `ansi.XParseColor`). pub fn xParseColor(s: []const u8) ?Rgb { if (std.mem.startsWith(u8, s, "#")) return parseHexColor(s[1..]); if (std.mem.startsWith(u8, s, "rgb:") or std.mem.startsWith(u8, s, "rgba:")) { // rgba has 4 /-separated parts; rgb has 3. const is_rgba = std.mem.startsWith(u8, s, "rgba:"); const body = if (is_rgba) s[5..] else s[4..]; var parts = std.mem.splitScalar(u8, body, '/'); const r = parts.next(); const g = parts.next(); const b = parts.next(); var a = parts.next(); if (r == null or g == null or b == null) return null; if (is_rgba and a == null) return null; if (!is_rgba) a = "ffff"; const rv = std.fmt.parseInt(u32, r.?, 16) catch return null; const gv = std.fmt.parseInt(u32, g.?, 16) catch return null; const bv = std.fmt.parseInt(u32, b.?, 16) catch return null; const av = std.fmt.parseInt(u32, a.?, 16) catch return null; return .{ .r = shiftChannel(rv), .g = shiftChannel(gv), .b = shiftChannel(bv), .a = shiftChannel(av) }; } return null; } fn parseHexColor(h: []const u8) ?Rgb { var out: Rgb = .{ .r = 0, .g = 0, .b = 0 }; if (h.len == 3) { const r1 = hexVal(h[0]) orelse return null; const g1 = hexVal(h[1]) orelse return null; const b1 = hexVal(h[2]) orelse return null; out.r = (@as(u8, r1) << 4) | @as(u8, r1); out.g = (@as(u8, g1) << 4) | @as(u8, g1); out.b = (@as(u8, b1) << 4) | @as(u8, b1); return out; } if (h.len == 6) { const r1 = hexVal(h[0]) orelse return null; const r2 = hexVal(h[1]) orelse return null; const g1 = hexVal(h[2]) orelse return null; const g2 = hexVal(h[3]) orelse return null; const b1 = hexVal(h[4]) orelse return null; const b2 = hexVal(h[5]) orelse return null; out.r = (@as(u8, r1) << 4) | @as(u8, r2); out.g = (@as(u8, g1) << 4) | @as(u8, g2); out.b = (@as(u8, b1) << 4) | @as(u8, b2); return out; } return null; } fn getMaxMin(a: f64, b: f64, c: f64) struct { ma: f64, mi: f64 } { var ma: f64 = undefined; var mi: f64 = undefined; if (a > b) { ma = a; mi = b; } else { ma = b; mi = a; } if (c > ma) { ma = c; } else if (c < mi) { mi = c; } return .{ .ma = ma, .mi = mi }; } fn round(x: f64) f64 { return @round(x * 1000) / 1000; } fn rgbToHSL(r: u8, g: u8, b: u8) struct { h: f64, s: f64, l: f64 } { const Rnot = @as(f64, @floatFromInt(r)) / 255; const Gnot = @as(f64, @floatFromInt(g)) / 255; const Bnot = @as(f64, @floatFromInt(b)) / 255; const mm = getMaxMin(Rnot, Gnot, Bnot); const Cmax = mm.ma; const Cmin = mm.mi; const delta = Cmax - Cmin; var h: f64 = 0; var s: f64 = 0; const l = (Cmax + Cmin) / 2; if (delta != 0) { if (Cmax == Rnot) { h = 60 * @mod((Gnot - Bnot) / delta, 6.0); } else if (Cmax == Gnot) { h = 60 * (((Bnot - Rnot) / delta) + 2); } else { h = 60 * (((Rnot - Gnot) / delta) + 4); } if (h < 0) h += 360; s = delta / (1 - @abs(2 * l - 1)); } return .{ .h = h, .s = round(s), .l = round(l) }; } /// Whether a color is dark (lightness < 0.5). pub fn isDarkColor(color: Rgb) bool { const hsl = rgbToHSL(color.r, color.g, color.b); return hsl.l < 0.5; } /// Hex string representation of a color (#rrggbb). pub fn colorToHex(c: Rgb, out: *[8]u8) []const u8 { _ = std.fmt.bufPrint(out, "#{x:0>2}{x:0>2}{x:0>2}", .{ c.r, c.g, c.b }) catch unreachable; return out[0..7]; } test "xparsecolor" { const c = xParseColor("#ff8000").?; try t.expectEqual(0xff, c.r); try t.expectEqual(0x80, c.g); try t.expectEqual(0x00, c.b); try t.expectEqual(@as(?Rgb, null), xParseColor("bogus")); const c2 = xParseColor("rgb:ffff/0000/8080").?; try t.expectEqual(0xff, c2.r); try t.expectEqual(0x00, c2.g); try t.expectEqual(0x80, c2.b); } test "is dark color" { try t.expect(isDarkColor(.{ .r = 0, .g = 0, .b = 0 })); try t.expect(!isDarkColor(.{ .r = 0xff, .g = 0xff, .b = 0xff })); } test "fuzz color" { try t.fuzz({}, fuzzColor, .{ .corpus = &.{ "", "#fff", "#ffffff", "#f", "rgb:ffff/ffff/ffff", "rgba:ff/ff/ff/ff", "rgba:ffff/ffff/ffff/ffff", "nope", }, }); } fn fuzzColor(_: void, smith: *t.Smith) anyerror!void { var buf: [64]u8 = undefined; const len = smith.slice(&buf); if (xParseColor(buf[0..len])) |c| { var hex: [8]u8 = undefined; _ = colorToHex(c, &hex); _ = isDarkColor(c); } }