From c254a8b09e719f8d82c881562e9f19252a1f881f Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 16 Aug 2023 10:36:22 -0700 Subject: [PATCH] input: encoding should always write to the buf --- src/input/KeyEncoder.zig | 14 +++++++++++--- src/input/key.zig | 4 ++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/input/KeyEncoder.zig b/src/input/KeyEncoder.zig index 0da31fd75..3ac8a5fc9 100644 --- a/src/input/KeyEncoder.zig +++ b/src/input/KeyEncoder.zig @@ -11,7 +11,7 @@ const testing = std.testing; const key = @import("key.zig"); const function_keys = @import("function_keys.zig"); -event: key.Event, +event: key.KeyEvent, /// The state of various modes of a terminal that impact encoding. alt_esc_prefix: bool = false, @@ -46,7 +46,7 @@ pub fn legacy( self.cursor_key_application, self.keypad_key_application, self.modify_other_keys_state_2, - )) |sequence| return sequence; + )) |sequence| return copyToBuf(buf, sequence); // If we match a control sequence, we output that directly. if (ctrlSeq(self.event.key, binding_mods)) |char| { @@ -154,7 +154,15 @@ pub fn legacy( return try std.fmt.bufPrint(buf, "\x1B{s}", .{utf8}); } - return utf8; + return try copyToBuf(buf, utf8); +} + +/// A helper to memcpy a src value to a buffer and return the result. +fn copyToBuf(buf: []u8, src: []const u8) ![]const u8 { + if (src.len > buf.len) return error.OutOfMemory; + const result = buf[0..src.len]; + @memcpy(result, src); + return result; } /// Determines whether the key should be encoded in the xterm diff --git a/src/input/key.zig b/src/input/key.zig index 92db8009e..622d50556 100644 --- a/src/input/key.zig +++ b/src/input/key.zig @@ -9,7 +9,7 @@ const Allocator = std.mem.Allocator; /// as GLFW. In this case, the apprt should provide as much information /// as it can and it should be expected that the terminal behavior /// will not be totally correct. -pub const Event = struct { +pub const KeyEvent = struct { /// The action: press, release, etc. action: Action = .press, @@ -43,7 +43,7 @@ pub const Event = struct { /// Returns the effective modifiers for this event. The effective /// modifiers are the mods that should be considered for keybindings. - pub fn effectiveMods(self: Event) Mods { + pub fn effectiveMods(self: KeyEvent) Mods { if (self.utf8.len == 0) return self.mods; return self.mods.unset(self.consumed_mods); }