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