zellzig/src/api.zig

83 lines
2.4 KiB
Zig

//! This module contains Zellij's API.
//! Every function in this module is used to communicate with zellij.
const std = @import("std");
const zz = @import("main.zig");
const json = @import("json");
const zapi = @import("zellij_api.zig");
const types = @import("types.zig");
/// Sends an object as JSON to zellij
pub fn sendObj(data: anytype) !void {
var stdout = std.io.getStdOut();
try json.toWriter(data, stdout.writer());
try stdout.writeAll("\n");
}
/// Receives a JSON object from zellij
pub fn recvObj(comptime T: type) !zz.OwnedDeserData(T) {
var stdin = std.io.getStdIn();
const data = (try stdin.reader().readUntilDelimiterOrEofAlloc(
zz.allocator.?,
'\n',
std.math.maxInt(usize),
)) orelse unreachable;
defer zz.allocator.?.free(data);
return zz.OwnedDeserData(T).deserialize(zz.allocator.?, data);
}
/// Subscribes to the given events.
/// `Plugin.update` will be called on the subscribed avents.
pub fn subscribe(event_types: []const types.EventType) !void {
try sendObj(event_types);
zapi.host_subscribe();
}
/// Unsubscribe from the given events.
/// `Plugin.update` will no longer be called upon receiving the given events.
pub fn unsubscribe(event_types: []const types.EventType) !void {
try sendObj(event_types);
zapi.host_unsubscribe();
}
/// If the plugin is set to be selectable, it will allow the user to tab into it,
/// and it will keep zellij alive if the other panes are closed.
pub fn setSelectable(selectable: bool) void {
zapi.host_set_selectable(@boolToInt(selectable));
}
/// Returns the ID of this plugin, and zellij's PID.
pub fn getPluginIds() !zz.OwnedDeserData(types.PluginIds) {
zapi.host_get_plugin_ids();
return try recvObj(types.PluginIds);
}
/// Returns zellij's version string.
pub fn getZellijVersion() !zz.OwnedDeserData([]const u8) {
zapi.host_get_zellij_version();
return try recvObj([]const u8);
}
pub fn openFile(path: []const u8) !void {
try sendObj(path);
zapi.host_open_file();
}
/// Switches the currently selected zellij tab to the given index.
pub fn switchTabTo(tab_idx: u32) void {
zapi.host_switch_tab_to(tab_idx);
}
/// Triggers the `.Timer` event in the given amount of seconds.
pub fn setTimeout(secs: f64) void {
zapi.host_set_timeout(secs);
}
/// Executes a system command. This must be enabled in the plugin's configuration.
pub fn execCmd(cmd: []const []const u8) !void {
try sendObj(cmd);
zapi.host_exec_cmd();
}