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