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