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