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