scritcher/src/runner.zig

410 lines
13 KiB
Zig
Raw Normal View History

2019-07-08 15:38:16 +00:00
const std = @import("std");
const lang = @import("lang.zig");
const images = @import("image.zig");
2019-07-09 01:40:52 +00:00
const plugin = @import("plugin.zig");
const custom = @import("custom.zig");
2019-07-22 22:28:55 +00:00
const magick = @import("magick.zig");
2019-07-08 15:38:16 +00:00
2019-07-10 20:15:57 +00:00
const Position = plugin.Position;
const ParamList = plugin.ParamList;
const ParamMap = plugin.ParamMap;
2019-07-10 20:15:57 +00:00
const Image = images.Image;
pub const RunError = error{
UnknownCommand,
NoBMP,
ImageRequired,
};
2019-07-08 15:38:16 +00:00
pub const Runner = struct {
allocator: *std.mem.Allocator,
/// The currently opened image in the runner
image: ?*Image = null,
2019-07-08 15:38:16 +00:00
/// If the runner is in REPL mode
repl: bool = false,
pub fn init(allocator: *std.mem.Allocator, repl: bool) Runner {
2019-07-09 03:04:01 +00:00
return Runner{
.allocator = allocator,
.repl = repl,
2019-07-09 03:04:01 +00:00
};
2019-07-08 15:38:16 +00:00
}
pub fn deinit(self: *Runner) void {
if (self.image) |image| {
image.close();
}
}
pub fn clone(self: *Runner) !Runner {
var cloned_image = if (self.image) |image| try image.clone() else null;
return Runner{ .allocator = self.allocator, .image = cloned_image };
}
2019-07-08 16:55:54 +00:00
fn resolveArg(self: *Runner, load_path: []const u8) ![]const u8 {
if (load_path[0] == ':') {
// parse the index from 1 to end
var index = try std.fmt.parseInt(usize, load_path[1..], 10);
// don't care about the 'repl' being prepended when we're in repl
if (self.repl) index += 1;
2019-07-08 16:55:54 +00:00
var args_it = std.process.args();
_ = args_it.skip();
var i: usize = 0;
while (i <= index) : (i += 1) {
_ = args_it.skip();
}
const arg = try (args_it.next(self.allocator) orelse @panic("expected argument"));
return arg;
} else {
return load_path;
}
}
fn resolveArgPath(self: *Runner, path_or_argidx: []const u8) ![]const u8 {
const path = try self.resolveArg(path_or_argidx);
const resolved_path = try std.fs.path.resolve(
self.allocator,
2019-12-08 15:14:31 +00:00
&[_][]const u8{path},
2019-07-08 16:55:54 +00:00
);
2019-07-08 16:55:54 +00:00
return resolved_path;
}
fn loadCmd(self: *Runner, path_or_argidx: []const u8) !void {
2019-07-08 16:55:54 +00:00
var load_path = try self.resolveArgPath(path_or_argidx);
2020-01-15 01:31:20 +00:00
std.debug.warn("\tload path: {}\n", .{load_path});
// we could use ImageMagick to convert from X to BMP
// but i can't find an easy way to do things in memory.
// the upside is that this allows some pre-processing by the user
// before loading the file into scritcher. for example, you can start
// krita/gimp and make it export a bmp and while in the program you can
// apply filters, etc.
if (!std.mem.endsWith(u8, load_path, ".bmp") and !std.mem.endsWith(u8, load_path, ".ppm")) {
2020-01-15 01:31:20 +00:00
std.debug.warn("Only BMP files are allowed to be loaded.\n", .{});
return RunError.NoBMP;
}
2019-07-10 15:00:43 +00:00
// we don't copy load_path into a temporary file because we're already
// loading it under the SFM_READ mode, which won't cause any destructive
// operations on the file.
self.image = try Image.open(self.allocator, load_path);
2019-07-08 16:55:54 +00:00
}
fn getImage(self: *Runner) !*Image {
if (self.image) |image| {
return image;
} else {
2020-01-15 01:31:20 +00:00
std.debug.warn("image is required!\n", .{});
return RunError.ImageRequired;
}
}
2019-07-11 00:43:23 +00:00
fn makeGlitchedPath(self: *Runner) ![]const u8 {
// we want to transform basename, if it is "x.bmp" to "x_gN.bmp", where
// N is the maximum non-used integer.
var image = try self.getImage();
const basename = std.fs.path.basename(image.path);
const dirname = std.fs.path.dirname(image.path).?;
2020-03-26 19:35:58 +00:00
var dir = try std.fs.cwd().openDir(dirname, .{ .iterate = true });
defer dir.close();
const period_idx = std.mem.lastIndexOf(u8, basename, ".").?;
const extension = basename[period_idx..basename.len];
// starts_with would be "x_g", we want to find all files in the directory
// that start with that name.
2020-01-15 01:31:20 +00:00
const starts_with = try std.fmt.allocPrint(self.allocator, "{}_g", .{
basename[0..period_idx],
2020-01-15 01:31:20 +00:00
});
2019-08-13 13:33:08 +00:00
defer self.allocator.free(starts_with);
var max: usize = 0;
2019-10-31 22:02:36 +00:00
var it = dir.iterate();
while (try it.next()) |entry| {
switch (entry.kind) {
.File => blk: {
if (!std.mem.startsWith(u8, entry.name, starts_with)) break :blk {};
// we want to get the N in x_gN.ext
const entry_gidx = std.mem.lastIndexOf(u8, entry.name, "_g").?;
const entry_pidx_opt = std.mem.lastIndexOf(u8, entry.name, ".");
if (entry_pidx_opt == null) break :blk {};
const entry_pidx = entry_pidx_opt.?;
// if N isn't a number, we just ignore that file
const idx_str = entry.name[entry_gidx + 2 .. entry_pidx];
const idx = std.fmt.parseInt(usize, idx_str, 10) catch |err| {
break :blk {};
};
if (idx > max) max = idx;
},
else => {},
}
}
2020-01-15 01:31:20 +00:00
const out_path = try std.fmt.allocPrint(self.allocator, "{}/{}{}{}", .{
2019-07-10 02:04:05 +00:00
dirname,
starts_with,
max + 1,
extension,
2020-01-15 01:31:20 +00:00
});
2019-07-10 02:04:05 +00:00
2019-07-11 00:43:23 +00:00
return out_path;
}
fn quicksaveCmd(self: *Runner) !void {
var image = try self.getImage();
const out_path = try self.makeGlitchedPath();
2019-07-10 02:04:05 +00:00
try image.saveTo(out_path);
}
2019-07-11 00:43:23 +00:00
fn runQSCmd(self: *Runner, program: []const u8) !void {
var image = try self.getImage();
const out_path = try self.makeGlitchedPath();
try image.saveTo(out_path);
var proc = try std.ChildProcess.init(
2019-12-08 15:14:31 +00:00
&[_][]const u8{ program, out_path },
2019-07-11 00:43:23 +00:00
self.allocator,
);
defer proc.deinit();
2020-01-15 01:31:20 +00:00
std.debug.warn("running '{} {}'\n", .{ program, out_path });
2019-07-11 00:43:23 +00:00
_ = try proc.spawnAndWait();
}
2019-07-23 01:22:01 +00:00
fn rotateCmd(
self: *Runner,
deg: f32,
bgfill: []const u8,
) !void {
2019-07-22 22:28:55 +00:00
var image = try self.getImage();
2019-07-23 01:22:01 +00:00
var c_bgfill = try std.cstr.addNullByte(self.allocator, bgfill);
defer self.allocator.free(c_bgfill);
try magick.runRotate(image, deg, c_bgfill);
2019-07-22 22:28:55 +00:00
}
fn executeLV2Command(self: *@This(), command: var) !void {
const pos = plugin.Position{
.split = command.split,
.index = command.index,
};
var params = ParamList.init(self.allocator);
defer params.deinit();
const typ = @TypeOf(command);
inline for (@typeInfo(@TypeOf(command.parameters)).Struct.fields) |cmd_field| {
try params.append(plugin.Param{
.sym = cmd_field.name,
.value = @field(command.parameters, cmd_field.name),
});
}
var image = try self.getImage();
try image.runPlugin(typ.lv2_url, pos, params);
}
2020-06-01 00:47:31 +00:00
fn executePlugin(self: *@This(), command: var) !void {
const pos = plugin.Position{
.split = command.split,
.index = command.index,
};
var params = ParamMap.init(self.allocator);
defer params.deinit();
inline for (@typeInfo(@TypeOf(command.parameters)).Struct.fields) |cmd_field| {
try params.put(
cmd_field.name,
@field(command.parameters, cmd_field.name),
);
}
var image = try self.getImage();
try image.runCustomPlugin(typ.plugin_type, pos, map);
}
2020-05-31 01:56:45 +00:00
fn newRunCommandSingle(
self: *@This(),
2020-05-31 20:18:36 +00:00
cmd: lang.Command,
comptime tag: lang.Command.Tag,
2020-05-31 01:56:45 +00:00
) !void {
2020-05-31 20:18:36 +00:00
comptime const typ = lang.Command.tagToType(tag);
2020-05-31 01:56:45 +00:00
const command = cmd.cast(typ).?;
inline for (@typeInfo(typ).Struct.decls) |decl| {
comptime {
if (!std.mem.eql(u8, decl.name, "command_type")) {
continue;
}
}
2020-05-31 01:56:45 +00:00
const ctype = typ.command_type;
switch (ctype) {
.lv2_command => try self.executeLV2Command(command.*),
2020-06-01 00:47:31 +00:00
.plugin_command => try self.executePlugin(command.*),
else => @panic("TODO support command type"),
}
}
2020-05-31 01:56:45 +00:00
}
2020-05-31 20:18:36 +00:00
fn newRunCommand(self: *@This(), cmd: lang.Command) !void {
2020-05-31 01:56:45 +00:00
switch (cmd.tag) {
.load => {
2020-05-31 20:18:36 +00:00
const command = cmd.cast(lang.Command.Load).?;
try self.loadCmd(command.path);
},
.quicksave => {
try self.quicksaveCmd();
},
.amp => try self.newRunCommandSingle(cmd, .amp),
2020-05-31 19:55:50 +00:00
.rflanger => try self.newRunCommandSingle(cmd, .rflanger),
.eq => try self.newRunCommandSingle(cmd, .eq),
.phaser => try self.newRunCommandSingle(cmd, .phaser),
2020-05-31 20:53:33 +00:00
.mbeq => try self.newRunCommandSingle(cmd, .mbeq),
.chorus => try self.newRunCommandSingle(cmd, .chorus),
.pitchscaler => try self.newRunCommandSingle(cmd, .pitchscaler),
.reverb => try self.newRunCommandSingle(cmd, .reverb),
.highpass => try self.newRunCommandSingle(cmd, .highpass),
.delay => try self.newRunCommandSingle(cmd, .delay),
.vinyl => try self.newRunCommandSingle(cmd, .vinyl),
.revdelay => try self.newRunCommandSingle(cmd, .revdelay),
.gate => try self.newRunCommandSingle(cmd, .gate),
.detune => try self.newRunCommandSingle(cmd, .detune),
.overdrive => try self.newRunCommandSingle(cmd, .overdrive),
.degrade => try self.newRunCommandSingle(cmd, .degrade),
.repsycho => try self.newRunCommandSingle(cmd, .repsycho),
.talkbox => try self.newRunCommandSingle(cmd, .talkbox),
.dyncomp => try self.newRunCommandSingle(cmd, .dyncomp),
.thruzero => try self.newRunCommandSingle(cmd, .thruzero),
.foverdrive => try self.newRunCommandSingle(cmd, .foverdrive),
.gverb => try self.newRunCommandSingle(cmd, .gverb),
.invert => try self.newRunCommandSingle(cmd, .invert),
.tapedelay => try self.newRunCommandSingle(cmd, .tapedelay),
.moddelay => try self.newRunCommandSingle(cmd, .moddelay),
.multichorus => try self.newRunCommandSingle(cmd, .multichorus),
.saturator => try self.newRunCommandSingle(cmd, .saturator),
.vintagedelay => try self.newRunCommandSingle(cmd, .vintagedelay),
2020-05-31 19:55:50 +00:00
2020-06-01 00:47:31 +00:00
.noise, .wildnoise, .write, .embed => |tag| try self.newRunCommandSingle(cmd, tag),
else => {
std.debug.warn("TODO support {}\n", .{@tagName(cmd.tag)});
@panic("TODO support tag");
},
2020-05-31 01:56:45 +00:00
}
}
2019-07-08 15:38:16 +00:00
fn runCommand(self: *Runner, cmd: *lang.Command) !void {
2019-07-10 20:15:57 +00:00
var params = ParamList.init(self.allocator);
2019-07-10 19:59:15 +00:00
defer params.deinit();
var map = ParamMap.init(self.allocator);
defer map.deinit();
2019-07-08 15:38:16 +00:00
return switch (cmd.command) {
.Noop => {},
2019-07-08 16:55:54 +00:00
.Load => blk: {
var path = cmd.args.items[0];
2019-07-08 16:55:54 +00:00
try self.loadCmd(path);
// TODO is this needed?
2019-07-08 16:55:54 +00:00
break :blk;
},
.Quicksave => try self.quicksaveCmd(),
.RunQS => try self.runQSCmd(cmd.args.items[0]),
2019-07-09 01:40:52 +00:00
.Noise => blk: {
const pos = try cmd.consumePosition();
try cmd.appendParamMap(&map, "seed");
try cmd.appendParamMap(&map, "fill_bytes");
try self.noiseCmd(pos, &map);
},
2019-07-13 22:55:57 +00:00
.WildNoise => blk: {
const pos = try cmd.consumePosition();
try cmd.appendParamMap(&map, "seed");
try cmd.appendParamMap(&map, "fill_bytes");
try self.wildNoiseCmd(pos, &map);
},
.Write => blk: {
const pos = try cmd.consumePosition();
try cmd.appendParamMap(&map, "data");
try self.writeCmd(pos, &map);
},
.Embed => blk: {
const pos = try cmd.consumePosition();
const path = cmd.args.items[2];
try self.embedCmd(pos, path);
},
2019-07-23 01:22:01 +00:00
.Rotate => blk: {
const deg = try cmd.floatArgAt(0);
const bgfill = try cmd.argAt(1);
try self.rotateCmd(deg, bgfill);
},
2019-07-22 22:28:55 +00:00
2019-07-08 15:38:16 +00:00
else => blk: {
2020-01-15 01:31:20 +00:00
std.debug.warn("Unsupported command: {}\n", .{cmd.command});
2019-07-08 15:38:16 +00:00
break :blk RunError.UnknownCommand;
},
};
}
/// Run a list of commands.
2019-07-08 16:13:03 +00:00
pub fn runCommands(
self: *Runner,
cmds: lang.CommandList,
debug_flag: bool,
) !void {
for (cmds.items) |cmd| {
2020-05-31 01:39:45 +00:00
cmd.print();
2020-05-31 02:57:34 +00:00
try self.newRunCommand(cmd.*);
2019-07-08 15:38:16 +00:00
}
}
};
test "running noop" {
const allocator = std.heap.direct_allocator;
var cmds = lang.CommandList.init(allocator);
defer cmds.deinit();
var cmd_ptr = try allocator.create(lang.Command);
cmd_ptr.* = lang.Command{
.command = .Noop,
.args = lang.ArgList.init(allocator),
};
try cmds.append(cmd_ptr);
var runner = Runner.init(allocator);
defer runner.deinit();
try runner.runCommands(cmds, false);
}