]> git.sur5r.net Git - i3/i3/blob - src/workspace.c
Turn "char *" into "const char *" for all command parser functions.
[i3/i3] / src / workspace.c
1 #undef I3__FILE__
2 #define I3__FILE__ "workspace.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * workspace.c: Modifying workspaces, accessing them, moving containers to
10  *              workspaces.
11  *
12  */
13 #include "all.h"
14 #include "yajl_utils.h"
15
16 /* Stores a copy of the name of the last used workspace for the workspace
17  * back-and-forth switching. */
18 static char *previous_workspace_name = NULL;
19
20 /* NULL-terminated list of workspace names (in order) extracted from
21  * keybindings. */
22 static char **binding_workspace_names = NULL;
23
24 /*
25  * Sets ws->layout to splith/splitv if default_orientation was specified in the
26  * configfile. Otherwise, it uses splith/splitv depending on whether the output
27  * is higher than wide.
28  *
29  */
30 static void _workspace_apply_default_orientation(Con *ws) {
31     /* If default_orientation is set to NO_ORIENTATION we determine
32      * orientation depending on output resolution. */
33     if (config.default_orientation == NO_ORIENTATION) {
34         Con *output = con_get_output(ws);
35         ws->layout = (output->rect.height > output->rect.width) ? L_SPLITV : L_SPLITH;
36         ws->rect = output->rect;
37         DLOG("Auto orientation. Workspace size set to (%d,%d), setting layout to %d.\n",
38              output->rect.width, output->rect.height, ws->layout);
39     } else {
40         ws->layout = (config.default_orientation == HORIZ) ? L_SPLITH : L_SPLITV;
41     }
42 }
43
44 /*
45  * Returns a pointer to the workspace with the given number (starting at 0),
46  * creating the workspace if necessary (by allocating the necessary amount of
47  * memory and initializing the data structures correctly).
48  *
49  */
50 Con *workspace_get(const char *num, bool *created) {
51     Con *output, *workspace = NULL;
52
53     TAILQ_FOREACH(output, &(croot->nodes_head), nodes)
54     GREP_FIRST(workspace, output_get_content(output), !strcasecmp(child->name, num));
55
56     if (workspace == NULL) {
57         LOG("Creating new workspace \"%s\"\n", num);
58         /* unless an assignment is found, we will create this workspace on the current output */
59         output = con_get_output(focused);
60         /* look for assignments */
61         struct Workspace_Assignment *assignment;
62
63         /* We set workspace->num to the number if this workspace’s name begins
64          * with a positive number. Otherwise it’s a named ws and num will be
65          * -1. */
66         long parsed_num = ws_name_to_number(num);
67
68         TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
69             if (strcmp(assignment->name, num) == 0) {
70                 DLOG("Found workspace name assignment to output \"%s\"\n", assignment->output);
71                 GREP_FIRST(output, croot, !strcmp(child->name, assignment->output));
72                 break;
73             } else if (parsed_num != -1 && name_is_digits(assignment->name) && ws_name_to_number(assignment->name) == parsed_num) {
74                 DLOG("Found workspace number assignment to output \"%s\"\n", assignment->output);
75                 GREP_FIRST(output, croot, !strcmp(child->name, assignment->output));
76             }
77         }
78
79         Con *content = output_get_content(output);
80         LOG("got output %p with content %p\n", output, content);
81         /* We need to attach this container after setting its type. con_attach
82          * will handle CT_WORKSPACEs differently */
83         workspace = con_new(NULL, NULL);
84         char *name;
85         sasprintf(&name, "[i3 con] workspace %s", num);
86         x_set_name(workspace, name);
87         free(name);
88         workspace->type = CT_WORKSPACE;
89         FREE(workspace->name);
90         workspace->name = sstrdup(num);
91         workspace->workspace_layout = config.default_layout;
92         workspace->num = parsed_num;
93         LOG("num = %d\n", workspace->num);
94
95         workspace->parent = content;
96         _workspace_apply_default_orientation(workspace);
97
98         con_attach(workspace, content, false);
99
100         ipc_send_workspace_event("init", workspace, NULL);
101         ewmh_update_number_of_desktops();
102         ewmh_update_desktop_names();
103         ewmh_update_desktop_viewport();
104         if (created != NULL)
105             *created = true;
106     } else if (created != NULL) {
107         *created = false;
108     }
109
110     return workspace;
111 }
112
113 /*
114  * Extracts workspace names from keybindings (e.g. “web” from “bindsym $mod+1
115  * workspace web”), so that when an output needs a workspace, i3 can start with
116  * the first configured one. Needs to be called before reorder_bindings() so
117  * that the config-file order is used, not the i3-internal order.
118  *
119  */
120 void extract_workspace_names_from_bindings(void) {
121     Binding *bind;
122     int n = 0;
123     if (binding_workspace_names != NULL) {
124         for (int i = 0; binding_workspace_names[i] != NULL; i++) {
125             free(binding_workspace_names[i]);
126         }
127         FREE(binding_workspace_names);
128     }
129     TAILQ_FOREACH(bind, bindings, bindings) {
130         DLOG("binding with command %s\n", bind->command);
131         if (strlen(bind->command) < strlen("workspace ") ||
132             strncasecmp(bind->command, "workspace", strlen("workspace")) != 0)
133             continue;
134         DLOG("relevant command = %s\n", bind->command);
135         const char *target = bind->command + strlen("workspace ");
136         while (*target == ' ' || *target == '\t')
137             target++;
138         /* We check if this is the workspace
139          * next/prev/next_on_output/prev_on_output/back_and_forth/number command.
140          * Beware: The workspace names "next", "prev", "next_on_output",
141          * "prev_on_output", "number", "back_and_forth" and "current" are OK,
142          * so we check before stripping the double quotes */
143         if (strncasecmp(target, "next", strlen("next")) == 0 ||
144             strncasecmp(target, "prev", strlen("prev")) == 0 ||
145             strncasecmp(target, "next_on_output", strlen("next_on_output")) == 0 ||
146             strncasecmp(target, "prev_on_output", strlen("prev_on_output")) == 0 ||
147             strncasecmp(target, "number", strlen("number")) == 0 ||
148             strncasecmp(target, "back_and_forth", strlen("back_and_forth")) == 0 ||
149             strncasecmp(target, "current", strlen("current")) == 0)
150             continue;
151         char *target_name = parse_string(&target, false);
152         if (target_name == NULL)
153             continue;
154         if (strncasecmp(target_name, "__", strlen("__")) == 0) {
155             LOG("Cannot create workspace \"%s\". Names starting with __ are i3-internal.\n", target);
156             free(target_name);
157             continue;
158         }
159         DLOG("Saving workspace name \"%s\"\n", target_name);
160
161         binding_workspace_names = srealloc(binding_workspace_names, ++n * sizeof(char *));
162         binding_workspace_names[n - 1] = target_name;
163     }
164     binding_workspace_names = srealloc(binding_workspace_names, ++n * sizeof(char *));
165     binding_workspace_names[n - 1] = NULL;
166 }
167
168 /*
169  * Returns a pointer to a new workspace in the given output. The workspace
170  * is created attached to the tree hierarchy through the given content
171  * container.
172  *
173  */
174 Con *create_workspace_on_output(Output *output, Con *content) {
175     /* add a workspace to this output */
176     Con *out, *current;
177     char *name;
178     bool exists = true;
179     Con *ws = con_new(NULL, NULL);
180     ws->type = CT_WORKSPACE;
181
182     /* try the configured workspace bindings first to find a free name */
183     for (int n = 0; binding_workspace_names[n] != NULL; n++) {
184         char *target_name = binding_workspace_names[n];
185         /* Ensure that this workspace is not assigned to a different output —
186          * otherwise we would create it, then move it over to its output, then
187          * find a new workspace, etc… */
188         bool assigned = false;
189         struct Workspace_Assignment *assignment;
190         TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
191             if (strcmp(assignment->name, target_name) != 0 ||
192                 strcmp(assignment->output, output->name) == 0)
193                 continue;
194
195             assigned = true;
196             break;
197         }
198
199         if (assigned)
200             continue;
201
202         current = NULL;
203         TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
204         GREP_FIRST(current, output_get_content(out), !strcasecmp(child->name, target_name));
205         exists = (current != NULL);
206         if (!exists) {
207             ws->name = sstrdup(target_name);
208             /* Set ->num to the number of the workspace, if the name actually
209              * is a number or starts with a number */
210             ws->num = ws_name_to_number(ws->name);
211             LOG("Used number %d for workspace with name %s\n", ws->num, ws->name);
212
213             break;
214         }
215     }
216
217     if (exists) {
218         /* get the next unused workspace number */
219         DLOG("Getting next unused workspace by number\n");
220         int c = 0;
221         while (exists) {
222             c++;
223
224             ws->num = c;
225
226             current = NULL;
227             TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
228             GREP_FIRST(current, output_get_content(out), child->num == ws->num);
229             exists = (current != NULL);
230
231             DLOG("result for ws %d: exists = %d\n", c, exists);
232         }
233         sasprintf(&(ws->name), "%d", c);
234     }
235     con_attach(ws, content, false);
236
237     sasprintf(&name, "[i3 con] workspace %s", ws->name);
238     x_set_name(ws, name);
239     free(name);
240
241     ws->fullscreen_mode = CF_OUTPUT;
242
243     ws->workspace_layout = config.default_layout;
244     _workspace_apply_default_orientation(ws);
245
246     return ws;
247 }
248
249 /*
250  * Returns true if the workspace is currently visible. Especially important for
251  * multi-monitor environments, as they can have multiple currenlty active
252  * workspaces.
253  *
254  */
255 bool workspace_is_visible(Con *ws) {
256     Con *output = con_get_output(ws);
257     if (output == NULL)
258         return false;
259     Con *fs = con_get_fullscreen_con(output, CF_OUTPUT);
260     LOG("workspace visible? fs = %p, ws = %p\n", fs, ws);
261     return (fs == ws);
262 }
263
264 /*
265  * XXX: we need to clean up all this recursive walking code.
266  *
267  */
268 Con *_get_sticky(Con *con, const char *sticky_group, Con *exclude) {
269     Con *current;
270
271     TAILQ_FOREACH(current, &(con->nodes_head), nodes) {
272         if (current != exclude &&
273             current->sticky_group != NULL &&
274             current->window != NULL &&
275             strcmp(current->sticky_group, sticky_group) == 0)
276             return current;
277
278         Con *recurse = _get_sticky(current, sticky_group, exclude);
279         if (recurse != NULL)
280             return recurse;
281     }
282
283     TAILQ_FOREACH(current, &(con->floating_head), floating_windows) {
284         if (current != exclude &&
285             current->sticky_group != NULL &&
286             current->window != NULL &&
287             strcmp(current->sticky_group, sticky_group) == 0)
288             return current;
289
290         Con *recurse = _get_sticky(current, sticky_group, exclude);
291         if (recurse != NULL)
292             return recurse;
293     }
294
295     return NULL;
296 }
297
298 /*
299  * Reassigns all child windows in sticky containers. Called when the user
300  * changes workspaces.
301  *
302  * XXX: what about sticky containers which contain containers?
303  *
304  */
305 static void workspace_reassign_sticky(Con *con) {
306     Con *current;
307     /* 1: go through all containers */
308
309     /* handle all children and floating windows of this node */
310     TAILQ_FOREACH(current, &(con->nodes_head), nodes) {
311         if (current->sticky_group == NULL) {
312             workspace_reassign_sticky(current);
313             continue;
314         }
315
316         LOG("Ah, this one is sticky: %s / %p\n", current->name, current);
317         /* 2: find a window which we can re-assign */
318         Con *output = con_get_output(current);
319         Con *src = _get_sticky(output, current->sticky_group, current);
320
321         if (src == NULL) {
322             LOG("No window found for this sticky group\n");
323             workspace_reassign_sticky(current);
324             continue;
325         }
326
327         x_move_win(src, current);
328         current->window = src->window;
329         current->mapped = true;
330         src->window = NULL;
331         src->mapped = false;
332
333         x_reparent_child(current, src);
334
335         LOG("re-assigned window from src %p to dest %p\n", src, current);
336     }
337
338     TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
339     workspace_reassign_sticky(current);
340 }
341
342 /*
343  * Callback to reset the urgent flag of the given con to false. May be started by
344  * _workspace_show to avoid urgency hints being lost by switching to a workspace
345  * focusing the con.
346  *
347  */
348 static void workspace_defer_update_urgent_hint_cb(EV_P_ ev_timer *w, int revents) {
349     Con *con = w->data;
350
351     ev_timer_stop(main_loop, con->urgency_timer);
352     FREE(con->urgency_timer);
353
354     if (con->urgent) {
355         DLOG("Resetting urgency flag of con %p by timer\n", con);
356         con_set_urgency(con, false);
357         con_update_parents_urgency(con);
358         workspace_update_urgent_flag(con_get_workspace(con));
359         ipc_send_window_event("urgent", con);
360         tree_render();
361     }
362 }
363
364 static void _workspace_show(Con *workspace) {
365     Con *current, *old = NULL;
366     Con *old_focus = focused;
367
368     /* safe-guard against showing i3-internal workspaces like __i3_scratch */
369     if (con_is_internal(workspace))
370         return;
371
372     /* disable fullscreen for the other workspaces and get the workspace we are
373      * currently on. */
374     TAILQ_FOREACH(current, &(workspace->parent->nodes_head), nodes) {
375         if (current->fullscreen_mode == CF_OUTPUT)
376             old = current;
377         current->fullscreen_mode = CF_NONE;
378     }
379
380     /* enable fullscreen for the target workspace. If it happens to be the
381      * same one we are currently on anyways, we can stop here. */
382     workspace->fullscreen_mode = CF_OUTPUT;
383     current = con_get_workspace(focused);
384     if (workspace == current) {
385         DLOG("Not switching, already there.\n");
386         return;
387     }
388
389     /* Remember currently focused workspace for switching back to it later with
390      * the 'workspace back_and_forth' command.
391      * NOTE: We have to duplicate the name as the original will be freed when
392      * the corresponding workspace is cleaned up.
393      * NOTE: Internal cons such as __i3_scratch (when a scratchpad window is
394      * focused) are skipped, see bug #868. */
395     if (current && !con_is_internal(current)) {
396         FREE(previous_workspace_name);
397         if (current) {
398             previous_workspace_name = sstrdup(current->name);
399             DLOG("Setting previous_workspace_name = %s\n", previous_workspace_name);
400         }
401     }
402
403     workspace_reassign_sticky(workspace);
404
405     DLOG("switching to %p / %s\n", workspace, workspace->name);
406     Con *next = con_descend_focused(workspace);
407
408     /* Memorize current output */
409     Con *old_output = con_get_output(focused);
410
411     /* Display urgency hint for a while if the newly visible workspace would
412      * focus and thereby immediately destroy it */
413     if (next->urgent && (int)(config.workspace_urgency_timer * 1000) > 0) {
414         /* focus for now… */
415         next->urgent = false;
416         con_focus(next);
417
418         /* … but immediately reset urgency flags; they will be set to false by
419          * the timer callback in case the container is focused at the time of
420          * its expiration */
421         focused->urgent = true;
422         workspace->urgent = true;
423
424         if (focused->urgency_timer == NULL) {
425             DLOG("Deferring reset of urgency flag of con %p on newly shown workspace %p\n",
426                  focused, workspace);
427             focused->urgency_timer = scalloc(1, sizeof(struct ev_timer));
428             /* use a repeating timer to allow for easy resets */
429             ev_timer_init(focused->urgency_timer, workspace_defer_update_urgent_hint_cb,
430                           config.workspace_urgency_timer, config.workspace_urgency_timer);
431             focused->urgency_timer->data = focused;
432             ev_timer_start(main_loop, focused->urgency_timer);
433         } else {
434             DLOG("Resetting urgency timer of con %p on workspace %p\n",
435                  focused, workspace);
436             ev_timer_again(main_loop, focused->urgency_timer);
437         }
438     } else
439         con_focus(next);
440
441     ipc_send_workspace_event("focus", workspace, current);
442
443     DLOG("old = %p / %s\n", old, (old ? old->name : "(null)"));
444     /* Close old workspace if necessary. This must be done *after* doing
445      * urgency handling, because tree_close() will do a con_focus() on the next
446      * client, which will clear the urgency flag too early. Also, there is no
447      * way for con_focus() to know about when to clear urgency immediately and
448      * when to defer it. */
449     if (old && TAILQ_EMPTY(&(old->nodes_head)) && TAILQ_EMPTY(&(old->floating_head))) {
450         /* check if this workspace is currently visible */
451         if (!workspace_is_visible(old)) {
452             LOG("Closing old workspace (%p / %s), it is empty\n", old, old->name);
453             yajl_gen gen = ipc_marshal_workspace_event("empty", old, NULL);
454             tree_close(old, DONT_KILL_WINDOW, false, false);
455
456             const unsigned char *payload;
457             ylength length;
458             y(get_buf, &payload, &length);
459             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
460
461             y(free);
462
463             ewmh_update_number_of_desktops();
464             ewmh_update_desktop_names();
465             ewmh_update_desktop_viewport();
466         }
467     }
468
469     workspace->fullscreen_mode = CF_OUTPUT;
470     LOG("focused now = %p / %s\n", focused, focused->name);
471
472     /* Set mouse pointer */
473     Con *new_output = con_get_output(focused);
474     if (old_output != new_output) {
475         x_set_warp_to(&next->rect);
476     }
477
478     /* Update the EWMH hints */
479     ewmh_update_current_desktop();
480
481     /* Push any sticky windows to the now visible workspace. */
482     output_push_sticky_windows(old_focus);
483 }
484
485 /*
486  * Switches to the given workspace
487  *
488  */
489 void workspace_show(Con *workspace) {
490     _workspace_show(workspace);
491 }
492
493 /*
494  * Looks up the workspace by name and switches to it.
495  *
496  */
497 void workspace_show_by_name(const char *num) {
498     Con *workspace;
499     workspace = workspace_get(num, NULL);
500     _workspace_show(workspace);
501 }
502
503 /*
504  * Focuses the next workspace.
505  *
506  */
507 Con *workspace_next(void) {
508     Con *current = con_get_workspace(focused);
509     Con *next = NULL;
510     Con *output;
511
512     if (current->num == -1) {
513         /* If currently a named workspace, find next named workspace. */
514         next = TAILQ_NEXT(current, nodes);
515     } else {
516         /* If currently a numbered workspace, find next numbered workspace. */
517         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
518             /* Skip outputs starting with __, they are internal. */
519             if (con_is_internal(output))
520                 continue;
521             NODES_FOREACH(output_get_content(output)) {
522                 if (child->type != CT_WORKSPACE)
523                     continue;
524                 if (child->num == -1)
525                     break;
526                 /* Need to check child against current and next because we are
527                  * traversing multiple lists and thus are not guaranteed the
528                  * relative order between the list of workspaces. */
529                 if (current->num < child->num && (!next || child->num < next->num))
530                     next = child;
531             }
532         }
533     }
534
535     /* Find next named workspace. */
536     if (!next) {
537         bool found_current = false;
538         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
539             /* Skip outputs starting with __, they are internal. */
540             if (con_is_internal(output))
541                 continue;
542             NODES_FOREACH(output_get_content(output)) {
543                 if (child->type != CT_WORKSPACE)
544                     continue;
545                 if (child == current) {
546                     found_current = 1;
547                 } else if (child->num == -1 && (current->num != -1 || found_current)) {
548                     next = child;
549                     goto workspace_next_end;
550                 }
551             }
552         }
553     }
554
555     /* Find first workspace. */
556     if (!next) {
557         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
558             /* Skip outputs starting with __, they are internal. */
559             if (con_is_internal(output))
560                 continue;
561             NODES_FOREACH(output_get_content(output)) {
562                 if (child->type != CT_WORKSPACE)
563                     continue;
564                 if (!next || (child->num != -1 && child->num < next->num))
565                     next = child;
566             }
567         }
568     }
569 workspace_next_end:
570     return next;
571 }
572
573 /*
574  * Focuses the previous workspace.
575  *
576  */
577 Con *workspace_prev(void) {
578     Con *current = con_get_workspace(focused);
579     Con *prev = NULL;
580     Con *output;
581
582     if (current->num == -1) {
583         /* If named workspace, find previous named workspace. */
584         prev = TAILQ_PREV(current, nodes_head, nodes);
585         if (prev && prev->num != -1)
586             prev = NULL;
587     } else {
588         /* If numbered workspace, find previous numbered workspace. */
589         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
590             /* Skip outputs starting with __, they are internal. */
591             if (con_is_internal(output))
592                 continue;
593             NODES_FOREACH_REVERSE(output_get_content(output)) {
594                 if (child->type != CT_WORKSPACE || child->num == -1)
595                     continue;
596                 /* Need to check child against current and previous because we
597                  * are traversing multiple lists and thus are not guaranteed
598                  * the relative order between the list of workspaces. */
599                 if (current->num > child->num && (!prev || child->num > prev->num))
600                     prev = child;
601             }
602         }
603     }
604
605     /* Find previous named workspace. */
606     if (!prev) {
607         bool found_current = false;
608         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
609             /* Skip outputs starting with __, they are internal. */
610             if (con_is_internal(output))
611                 continue;
612             NODES_FOREACH_REVERSE(output_get_content(output)) {
613                 if (child->type != CT_WORKSPACE)
614                     continue;
615                 if (child == current) {
616                     found_current = true;
617                 } else if (child->num == -1 && (current->num != -1 || found_current)) {
618                     prev = child;
619                     goto workspace_prev_end;
620                 }
621             }
622         }
623     }
624
625     /* Find last workspace. */
626     if (!prev) {
627         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
628             /* Skip outputs starting with __, they are internal. */
629             if (con_is_internal(output))
630                 continue;
631             NODES_FOREACH_REVERSE(output_get_content(output)) {
632                 if (child->type != CT_WORKSPACE)
633                     continue;
634                 if (!prev || child->num > prev->num)
635                     prev = child;
636             }
637         }
638     }
639
640 workspace_prev_end:
641     return prev;
642 }
643
644 /*
645  * Focuses the next workspace on the same output.
646  *
647  */
648 Con *workspace_next_on_output(void) {
649     Con *current = con_get_workspace(focused);
650     Con *next = NULL;
651     Con *output = con_get_output(focused);
652
653     if (current->num == -1) {
654         /* If currently a named workspace, find next named workspace. */
655         next = TAILQ_NEXT(current, nodes);
656     } else {
657         /* If currently a numbered workspace, find next numbered workspace. */
658         NODES_FOREACH(output_get_content(output)) {
659             if (child->type != CT_WORKSPACE)
660                 continue;
661             if (child->num == -1)
662                 break;
663             /* Need to check child against current and next because we are
664              * traversing multiple lists and thus are not guaranteed the
665              * relative order between the list of workspaces. */
666             if (current->num < child->num && (!next || child->num < next->num))
667                 next = child;
668         }
669     }
670
671     /* Find next named workspace. */
672     if (!next) {
673         bool found_current = false;
674         NODES_FOREACH(output_get_content(output)) {
675             if (child->type != CT_WORKSPACE)
676                 continue;
677             if (child == current) {
678                 found_current = 1;
679             } else if (child->num == -1 && (current->num != -1 || found_current)) {
680                 next = child;
681                 goto workspace_next_on_output_end;
682             }
683         }
684     }
685
686     /* Find first workspace. */
687     if (!next) {
688         NODES_FOREACH(output_get_content(output)) {
689             if (child->type != CT_WORKSPACE)
690                 continue;
691             if (!next || (child->num != -1 && child->num < next->num))
692                 next = child;
693         }
694     }
695 workspace_next_on_output_end:
696     return next;
697 }
698
699 /*
700  * Focuses the previous workspace on same output.
701  *
702  */
703 Con *workspace_prev_on_output(void) {
704     Con *current = con_get_workspace(focused);
705     Con *prev = NULL;
706     Con *output = con_get_output(focused);
707     DLOG("output = %s\n", output->name);
708
709     if (current->num == -1) {
710         /* If named workspace, find previous named workspace. */
711         prev = TAILQ_PREV(current, nodes_head, nodes);
712         if (prev && prev->num != -1)
713             prev = NULL;
714     } else {
715         /* If numbered workspace, find previous numbered workspace. */
716         NODES_FOREACH_REVERSE(output_get_content(output)) {
717             if (child->type != CT_WORKSPACE || child->num == -1)
718                 continue;
719             /* Need to check child against current and previous because we
720              * are traversing multiple lists and thus are not guaranteed
721              * the relative order between the list of workspaces. */
722             if (current->num > child->num && (!prev || child->num > prev->num))
723                 prev = child;
724         }
725     }
726
727     /* Find previous named workspace. */
728     if (!prev) {
729         bool found_current = false;
730         NODES_FOREACH_REVERSE(output_get_content(output)) {
731             if (child->type != CT_WORKSPACE)
732                 continue;
733             if (child == current) {
734                 found_current = true;
735             } else if (child->num == -1 && (current->num != -1 || found_current)) {
736                 prev = child;
737                 goto workspace_prev_on_output_end;
738             }
739         }
740     }
741
742     /* Find last workspace. */
743     if (!prev) {
744         NODES_FOREACH_REVERSE(output_get_content(output)) {
745             if (child->type != CT_WORKSPACE)
746                 continue;
747             if (!prev || child->num > prev->num)
748                 prev = child;
749         }
750     }
751
752 workspace_prev_on_output_end:
753     return prev;
754 }
755
756 /*
757  * Focuses the previously focused workspace.
758  *
759  */
760 void workspace_back_and_forth(void) {
761     if (!previous_workspace_name) {
762         DLOG("No previous workspace name set. Not switching.\n");
763         return;
764     }
765
766     workspace_show_by_name(previous_workspace_name);
767 }
768
769 /*
770  * Returns the previously focused workspace con, or NULL if unavailable.
771  *
772  */
773 Con *workspace_back_and_forth_get(void) {
774     if (!previous_workspace_name) {
775         DLOG("No previous workspace name set.\n");
776         return NULL;
777     }
778
779     Con *workspace;
780     workspace = workspace_get(previous_workspace_name, NULL);
781
782     return workspace;
783 }
784
785 static bool get_urgency_flag(Con *con) {
786     Con *child;
787     TAILQ_FOREACH(child, &(con->nodes_head), nodes)
788     if (child->urgent || get_urgency_flag(child))
789         return true;
790
791     TAILQ_FOREACH(child, &(con->floating_head), floating_windows)
792     if (child->urgent || get_urgency_flag(child))
793         return true;
794
795     return false;
796 }
797
798 /*
799  * Goes through all clients on the given workspace and updates the workspace’s
800  * urgent flag accordingly.
801  *
802  */
803 void workspace_update_urgent_flag(Con *ws) {
804     bool old_flag = ws->urgent;
805     ws->urgent = get_urgency_flag(ws);
806     DLOG("Workspace urgency flag changed from %d to %d\n", old_flag, ws->urgent);
807
808     if (old_flag != ws->urgent)
809         ipc_send_workspace_event("urgent", ws, NULL);
810 }
811
812 /*
813  * 'Forces' workspace orientation by moving all cons into a new split-con with
814  * the same layout as the workspace and then changing the workspace layout.
815  *
816  */
817 void ws_force_orientation(Con *ws, orientation_t orientation) {
818     /* 1: create a new split container */
819     Con *split = con_new(NULL, NULL);
820     split->parent = ws;
821
822     /* 2: copy layout from workspace */
823     split->layout = ws->layout;
824
825     Con *old_focused = TAILQ_FIRST(&(ws->focus_head));
826
827     /* 3: move the existing cons of this workspace below the new con */
828     DLOG("Moving cons\n");
829     while (!TAILQ_EMPTY(&(ws->nodes_head))) {
830         Con *child = TAILQ_FIRST(&(ws->nodes_head));
831         con_detach(child);
832         con_attach(child, split, true);
833     }
834
835     /* 4: switch workspace layout */
836     ws->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
837     DLOG("split->layout = %d, ws->layout = %d\n", split->layout, ws->layout);
838
839     /* 5: attach the new split container to the workspace */
840     DLOG("Attaching new split (%p) to ws (%p)\n", split, ws);
841     con_attach(split, ws, false);
842
843     /* 6: fix the percentages */
844     con_fix_percent(ws);
845
846     if (old_focused)
847         con_focus(old_focused);
848 }
849
850 /*
851  * Called when a new con (with a window, not an empty or split con) should be
852  * attached to the workspace (for example when managing a new window or when
853  * moving an existing window to the workspace level).
854  *
855  * Depending on the workspace_layout setting, this function either returns the
856  * workspace itself (default layout) or creates a new stacked/tabbed con and
857  * returns that.
858  *
859  */
860 Con *workspace_attach_to(Con *ws) {
861     DLOG("Attaching a window to workspace %p / %s\n", ws, ws->name);
862
863     if (ws->workspace_layout == L_DEFAULT) {
864         DLOG("Default layout, just attaching it to the workspace itself.\n");
865         return ws;
866     }
867
868     DLOG("Non-default layout, creating a new split container\n");
869     /* 1: create a new split container */
870     Con *new = con_new(NULL, NULL);
871     new->parent = ws;
872
873     /* 2: set the requested layout on the split con */
874     new->layout = ws->workspace_layout;
875
876     /* 4: attach the new split container to the workspace */
877     DLOG("Attaching new split %p to workspace %p\n", new, ws);
878     con_attach(new, ws, false);
879
880     /* 5: fix the percentages */
881     con_fix_percent(ws);
882
883     return new;
884 }
885
886 /**
887  * Creates a new container and re-parents all of children from the given
888  * workspace into it.
889  *
890  * The container inherits the layout from the workspace.
891  */
892 Con *workspace_encapsulate(Con *ws) {
893     if (TAILQ_EMPTY(&(ws->nodes_head))) {
894         ELOG("Workspace %p / %s has no children to encapsulate\n", ws, ws->name);
895         return NULL;
896     }
897
898     Con *new = con_new(NULL, NULL);
899     new->parent = ws;
900     new->layout = ws->layout;
901
902     DLOG("Moving children of workspace %p / %s into container %p\n",
903          ws, ws->name, new);
904
905     Con *child;
906     while (!TAILQ_EMPTY(&(ws->nodes_head))) {
907         child = TAILQ_FIRST(&(ws->nodes_head));
908         con_detach(child);
909         con_attach(child, new, true);
910     }
911
912     con_attach(new, ws, true);
913
914     return new;
915 }
916
917 /**
918  * Move the given workspace to the specified output.
919  * This returns true if and only if moving the workspace was successful.
920  */
921 bool workspace_move_to_output(Con *ws, const char *name) {
922     LOG("Trying to move workspace %p / %s to output \"%s\".\n", ws, ws->name, name);
923
924     Con *current_output_con = con_get_output(ws);
925     if (!current_output_con) {
926         ELOG("Could not get the output container for workspace %p / %s.\n", ws, ws->name);
927         return false;
928     }
929
930     Output *current_output = get_output_by_name(current_output_con->name);
931     if (!current_output) {
932         ELOG("Cannot get current output. This is a bug in i3.\n");
933         return false;
934     }
935     Output *output = get_output_from_string(current_output, name);
936     if (!output) {
937         ELOG("Could not get output from string \"%s\"\n", name);
938         return false;
939     }
940
941     Con *content = output_get_content(output->con);
942     LOG("got output %p with content %p\n", output, content);
943
944     Con *previously_visible_ws = TAILQ_FIRST(&(content->nodes_head));
945     LOG("Previously visible workspace = %p / %s\n", previously_visible_ws, previously_visible_ws->name);
946
947     bool workspace_was_visible = workspace_is_visible(ws);
948     if (con_num_children(ws->parent) == 1) {
949         LOG("Creating a new workspace to replace \"%s\" (last on its output).\n", ws->name);
950
951         /* check if we can find a workspace assigned to this output */
952         bool used_assignment = false;
953         struct Workspace_Assignment *assignment;
954         TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
955             if (assignment->output == NULL || strcmp(assignment->output, current_output->name) != 0)
956                 continue;
957
958             /* check if this workspace is already attached to the tree */
959             Con *workspace = NULL, *out;
960             TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
961             GREP_FIRST(workspace, output_get_content(out),
962                        !strcasecmp(child->name, assignment->name));
963             if (workspace != NULL)
964                 continue;
965
966             /* so create the workspace referenced to by this assignment */
967             LOG("Creating workspace from assignment %s.\n", assignment->name);
968             workspace_get(assignment->name, NULL);
969             used_assignment = true;
970             break;
971         }
972
973         /* if we couldn't create the workspace using an assignment, create
974          * it on the output */
975         if (!used_assignment)
976             create_workspace_on_output(current_output, ws->parent);
977
978         /* notify the IPC listeners */
979         ipc_send_workspace_event("init", ws, NULL);
980     }
981     DLOG("Detaching\n");
982
983     /* detach from the old output and attach to the new output */
984     Con *old_content = ws->parent;
985     con_detach(ws);
986     if (workspace_was_visible) {
987         /* The workspace which we just detached was visible, so focus
988          * the next one in the focus-stack. */
989         Con *focus_ws = TAILQ_FIRST(&(old_content->focus_head));
990         LOG("workspace was visible, focusing %p / %s now\n", focus_ws, focus_ws->name);
991         workspace_show(focus_ws);
992     }
993     con_attach(ws, content, false);
994
995     /* fix the coordinates of the floating containers */
996     Con *floating_con;
997     TAILQ_FOREACH(floating_con, &(ws->floating_head), floating_windows)
998     floating_fix_coordinates(floating_con, &(old_content->rect), &(content->rect));
999
1000     ipc_send_workspace_event("move", ws, NULL);
1001     if (workspace_was_visible) {
1002         /* Focus the moved workspace on the destination output. */
1003         workspace_show(ws);
1004     }
1005
1006     /* NB: We cannot simply work with previously_visible_ws since it might
1007      * have been cleaned up by workspace_show() already, depending on the
1008      * focus order/number of other workspaces on the output.
1009      * Instead, we loop through the available workspaces and only work with
1010      * previously_visible_ws if we still find it. */
1011     TAILQ_FOREACH(ws, &(content->nodes_head), nodes) {
1012         if (ws != previously_visible_ws)
1013             continue;
1014
1015         /* Call the on_remove_child callback of the workspace which previously
1016          * was visible on the destination output. Since it is no longer
1017          * visible, it might need to get cleaned up. */
1018         CALL(previously_visible_ws, on_remove_child);
1019         break;
1020     }
1021
1022     return true;
1023 }