]> git.sur5r.net Git - i3/i3/blob - src/workspace.c
Extract workspace names from bindings before reordering.
[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
367     /* safe-guard against showing i3-internal workspaces like __i3_scratch */
368     if (con_is_internal(workspace))
369         return;
370
371     /* disable fullscreen for the other workspaces and get the workspace we are
372      * currently on. */
373     TAILQ_FOREACH(current, &(workspace->parent->nodes_head), nodes) {
374         if (current->fullscreen_mode == CF_OUTPUT)
375             old = current;
376         current->fullscreen_mode = CF_NONE;
377     }
378
379     /* enable fullscreen for the target workspace. If it happens to be the
380      * same one we are currently on anyways, we can stop here. */
381     workspace->fullscreen_mode = CF_OUTPUT;
382     current = con_get_workspace(focused);
383     if (workspace == current) {
384         DLOG("Not switching, already there.\n");
385         return;
386     }
387
388     /* Remember currently focused workspace for switching back to it later with
389      * the 'workspace back_and_forth' command.
390      * NOTE: We have to duplicate the name as the original will be freed when
391      * the corresponding workspace is cleaned up.
392      * NOTE: Internal cons such as __i3_scratch (when a scratchpad window is
393      * focused) are skipped, see bug #868. */
394     if (current && !con_is_internal(current)) {
395         FREE(previous_workspace_name);
396         if (current) {
397             previous_workspace_name = sstrdup(current->name);
398             DLOG("Setting previous_workspace_name = %s\n", previous_workspace_name);
399         }
400     }
401
402     workspace_reassign_sticky(workspace);
403
404     DLOG("switching to %p / %s\n", workspace, workspace->name);
405     Con *next = con_descend_focused(workspace);
406
407     /* Memorize current output */
408     Con *old_output = con_get_output(focused);
409
410     /* Display urgency hint for a while if the newly visible workspace would
411      * focus and thereby immediately destroy it */
412     if (next->urgent && (int)(config.workspace_urgency_timer * 1000) > 0) {
413         /* focus for now… */
414         next->urgent = false;
415         con_focus(next);
416
417         /* … but immediately reset urgency flags; they will be set to false by
418          * the timer callback in case the container is focused at the time of
419          * its expiration */
420         focused->urgent = true;
421         workspace->urgent = true;
422
423         if (focused->urgency_timer == NULL) {
424             DLOG("Deferring reset of urgency flag of con %p on newly shown workspace %p\n",
425                  focused, workspace);
426             focused->urgency_timer = scalloc(1, sizeof(struct ev_timer));
427             /* use a repeating timer to allow for easy resets */
428             ev_timer_init(focused->urgency_timer, workspace_defer_update_urgent_hint_cb,
429                           config.workspace_urgency_timer, config.workspace_urgency_timer);
430             focused->urgency_timer->data = focused;
431             ev_timer_start(main_loop, focused->urgency_timer);
432         } else {
433             DLOG("Resetting urgency timer of con %p on workspace %p\n",
434                  focused, workspace);
435             ev_timer_again(main_loop, focused->urgency_timer);
436         }
437     } else
438         con_focus(next);
439
440     ipc_send_workspace_event("focus", workspace, current);
441
442     DLOG("old = %p / %s\n", old, (old ? old->name : "(null)"));
443     /* Close old workspace if necessary. This must be done *after* doing
444      * urgency handling, because tree_close() will do a con_focus() on the next
445      * client, which will clear the urgency flag too early. Also, there is no
446      * way for con_focus() to know about when to clear urgency immediately and
447      * when to defer it. */
448     if (old && TAILQ_EMPTY(&(old->nodes_head)) && TAILQ_EMPTY(&(old->floating_head))) {
449         /* check if this workspace is currently visible */
450         if (!workspace_is_visible(old)) {
451             LOG("Closing old workspace (%p / %s), it is empty\n", old, old->name);
452             yajl_gen gen = ipc_marshal_workspace_event("empty", old, NULL);
453             tree_close(old, DONT_KILL_WINDOW, false, false);
454
455             const unsigned char *payload;
456             ylength length;
457             y(get_buf, &payload, &length);
458             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
459
460             y(free);
461
462             ewmh_update_number_of_desktops();
463             ewmh_update_desktop_names();
464             ewmh_update_desktop_viewport();
465         }
466     }
467
468     workspace->fullscreen_mode = CF_OUTPUT;
469     LOG("focused now = %p / %s\n", focused, focused->name);
470
471     /* Set mouse pointer */
472     Con *new_output = con_get_output(focused);
473     if (old_output != new_output) {
474         x_set_warp_to(&next->rect);
475     }
476
477     /* Update the EWMH hints */
478     ewmh_update_current_desktop();
479
480     /* Push any sticky windows to the now visible workspace. */
481     output_push_sticky_windows();
482 }
483
484 /*
485  * Switches to the given workspace
486  *
487  */
488 void workspace_show(Con *workspace) {
489     _workspace_show(workspace);
490 }
491
492 /*
493  * Looks up the workspace by name and switches to it.
494  *
495  */
496 void workspace_show_by_name(const char *num) {
497     Con *workspace;
498     workspace = workspace_get(num, NULL);
499     _workspace_show(workspace);
500 }
501
502 /*
503  * Focuses the next workspace.
504  *
505  */
506 Con *workspace_next(void) {
507     Con *current = con_get_workspace(focused);
508     Con *next = NULL;
509     Con *output;
510
511     if (current->num == -1) {
512         /* If currently a named workspace, find next named workspace. */
513         next = TAILQ_NEXT(current, nodes);
514     } else {
515         /* If currently a numbered workspace, find next numbered workspace. */
516         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
517             /* Skip outputs starting with __, they are internal. */
518             if (con_is_internal(output))
519                 continue;
520             NODES_FOREACH(output_get_content(output)) {
521                 if (child->type != CT_WORKSPACE)
522                     continue;
523                 if (child->num == -1)
524                     break;
525                 /* Need to check child against current and next because we are
526                  * traversing multiple lists and thus are not guaranteed the
527                  * relative order between the list of workspaces. */
528                 if (current->num < child->num && (!next || child->num < next->num))
529                     next = child;
530             }
531         }
532     }
533
534     /* Find next named workspace. */
535     if (!next) {
536         bool found_current = false;
537         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
538             /* Skip outputs starting with __, they are internal. */
539             if (con_is_internal(output))
540                 continue;
541             NODES_FOREACH(output_get_content(output)) {
542                 if (child->type != CT_WORKSPACE)
543                     continue;
544                 if (child == current) {
545                     found_current = 1;
546                 } else if (child->num == -1 && (current->num != -1 || found_current)) {
547                     next = child;
548                     goto workspace_next_end;
549                 }
550             }
551         }
552     }
553
554     /* Find first workspace. */
555     if (!next) {
556         TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
557             /* Skip outputs starting with __, they are internal. */
558             if (con_is_internal(output))
559                 continue;
560             NODES_FOREACH(output_get_content(output)) {
561                 if (child->type != CT_WORKSPACE)
562                     continue;
563                 if (!next || (child->num != -1 && child->num < next->num))
564                     next = child;
565             }
566         }
567     }
568 workspace_next_end:
569     return next;
570 }
571
572 /*
573  * Focuses the previous workspace.
574  *
575  */
576 Con *workspace_prev(void) {
577     Con *current = con_get_workspace(focused);
578     Con *prev = NULL;
579     Con *output;
580
581     if (current->num == -1) {
582         /* If named workspace, find previous named workspace. */
583         prev = TAILQ_PREV(current, nodes_head, nodes);
584         if (prev && prev->num != -1)
585             prev = NULL;
586     } else {
587         /* If numbered workspace, find previous numbered workspace. */
588         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
589             /* Skip outputs starting with __, they are internal. */
590             if (con_is_internal(output))
591                 continue;
592             NODES_FOREACH_REVERSE(output_get_content(output)) {
593                 if (child->type != CT_WORKSPACE || child->num == -1)
594                     continue;
595                 /* Need to check child against current and previous because we
596                  * are traversing multiple lists and thus are not guaranteed
597                  * the relative order between the list of workspaces. */
598                 if (current->num > child->num && (!prev || child->num > prev->num))
599                     prev = child;
600             }
601         }
602     }
603
604     /* Find previous named workspace. */
605     if (!prev) {
606         bool found_current = false;
607         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
608             /* Skip outputs starting with __, they are internal. */
609             if (con_is_internal(output))
610                 continue;
611             NODES_FOREACH_REVERSE(output_get_content(output)) {
612                 if (child->type != CT_WORKSPACE)
613                     continue;
614                 if (child == current) {
615                     found_current = true;
616                 } else if (child->num == -1 && (current->num != -1 || found_current)) {
617                     prev = child;
618                     goto workspace_prev_end;
619                 }
620             }
621         }
622     }
623
624     /* Find last workspace. */
625     if (!prev) {
626         TAILQ_FOREACH_REVERSE(output, &(croot->nodes_head), nodes_head, nodes) {
627             /* Skip outputs starting with __, they are internal. */
628             if (con_is_internal(output))
629                 continue;
630             NODES_FOREACH_REVERSE(output_get_content(output)) {
631                 if (child->type != CT_WORKSPACE)
632                     continue;
633                 if (!prev || child->num > prev->num)
634                     prev = child;
635             }
636         }
637     }
638
639 workspace_prev_end:
640     return prev;
641 }
642
643 /*
644  * Focuses the next workspace on the same output.
645  *
646  */
647 Con *workspace_next_on_output(void) {
648     Con *current = con_get_workspace(focused);
649     Con *next = NULL;
650     Con *output = con_get_output(focused);
651
652     if (current->num == -1) {
653         /* If currently a named workspace, find next named workspace. */
654         next = TAILQ_NEXT(current, nodes);
655     } else {
656         /* If currently a numbered workspace, find next numbered workspace. */
657         NODES_FOREACH(output_get_content(output)) {
658             if (child->type != CT_WORKSPACE)
659                 continue;
660             if (child->num == -1)
661                 break;
662             /* Need to check child against current and next because we are
663              * traversing multiple lists and thus are not guaranteed the
664              * relative order between the list of workspaces. */
665             if (current->num < child->num && (!next || child->num < next->num))
666                 next = child;
667         }
668     }
669
670     /* Find next named workspace. */
671     if (!next) {
672         bool found_current = false;
673         NODES_FOREACH(output_get_content(output)) {
674             if (child->type != CT_WORKSPACE)
675                 continue;
676             if (child == current) {
677                 found_current = 1;
678             } else if (child->num == -1 && (current->num != -1 || found_current)) {
679                 next = child;
680                 goto workspace_next_on_output_end;
681             }
682         }
683     }
684
685     /* Find first workspace. */
686     if (!next) {
687         NODES_FOREACH(output_get_content(output)) {
688             if (child->type != CT_WORKSPACE)
689                 continue;
690             if (!next || (child->num != -1 && child->num < next->num))
691                 next = child;
692         }
693     }
694 workspace_next_on_output_end:
695     return next;
696 }
697
698 /*
699  * Focuses the previous workspace on same output.
700  *
701  */
702 Con *workspace_prev_on_output(void) {
703     Con *current = con_get_workspace(focused);
704     Con *prev = NULL;
705     Con *output = con_get_output(focused);
706     DLOG("output = %s\n", output->name);
707
708     if (current->num == -1) {
709         /* If named workspace, find previous named workspace. */
710         prev = TAILQ_PREV(current, nodes_head, nodes);
711         if (prev && prev->num != -1)
712             prev = NULL;
713     } else {
714         /* If numbered workspace, find previous numbered workspace. */
715         NODES_FOREACH_REVERSE(output_get_content(output)) {
716             if (child->type != CT_WORKSPACE || child->num == -1)
717                 continue;
718             /* Need to check child against current and previous because we
719              * are traversing multiple lists and thus are not guaranteed
720              * the relative order between the list of workspaces. */
721             if (current->num > child->num && (!prev || child->num > prev->num))
722                 prev = child;
723         }
724     }
725
726     /* Find previous named workspace. */
727     if (!prev) {
728         bool found_current = false;
729         NODES_FOREACH_REVERSE(output_get_content(output)) {
730             if (child->type != CT_WORKSPACE)
731                 continue;
732             if (child == current) {
733                 found_current = true;
734             } else if (child->num == -1 && (current->num != -1 || found_current)) {
735                 prev = child;
736                 goto workspace_prev_on_output_end;
737             }
738         }
739     }
740
741     /* Find last workspace. */
742     if (!prev) {
743         NODES_FOREACH_REVERSE(output_get_content(output)) {
744             if (child->type != CT_WORKSPACE)
745                 continue;
746             if (!prev || child->num > prev->num)
747                 prev = child;
748         }
749     }
750
751 workspace_prev_on_output_end:
752     return prev;
753 }
754
755 /*
756  * Focuses the previously focused workspace.
757  *
758  */
759 void workspace_back_and_forth(void) {
760     if (!previous_workspace_name) {
761         DLOG("No previous workspace name set. Not switching.\n");
762         return;
763     }
764
765     workspace_show_by_name(previous_workspace_name);
766 }
767
768 /*
769  * Returns the previously focused workspace con, or NULL if unavailable.
770  *
771  */
772 Con *workspace_back_and_forth_get(void) {
773     if (!previous_workspace_name) {
774         DLOG("No previous workspace name set.\n");
775         return NULL;
776     }
777
778     Con *workspace;
779     workspace = workspace_get(previous_workspace_name, NULL);
780
781     return workspace;
782 }
783
784 static bool get_urgency_flag(Con *con) {
785     Con *child;
786     TAILQ_FOREACH(child, &(con->nodes_head), nodes)
787     if (child->urgent || get_urgency_flag(child))
788         return true;
789
790     TAILQ_FOREACH(child, &(con->floating_head), floating_windows)
791     if (child->urgent || get_urgency_flag(child))
792         return true;
793
794     return false;
795 }
796
797 /*
798  * Goes through all clients on the given workspace and updates the workspace’s
799  * urgent flag accordingly.
800  *
801  */
802 void workspace_update_urgent_flag(Con *ws) {
803     bool old_flag = ws->urgent;
804     ws->urgent = get_urgency_flag(ws);
805     DLOG("Workspace urgency flag changed from %d to %d\n", old_flag, ws->urgent);
806
807     if (old_flag != ws->urgent)
808         ipc_send_workspace_event("urgent", ws, NULL);
809 }
810
811 /*
812  * 'Forces' workspace orientation by moving all cons into a new split-con with
813  * the same layout as the workspace and then changing the workspace layout.
814  *
815  */
816 void ws_force_orientation(Con *ws, orientation_t orientation) {
817     /* 1: create a new split container */
818     Con *split = con_new(NULL, NULL);
819     split->parent = ws;
820
821     /* 2: copy layout from workspace */
822     split->layout = ws->layout;
823
824     Con *old_focused = TAILQ_FIRST(&(ws->focus_head));
825
826     /* 3: move the existing cons of this workspace below the new con */
827     DLOG("Moving cons\n");
828     while (!TAILQ_EMPTY(&(ws->nodes_head))) {
829         Con *child = TAILQ_FIRST(&(ws->nodes_head));
830         con_detach(child);
831         con_attach(child, split, true);
832     }
833
834     /* 4: switch workspace layout */
835     ws->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
836     DLOG("split->layout = %d, ws->layout = %d\n", split->layout, ws->layout);
837
838     /* 5: attach the new split container to the workspace */
839     DLOG("Attaching new split (%p) to ws (%p)\n", split, ws);
840     con_attach(split, ws, false);
841
842     /* 6: fix the percentages */
843     con_fix_percent(ws);
844
845     if (old_focused)
846         con_focus(old_focused);
847 }
848
849 /*
850  * Called when a new con (with a window, not an empty or split con) should be
851  * attached to the workspace (for example when managing a new window or when
852  * moving an existing window to the workspace level).
853  *
854  * Depending on the workspace_layout setting, this function either returns the
855  * workspace itself (default layout) or creates a new stacked/tabbed con and
856  * returns that.
857  *
858  */
859 Con *workspace_attach_to(Con *ws) {
860     DLOG("Attaching a window to workspace %p / %s\n", ws, ws->name);
861
862     if (ws->workspace_layout == L_DEFAULT) {
863         DLOG("Default layout, just attaching it to the workspace itself.\n");
864         return ws;
865     }
866
867     DLOG("Non-default layout, creating a new split container\n");
868     /* 1: create a new split container */
869     Con *new = con_new(NULL, NULL);
870     new->parent = ws;
871
872     /* 2: set the requested layout on the split con */
873     new->layout = ws->workspace_layout;
874
875     /* 4: attach the new split container to the workspace */
876     DLOG("Attaching new split %p to workspace %p\n", new, ws);
877     con_attach(new, ws, false);
878
879     /* 5: fix the percentages */
880     con_fix_percent(ws);
881
882     return new;
883 }
884
885 /**
886  * Creates a new container and re-parents all of children from the given
887  * workspace into it.
888  *
889  * The container inherits the layout from the workspace.
890  */
891 Con *workspace_encapsulate(Con *ws) {
892     if (TAILQ_EMPTY(&(ws->nodes_head))) {
893         ELOG("Workspace %p / %s has no children to encapsulate\n", ws, ws->name);
894         return NULL;
895     }
896
897     Con *new = con_new(NULL, NULL);
898     new->parent = ws;
899     new->layout = ws->layout;
900
901     DLOG("Moving children of workspace %p / %s into container %p\n",
902          ws, ws->name, new);
903
904     Con *child;
905     while (!TAILQ_EMPTY(&(ws->nodes_head))) {
906         child = TAILQ_FIRST(&(ws->nodes_head));
907         con_detach(child);
908         con_attach(child, new, true);
909     }
910
911     con_attach(new, ws, true);
912
913     return new;
914 }
915
916 /**
917  * Move the given workspace to the specified output.
918  * This returns true if and only if moving the workspace was successful.
919  */
920 bool workspace_move_to_output(Con *ws, char *name) {
921     LOG("Trying to move workspace %p / %s to output \"%s\".\n", ws, ws->name, name);
922
923     Con *current_output_con = con_get_output(ws);
924     if (!current_output_con) {
925         ELOG("Could not get the output container for workspace %p / %s.\n", ws, ws->name);
926         return false;
927     }
928
929     Output *current_output = get_output_by_name(current_output_con->name);
930     if (!current_output) {
931         ELOG("Cannot get current output. This is a bug in i3.\n");
932         return false;
933     }
934     Output *output = get_output_from_string(current_output, name);
935     if (!output) {
936         ELOG("Could not get output from string \"%s\"\n", name);
937         return false;
938     }
939
940     Con *content = output_get_content(output->con);
941     LOG("got output %p with content %p\n", output, content);
942
943     Con *previously_visible_ws = TAILQ_FIRST(&(content->nodes_head));
944     LOG("Previously visible workspace = %p / %s\n", previously_visible_ws, previously_visible_ws->name);
945
946     bool workspace_was_visible = workspace_is_visible(ws);
947     if (con_num_children(ws->parent) == 1) {
948         LOG("Creating a new workspace to replace \"%s\" (last on its output).\n", ws->name);
949
950         /* check if we can find a workspace assigned to this output */
951         bool used_assignment = false;
952         struct Workspace_Assignment *assignment;
953         TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
954             if (assignment->output == NULL || strcmp(assignment->output, current_output->name) != 0)
955                 continue;
956
957             /* check if this workspace is already attached to the tree */
958             Con *workspace = NULL, *out;
959             TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
960             GREP_FIRST(workspace, output_get_content(out),
961                        !strcasecmp(child->name, assignment->name));
962             if (workspace != NULL)
963                 continue;
964
965             /* so create the workspace referenced to by this assignment */
966             LOG("Creating workspace from assignment %s.\n", assignment->name);
967             workspace_get(assignment->name, NULL);
968             used_assignment = true;
969             break;
970         }
971
972         /* if we couldn't create the workspace using an assignment, create
973          * it on the output */
974         if (!used_assignment)
975             create_workspace_on_output(current_output, ws->parent);
976
977         /* notify the IPC listeners */
978         ipc_send_workspace_event("init", ws, NULL);
979     }
980     DLOG("Detaching\n");
981
982     /* detach from the old output and attach to the new output */
983     Con *old_content = ws->parent;
984     con_detach(ws);
985     if (workspace_was_visible) {
986         /* The workspace which we just detached was visible, so focus
987          * the next one in the focus-stack. */
988         Con *focus_ws = TAILQ_FIRST(&(old_content->focus_head));
989         LOG("workspace was visible, focusing %p / %s now\n", focus_ws, focus_ws->name);
990         workspace_show(focus_ws);
991     }
992     con_attach(ws, content, false);
993
994     /* fix the coordinates of the floating containers */
995     Con *floating_con;
996     TAILQ_FOREACH(floating_con, &(ws->floating_head), floating_windows)
997     floating_fix_coordinates(floating_con, &(old_content->rect), &(content->rect));
998
999     ipc_send_workspace_event("move", ws, NULL);
1000     if (workspace_was_visible) {
1001         /* Focus the moved workspace on the destination output. */
1002         workspace_show(ws);
1003     }
1004
1005     /* NB: We cannot simply work with previously_visible_ws since it might
1006      * have been cleaned up by workspace_show() already, depending on the
1007      * focus order/number of other workspaces on the output.
1008      * Instead, we loop through the available workspaces and only work with
1009      * previously_visible_ws if we still find it. */
1010     TAILQ_FOREACH(ws, &(content->nodes_head), nodes) {
1011         if (ws != previously_visible_ws)
1012             continue;
1013
1014         /* Call the on_remove_child callback of the workspace which previously
1015          * was visible on the destination output. Since it is no longer
1016          * visible, it might need to get cleaned up. */
1017         CALL(previously_visible_ws, on_remove_child);
1018         break;
1019     }
1020
1021     return true;
1022 }