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