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