]> git.sur5r.net Git - i3/i3/blob - src/cfgparse.y
Implement 'workspace back_and_forth' (Patch by Michael Walle)
[i3/i3] / src / cfgparse.y
1 %{
2 /*
3  * vim:ts=4:sw=4:expandtab
4  *
5  */
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <sys/wait.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11
12 #include "all.h"
13
14 static pid_t configerror_pid = -1;
15
16 static Match current_match;
17
18 typedef struct yy_buffer_state *YY_BUFFER_STATE;
19 extern int yylex(struct context *context);
20 extern int yyparse(void);
21 extern int yylex_destroy(void);
22 extern FILE *yyin;
23 YY_BUFFER_STATE yy_scan_string(const char *);
24
25 static struct bindings_head *current_bindings;
26 static struct context *context;
27
28 /* We don’t need yydebug for now, as we got decent error messages using
29  * yyerror(). Should you ever want to extend the parser, it might be handy
30  * to just comment it in again, so it stays here. */
31 //int yydebug = 1;
32
33 void yyerror(const char *error_message) {
34     context->has_errors = true;
35
36     ELOG("\n");
37     ELOG("CONFIG: %s\n", error_message);
38     ELOG("CONFIG: in file \"%s\", line %d:\n",
39         context->filename, context->line_number);
40     ELOG("CONFIG:   %s\n", context->line_copy);
41     char buffer[context->last_column+1];
42     buffer[context->last_column] = '\0';
43     for (int c = 1; c <= context->last_column; c++)
44         buffer[c-1] = (c >= context->first_column ? '^' : ' ');
45     ELOG("CONFIG:   %s\n", buffer);
46     ELOG("\n");
47 }
48
49 int yywrap() {
50     return 1;
51 }
52
53 /*
54  * Goes through each line of buf (separated by \n) and checks for statements /
55  * commands which only occur in i3 v4 configuration files. If it finds any, it
56  * returns version 4, otherwise it returns version 3.
57  *
58  */
59 static int detect_version(char *buf) {
60     char *walk = buf;
61     char *line = buf;
62     while (*walk != '\0') {
63         if (*walk != '\n') {
64             walk++;
65             continue;
66         }
67
68         /* check for some v4-only statements */
69         if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
70             strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
71             strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
72             strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
73             printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
74             return 4;
75         }
76
77         /* if this is a bind statement, we can check the command */
78         if (strncasecmp(line, "bind", strlen("bind")) == 0) {
79             char *bind = strchr(line, ' ');
80             if (bind == NULL)
81                 goto next;
82             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
83                 bind++;
84             if (*bind == '\0')
85                 goto next;
86             if ((bind = strchr(bind, ' ')) == NULL)
87                 goto next;
88             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
89                 bind++;
90             if (*bind == '\0')
91                 goto next;
92             if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
93                 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
94                 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
95                 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
96                 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
97                 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
98                 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
99                 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
100                 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
101                 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0) {
102                 printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
103                 return 4;
104             }
105         }
106
107 next:
108         /* advance to the next line */
109         walk++;
110         line = walk;
111     }
112
113     return 3;
114 }
115
116 /*
117  * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
118  * buffer).
119  *
120  * Returns the converted config file or NULL if there was an error (for
121  * example the script could not be found in $PATH or the i3 executable’s
122  * directory).
123  *
124  */
125 static char *migrate_config(char *input, off_t size) {
126     int writepipe[2];
127     int readpipe[2];
128
129     if (pipe(writepipe) != 0 ||
130         pipe(readpipe) != 0) {
131         warn("migrate_config: Could not create pipes");
132         return NULL;
133     }
134
135     pid_t pid = fork();
136     if (pid == -1) {
137         warn("Could not fork()");
138         return NULL;
139     }
140
141     /* child */
142     if (pid == 0) {
143         /* close writing end of writepipe, connect reading side to stdin */
144         close(writepipe[1]);
145         dup2(writepipe[0], 0);
146
147         /* close reading end of readpipe, connect writing side to stdout */
148         close(readpipe[0]);
149         dup2(readpipe[1], 1);
150
151         static char *argv[] = {
152             NULL, /* will be replaced by the executable path */
153             NULL
154         };
155         exec_i3_utility("i3-migrate-config-to-v4", argv);
156     }
157
158     /* parent */
159
160     /* close reading end of the writepipe (connected to the script’s stdin) */
161     close(writepipe[0]);
162
163     /* write the whole config file to the pipe, the script will read everything
164      * immediately */
165     int written = 0;
166     int ret;
167     while (written < size) {
168         if ((ret = write(writepipe[1], input + written, size - written)) < 0) {
169             warn("Could not write to pipe");
170             return NULL;
171         }
172         written += ret;
173     }
174     close(writepipe[1]);
175
176     /* close writing end of the readpipe (connected to the script’s stdout) */
177     close(readpipe[1]);
178
179     /* read the script’s output */
180     int conv_size = 65535;
181     char *converted = malloc(conv_size);
182     int read_bytes = 0;
183     do {
184         if (read_bytes == conv_size) {
185             conv_size += 65535;
186             converted = realloc(converted, conv_size);
187         }
188         ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
189         if (ret == -1) {
190             warn("Cannot read from pipe");
191             FREE(converted);
192             return NULL;
193         }
194         read_bytes += ret;
195     } while (ret > 0);
196
197     /* get the returncode */
198     int status;
199     wait(&status);
200     if (!WIFEXITED(status)) {
201         fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
202         return NULL;
203     }
204
205     int returncode = WEXITSTATUS(status);
206     if (returncode != 0) {
207         fprintf(stderr, "Migration process exit code was != 0\n");
208         if (returncode == 2) {
209             fprintf(stderr, "could not start the migration script\n");
210             /* TODO: script was not found. tell the user to fix his system or create a v4 config */
211         } else if (returncode == 1) {
212             fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
213             fprintf(stderr, "# i3 config file (v4)\n");
214             /* TODO: nag the user with a message to include a hint for i3 in his config file */
215         }
216         return NULL;
217     }
218
219     return converted;
220 }
221
222 /*
223  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
224  * it exited (or could not be started, depending on the exit code).
225  *
226  */
227 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
228     ev_child_stop(EV_A_ watcher);
229     if (!WIFEXITED(watcher->rstatus)) {
230         fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
231         return;
232     }
233
234     int exitcode = WEXITSTATUS(watcher->rstatus);
235     printf("i3-nagbar process exited with status %d\n", exitcode);
236     if (exitcode == 2) {
237         fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
238     }
239
240     configerror_pid = -1;
241 }
242
243 /* We need ev >= 4 for the following code. Since it is not *that* important (it
244  * only makes sure that there are no i3-nagbar instances left behind) we still
245  * support old systems with libev 3. */
246 #if EV_VERSION_MAJOR >= 4
247 /*
248  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
249  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
250  *
251  */
252 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
253     if (configerror_pid != -1) {
254         LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", configerror_pid);
255         kill(configerror_pid, SIGKILL);
256     }
257 }
258 #endif
259
260 /*
261  * Starts an i3-nagbar process which alerts the user that his configuration
262  * file contains one or more errors. Also offers two buttons: One to launch an
263  * $EDITOR on the config file and another one to launch a $PAGER on the error
264  * logfile.
265  *
266  */
267 static void start_configerror_nagbar(const char *config_path) {
268     fprintf(stderr, "Would start i3-nagscreen now\n");
269     configerror_pid = fork();
270     if (configerror_pid == -1) {
271         warn("Could not fork()");
272         return;
273     }
274
275     /* child */
276     if (configerror_pid == 0) {
277         char *editaction,
278              *pageraction;
279         if (asprintf(&editaction, "i3-sensible-terminal -e sh -c \"i3-sensible-editor \\\"%s\\\" && i3-msg reload\"", config_path) == -1)
280             exit(1);
281         if (asprintf(&pageraction, "i3-sensible-terminal -e i3-sensible-pager \"%s\"", errorfilename) == -1)
282             exit(1);
283         char *argv[] = {
284             NULL, /* will be replaced by the executable path */
285             "-m",
286             "You have an error in your i3 config file!",
287             "-b",
288             "edit config",
289             editaction,
290             (errorfilename ? "-b" : NULL),
291             "show errors",
292             pageraction,
293             NULL
294         };
295         exec_i3_utility("i3-nagbar", argv);
296     }
297
298     /* parent */
299     /* install a child watcher */
300     ev_child *child = smalloc(sizeof(ev_child));
301     ev_child_init(child, &nagbar_exited, configerror_pid, 0);
302     ev_child_start(main_loop, child);
303
304 /* We need ev >= 4 for the following code. Since it is not *that* important (it
305  * only makes sure that there are no i3-nagbar instances left behind) we still
306  * support old systems with libev 3. */
307 #if EV_VERSION_MAJOR >= 4
308     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
309      * still running) */
310     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
311     ev_cleanup_init(cleanup, nagbar_cleanup);
312     ev_cleanup_start(main_loop, cleanup);
313 #endif
314 }
315
316 /*
317  * Kills the configerror i3-nagbar process, if any.
318  *
319  * Called when reloading/restarting.
320  *
321  * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
322  * ev is assumed to handle it (reloading).
323  *
324  */
325 void kill_configerror_nagbar(bool wait_for_it) {
326     if (configerror_pid == -1)
327         return;
328
329     if (kill(configerror_pid, SIGTERM) == -1)
330         warn("kill(configerror_nagbar) failed");
331
332     if (!wait_for_it)
333         return;
334
335     /* When restarting, we don’t enter the ev main loop anymore and after the
336      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
337      * for us and we would end up with a <defunct> process. Therefore we
338      * waitpid() here. */
339     waitpid(configerror_pid, NULL, 0);
340 }
341
342 /*
343  * Checks for duplicate key bindings (the same keycode or keysym is configured
344  * more than once). If a duplicate binding is found, a message is printed to
345  * stderr and the has_errors variable is set to true, which will start
346  * i3-nagbar.
347  *
348  */
349 static void check_for_duplicate_bindings(struct context *context) {
350     Binding *bind, *current;
351     TAILQ_FOREACH(current, bindings, bindings) {
352         TAILQ_FOREACH(bind, bindings, bindings) {
353             /* Abort when we reach the current keybinding, only check the
354              * bindings before */
355             if (bind == current)
356                 break;
357
358             /* Check if one is using keysym while the other is using bindsym.
359              * If so, skip. */
360             /* XXX: It should be checked at a later place (when translating the
361              * keysym to keycodes) if there are any duplicates */
362             if ((bind->symbol == NULL && current->symbol != NULL) ||
363                 (bind->symbol != NULL && current->symbol == NULL))
364                 continue;
365
366             /* If bind is NULL, current has to be NULL, too (see above).
367              * If the keycodes differ, it can't be a duplicate. */
368             if (bind->symbol != NULL &&
369                 strcasecmp(bind->symbol, current->symbol) != 0)
370                 continue;
371
372             /* Check if the keycodes or modifiers are different. If so, they
373              * can't be duplicate */
374             if (bind->keycode != current->keycode ||
375                 bind->mods != current->mods)
376                 continue;
377             context->has_errors = true;
378             if (current->keycode != 0) {
379                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keycode %d, command \"%s\"\n",
380                      current->mods, current->keycode, current->command);
381             } else {
382                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keysym %s, command \"%s\"\n",
383                      current->mods, current->symbol, current->command);
384             }
385         }
386     }
387 }
388
389 void parse_file(const char *f) {
390     SLIST_HEAD(variables_head, Variable) variables = SLIST_HEAD_INITIALIZER(&variables);
391     int fd, ret, read_bytes = 0;
392     struct stat stbuf;
393     char *buf;
394     FILE *fstr;
395     char buffer[1026], key[512], value[512];
396
397     if ((fd = open(f, O_RDONLY)) == -1)
398         die("Could not open configuration file: %s\n", strerror(errno));
399
400     if (fstat(fd, &stbuf) == -1)
401         die("Could not fstat file: %s\n", strerror(errno));
402
403     buf = scalloc((stbuf.st_size + 1) * sizeof(char));
404     while (read_bytes < stbuf.st_size) {
405         if ((ret = read(fd, buf + read_bytes, (stbuf.st_size - read_bytes))) < 0)
406             die("Could not read(): %s\n", strerror(errno));
407         read_bytes += ret;
408     }
409
410     if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
411         die("Could not lseek: %s\n", strerror(errno));
412
413     if ((fstr = fdopen(fd, "r")) == NULL)
414         die("Could not fdopen: %s\n", strerror(errno));
415
416     while (!feof(fstr)) {
417         if (fgets(buffer, 1024, fstr) == NULL) {
418             if (feof(fstr))
419                 break;
420             die("Could not read configuration file\n");
421         }
422
423         /* sscanf implicitly strips whitespace. Also, we skip comments and empty lines. */
424         if (sscanf(buffer, "%s %[^\n]", key, value) < 1 ||
425             key[0] == '#' || strlen(key) < 3)
426             continue;
427
428         if (strcasecmp(key, "set") == 0) {
429             if (value[0] != '$') {
430                 ELOG("Malformed variable assignment, name has to start with $\n");
431                 continue;
432             }
433
434             /* get key/value for this variable */
435             char *v_key = value, *v_value;
436             if (strstr(value, " ") == NULL && strstr(value, "\t") == NULL) {
437                 ELOG("Malformed variable assignment, need a value\n");
438                 continue;
439             }
440
441             if (!(v_value = strstr(value, " ")))
442                 v_value = strstr(value, "\t");
443
444             *(v_value++) = '\0';
445
446             struct Variable *new = scalloc(sizeof(struct Variable));
447             new->key = sstrdup(v_key);
448             new->value = sstrdup(v_value);
449             SLIST_INSERT_HEAD(&variables, new, variables);
450             DLOG("Got new variable %s = %s\n", v_key, v_value);
451             continue;
452         }
453     }
454     fclose(fstr);
455
456     /* For every custom variable, see how often it occurs in the file and
457      * how much extra bytes it requires when replaced. */
458     struct Variable *current, *nearest;
459     int extra_bytes = 0;
460     /* We need to copy the buffer because we need to invalidate the
461      * variables (otherwise we will count them twice, which is bad when
462      * 'extra' is negative) */
463     char *bufcopy = sstrdup(buf);
464     SLIST_FOREACH(current, &variables, variables) {
465         int extra = (strlen(current->value) - strlen(current->key));
466         char *next;
467         for (next = bufcopy;
468              next < (bufcopy + stbuf.st_size) &&
469              (next = strcasestr(next, current->key)) != NULL;
470              next += strlen(current->key)) {
471             *next = '_';
472             extra_bytes += extra;
473         }
474     }
475     FREE(bufcopy);
476
477     /* Then, allocate a new buffer and copy the file over to the new one,
478      * but replace occurences of our variables */
479     char *walk = buf, *destwalk;
480     char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
481     destwalk = new;
482     while (walk < (buf + stbuf.st_size)) {
483         /* Find the next variable */
484         SLIST_FOREACH(current, &variables, variables)
485             current->next_match = strcasestr(walk, current->key);
486         nearest = NULL;
487         int distance = stbuf.st_size;
488         SLIST_FOREACH(current, &variables, variables) {
489             if (current->next_match == NULL)
490                 continue;
491             if ((current->next_match - walk) < distance) {
492                 distance = (current->next_match - walk);
493                 nearest = current;
494             }
495         }
496         if (nearest == NULL) {
497             /* If there are no more variables, we just copy the rest */
498             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
499             destwalk += (buf + stbuf.st_size) - walk;
500             *destwalk = '\0';
501             break;
502         } else {
503             /* Copy until the next variable, then copy its value */
504             strncpy(destwalk, walk, distance);
505             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
506             walk += distance + strlen(nearest->key);
507             destwalk += distance + strlen(nearest->value);
508         }
509     }
510
511     /* analyze the string to find out whether this is an old config file (3.x)
512      * or a new config file (4.x). If it’s old, we run the converter script. */
513     int version = detect_version(buf);
514     if (version == 3) {
515         /* We need to convert this v3 configuration */
516         char *converted = migrate_config(new, stbuf.st_size);
517         if (converted != NULL) {
518             printf("\n");
519             printf("****************************************************************\n");
520             printf("NOTE: Automatically converted configuration file from v3 to v4.\n");
521             printf("\n");
522             printf("Please convert your config file to v4. You can use this command:\n");
523             printf("    mv %s %s.O\n", f, f);
524             printf("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
525             printf("****************************************************************\n");
526             printf("\n");
527             free(new);
528             new = converted;
529         } else {
530             printf("\n");
531             printf("**********************************************************************\n");
532             printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
533             printf("was not correctly installed on your system?\n");
534             printf("**********************************************************************\n");
535             printf("\n");
536         }
537     }
538
539     /* now lex/parse it */
540     yy_scan_string(new);
541
542     context = scalloc(sizeof(struct context));
543     context->filename = f;
544
545     if (yyparse() != 0) {
546         fprintf(stderr, "Could not parse configfile\n");
547         exit(1);
548     }
549
550     check_for_duplicate_bindings(context);
551
552     if (context->has_errors) {
553         start_configerror_nagbar(f);
554     }
555
556     yylex_destroy();
557     FREE(context->line_copy);
558     free(context);
559     free(new);
560     free(buf);
561
562     while (!SLIST_EMPTY(&variables)) {
563         current = SLIST_FIRST(&variables);
564         FREE(current->key);
565         FREE(current->value);
566         SLIST_REMOVE_HEAD(&variables, variables);
567         FREE(current);
568     }
569 }
570
571 %}
572
573 %error-verbose
574 %lex-param { struct context *context }
575
576 %union {
577     int number;
578     char *string;
579     uint32_t *single_color;
580     struct Colortriple *color;
581     Match *match;
582     struct Binding *binding;
583 }
584
585 %token  <number>        NUMBER                      "<number>"
586 %token  <string>        WORD                        "<word>"
587 %token  <string>        STR                         "<string>"
588 %token  <string>        STR_NG                      "<string (non-greedy)>"
589 %token  <string>        HEX                         "<hex>"
590 %token  <string>        OUTPUT                      "<RandR output>"
591 %token                  TOKBINDCODE
592 %token                  TOKTERMINAL
593 %token                  TOKCOMMENT                  "<comment>"
594 %token                  TOKFONT                     "font"
595 %token                  TOKBINDSYM                  "bindsym"
596 %token  <number>        MODIFIER                    "<modifier>"
597 %token                  TOKCONTROL                  "control"
598 %token                  TOKSHIFT                    "shift"
599 %token                  TOKFLOATING_MODIFIER        "floating_modifier"
600 %token  <string>        QUOTEDSTRING                "<quoted string>"
601 %token                  TOKWORKSPACE                "workspace"
602 %token                  TOKOUTPUT                   "output"
603 %token                  TOKASSIGN                   "assign"
604 %token                  TOKSET
605 %token                  TOKIPCSOCKET                "ipc_socket"
606 %token                  TOKRESTARTSTATE             "restart_state"
607 %token                  TOKEXEC                     "exec"
608 %token                  TOKEXEC_ALWAYS              "exec_always"
609 %token  <single_color>  TOKSINGLECOLOR
610 %token  <color>         TOKCOLOR
611 %token                  TOKARROW                    "→"
612 %token                  TOKMODE                     "mode"
613 %token                  TOK_ORIENTATION             "default_orientation"
614 %token                  TOK_HORIZ                   "horizontal"
615 %token                  TOK_VERT                    "vertical"
616 %token                  TOK_AUTO                    "auto"
617 %token                  TOK_WORKSPACE_LAYOUT        "workspace_layout"
618 %token                  TOKNEWWINDOW                "new_window"
619 %token                  TOKNEWFLOAT                 "new_float"
620 %token                  TOK_NORMAL                  "normal"
621 %token                  TOK_NONE                    "none"
622 %token                  TOK_1PIXEL                  "1pixel"
623 %token                  TOKFOCUSFOLLOWSMOUSE        "focus_follows_mouse"
624 %token                  TOK_FORCE_FOCUS_WRAPPING    "force_focus_wrapping"
625 %token                  TOK_FORCE_XINERAMA          "force_xinerama"
626 %token                  TOK_WORKSPACE_AUTO_BAF      "workspace_auto_back_and_forth"
627 %token                  TOKWORKSPACEBAR             "workspace_bar"
628 %token                  TOK_DEFAULT                 "default"
629 %token                  TOK_STACKING                "stacking"
630 %token                  TOK_TABBED                  "tabbed"
631 %token  <number>        TOKSTACKLIMIT               "stack-limit"
632 %token                  TOK_POPUP_DURING_FULLSCREEN "popup_during_fullscreen"
633 %token                  TOK_IGNORE                  "ignore"
634 %token                  TOK_LEAVE_FULLSCREEN        "leave_fullscreen"
635 %token                  TOK_FOR_WINDOW              "for_window"
636
637 %token              TOK_MARK            "mark"
638 %token              TOK_CLASS           "class"
639 %token              TOK_INSTANCE        "instance"
640 %token              TOK_WINDOW_ROLE     "window_role"
641 %token              TOK_ID              "id"
642 %token              TOK_CON_ID          "con_id"
643 %token              TOK_TITLE           "title"
644
645 %type   <binding>       binding
646 %type   <binding>       bindcode
647 %type   <binding>       bindsym
648 %type   <number>        binding_modifiers
649 %type   <number>        binding_modifier
650 %type   <number>        direction
651 %type   <number>        layout_mode
652 %type   <number>        border_style
653 %type   <number>        new_window
654 %type   <number>        new_float
655 %type   <number>        colorpixel
656 %type   <number>        bool
657 %type   <number>        popup_setting
658 %type   <string>        command
659 %type   <string>        word_or_number
660 %type   <string>        optional_workspace_name
661 %type   <string>        workspace_name
662 %type   <string>        window_class
663
664 %%
665
666 lines: /* empty */
667     | lines error
668     | lines line
669     ;
670
671 line:
672     bindline
673     | for_window
674     | mode
675     | floating_modifier
676     | orientation
677     | workspace_layout
678     | new_window
679     | new_float
680     | focus_follows_mouse
681     | force_focus_wrapping
682     | force_xinerama
683     | workspace_back_and_forth
684     | workspace_bar
685     | workspace
686     | assign
687     | ipcsocket
688     | restart_state
689     | exec
690     | exec_always
691     | single_color
692     | color
693     | terminal
694     | font
695     | comment
696     | popup_during_fullscreen
697     ;
698
699 comment:
700     TOKCOMMENT
701     ;
702
703 command:
704     STR
705     ;
706
707 bindline:
708     binding
709     {
710         TAILQ_INSERT_TAIL(bindings, $1, bindings);
711     }
712     ;
713
714 binding:
715     TOKBINDCODE bindcode         { $$ = $2; }
716     | TOKBINDSYM bindsym         { $$ = $2; }
717     ;
718
719 bindcode:
720     binding_modifiers NUMBER command
721     {
722         printf("\tFound keycode binding mod%d with key %d and command %s\n", $1, $2, $3);
723         Binding *new = scalloc(sizeof(Binding));
724
725         new->keycode = $2;
726         new->mods = $1;
727         new->command = $3;
728
729         $$ = new;
730     }
731     ;
732
733 bindsym:
734     binding_modifiers word_or_number command
735     {
736         printf("\tFound keysym binding mod%d with key %s and command %s\n", $1, $2, $3);
737         Binding *new = scalloc(sizeof(Binding));
738
739         new->symbol = $2;
740         new->mods = $1;
741         new->command = $3;
742
743         $$ = new;
744     }
745     ;
746
747 for_window:
748     TOK_FOR_WINDOW match command
749     {
750         if (match_is_empty(&current_match)) {
751             ELOG("Match is empty, ignoring this for_window statement\n");
752             break;
753         }
754         printf("\t should execute command %s for the criteria mentioned above\n", $3);
755         Assignment *assignment = scalloc(sizeof(Assignment));
756         assignment->type = A_COMMAND;
757         assignment->match = current_match;
758         assignment->dest.command = $3;
759         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
760     }
761     ;
762
763 match:
764     | matchstart criteria matchend
765     {
766         printf("match parsed\n");
767     }
768     ;
769
770 matchstart:
771     '['
772     {
773         printf("start\n");
774         match_init(&current_match);
775     }
776     ;
777
778 matchend:
779     ']'
780     {
781         printf("match specification finished\n");
782     }
783     ;
784
785 criteria:
786     criteria criterion
787     | criterion
788     ;
789
790 criterion:
791     TOK_CLASS '=' STR
792     {
793         printf("criteria: class = %s\n", $3);
794         current_match.class = regex_new($3);
795         free($3);
796     }
797     | TOK_INSTANCE '=' STR
798     {
799         printf("criteria: instance = %s\n", $3);
800         current_match.instance = regex_new($3);
801         free($3);
802     }
803     | TOK_WINDOW_ROLE '=' STR
804     {
805         printf("criteria: window_role = %s\n", $3);
806         current_match.role = regex_new($3);
807         free($3);
808     }
809     | TOK_CON_ID '=' STR
810     {
811         printf("criteria: id = %s\n", $3);
812         char *end;
813         long parsed = strtol($3, &end, 10);
814         if (parsed == LONG_MIN ||
815             parsed == LONG_MAX ||
816             parsed < 0 ||
817             (end && *end != '\0')) {
818             ELOG("Could not parse con id \"%s\"\n", $3);
819         } else {
820             current_match.con_id = (Con*)parsed;
821             printf("id as int = %p\n", current_match.con_id);
822         }
823     }
824     | TOK_ID '=' STR
825     {
826         printf("criteria: window id = %s\n", $3);
827         char *end;
828         long parsed = strtol($3, &end, 10);
829         if (parsed == LONG_MIN ||
830             parsed == LONG_MAX ||
831             parsed < 0 ||
832             (end && *end != '\0')) {
833             ELOG("Could not parse window id \"%s\"\n", $3);
834         } else {
835             current_match.id = parsed;
836             printf("window id as int = %d\n", current_match.id);
837         }
838     }
839     | TOK_MARK '=' STR
840     {
841         printf("criteria: mark = %s\n", $3);
842         current_match.mark = regex_new($3);
843         free($3);
844     }
845     | TOK_TITLE '=' STR
846     {
847         printf("criteria: title = %s\n", $3);
848         current_match.title = regex_new($3);
849         free($3);
850     }
851     ;
852
853
854
855 word_or_number:
856     WORD
857     | NUMBER
858     {
859         asprintf(&$$, "%d", $1);
860     }
861     ;
862
863 mode:
864     TOKMODE QUOTEDSTRING '{' modelines '}'
865     {
866         if (strcasecmp($2, "default") == 0) {
867             printf("You cannot use the name \"default\" for your mode\n");
868             exit(1);
869         }
870         printf("\t now in mode %s\n", $2);
871         printf("\t current bindings = %p\n", current_bindings);
872         Binding *binding;
873         TAILQ_FOREACH(binding, current_bindings, bindings) {
874             printf("got binding on mods %d, keycode %d, symbol %s, command %s\n",
875                             binding->mods, binding->keycode, binding->symbol, binding->command);
876         }
877
878         struct Mode *mode = scalloc(sizeof(struct Mode));
879         mode->name = $2;
880         mode->bindings = current_bindings;
881         current_bindings = NULL;
882         SLIST_INSERT_HEAD(&modes, mode, modes);
883     }
884     ;
885
886
887 modelines:
888     /* empty */
889     | modelines modeline
890     ;
891
892 modeline:
893     comment
894     | binding
895     {
896         if (current_bindings == NULL) {
897             current_bindings = scalloc(sizeof(struct bindings_head));
898             TAILQ_INIT(current_bindings);
899         }
900
901         TAILQ_INSERT_TAIL(current_bindings, $1, bindings);
902     }
903     ;
904
905 floating_modifier:
906     TOKFLOATING_MODIFIER binding_modifiers
907     {
908         DLOG("floating modifier = %d\n", $2);
909         config.floating_modifier = $2;
910     }
911     ;
912
913 orientation:
914     TOK_ORIENTATION direction
915     {
916         DLOG("New containers should start with split direction %d\n", $2);
917         config.default_orientation = $2;
918     }
919     ;
920
921 direction:
922     TOK_HORIZ       { $$ = HORIZ; }
923     | TOK_VERT      { $$ = VERT; }
924     | TOK_AUTO      { $$ = NO_ORIENTATION; }
925     ;
926
927 workspace_layout:
928     TOK_WORKSPACE_LAYOUT layout_mode
929     {
930         DLOG("new containers will be in mode %d\n", $2);
931         config.default_layout = $2;
932
933 #if 0
934         /* We also need to change the layout of the already existing
935          * workspaces here. Workspaces may exist at this point because
936          * of the other directives which are modifying workspaces
937          * (setting the preferred screen or name). While the workspace
938          * objects are already created, they have never been used.
939          * Thus, the user very likely awaits the default container mode
940          * to trigger in this case, regardless of where it is inside
941          * his configuration file. */
942         Workspace *ws;
943         TAILQ_FOREACH(ws, workspaces, workspaces) {
944                 if (ws->table == NULL)
945                         continue;
946                 switch_layout_mode(global_conn,
947                                    ws->table[0][0],
948                                    config.container_mode);
949         }
950 #endif
951     }
952     | TOK_WORKSPACE_LAYOUT TOKSTACKLIMIT TOKSTACKLIMIT NUMBER
953     {
954         DLOG("stack-limit %d with val %d\n", $3, $4);
955         config.container_stack_limit = $3;
956         config.container_stack_limit_value = $4;
957
958 #if 0
959         /* See the comment above */
960         Workspace *ws;
961         TAILQ_FOREACH(ws, workspaces, workspaces) {
962                 if (ws->table == NULL)
963                         continue;
964                 Container *con = ws->table[0][0];
965                 con->stack_limit = config.container_stack_limit;
966                 con->stack_limit_value = config.container_stack_limit_value;
967         }
968 #endif
969     }
970     ;
971
972 layout_mode:
973     TOK_DEFAULT       { $$ = L_DEFAULT; }
974     | TOK_STACKING    { $$ = L_STACKED; }
975     | TOK_TABBED      { $$ = L_TABBED; }
976     ;
977
978 new_window:
979     TOKNEWWINDOW border_style
980     {
981         DLOG("new windows should start with border style %d\n", $2);
982         config.default_border = $2;
983     }
984     ;
985
986 new_float:
987     TOKNEWFLOAT border_style
988     {
989        DLOG("new floating windows should start with border style %d\n", $2);
990        config.default_floating_border = $2;
991     }
992     ;
993
994 border_style:
995     TOK_NORMAL      { $$ = BS_NORMAL; }
996     | TOK_NONE      { $$ = BS_NONE; }
997     | TOK_1PIXEL    { $$ = BS_1PIXEL; }
998     ;
999
1000 bool:
1001     NUMBER
1002     {
1003         $$ = ($1 == 1);
1004     }
1005     | WORD
1006     {
1007         DLOG("checking word \"%s\"\n", $1);
1008         $$ = (strcasecmp($1, "yes") == 0 ||
1009               strcasecmp($1, "true") == 0 ||
1010               strcasecmp($1, "on") == 0 ||
1011               strcasecmp($1, "enable") == 0 ||
1012               strcasecmp($1, "active") == 0);
1013     }
1014     ;
1015
1016 focus_follows_mouse:
1017     TOKFOCUSFOLLOWSMOUSE bool
1018     {
1019         DLOG("focus follows mouse = %d\n", $2);
1020         config.disable_focus_follows_mouse = !($2);
1021     }
1022     ;
1023
1024 force_focus_wrapping:
1025     TOK_FORCE_FOCUS_WRAPPING bool
1026     {
1027         DLOG("force focus wrapping = %d\n", $2);
1028         config.force_focus_wrapping = $2;
1029     }
1030     ;
1031
1032 force_xinerama:
1033     TOK_FORCE_XINERAMA bool
1034     {
1035         DLOG("force xinerama = %d\n", $2);
1036         config.force_xinerama = $2;
1037     }
1038     ;
1039
1040 workspace_back_and_forth:
1041     TOK_WORKSPACE_AUTO_BAF bool
1042     {
1043         DLOG("automatic workspace back-and-forth = %d\n", $2);
1044         config.workspace_auto_back_and_forth = $2;
1045     }
1046     ;
1047
1048 workspace_bar:
1049     TOKWORKSPACEBAR bool
1050     {
1051         DLOG("workspace bar = %d\n", $2);
1052         config.disable_workspace_bar = !($2);
1053     }
1054     ;
1055
1056 workspace:
1057     TOKWORKSPACE NUMBER TOKOUTPUT OUTPUT optional_workspace_name
1058     {
1059         int ws_num = $2;
1060         if (ws_num < 1) {
1061             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
1062         } else {
1063             char *ws_name = NULL;
1064             if ($5 == NULL) {
1065                 asprintf(&ws_name, "%d", ws_num);
1066             } else {
1067                 ws_name = $5;
1068             }
1069
1070             DLOG("Should assign workspace %s to output %s\n", ws_name, $4);
1071             /* Check for earlier assignments of the same workspace so that we
1072              * don’t have assignments of a single workspace to different
1073              * outputs */
1074             struct Workspace_Assignment *assignment;
1075             bool duplicate = false;
1076             TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
1077                 if (strcasecmp(assignment->name, ws_name) == 0) {
1078                     ELOG("You have a duplicate workspace assignment for workspace \"%s\"\n",
1079                          ws_name);
1080                     assignment->output = $4;
1081                     duplicate = true;
1082                 }
1083             }
1084             if (!duplicate) {
1085                 assignment = scalloc(sizeof(struct Workspace_Assignment));
1086                 assignment->name = ws_name;
1087                 assignment->output = $4;
1088                 TAILQ_INSERT_TAIL(&ws_assignments, assignment, ws_assignments);
1089             }
1090         }
1091     }
1092     | TOKWORKSPACE NUMBER workspace_name
1093     {
1094         int ws_num = $2;
1095         if (ws_num < 1) {
1096             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
1097         } else {
1098             DLOG("workspace name to: %s\n", $3);
1099 #if 0
1100             if ($<string>3 != NULL) {
1101                     workspace_set_name(workspace_get(ws_num - 1), $<string>3);
1102                     free($<string>3);
1103             }
1104 #endif
1105         }
1106     }
1107     ;
1108
1109 optional_workspace_name:
1110     /* empty */          { $$ = NULL; }
1111     | workspace_name     { $$ = $1; }
1112     ;
1113
1114 workspace_name:
1115     QUOTEDSTRING         { $$ = $1; }
1116     | STR                { $$ = $1; }
1117     | WORD               { $$ = $1; }
1118     ;
1119
1120 assign:
1121     TOKASSIGN window_class STR
1122     {
1123         /* This is the old, deprecated form of assignments. It’s provided for
1124          * compatibility in version (4.1, 4.2, 4.3) and will be removed
1125          * afterwards. It triggers an i3-nagbar warning starting from 4.1. */
1126         ELOG("You are using the old assign syntax (without criteria). "
1127              "Please see the User's Guide for the new syntax and fix "
1128              "your config file.\n");
1129         context->has_errors = true;
1130         printf("assignment of %s to *%s*\n", $2, $3);
1131         char *workspace = $3;
1132         char *criteria = $2;
1133
1134         Assignment *assignment = scalloc(sizeof(Assignment));
1135         Match *match = &(assignment->match);
1136         match_init(match);
1137
1138         char *separator = NULL;
1139         if ((separator = strchr(criteria, '/')) != NULL) {
1140             *(separator++) = '\0';
1141             char *pattern;
1142             if (asprintf(&pattern, "(?i)%s", separator) == -1) {
1143                 ELOG("asprintf failed\n");
1144                 break;
1145             }
1146             match->title = regex_new(pattern);
1147             free(pattern);
1148             printf("  title = %s\n", separator);
1149         }
1150         if (*criteria != '\0') {
1151             char *pattern;
1152             if (asprintf(&pattern, "(?i)%s", criteria) == -1) {
1153                 ELOG("asprintf failed\n");
1154                 break;
1155             }
1156             match->class = regex_new(pattern);
1157             free(pattern);
1158             printf("  class = %s\n", criteria);
1159         }
1160         free(criteria);
1161
1162         /* Compatibility with older versions: If the assignment target starts
1163          * with ~, we create the equivalent of:
1164          *
1165          * for_window [class="foo"] floating enable
1166          */
1167         if (*workspace == '~') {
1168             workspace++;
1169             if (*workspace == '\0') {
1170                 /* This assignment was *only* for floating */
1171                 assignment->type = A_COMMAND;
1172                 assignment->dest.command = sstrdup("floating enable");
1173                 TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1174                 break;
1175             } else {
1176                 /* Create a new assignment and continue afterwards */
1177                 Assignment *floating = scalloc(sizeof(Assignment));
1178                 match_copy(&(floating->match), match);
1179                 floating->type = A_COMMAND;
1180                 floating->dest.command = sstrdup("floating enable");
1181                 TAILQ_INSERT_TAIL(&assignments, floating, assignments);
1182             }
1183         }
1184
1185         assignment->type = A_TO_WORKSPACE;
1186         assignment->dest.workspace = workspace;
1187         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1188     }
1189     | TOKASSIGN match STR
1190     {
1191         if (match_is_empty(&current_match)) {
1192             ELOG("Match is empty, ignoring this assignment\n");
1193             break;
1194         }
1195         printf("new assignment, using above criteria, to workspace %s\n", $3);
1196         Assignment *assignment = scalloc(sizeof(Assignment));
1197         assignment->match = current_match;
1198         assignment->type = A_TO_WORKSPACE;
1199         assignment->dest.workspace = $3;
1200         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1201     }
1202     ;
1203
1204 window_class:
1205     QUOTEDSTRING
1206     | STR_NG
1207     ;
1208
1209 ipcsocket:
1210     TOKIPCSOCKET STR
1211     {
1212         config.ipc_socket_path = $2;
1213     }
1214     ;
1215
1216 restart_state:
1217     TOKRESTARTSTATE STR
1218     {
1219         config.restart_state_path = $2;
1220     }
1221     ;
1222
1223 exec:
1224     TOKEXEC STR
1225     {
1226         struct Autostart *new = smalloc(sizeof(struct Autostart));
1227         new->command = $2;
1228         TAILQ_INSERT_TAIL(&autostarts, new, autostarts);
1229     }
1230     ;
1231
1232 exec_always:
1233     TOKEXEC_ALWAYS STR
1234     {
1235         struct Autostart *new = smalloc(sizeof(struct Autostart));
1236         new->command = $2;
1237         TAILQ_INSERT_TAIL(&autostarts_always, new, autostarts_always);
1238     }
1239     ;
1240
1241 terminal:
1242     TOKTERMINAL STR
1243     {
1244         ELOG("The terminal option is DEPRECATED and has no effect. "
1245             "Please remove it from your configuration file.\n");
1246     }
1247     ;
1248
1249 font:
1250     TOKFONT STR
1251     {
1252         config.font = load_font($2, true);
1253         printf("font %s\n", $2);
1254         free($2);
1255     }
1256     ;
1257
1258 single_color:
1259     TOKSINGLECOLOR colorpixel
1260     {
1261         uint32_t *dest = $1;
1262         *dest = $2;
1263     }
1264     ;
1265
1266 color:
1267     TOKCOLOR colorpixel colorpixel colorpixel
1268     {
1269         struct Colortriple *dest = $1;
1270
1271         dest->border = $2;
1272         dest->background = $3;
1273         dest->text = $4;
1274     }
1275     ;
1276
1277 colorpixel:
1278     '#' HEX
1279     {
1280         char *hex;
1281         if (asprintf(&hex, "#%s", $2) == -1)
1282             die("asprintf()");
1283         free($2);
1284         $$ = get_colorpixel(hex);
1285         free(hex);
1286     }
1287     ;
1288
1289
1290 binding_modifiers:
1291     /* NULL */                               { $$ = 0; }
1292     | binding_modifier
1293     | binding_modifiers '+' binding_modifier { $$ = $1 | $3; }
1294     | binding_modifiers '+'                  { $$ = $1; }
1295     ;
1296
1297 binding_modifier:
1298     MODIFIER        { $$ = $1; }
1299     | TOKCONTROL    { $$ = BIND_CONTROL; }
1300     | TOKSHIFT      { $$ = BIND_SHIFT; }
1301     ;
1302
1303 popup_during_fullscreen:
1304     TOK_POPUP_DURING_FULLSCREEN popup_setting
1305     {
1306         DLOG("popup_during_fullscreen setting: %d\n", $2);
1307         config.popup_during_fullscreen = $2;
1308     }
1309     ;
1310
1311 popup_setting:
1312     TOK_IGNORE              { $$ = PDF_IGNORE; }
1313     | TOK_LEAVE_FULLSCREEN  { $$ = PDF_LEAVE_FULLSCREEN; }
1314     ;