]> git.sur5r.net Git - i3/i3/blob - i3-nagbar/main.c
Merge branch 'fix-nagbar'
[i3/i3] / i3-nagbar / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-nagbar is a utility which displays a nag message, for example in the case
8  * when the user has an error in his configuration file.
9  *
10  */
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/wait.h>
15 #include <stdlib.h>
16 #include <stdbool.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <errno.h>
20 #include <err.h>
21 #include <stdint.h>
22 #include <getopt.h>
23 #include <limits.h>
24 #include <fcntl.h>
25
26 #include <xcb/xcb.h>
27 #include <xcb/xcb_aux.h>
28 #include <xcb/xcb_event.h>
29
30 #include "libi3.h"
31 #include "i3-nagbar.h"
32
33 static char *argv0 = NULL;
34
35 typedef struct {
36     i3String *label;
37     char *action;
38     int16_t x;
39     uint16_t width;
40 } button_t;
41
42 static xcb_window_t win;
43 static xcb_pixmap_t pixmap;
44 static xcb_gcontext_t pixmap_gc;
45 static xcb_rectangle_t rect = { 0, 0, 600, 20 };
46 static i3Font font;
47 static i3String *prompt;
48 static button_t *buttons;
49 static int buttoncnt;
50
51 /* Result of get_colorpixel() for the various colors. */
52 static uint32_t color_background;        /* background of the bar */
53 static uint32_t color_button_background; /* background for buttons */
54 static uint32_t color_border;            /* color of the button border */
55 static uint32_t color_border_bottom;     /* color of the bottom border */
56 static uint32_t color_text;              /* color of the text */
57
58 xcb_window_t root;
59 xcb_connection_t *conn;
60 xcb_screen_t *root_screen;
61
62 /*
63  * Having verboselog() and errorlog() is necessary when using libi3.
64  *
65  */
66 void verboselog(char *fmt, ...) {
67     va_list args;
68
69     va_start(args, fmt);
70     vfprintf(stdout, fmt, args);
71     va_end(args);
72 }
73
74 void errorlog(char *fmt, ...) {
75     va_list args;
76
77     va_start(args, fmt);
78     vfprintf(stderr, fmt, args);
79     va_end(args);
80 }
81
82 /*
83  * Starts the given application by passing it through a shell. We use double fork
84  * to avoid zombie processes. As the started application’s parent exits (immediately),
85  * the application is reparented to init (process-id 1), which correctly handles
86  * childs, so we don’t have to do it :-).
87  *
88  * The shell is determined by looking for the SHELL environment variable. If it
89  * does not exist, /bin/sh is used.
90  *
91  */
92 static void start_application(const char *command) {
93     printf("executing: %s\n", command);
94     if (fork() == 0) {
95         /* Child process */
96         setsid();
97         if (fork() == 0) {
98             /* Stores the path of the shell */
99             static const char *shell = NULL;
100
101             if (shell == NULL)
102                 if ((shell = getenv("SHELL")) == NULL)
103                     shell = "/bin/sh";
104
105             /* This is the child */
106             execl(shell, shell, "-c", command, (void*)NULL);
107             /* not reached */
108         }
109         exit(0);
110     }
111     wait(0);
112 }
113
114 static button_t *get_button_at(int16_t x, int16_t y) {
115     for (int c = 0; c < buttoncnt; c++)
116         if (x >= (buttons[c].x) && x <= (buttons[c].x + buttons[c].width))
117             return &buttons[c];
118
119     return NULL;
120 }
121
122 static void handle_button_press(xcb_connection_t *conn, xcb_button_press_event_t *event) {
123     printf("button pressed on x = %d, y = %d\n",
124             event->event_x, event->event_y);
125     /* TODO: set a flag for the button, re-render */
126 }
127
128 /*
129  * Called when the user releases the mouse button. Checks whether the
130  * coordinates are over a button and executes the appropriate action.
131  *
132  */
133 static void handle_button_release(xcb_connection_t *conn, xcb_button_release_event_t *event) {
134     printf("button released on x = %d, y = %d\n",
135             event->event_x, event->event_y);
136     /* If the user hits the close button, we exit(0) */
137     if (event->event_x >= (rect.width - 32))
138         exit(0);
139     button_t *button = get_button_at(event->event_x, event->event_y);
140     if (!button)
141         return;
142
143     /* We need to create a custom script containing our actual command
144      * since not every terminal emulator which is contained in
145      * i3-sensible-terminal supports -e with multiple arguments (and not
146      * all of them support -e with one quoted argument either).
147      *
148      * NB: The paths need to be unique, that is, don’t assume users close
149      * their nagbars at any point in time (and they still need to work).
150      * */
151     char *script_path = get_process_filename("nagbar-cmd");
152
153     int fd = open(script_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
154     if (fd == -1) {
155         warn("Could not create temporary script to store the nagbar command");
156         return;
157     }
158     FILE *script = fdopen(fd, "w");
159     if (script == NULL) {
160         warn("Could not fdopen() temporary script to store the nagbar command");
161         return;
162     }
163     fprintf(script, "#!/bin/sh\nrm %s\n%s", script_path, button->action);
164     /* Also closes fd */
165     fclose(script);
166
167     char *terminal_cmd;
168     sasprintf(&terminal_cmd, "i3-sensible-terminal -e %s", argv0);
169     printf("argv0 = %s\n", argv0);
170     printf("terminal_cmd = %s\n", terminal_cmd);
171
172     setenv("_I3_NAGBAR_CMD", script_path, 1);
173     start_application(terminal_cmd);
174     unsetenv("_I3_NAGBAR_CMD");
175
176     free(terminal_cmd);
177     free(script_path);
178
179     /* TODO: unset flag, re-render */
180 }
181
182 /*
183  * Handles expose events (redraws of the window) and rendering in general. Will
184  * be called from the code with event == NULL or from X with event != NULL.
185  *
186  */
187 static int handle_expose(xcb_connection_t *conn, xcb_expose_event_t *event) {
188     /* re-draw the background */
189     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_background });
190     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &rect);
191
192     /* restore font color */
193     set_font_colors(pixmap_gc, color_text, color_background);
194     draw_text(prompt, pixmap, pixmap_gc,
195             4 + 4, 4 + 4, rect.width - 4 - 4);
196
197     /* render close button */
198     int line_width = 4;
199     int w = 20;
200     int y = rect.width;
201     uint32_t values[3];
202     values[0] = color_button_background;
203     values[1] = line_width;
204     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
205
206     xcb_rectangle_t close = { y - w - (2 * line_width), 0, w + (2 * line_width), rect.height };
207     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &close);
208
209     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_border });
210     xcb_point_t points[] = {
211         { y - w - (2 * line_width), line_width / 2 },
212         { y - (line_width / 2), line_width / 2 },
213         { y - (line_width / 2), (rect.height - (line_width / 2)) - 2 },
214         { y - w - (2 * line_width), (rect.height - (line_width / 2)) - 2 },
215         { y - w - (2 * line_width), line_width / 2 }
216     };
217     xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 5, points);
218
219     values[0] = 1;
220     set_font_colors(pixmap_gc, color_text, color_button_background);
221     draw_text_ascii("X", pixmap, pixmap_gc, y - w - line_width + w / 2 - 4,
222             4 + 4 - 1, rect.width - y + w + line_width - w / 2 + 4);
223     y -= w;
224
225     y -= 20;
226
227     /* render custom buttons */
228     line_width = 1;
229     for (int c = 0; c < buttoncnt; c++) {
230         /* TODO: make w = text extents of the label */
231         w = 100;
232         y -= 30;
233         xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_button_background });
234         close = (xcb_rectangle_t){ y - w - (2 * line_width), 2, w + (2 * line_width), rect.height - 6 };
235         xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &close);
236
237         xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_border });
238         buttons[c].x = y - w - (2 * line_width);
239         buttons[c].width = w;
240         xcb_point_t points2[] = {
241             { y - w - (2 * line_width), (line_width / 2) + 2 },
242             { y - (line_width / 2), (line_width / 2) + 2 },
243             { y - (line_width / 2), (rect.height - 4 - (line_width / 2)) },
244             { y - w - (2 * line_width), (rect.height - 4 - (line_width / 2)) },
245             { y - w - (2 * line_width), (line_width / 2) + 2 }
246         };
247         xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 5, points2);
248
249         values[0] = color_text;
250         values[1] = color_button_background;
251         set_font_colors(pixmap_gc, color_text, color_button_background);
252         draw_text(buttons[c].label, pixmap, pixmap_gc,
253                 y - w - line_width + 6, 4 + 3, rect.width - y + w + line_width - 6);
254
255         y -= w;
256     }
257
258     /* border line at the bottom */
259     line_width = 2;
260     values[0] = color_border_bottom;
261     values[1] = line_width;
262     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
263     xcb_point_t bottom[] = {
264         { 0, rect.height - 0 },
265         { rect.width, rect.height - 0 }
266     };
267     xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 2, bottom);
268
269
270     /* Copy the contents of the pixmap to the real window */
271     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, rect.width, rect.height);
272     xcb_flush(conn);
273
274     return 1;
275 }
276
277 int main(int argc, char *argv[]) {
278     /* The following lines are a horrible kludge. Because terminal emulators
279      * have different ways of interpreting the -e command line argument (some
280      * need -e "less /etc/fstab", others need -e less /etc/fstab), we need to
281      * write commands to a script and then just run that script. However, since
282      * on some machines, $XDG_RUNTIME_DIR and $TMPDIR are mounted with noexec,
283      * we cannot directly execute the script either.
284      *
285      * Therefore, we run i3-nagbar instead and pass the path to the script in
286      * the environment variable $_I3_NAGBAR_CMD. i3-nagbar then execs /bin/sh
287      * with that path in order to run that script.
288      *
289      * From a security point of view, i3-nagbar is just an alias to /bin/sh in
290      * certain circumstances. This should not open any new security issues, I
291      * hope. */
292     char *cmd = NULL;
293     if ((cmd = getenv("_I3_NAGBAR_CMD")) != NULL) {
294         unsetenv("_I3_NAGBAR_CMD");
295         execl("/bin/sh", "/bin/sh", cmd, NULL);
296         err(EXIT_FAILURE, "execv(/bin/sh, /bin/sh, %s)", cmd);
297     }
298
299     argv0 = argv[0];
300
301     char *pattern = sstrdup("-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1");
302     int o, option_index = 0;
303     enum { TYPE_ERROR = 0, TYPE_WARNING = 1 } bar_type = TYPE_ERROR;
304
305     static struct option long_options[] = {
306         {"version", no_argument, 0, 'v'},
307         {"font", required_argument, 0, 'f'},
308         {"button", required_argument, 0, 'b'},
309         {"help", no_argument, 0, 'h'},
310         {"message", required_argument, 0, 'm'},
311         {"type", required_argument, 0, 't'},
312         {0, 0, 0, 0}
313     };
314
315     char *options_string = "b:f:m:t:vh";
316
317     prompt = i3string_from_utf8("Please do not run this program.");
318
319     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
320         switch (o) {
321             case 'v':
322                 printf("i3-nagbar " I3_VERSION);
323                 return 0;
324             case 'f':
325                 FREE(pattern);
326                 pattern = sstrdup(optarg);
327                 break;
328             case 'm':
329                 i3string_free(prompt);
330                 prompt = i3string_from_utf8(optarg);
331                 break;
332             case 't':
333                 bar_type = (strcasecmp(optarg, "warning") == 0 ? TYPE_WARNING : TYPE_ERROR);
334                 break;
335             case 'h':
336                 printf("i3-nagbar " I3_VERSION "\n");
337                 printf("i3-nagbar [-m <message>] [-b <button> <action>] [-t warning|error] [-f <font>] [-v]\n");
338                 return 0;
339             case 'b':
340                 buttons = realloc(buttons, sizeof(button_t) * (buttoncnt + 1));
341                 buttons[buttoncnt].label = i3string_from_utf8(optarg);
342                 buttons[buttoncnt].action = argv[optind];
343                 printf("button with label *%s* and action *%s*\n",
344                         i3string_as_utf8(buttons[buttoncnt].label),
345                         buttons[buttoncnt].action);
346                 buttoncnt++;
347                 printf("now %d buttons\n", buttoncnt);
348                 if (optind < argc)
349                     optind++;
350                 break;
351         }
352     }
353
354     int screens;
355     if ((conn = xcb_connect(NULL, &screens)) == NULL ||
356         xcb_connection_has_error(conn))
357         die("Cannot open display\n");
358
359     /* Place requests for the atoms we need as soon as possible */
360     #define xmacro(atom) \
361         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
362     #include "atoms.xmacro"
363     #undef xmacro
364
365     root_screen = xcb_aux_get_screen(conn, screens);
366     root = root_screen->root;
367
368     if (bar_type == TYPE_ERROR) {
369         /* Red theme for error messages */
370         color_button_background = get_colorpixel("#680a0a");
371         color_background = get_colorpixel("#900000");
372         color_text = get_colorpixel("#ffffff");
373         color_border = get_colorpixel("#d92424");
374         color_border_bottom = get_colorpixel("#470909");
375     } else {
376         /* Yellowish theme for warnings */
377         color_button_background = get_colorpixel("#ffc100");
378         color_background = get_colorpixel("#ffa8000");
379         color_text = get_colorpixel("#000000");
380         color_border = get_colorpixel("#ab7100");
381         color_border_bottom = get_colorpixel("#ab7100");
382     }
383
384     font = load_font(pattern, true);
385     set_font(&font);
386
387     /* Open an input window */
388     win = xcb_generate_id(conn);
389
390     xcb_create_window(
391         conn,
392         XCB_COPY_FROM_PARENT,
393         win, /* the window id */
394         root, /* parent == root */
395         50, 50, 500, font.height + 8 + 8 /* 8 px padding */, /* dimensions */
396         0, /* x11 border = 0, we draw our own */
397         XCB_WINDOW_CLASS_INPUT_OUTPUT,
398         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
399         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
400         (uint32_t[]){
401             0, /* back pixel: black */
402             XCB_EVENT_MASK_EXPOSURE |
403             XCB_EVENT_MASK_STRUCTURE_NOTIFY |
404             XCB_EVENT_MASK_BUTTON_PRESS |
405             XCB_EVENT_MASK_BUTTON_RELEASE
406         });
407
408     /* Map the window (make it visible) */
409     xcb_map_window(conn, win);
410
411     /* Setup NetWM atoms */
412     #define xmacro(name) \
413         do { \
414             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
415             if (!reply) \
416                 die("Could not get atom " # name "\n"); \
417             \
418             A_ ## name = reply->atom; \
419             free(reply); \
420         } while (0);
421     #include "atoms.xmacro"
422     #undef xmacro
423
424     /* Set dock mode */
425     xcb_change_property(conn,
426         XCB_PROP_MODE_REPLACE,
427         win,
428         A__NET_WM_WINDOW_TYPE,
429         A_ATOM,
430         32,
431         1,
432         (unsigned char*) &A__NET_WM_WINDOW_TYPE_DOCK);
433
434     /* Reserve some space at the top of the screen */
435     struct {
436         uint32_t left;
437         uint32_t right;
438         uint32_t top;
439         uint32_t bottom;
440         uint32_t left_start_y;
441         uint32_t left_end_y;
442         uint32_t right_start_y;
443         uint32_t right_end_y;
444         uint32_t top_start_x;
445         uint32_t top_end_x;
446         uint32_t bottom_start_x;
447         uint32_t bottom_end_x;
448     } __attribute__((__packed__)) strut_partial = {0,};
449
450     strut_partial.top = font.height + 6;
451     strut_partial.top_start_x = 0;
452     strut_partial.top_end_x = 800;
453
454     xcb_change_property(conn,
455         XCB_PROP_MODE_REPLACE,
456         win,
457         A__NET_WM_STRUT_PARTIAL,
458         A_CARDINAL,
459         32,
460         12,
461         &strut_partial);
462
463     /* Create pixmap */
464     pixmap = xcb_generate_id(conn);
465     pixmap_gc = xcb_generate_id(conn);
466     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, font.height + 8);
467     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
468
469     /* Grab the keyboard to get all input */
470     xcb_flush(conn);
471
472     xcb_generic_event_t *event;
473     while ((event = xcb_wait_for_event(conn)) != NULL) {
474         if (event->response_type == 0) {
475             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
476             continue;
477         }
478
479         /* Strip off the highest bit (set if the event is generated) */
480         int type = (event->response_type & 0x7F);
481
482         switch (type) {
483             case XCB_EXPOSE:
484                 handle_expose(conn, (xcb_expose_event_t*)event);
485                 break;
486
487             case XCB_BUTTON_PRESS:
488                 handle_button_press(conn, (xcb_button_press_event_t*)event);
489                 break;
490
491             case XCB_BUTTON_RELEASE:
492                 handle_button_release(conn, (xcb_button_release_event_t*)event);
493                 break;
494
495             case XCB_CONFIGURE_NOTIFY: {
496                 xcb_configure_notify_event_t *configure_notify = (xcb_configure_notify_event_t*)event;
497                 rect = (xcb_rectangle_t){
498                     configure_notify->x,
499                     configure_notify->y,
500                     configure_notify->width,
501                     configure_notify->height
502                 };
503
504                 /* Recreate the pixmap / gc */
505                 xcb_free_pixmap(conn, pixmap);
506                 xcb_free_gc(conn, pixmap_gc);
507
508                 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, rect.width, rect.height);
509                 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
510                 break;
511             }
512         }
513
514         free(event);
515     }
516
517     FREE(pattern);
518
519     return 0;
520 }