module patch.iso14755;

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

static if (isPatchEnabled!"ISO14755_PATCH") {
    enum NUMMAXLEN(T) = cast(int)(T.sizeof * 2.56 + 0.5) + 1;
    enum ISO14755CMD = "dmenu -w \"$WINDOWID\" -p codepoint: </dev/null";

    extern(C) void iso14755(const(Arg)* arg) {
        FILE* p;
        char* us;
        char* e;
        char[9] codepoint;
        char[UTF_SIZ] uc;
        ulong utf32;

        p = popen(ISO14755CMD.toStringz, "r".toStringz);
        if (!p)
            return;

        us = fgets(codepoint.ptr, codepoint.sizeof, p);
        pclose(p);

        if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
            return;
        
        utf32 = strtoul(us, &e, 16);
        if (utf32 == ULONG_MAX || (*e != '\n' && *e != '\0'))
            return;

        int len = utf8encode(utf32, uc.ptr);
        ttywrite(uc.ptr, len, 1);
    }
}