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