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