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