module patch.opencopied;

import st;
import x;
import config;
import patches;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.string : toStringz;

static if (isPatchEnabled!"OPENCOPIED_PATCH") {
    extern(C) void opencopied(const(Arg)* arg) {
        int res;
        enum size_t max_cmd = 2048;
        char* clip = xsel.clipboard;
        
        if (!clip) {
            fprintf(stderr, "Warning: nothing copied to clipboard\n");
            return;
        }

        /* account for space/quote (3) and \0 (1) and & (1) */
        /* e.g.: xdg-open "https://st.suckless.org"& */
        size_t cmd_size = max_cmd + strlen(clip) + 5;
        char* cmd = cast(char*)malloc(cmd_size);
        if (!cmd) {
            fprintf(stderr, "Error: failed to allocate memory for command\n");
            return;
        }

        snprintf(cmd, cmd_size, "%s \"%s\"&", cast(char*)arg.v, clip);
        res = system(cmd);
        free(cmd);
    }
}