]> mj.ucw.cz Git - misc.git/blob - xclipsend.c
Merge branch 'master' of git+ssh://git.ucw.cz/home/mj/GIT/misc
[misc.git] / xclipsend.c
1 /*
2  *  Send data to primary X selection. Inspired by the `xclip' utility by Kim Saunders.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <X11/Xlib.h>
8 #include <X11/Xatom.h>
9
10 static Display *dpy;
11 static Window win;
12
13 static void die(char *msg)
14 {
15   fprintf(stderr, "xclipsend: %s\n", msg);
16   exit(1);
17 }
18
19 int main(void)
20 {
21   /* Prepare the string */
22   char send[] = "Brum!\n";
23   int len = sizeof(send);
24
25   /* Create display and window */
26   if (!(dpy = XOpenDisplay(NULL)))
27     die("Cannot open display");
28   win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, 0);
29
30   /* Select which events we want to listen to */
31   XSelectInput(dpy, win, PropertyChangeMask);
32
33   /* Take hold of the needed atoms */
34   Atom targets = XInternAtom(dpy, "TARGETS", False);
35
36   /* Assert ownership of the selection */
37   XSetSelectionOwner(dpy, XA_PRIMARY, win, CurrentTime);
38
39   /* Wait for the right event */
40   XEvent ev;
41   for (;;)
42     {
43       XNextEvent(dpy, &ev);
44       if (ev.type == SelectionClear)
45         break;
46       if (ev.type != SelectionRequest)
47         continue;
48
49       Window req_win = ev.xselectionrequest.requestor;
50       Atom req_pty = ev.xselectionrequest.property;
51       if (ev.xselectionrequest.target == targets)
52         {
53           /* We were asked to send a list of supported formats */
54           puts("Type list requested");
55           Atom formats[2] = { targets, XA_STRING };
56           XChangeProperty(dpy, req_win, req_pty, targets, 8, PropModeReplace, (unsigned char *) formats, (int) sizeof(formats));
57         }
58       else
59         {
60           /* We were asked to send the contents */
61           puts("Selection contents requested");
62           XChangeProperty(dpy, req_win, req_pty, XA_STRING, 8, PropModeReplace, (unsigned char *) send, len);
63         }
64
65       /* Respond with another event */
66       XEvent re;
67       re.xselection.property = req_pty;
68       re.xselection.type = SelectionNotify;
69       re.xselection.display = ev.xselectionrequest.display;
70       re.xselection.requestor = req_win;
71       re.xselection.selection = ev.xselectionrequest.selection;
72       re.xselection.target = ev.xselectionrequest.target;
73       re.xselection.time = ev.xselectionrequest.time;
74       XSendEvent(dpy, req_win, 0, 0, &re);
75       XFlush(dpy);
76     }
77   puts("Selection replaced, good bye!");
78
79   return 0;
80 }