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