Skip to content

Commit

Permalink
fix: optimize preview spawning
Browse files Browse the repository at this point in the history
Don't show a preview when there are no lines selected, and don't respawn
a preview if the same line is selected between redraws.
  • Loading branch information
natecraddock committed Jul 28, 2023
1 parent dffdd95 commit 60dd554
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
16 changes: 14 additions & 2 deletions src/Previewer.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Manages child processes used for previewing information about the selected line

const mem = std.mem;
const process = std.process;
const std = @import("std");

Expand All @@ -16,6 +17,8 @@ loop: *Loop,
shell: []const u8,
cmd_parts: [2][]const u8,

current_arg: []const u8 = "",

child: ?Child = null,
stdout: ArrayList(u8),
stderr: ArrayList(u8),
Expand All @@ -42,12 +45,21 @@ pub fn init(allocator: Allocator, loop: *Loop, cmd: []const u8, arg: []const u8)
return previewer;
}

pub fn spawn(previewer: *Previewer, arg: []const u8) !void {
pub fn reset(previewer: *Previewer) !void {
previewer.stdout.clearRetainingCapacity();
previewer.stderr.clearRetainingCapacity();
if (previewer.child) |*child| {
_ = try child.kill();
}
}

pub fn spawn(previewer: *Previewer, arg: []const u8) !void {
// If the arg is already being previewed we don't need to do any work
if (mem.eql(u8, arg, previewer.current_arg)) {
return;
}

try previewer.reset();

const command = try std.fmt.allocPrint(previewer.allocator, "{s}{s}{s} | expand -t4", .{ previewer.cmd_parts[0], arg, previewer.cmd_parts[1] });

Expand All @@ -58,8 +70,8 @@ pub fn spawn(previewer: *Previewer, arg: []const u8) !void {
try child.spawn();

previewer.loop.setChild(child.stdout.?.handle, child.stderr.?.handle);

previewer.child = child;
previewer.current_arg = try previewer.allocator.dupe(u8, arg);
}

pub fn read(previewer: *Previewer, stream: enum { stdout, stderr }) !void {
Expand Down
8 changes: 4 additions & 4 deletions src/ui.zig
Original file line number Diff line number Diff line change
Expand Up @@ -424,12 +424,12 @@ pub fn run(
}

// The selection changed and the child process should be respawned
if (state.selection_changed and state.preview != null) {
if (state.selection_changed) if (state.preview) |*preview| {
state.selection_changed = false;
if (filtered.len > 0) {
try state.preview.?.spawn(filtered[state.selected + state.offset].str);
}
}
try preview.spawn(filtered[state.selected + state.offset].str);
} else try preview.reset();
};

if (state.redraw) {
state.redraw = false;
Expand Down

0 comments on commit 60dd554

Please sign in to comment.