diff --git a/src/main.c b/src/main.c index 7a45a95..84321fc 100644 --- a/src/main.c +++ b/src/main.c @@ -16,16 +16,120 @@ * along with this program. If not, see . */ +#include #include +#include #include +int run; +void *data; +size_t data_size; + +void quit() { + run = 0; +} + +void send_selection(Display *display, XSelectionRequestEvent *sre, Atom utf8) { + XSelectionEvent se; + time_t now_tm; + char *now; + + now_tm = time(NULL); + now = ctime(&now_tm); + +#ifdef DEBUG + char *an = XGetAtomName(display, sre->property); + printf("Sending CLIPBOARD to window 0x%1x, property '%s'\n", sre->requestor, an); + if(an) + XFree(an); +#endif + + XChangeProperty(display, sre->requestor, sre->property, utf8, 8, PropModeReplace, data, data_size); + +} + int main() { - Display *display = XOpenDisplay(NULL); + Display *display; + Window clip_win, root, owner; + int screen; + Atom selection, utf8, clip_property; + XEvent event; + + // get current X display + display = XOpenDisplay(NULL); if(!display) { fprintf(stderr, "Could not open X display.\n"); return 1; } + screen = DefaultScreen(display); + root = RootWindow(display, screen); + + // create a dummy window for tinyclip + clip_win = XCreateSimpleWindow(display, root, -10, -10, 1, 1, 0, 0, 0); + XSelectInput(display, clip_win, + SelectionClear | SelectionRequest | SelectionNotify); + + // create atoms for selections + selection = XInternAtom(display, "CLIPBOARD", 0); + utf8 = XInternAtom(display, "UTF8_STRING", 0); + clip_property = XInternAtom(display, "TINYCLIP", 0); + + // check if there is currently someone using the clipboard + owner = XGetSelectionOwner(display, selection); + if(owner != None) + { + // take ownership of clipboard while copying contents +#ifdef DEBUG + printf("Current owner: 0x%1X\n", owner); +#endif + XConvertSelection(display, selection, utf8, + clip_property, clip_win, CurrentTime); + } + else + { + XSetSelectionOwner(display, selection, clip_win, CurrentTime); + } + + run = 1; + signal(SIGINT, quit); + + while(run) + { + XNextEvent(display, &event); + XSelectionRequestEvent *sre; + XSelectionEvent *se; + switch(event.type) + { + case SelectionClear: + // if someone else took the clipboard, regain ownership +#ifdef DEBUG + printf("Lost selection.\n"); +#endif + XConvertSelection(display, selection, utf8, + clip_property, clip_win, CurrentTime); + break; + case SelectionNotify: + se = (XSelectionEvent*)&event.xselection; + if(se->property == None) + fprintf(stderr, "Conversion impossible."); + else + { + // TODO: handle new clipboard information + } + XSetSelectionOwner(display, selection, clip_win, CurrentTime); + break; + case SelectionRequest: + // respond to request for clipboard + sre = (XSelectionRequestEvent*) &event.xselectionrequest; +#ifdef DEBUG + printf("New selection request:\n" + " requestor: 0x%1x\n", sre->requestor); +#endif + send_selection(display, sre, utf8); + break; + } + } return 0; }