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