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