]> git.sur5r.net Git - i3/i3/blob - src/cfgparse.y
Introduce a new syntax for the 'assign' command:
[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 /*
244  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
245  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
246  *
247  */
248 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
249     if (configerror_pid != -1) {
250         LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", configerror_pid);
251         kill(configerror_pid, SIGKILL);
252     }
253 }
254
255 /*
256  * Starts an i3-nagbar process which alerts the user that his configuration
257  * file contains one or more errors. Also offers two buttons: One to launch an
258  * $EDITOR on the config file and another one to launch a $PAGER on the error
259  * logfile.
260  *
261  */
262 static void start_configerror_nagbar(const char *config_path) {
263     fprintf(stderr, "Would start i3-nagscreen now\n");
264     configerror_pid = fork();
265     if (configerror_pid == -1) {
266         warn("Could not fork()");
267         return;
268     }
269
270     /* child */
271     if (configerror_pid == 0) {
272         char *editaction,
273              *pageraction;
274         if (asprintf(&editaction, TERM_EMU " -e sh -c \"${EDITOR:-vi} \"%s\" && i3-msg reload\"", config_path) == -1)
275             exit(1);
276         if (asprintf(&pageraction, TERM_EMU " -e sh -c \"${PAGER:-less} \"%s\"\"", errorfilename) == -1)
277             exit(1);
278         char *argv[] = {
279             NULL, /* will be replaced by the executable path */
280             "-m",
281             "You have an error in your i3 config file!",
282             "-b",
283             "edit config",
284             editaction,
285             (errorfilename ? "-b" : NULL),
286             "show errors",
287             pageraction,
288             NULL
289         };
290         exec_i3_utility("i3-nagbar", argv);
291     }
292
293     /* parent */
294     /* install a child watcher */
295     ev_child *child = smalloc(sizeof(ev_child));
296     ev_child_init(child, &nagbar_exited, configerror_pid, 0);
297     ev_child_start(main_loop, child);
298
299     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
300      * still running) */
301     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
302     ev_cleanup_init(cleanup, nagbar_cleanup);
303     ev_cleanup_start(main_loop, cleanup);
304 }
305
306 /*
307  * Kills the configerror i3-nagbar process, if any.
308  *
309  * Called when reloading/restarting.
310  *
311  * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
312  * ev is assumed to handle it (reloading).
313  *
314  */
315 void kill_configerror_nagbar(bool wait_for_it) {
316     if (configerror_pid == -1)
317         return;
318
319     if (kill(configerror_pid, SIGTERM) == -1)
320         warn("kill(configerror_nagbar) failed");
321
322     if (!wait_for_it)
323         return;
324
325     /* When restarting, we don’t enter the ev main loop anymore and after the
326      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
327      * for us and we would end up with a <defunct> process. Therefore we
328      * waitpid() here. */
329     waitpid(configerror_pid, NULL, 0);
330 }
331
332 /*
333  * Checks for duplicate key bindings (the same keycode or keysym is configured
334  * more than once). If a duplicate binding is found, a message is printed to
335  * stderr and the has_errors variable is set to true, which will start
336  * i3-nagbar.
337  *
338  */
339 static void check_for_duplicate_bindings(struct context *context) {
340     Binding *bind, *current;
341     TAILQ_FOREACH(current, bindings, bindings) {
342         TAILQ_FOREACH(bind, bindings, bindings) {
343             /* Abort when we reach the current keybinding, only check the
344              * bindings before */
345             if (bind == current)
346                 break;
347
348             /* Check if one is using keysym while the other is using bindsym.
349              * If so, skip. */
350             /* XXX: It should be checked at a later place (when translating the
351              * keysym to keycodes) if there are any duplicates */
352             if ((bind->symbol == NULL && current->symbol != NULL) ||
353                 (bind->symbol != NULL && current->symbol == NULL))
354                 continue;
355
356             /* If bind is NULL, current has to be NULL, too (see above).
357              * If the keycodes differ, it can't be a duplicate. */
358             if (bind->symbol != NULL &&
359                 strcasecmp(bind->symbol, current->symbol) != 0)
360                 continue;
361
362             /* Check if the keycodes or modifiers are different. If so, they
363              * can't be duplicate */
364             if (bind->keycode != current->keycode ||
365                 bind->mods != current->mods)
366                 continue;
367             context->has_errors = true;
368             if (current->keycode != 0) {
369                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keycode %d, command \"%s\"\n",
370                      current->mods, current->keycode, current->command);
371             } else {
372                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keysym %s, command \"%s\"\n",
373                      current->mods, current->symbol, current->command);
374             }
375         }
376     }
377 }
378
379 void parse_file(const char *f) {
380     SLIST_HEAD(variables_head, Variable) variables = SLIST_HEAD_INITIALIZER(&variables);
381     int fd, ret, read_bytes = 0;
382     struct stat stbuf;
383     char *buf;
384     FILE *fstr;
385     char buffer[1026], key[512], value[512];
386
387     if ((fd = open(f, O_RDONLY)) == -1)
388         die("Could not open configuration file: %s\n", strerror(errno));
389
390     if (fstat(fd, &stbuf) == -1)
391         die("Could not fstat file: %s\n", strerror(errno));
392
393     buf = scalloc((stbuf.st_size + 1) * sizeof(char));
394     while (read_bytes < stbuf.st_size) {
395         if ((ret = read(fd, buf + read_bytes, (stbuf.st_size - read_bytes))) < 0)
396             die("Could not read(): %s\n", strerror(errno));
397         read_bytes += ret;
398     }
399
400     if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
401         die("Could not lseek: %s\n", strerror(errno));
402
403     if ((fstr = fdopen(fd, "r")) == NULL)
404         die("Could not fdopen: %s\n", strerror(errno));
405
406     while (!feof(fstr)) {
407         if (fgets(buffer, 1024, fstr) == NULL) {
408             if (feof(fstr))
409                 break;
410             die("Could not read configuration file\n");
411         }
412
413         /* sscanf implicitly strips whitespace. Also, we skip comments and empty lines. */
414         if (sscanf(buffer, "%s %[^\n]", key, value) < 1 ||
415             key[0] == '#' || strlen(key) < 3)
416             continue;
417
418         if (strcasecmp(key, "set") == 0) {
419             if (value[0] != '$') {
420                 ELOG("Malformed variable assignment, name has to start with $\n");
421                 continue;
422             }
423
424             /* get key/value for this variable */
425             char *v_key = value, *v_value;
426             if ((v_value = strstr(value, " ")) == NULL &&
427                 (v_value = strstr(value, "\t")) == NULL) {
428                 ELOG("Malformed variable assignment, need a value\n");
429                 continue;
430             }
431
432             *(v_value++) = '\0';
433
434             struct Variable *new = scalloc(sizeof(struct Variable));
435             new->key = sstrdup(v_key);
436             new->value = sstrdup(v_value);
437             SLIST_INSERT_HEAD(&variables, new, variables);
438             DLOG("Got new variable %s = %s\n", v_key, v_value);
439             continue;
440         }
441     }
442     fclose(fstr);
443
444     /* For every custom variable, see how often it occurs in the file and
445      * how much extra bytes it requires when replaced. */
446     struct Variable *current, *nearest;
447     int extra_bytes = 0;
448     /* We need to copy the buffer because we need to invalidate the
449      * variables (otherwise we will count them twice, which is bad when
450      * 'extra' is negative) */
451     char *bufcopy = sstrdup(buf);
452     SLIST_FOREACH(current, &variables, variables) {
453         int extra = (strlen(current->value) - strlen(current->key));
454         char *next;
455         for (next = bufcopy;
456              (next = strcasestr(bufcopy + (next - bufcopy), current->key)) != NULL;
457              next += strlen(current->key)) {
458             *next = '_';
459             extra_bytes += extra;
460         }
461     }
462     FREE(bufcopy);
463
464     /* Then, allocate a new buffer and copy the file over to the new one,
465      * but replace occurences of our variables */
466     char *walk = buf, *destwalk;
467     char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
468     destwalk = new;
469     while (walk < (buf + stbuf.st_size)) {
470         /* Find the next variable */
471         SLIST_FOREACH(current, &variables, variables)
472             current->next_match = strcasestr(walk, current->key);
473         nearest = NULL;
474         int distance = stbuf.st_size;
475         SLIST_FOREACH(current, &variables, variables) {
476             if (current->next_match == NULL)
477                 continue;
478             if ((current->next_match - walk) < distance) {
479                 distance = (current->next_match - walk);
480                 nearest = current;
481             }
482         }
483         if (nearest == NULL) {
484             /* If there are no more variables, we just copy the rest */
485             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
486             destwalk += (buf + stbuf.st_size) - walk;
487             *destwalk = '\0';
488             break;
489         } else {
490             /* Copy until the next variable, then copy its value */
491             strncpy(destwalk, walk, distance);
492             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
493             walk += distance + strlen(nearest->key);
494             destwalk += distance + strlen(nearest->value);
495         }
496     }
497
498     /* analyze the string to find out whether this is an old config file (3.x)
499      * or a new config file (4.x). If it’s old, we run the converter script. */
500     int version = detect_version(buf);
501     if (version == 3) {
502         /* We need to convert this v3 configuration */
503         char *converted = migrate_config(new, stbuf.st_size);
504         if (converted != NULL) {
505             printf("\n");
506             printf("****************************************************************\n");
507             printf("NOTE: Automatically converted configuration file from v3 to v4.\n");
508             printf("\n");
509             printf("Please convert your config file to v4. You can use this command:\n");
510             printf("    mv %s %s.O\n", f, f);
511             printf("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
512             printf("****************************************************************\n");
513             printf("\n");
514             free(new);
515             new = converted;
516         } else {
517             printf("\n");
518             printf("**********************************************************************\n");
519             printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
520             printf("was not correctly installed on your system?\n");
521             printf("**********************************************************************\n");
522             printf("\n");
523         }
524     }
525
526     /* now lex/parse it */
527     yy_scan_string(new);
528
529     context = scalloc(sizeof(struct context));
530     context->filename = f;
531
532     if (yyparse() != 0) {
533         fprintf(stderr, "Could not parse configfile\n");
534         exit(1);
535     }
536
537     check_for_duplicate_bindings(context);
538
539     if (context->has_errors) {
540         start_configerror_nagbar(f);
541     }
542
543     yylex_destroy();
544     FREE(context->line_copy);
545     free(context);
546     free(new);
547     free(buf);
548
549     while (!SLIST_EMPTY(&variables)) {
550         current = SLIST_FIRST(&variables);
551         FREE(current->key);
552         FREE(current->value);
553         SLIST_REMOVE_HEAD(&variables, variables);
554         FREE(current);
555     }
556 }
557
558 %}
559
560 %error-verbose
561 %lex-param { struct context *context }
562
563 %union {
564     int number;
565     char *string;
566     uint32_t *single_color;
567     struct Colortriple *color;
568     Match *match;
569     struct Binding *binding;
570 }
571
572 %token  <number>        NUMBER                      "<number>"
573 %token  <string>        WORD                        "<word>"
574 %token  <string>        STR                         "<string>"
575 %token  <string>        STR_NG                      "<string (non-greedy)>"
576 %token  <string>        HEX                         "<hex>"
577 %token  <string>        OUTPUT                      "<RandR output>"
578 %token                  TOKBINDCODE
579 %token                  TOKTERMINAL
580 %token                  TOKCOMMENT                  "<comment>"
581 %token                  TOKFONT                     "font"
582 %token                  TOKBINDSYM                  "bindsym"
583 %token  <number>        MODIFIER                    "<modifier>"
584 %token                  TOKCONTROL                  "control"
585 %token                  TOKSHIFT                    "shift"
586 %token                  TOKFLOATING_MODIFIER        "floating_modifier"
587 %token  <string>        QUOTEDSTRING                "<quoted string>"
588 %token                  TOKWORKSPACE                "workspace"
589 %token                  TOKOUTPUT                   "output"
590 %token                  TOKASSIGN                   "assign"
591 %token                  TOKSET
592 %token                  TOKIPCSOCKET                "ipc_socket"
593 %token                  TOKRESTARTSTATE             "restart_state"
594 %token                  TOKEXEC                     "exec"
595 %token                  TOKEXEC_ALWAYS              "exec_always"
596 %token  <single_color>  TOKSINGLECOLOR
597 %token  <color>         TOKCOLOR
598 %token                  TOKARROW                    "→"
599 %token                  TOKMODE                     "mode"
600 %token                  TOK_ORIENTATION             "default_orientation"
601 %token                  TOK_HORIZ                   "horizontal"
602 %token                  TOK_VERT                    "vertical"
603 %token                  TOK_AUTO                    "auto"
604 %token                  TOK_WORKSPACE_LAYOUT        "workspace_layout"
605 %token                  TOKNEWWINDOW                "new_window"
606 %token                  TOKNEWFLOAT                 "new_float"
607 %token                  TOK_NORMAL                  "normal"
608 %token                  TOK_NONE                    "none"
609 %token                  TOK_1PIXEL                  "1pixel"
610 %token                  TOKFOCUSFOLLOWSMOUSE        "focus_follows_mouse"
611 %token                  TOK_FORCE_FOCUS_WRAPPING    "force_focus_wrapping"
612 %token                  TOKWORKSPACEBAR             "workspace_bar"
613 %token                  TOK_DEFAULT                 "default"
614 %token                  TOK_STACKING                "stacking"
615 %token                  TOK_TABBED                  "tabbed"
616 %token  <number>        TOKSTACKLIMIT               "stack-limit"
617 %token                  TOK_POPUP_DURING_FULLSCREEN "popup_during_fullscreen"
618 %token                  TOK_IGNORE                  "ignore"
619 %token                  TOK_LEAVE_FULLSCREEN        "leave_fullscreen"
620 %token                  TOK_FOR_WINDOW              "for_window"
621
622 %token              TOK_MARK            "mark"
623 %token              TOK_CLASS           "class"
624 %token              TOK_INSTANCE        "instance"
625 %token              TOK_ID              "id"
626 %token              TOK_CON_ID          "con_id"
627 %token              TOK_TITLE           "title"
628
629 %type   <binding>       binding
630 %type   <binding>       bindcode
631 %type   <binding>       bindsym
632 %type   <number>        binding_modifiers
633 %type   <number>        binding_modifier
634 %type   <number>        direction
635 %type   <number>        layout_mode
636 %type   <number>        border_style
637 %type   <number>        new_window
638 %type   <number>        new_float
639 %type   <number>        colorpixel
640 %type   <number>        bool
641 %type   <number>        popup_setting
642 %type   <string>        command
643 %type   <string>        word_or_number
644 %type   <string>        optional_workspace_name
645 %type   <string>        workspace_name
646 %type   <string>        window_class
647
648 %%
649
650 lines: /* empty */
651     | lines error
652     | lines line
653     ;
654
655 line:
656     bindline
657     | for_window
658     | mode
659     | floating_modifier
660     | orientation
661     | workspace_layout
662     | new_window
663     | new_float
664     | focus_follows_mouse
665     | force_focus_wrapping
666     | workspace_bar
667     | workspace
668     | assign
669     | ipcsocket
670     | restart_state
671     | exec
672     | exec_always
673     | single_color
674     | color
675     | terminal
676     | font
677     | comment
678     | popup_during_fullscreen
679     ;
680
681 comment:
682     TOKCOMMENT
683     ;
684
685 command:
686     STR
687     ;
688
689 bindline:
690     binding
691     {
692         TAILQ_INSERT_TAIL(bindings, $1, bindings);
693     }
694     ;
695
696 binding:
697     TOKBINDCODE bindcode         { $$ = $2; }
698     | TOKBINDSYM bindsym         { $$ = $2; }
699     ;
700
701 bindcode:
702     binding_modifiers NUMBER command
703     {
704         printf("\tFound keycode binding mod%d with key %d and command %s\n", $1, $2, $3);
705         Binding *new = scalloc(sizeof(Binding));
706
707         new->keycode = $2;
708         new->mods = $1;
709         new->command = $3;
710
711         $$ = new;
712     }
713     ;
714
715 bindsym:
716     binding_modifiers word_or_number command
717     {
718         printf("\tFound keysym binding mod%d with key %s and command %s\n", $1, $2, $3);
719         Binding *new = scalloc(sizeof(Binding));
720
721         new->symbol = $2;
722         new->mods = $1;
723         new->command = $3;
724
725         $$ = new;
726     }
727     ;
728
729 for_window:
730     TOK_FOR_WINDOW match command
731     {
732         printf("\t should execute command %s for the criteria mentioned above\n", $3);
733         Assignment *assignment = scalloc(sizeof(Assignment));
734         assignment->type = A_COMMAND;
735         assignment->match = current_match;
736         assignment->dest.command = $3;
737         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
738     }
739     ;
740
741 match:
742     | matchstart criteria matchend
743     {
744         printf("match parsed\n");
745     }
746     ;
747
748 matchstart:
749     '['
750     {
751         printf("start\n");
752         match_init(&current_match);
753     }
754     ;
755
756 matchend:
757     ']'
758     {
759         printf("match specification finished\n");
760     }
761     ;
762
763 criteria:
764     criteria criterion
765     | criterion
766     ;
767
768 criterion:
769     TOK_CLASS '=' STR
770     {
771         printf("criteria: class = %s\n", $3);
772         current_match.class = regex_new($3);
773         free($3);
774     }
775     | TOK_INSTANCE '=' STR
776     {
777         printf("criteria: instance = %s\n", $3);
778         current_match.instance = regex_new($3);
779         free($3);
780     }
781     | TOK_CON_ID '=' STR
782     {
783         printf("criteria: id = %s\n", $3);
784         char *end;
785         long parsed = strtol($3, &end, 10);
786         if (parsed == LONG_MIN ||
787             parsed == LONG_MAX ||
788             parsed < 0 ||
789             (end && *end != '\0')) {
790             ELOG("Could not parse con id \"%s\"\n", $3);
791         } else {
792             current_match.con_id = (Con*)parsed;
793             printf("id as int = %p\n", current_match.con_id);
794         }
795     }
796     | TOK_ID '=' STR
797     {
798         printf("criteria: window id = %s\n", $3);
799         char *end;
800         long parsed = strtol($3, &end, 10);
801         if (parsed == LONG_MIN ||
802             parsed == LONG_MAX ||
803             parsed < 0 ||
804             (end && *end != '\0')) {
805             ELOG("Could not parse window id \"%s\"\n", $3);
806         } else {
807             current_match.id = parsed;
808             printf("window id as int = %d\n", current_match.id);
809         }
810     }
811     | TOK_MARK '=' STR
812     {
813         printf("criteria: mark = %s\n", $3);
814         current_match.mark = regex_new($3);
815         free($3);
816     }
817     | TOK_TITLE '=' STR
818     {
819         printf("criteria: title = %s\n", $3);
820         current_match.title = regex_new($3);
821         free($3);
822     }
823     ;
824
825
826
827 word_or_number:
828     WORD
829     | NUMBER
830     {
831         asprintf(&$$, "%d", $1);
832     }
833     ;
834
835 mode:
836     TOKMODE QUOTEDSTRING '{' modelines '}'
837     {
838         if (strcasecmp($2, "default") == 0) {
839             printf("You cannot use the name \"default\" for your mode\n");
840             exit(1);
841         }
842         printf("\t now in mode %s\n", $2);
843         printf("\t current bindings = %p\n", current_bindings);
844         Binding *binding;
845         TAILQ_FOREACH(binding, current_bindings, bindings) {
846             printf("got binding on mods %d, keycode %d, symbol %s, command %s\n",
847                             binding->mods, binding->keycode, binding->symbol, binding->command);
848         }
849
850         struct Mode *mode = scalloc(sizeof(struct Mode));
851         mode->name = $2;
852         mode->bindings = current_bindings;
853         current_bindings = NULL;
854         SLIST_INSERT_HEAD(&modes, mode, modes);
855     }
856     ;
857
858
859 modelines:
860     /* empty */
861     | modelines modeline
862     ;
863
864 modeline:
865     comment
866     | binding
867     {
868         if (current_bindings == NULL) {
869             current_bindings = scalloc(sizeof(struct bindings_head));
870             TAILQ_INIT(current_bindings);
871         }
872
873         TAILQ_INSERT_TAIL(current_bindings, $1, bindings);
874     }
875     ;
876
877 floating_modifier:
878     TOKFLOATING_MODIFIER binding_modifiers
879     {
880         DLOG("floating modifier = %d\n", $2);
881         config.floating_modifier = $2;
882     }
883     ;
884
885 orientation:
886     TOK_ORIENTATION direction
887     {
888         DLOG("New containers should start with split direction %d\n", $2);
889         config.default_orientation = $2;
890     }
891     ;
892
893 direction:
894     TOK_HORIZ       { $$ = HORIZ; }
895     | TOK_VERT      { $$ = VERT; }
896     | TOK_AUTO      { $$ = NO_ORIENTATION; }
897     ;
898
899 workspace_layout:
900     TOK_WORKSPACE_LAYOUT layout_mode
901     {
902         DLOG("new containers will be in mode %d\n", $2);
903         config.default_layout = $2;
904
905 #if 0
906         /* We also need to change the layout of the already existing
907          * workspaces here. Workspaces may exist at this point because
908          * of the other directives which are modifying workspaces
909          * (setting the preferred screen or name). While the workspace
910          * objects are already created, they have never been used.
911          * Thus, the user very likely awaits the default container mode
912          * to trigger in this case, regardless of where it is inside
913          * his configuration file. */
914         Workspace *ws;
915         TAILQ_FOREACH(ws, workspaces, workspaces) {
916                 if (ws->table == NULL)
917                         continue;
918                 switch_layout_mode(global_conn,
919                                    ws->table[0][0],
920                                    config.container_mode);
921         }
922 #endif
923     }
924     | TOK_WORKSPACE_LAYOUT TOKSTACKLIMIT TOKSTACKLIMIT NUMBER
925     {
926         DLOG("stack-limit %d with val %d\n", $3, $4);
927         config.container_stack_limit = $3;
928         config.container_stack_limit_value = $4;
929
930 #if 0
931         /* See the comment above */
932         Workspace *ws;
933         TAILQ_FOREACH(ws, workspaces, workspaces) {
934                 if (ws->table == NULL)
935                         continue;
936                 Container *con = ws->table[0][0];
937                 con->stack_limit = config.container_stack_limit;
938                 con->stack_limit_value = config.container_stack_limit_value;
939         }
940 #endif
941     }
942     ;
943
944 layout_mode:
945     TOK_DEFAULT       { $$ = L_DEFAULT; }
946     | TOK_STACKING    { $$ = L_STACKED; }
947     | TOK_TABBED      { $$ = L_TABBED; }
948     ;
949
950 new_window:
951     TOKNEWWINDOW border_style
952     {
953         DLOG("new windows should start with border style %d\n", $2);
954         config.default_border = $2;
955     }
956     ;
957
958 new_float:
959     TOKNEWFLOAT border_style
960     {
961        DLOG("new floating windows should start with border style %d\n", $2);
962        config.default_floating_border = $2;
963     }
964     ;
965
966 border_style:
967     TOK_NORMAL      { $$ = BS_NORMAL; }
968     | TOK_NONE      { $$ = BS_NONE; }
969     | TOK_1PIXEL    { $$ = BS_1PIXEL; }
970     ;
971
972 bool:
973     NUMBER
974     {
975         $$ = ($1 == 1);
976     }
977     | WORD
978     {
979         DLOG("checking word \"%s\"\n", $1);
980         $$ = (strcasecmp($1, "yes") == 0 ||
981               strcasecmp($1, "true") == 0 ||
982               strcasecmp($1, "on") == 0 ||
983               strcasecmp($1, "enable") == 0 ||
984               strcasecmp($1, "active") == 0);
985     }
986     ;
987
988 focus_follows_mouse:
989     TOKFOCUSFOLLOWSMOUSE bool
990     {
991         DLOG("focus follows mouse = %d\n", $2);
992         config.disable_focus_follows_mouse = !($2);
993     }
994     ;
995
996 force_focus_wrapping:
997     TOK_FORCE_FOCUS_WRAPPING bool
998     {
999         DLOG("force focus wrapping = %d\n", $2);
1000         config.force_focus_wrapping = $2;
1001     }
1002     ;
1003
1004 workspace_bar:
1005     TOKWORKSPACEBAR bool
1006     {
1007         DLOG("workspace bar = %d\n", $2);
1008         config.disable_workspace_bar = !($2);
1009     }
1010     ;
1011
1012 workspace:
1013     TOKWORKSPACE NUMBER TOKOUTPUT OUTPUT optional_workspace_name
1014     {
1015         int ws_num = $2;
1016         if (ws_num < 1) {
1017             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
1018         } else {
1019             char *ws_name = NULL;
1020             if ($5 == NULL) {
1021                 asprintf(&ws_name, "%d", ws_num);
1022             } else {
1023                 ws_name = $5;
1024             }
1025
1026             DLOG("Should assign workspace %s to output %s\n", ws_name, $4);
1027             /* Check for earlier assignments of the same workspace so that we
1028              * don’t have assignments of a single workspace to different
1029              * outputs */
1030             struct Workspace_Assignment *assignment;
1031             bool duplicate = false;
1032             TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
1033                 if (strcasecmp(assignment->name, ws_name) == 0) {
1034                     ELOG("You have a duplicate workspace assignment for workspace \"%s\"\n",
1035                          ws_name);
1036                     assignment->output = $4;
1037                     duplicate = true;
1038                 }
1039             }
1040             if (!duplicate) {
1041                 assignment = scalloc(sizeof(struct Workspace_Assignment));
1042                 assignment->name = ws_name;
1043                 assignment->output = $4;
1044                 TAILQ_INSERT_TAIL(&ws_assignments, assignment, ws_assignments);
1045             }
1046         }
1047     }
1048     | TOKWORKSPACE NUMBER workspace_name
1049     {
1050         int ws_num = $2;
1051         if (ws_num < 1) {
1052             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
1053         } else {
1054             DLOG("workspace name to: %s\n", $3);
1055 #if 0
1056             if ($<string>3 != NULL) {
1057                     workspace_set_name(workspace_get(ws_num - 1), $<string>3);
1058                     free($<string>3);
1059             }
1060 #endif
1061         }
1062     }
1063     ;
1064
1065 optional_workspace_name:
1066     /* empty */          { $$ = NULL; }
1067     | workspace_name     { $$ = $1; }
1068     ;
1069
1070 workspace_name:
1071     QUOTEDSTRING         { $$ = $1; }
1072     | STR                { $$ = $1; }
1073     | WORD               { $$ = $1; }
1074     ;
1075
1076 assign:
1077     TOKASSIGN window_class STR
1078     {
1079         /* TODO: the assign command also needs some kind of new syntax where we
1080          * just use criteria. Then deprecate the old form */
1081         printf("assignment of %s to *%s*\n", $2, $3);
1082         char *workspace = $3;
1083         char *criteria = $2;
1084
1085         Assignment *assignment = scalloc(sizeof(Assignment));
1086         Match *match = &(assignment->match);
1087         match_init(match);
1088
1089         char *separator = NULL;
1090         if ((separator = strchr(criteria, '/')) != NULL) {
1091             *(separator++) = '\0';
1092             char *pattern;
1093             if (asprintf(&pattern, "(?i)%s", separator) == -1) {
1094                 ELOG("asprintf failed\n");
1095                 break;
1096             }
1097             match->title = regex_new(pattern);
1098             free(pattern);
1099             printf("  title = %s\n", separator);
1100         }
1101         if (*criteria != '\0') {
1102             char *pattern;
1103             if (asprintf(&pattern, "(?i)%s", criteria) == -1) {
1104                 ELOG("asprintf failed\n");
1105                 break;
1106             }
1107             match->class = regex_new(pattern);
1108             free(pattern);
1109             printf("  class = %s\n", criteria);
1110         }
1111         free(criteria);
1112
1113         /* Compatibility with older versions: If the assignment target starts
1114          * with ~, we create the equivalent of:
1115          *
1116          * for_window [class="foo"] floating enable
1117          */
1118         if (*workspace == '~') {
1119             workspace++;
1120             if (*workspace == '\0') {
1121                 /* This assignment was *only* for floating */
1122                 assignment->type = A_COMMAND;
1123                 assignment->dest.command = sstrdup("floating enable");
1124                 TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1125                 break;
1126             } else {
1127                 /* Create a new assignment and continue afterwards */
1128                 Assignment *floating = scalloc(sizeof(Assignment));
1129                 match_copy(&(floating->match), match);
1130                 floating->type = A_COMMAND;
1131                 floating->dest.command = sstrdup("floating enable");
1132                 TAILQ_INSERT_TAIL(&assignments, floating, assignments);
1133             }
1134         }
1135
1136         assignment->type = A_TO_WORKSPACE;
1137         assignment->dest.workspace = workspace;
1138         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1139     }
1140     | TOKASSIGN match STR
1141     {
1142         printf("new assignment, using above criteria, to workspace %s\n", $3);
1143         Assignment *assignment = scalloc(sizeof(Assignment));
1144         assignment->match = current_match;
1145         assignment->type = A_TO_WORKSPACE;
1146         assignment->dest.workspace = $3;
1147         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1148     }
1149     ;
1150
1151 window_class:
1152     QUOTEDSTRING
1153     | STR_NG
1154     ;
1155
1156 ipcsocket:
1157     TOKIPCSOCKET STR
1158     {
1159         config.ipc_socket_path = $2;
1160     }
1161     ;
1162
1163 restart_state:
1164     TOKRESTARTSTATE STR
1165     {
1166         config.restart_state_path = $2;
1167     }
1168     ;
1169
1170 exec:
1171     TOKEXEC STR
1172     {
1173         struct Autostart *new = smalloc(sizeof(struct Autostart));
1174         new->command = $2;
1175         TAILQ_INSERT_TAIL(&autostarts, new, autostarts);
1176     }
1177     ;
1178
1179 exec_always:
1180     TOKEXEC_ALWAYS STR
1181     {
1182         struct Autostart *new = smalloc(sizeof(struct Autostart));
1183         new->command = $2;
1184         TAILQ_INSERT_TAIL(&autostarts_always, new, autostarts_always);
1185     }
1186     ;
1187
1188 terminal:
1189     TOKTERMINAL STR
1190     {
1191         ELOG("The terminal option is DEPRECATED and has no effect. "
1192             "Please remove it from your configuration file.\n");
1193     }
1194     ;
1195
1196 font:
1197     TOKFONT STR
1198     {
1199         config.font = load_font($2, true);
1200         printf("font %s\n", $2);
1201         free($2);
1202     }
1203     ;
1204
1205 single_color:
1206     TOKSINGLECOLOR colorpixel
1207     {
1208         uint32_t *dest = $1;
1209         *dest = $2;
1210     }
1211     ;
1212
1213 color:
1214     TOKCOLOR colorpixel colorpixel colorpixel
1215     {
1216         struct Colortriple *dest = $1;
1217
1218         dest->border = $2;
1219         dest->background = $3;
1220         dest->text = $4;
1221     }
1222     ;
1223
1224 colorpixel:
1225     '#' HEX
1226     {
1227         char *hex;
1228         if (asprintf(&hex, "#%s", $2) == -1)
1229             die("asprintf()");
1230         free($2);
1231         $$ = get_colorpixel(hex);
1232         free(hex);
1233     }
1234     ;
1235
1236
1237 binding_modifiers:
1238     /* NULL */                               { $$ = 0; }
1239     | binding_modifier
1240     | binding_modifiers '+' binding_modifier { $$ = $1 | $3; }
1241     | binding_modifiers '+'                  { $$ = $1; }
1242     ;
1243
1244 binding_modifier:
1245     MODIFIER        { $$ = $1; }
1246     | TOKCONTROL    { $$ = BIND_CONTROL; }
1247     | TOKSHIFT      { $$ = BIND_SHIFT; }
1248     ;
1249
1250 popup_during_fullscreen:
1251     TOK_POPUP_DURING_FULLSCREEN popup_setting
1252     {
1253         DLOG("popup_during_fullscreen setting: %d\n", $2);
1254         config.popup_during_fullscreen = $2;
1255     }
1256     ;
1257
1258 popup_setting:
1259     TOK_IGNORE              { $$ = PDF_IGNORE; }
1260     | TOK_LEAVE_FULLSCREEN  { $$ = PDF_LEAVE_FULLSCREEN; }
1261     ;