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