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