]> git.sur5r.net Git - i3/i3/blob - src/randr.c
Store output names as a linked list
[i3/i3] / src / randr.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  * For more information on RandR, please see the X.org RandR specification at
8  * http://cgit.freedesktop.org/xorg/proto/randrproto/tree/randrproto.txt
9  * (take your time to read it completely, it answers all questions).
10  *
11  */
12 #include "all.h"
13
14 #include <time.h>
15 #include <xcb/randr.h>
16
17 /* Pointer to the result of the query for primary output */
18 xcb_randr_get_output_primary_reply_t *primary;
19
20 /* Stores all outputs available in your current session. */
21 struct outputs_head outputs = TAILQ_HEAD_INITIALIZER(outputs);
22
23 /* This is the output covering the root window */
24 static Output *root_output;
25 static bool has_randr_1_5 = false;
26
27 /*
28  * Get a specific output by its internal X11 id. Used by randr_query_outputs
29  * to check if the output is new (only in the first scan) or if we are
30  * re-scanning.
31  *
32  */
33 static Output *get_output_by_id(xcb_randr_output_t id) {
34     Output *output;
35     TAILQ_FOREACH(output, &outputs, outputs)
36     if (output->id == id)
37         return output;
38
39     return NULL;
40 }
41
42 /*
43  * Returns the output with the given name or NULL.
44  * If require_active is true, only active outputs are considered.
45  *
46  */
47 Output *get_output_by_name(const char *name, const bool require_active) {
48     Output *output;
49     bool get_primary = (strcasecmp("primary", name) == 0);
50     TAILQ_FOREACH(output, &outputs, outputs) {
51         if ((output->primary && get_primary) ||
52             ((!require_active || output->active) && strcasecmp(output_primary_name(output), name) == 0)) {
53             return output;
54         }
55     }
56
57     return NULL;
58 }
59
60 /*
61  * Returns the first output which is active.
62  *
63  */
64 Output *get_first_output(void) {
65     Output *output;
66
67     TAILQ_FOREACH(output, &outputs, outputs)
68     if (output->active)
69         return output;
70
71     die("No usable outputs available.\n");
72 }
73
74 /*
75  * Check whether there are any active outputs (excluding the root output).
76  *
77  */
78 static bool any_randr_output_active(void) {
79     Output *output;
80
81     TAILQ_FOREACH(output, &outputs, outputs) {
82         if (output != root_output && !output->to_be_disabled && output->active)
83             return true;
84     }
85
86     return false;
87 }
88
89 /*
90  * Returns the active (!) output which contains the coordinates x, y or NULL
91  * if there is no output which contains these coordinates.
92  *
93  */
94 Output *get_output_containing(unsigned int x, unsigned int y) {
95     Output *output;
96     TAILQ_FOREACH(output, &outputs, outputs) {
97         if (!output->active)
98             continue;
99         DLOG("comparing x=%d y=%d with x=%d and y=%d width %d height %d\n",
100              x, y, output->rect.x, output->rect.y, output->rect.width, output->rect.height);
101         if (x >= output->rect.x && x < (output->rect.x + output->rect.width) &&
102             y >= output->rect.y && y < (output->rect.y + output->rect.height))
103             return output;
104     }
105
106     return NULL;
107 }
108
109 /*
110  * Returns the active output which spans exactly the area specified by
111  * rect or NULL if there is no output like this.
112  *
113  */
114 Output *get_output_with_dimensions(Rect rect) {
115     Output *output;
116     TAILQ_FOREACH(output, &outputs, outputs) {
117         if (!output->active)
118             continue;
119         DLOG("comparing x=%d y=%d %dx%d with x=%d and y=%d %dx%d\n",
120              rect.x, rect.y, rect.width, rect.height,
121              output->rect.x, output->rect.y, output->rect.width, output->rect.height);
122         if (rect.x == output->rect.x && rect.width == output->rect.width &&
123             rect.y == output->rect.y && rect.height == output->rect.height)
124             return output;
125     }
126
127     return NULL;
128 }
129
130 /*
131  * In contained_by_output, we check if any active output contains part of the container.
132  * We do this by checking if the output rect is intersected by the Rect.
133  * This is the 2-dimensional counterpart of get_output_containing.
134  * Since we don't actually need the outputs intersected by the given Rect (There could
135  * be many), we just return true or false for convenience.
136  *
137  */
138 bool contained_by_output(Rect rect) {
139     Output *output;
140     int lx = rect.x, uy = rect.y;
141     int rx = rect.x + rect.width, by = rect.y + rect.height;
142     TAILQ_FOREACH(output, &outputs, outputs) {
143         if (!output->active)
144             continue;
145         DLOG("comparing x=%d y=%d with x=%d and y=%d width %d height %d\n",
146              rect.x, rect.y, output->rect.x, output->rect.y, output->rect.width, output->rect.height);
147         if (rx >= (int)output->rect.x && lx <= (int)(output->rect.x + output->rect.width) &&
148             by >= (int)output->rect.y && uy <= (int)(output->rect.y + output->rect.height))
149             return true;
150     }
151     return false;
152 }
153
154 /*
155  * Like get_output_next with close_far == CLOSEST_OUTPUT, but wraps.
156  *
157  * For example if get_output_next(D_DOWN, x, FARTHEST_OUTPUT) = NULL, then
158  * get_output_next_wrap(D_DOWN, x) will return the topmost output.
159  *
160  * This function always returns a output: if no active outputs can be found,
161  * current itself is returned.
162  *
163  */
164 Output *get_output_next_wrap(direction_t direction, Output *current) {
165     Output *best = get_output_next(direction, current, CLOSEST_OUTPUT);
166     /* If no output can be found, wrap */
167     if (!best) {
168         direction_t opposite;
169         if (direction == D_RIGHT)
170             opposite = D_LEFT;
171         else if (direction == D_LEFT)
172             opposite = D_RIGHT;
173         else if (direction == D_DOWN)
174             opposite = D_UP;
175         else
176             opposite = D_DOWN;
177         best = get_output_next(opposite, current, FARTHEST_OUTPUT);
178     }
179     if (!best)
180         best = current;
181     DLOG("current = %s, best = %s\n", output_primary_name(current), output_primary_name(best));
182     return best;
183 }
184
185 /*
186  * Gets the output which is the next one in the given direction.
187  *
188  * If close_far == CLOSEST_OUTPUT, then the output next to the current one will
189  * selected. If close_far == FARTHEST_OUTPUT, the output which is the last one
190  * in the given direction will be selected.
191  *
192  * NULL will be returned when no active outputs are present in the direction
193  * specified (note that “current” counts as such an output).
194  *
195  */
196 Output *get_output_next(direction_t direction, Output *current, output_close_far_t close_far) {
197     Rect *cur = &(current->rect),
198          *other;
199     Output *output,
200         *best = NULL;
201     TAILQ_FOREACH(output, &outputs, outputs) {
202         if (!output->active)
203             continue;
204
205         other = &(output->rect);
206
207         if ((direction == D_RIGHT && other->x > cur->x) ||
208             (direction == D_LEFT && other->x < cur->x)) {
209             /* Skip the output when it doesn’t overlap the other one’s y
210              * coordinate at all. */
211             if ((other->y + other->height) <= cur->y ||
212                 (cur->y + cur->height) <= other->y)
213                 continue;
214         } else if ((direction == D_DOWN && other->y > cur->y) ||
215                    (direction == D_UP && other->y < cur->y)) {
216             /* Skip the output when it doesn’t overlap the other one’s x
217              * coordinate at all. */
218             if ((other->x + other->width) <= cur->x ||
219                 (cur->x + cur->width) <= other->x)
220                 continue;
221         } else
222             continue;
223
224         /* No candidate yet? Start with this one. */
225         if (!best) {
226             best = output;
227             continue;
228         }
229
230         if (close_far == CLOSEST_OUTPUT) {
231             /* Is this output better (closer to the current output) than our
232              * current best bet? */
233             if ((direction == D_RIGHT && other->x < best->rect.x) ||
234                 (direction == D_LEFT && other->x > best->rect.x) ||
235                 (direction == D_DOWN && other->y < best->rect.y) ||
236                 (direction == D_UP && other->y > best->rect.y)) {
237                 best = output;
238                 continue;
239             }
240         } else {
241             /* Is this output better (farther to the current output) than our
242              * current best bet? */
243             if ((direction == D_RIGHT && other->x > best->rect.x) ||
244                 (direction == D_LEFT && other->x < best->rect.x) ||
245                 (direction == D_DOWN && other->y > best->rect.y) ||
246                 (direction == D_UP && other->y < best->rect.y)) {
247                 best = output;
248                 continue;
249             }
250         }
251     }
252
253     DLOG("current = %s, best = %s\n", output_primary_name(current), (best ? output_primary_name(best) : "NULL"));
254     return best;
255 }
256
257 /*
258  * Creates an output covering the root window.
259  *
260  */
261 Output *create_root_output(xcb_connection_t *conn) {
262     Output *s = scalloc(1, sizeof(Output));
263
264     s->active = false;
265     s->rect.x = 0;
266     s->rect.y = 0;
267     s->rect.width = root_screen->width_in_pixels;
268     s->rect.height = root_screen->height_in_pixels;
269
270     struct output_name *output_name = scalloc(1, sizeof(struct output_name));
271     output_name->name = "xroot-0";
272     SLIST_INIT(&s->names_head);
273     SLIST_INSERT_HEAD(&s->names_head, output_name, names);
274
275     return s;
276 }
277
278 /*
279  * Initializes a CT_OUTPUT Con (searches existing ones from inplace restart
280  * before) to use for the given Output.
281  *
282  */
283 void output_init_con(Output *output) {
284     Con *con = NULL, *current;
285     bool reused = false;
286
287     DLOG("init_con for output %s\n", output_primary_name(output));
288
289     /* Search for a Con with that name directly below the root node. There
290      * might be one from a restored layout. */
291     TAILQ_FOREACH(current, &(croot->nodes_head), nodes) {
292         if (strcmp(current->name, output_primary_name(output)) != 0)
293             continue;
294
295         con = current;
296         reused = true;
297         DLOG("Using existing con %p / %s\n", con, con->name);
298         break;
299     }
300
301     if (con == NULL) {
302         con = con_new(croot, NULL);
303         FREE(con->name);
304         con->name = sstrdup(output_primary_name(output));
305         con->type = CT_OUTPUT;
306         con->layout = L_OUTPUT;
307         con_fix_percent(croot);
308     }
309     con->rect = output->rect;
310     output->con = con;
311
312     char *name;
313     sasprintf(&name, "[i3 con] output %s", con->name);
314     x_set_name(con, name);
315     FREE(name);
316
317     if (reused) {
318         DLOG("Not adding workspace, this was a reused con\n");
319         return;
320     }
321
322     DLOG("Changing layout, adding top/bottom dockarea\n");
323     Con *topdock = con_new(NULL, NULL);
324     topdock->type = CT_DOCKAREA;
325     topdock->layout = L_DOCKAREA;
326     /* this container swallows dock clients */
327     Match *match = scalloc(1, sizeof(Match));
328     match_init(match);
329     match->dock = M_DOCK_TOP;
330     match->insert_where = M_BELOW;
331     TAILQ_INSERT_TAIL(&(topdock->swallow_head), match, matches);
332
333     FREE(topdock->name);
334     topdock->name = sstrdup("topdock");
335
336     sasprintf(&name, "[i3 con] top dockarea %s", con->name);
337     x_set_name(topdock, name);
338     FREE(name);
339     DLOG("attaching\n");
340     con_attach(topdock, con, false);
341
342     /* content container */
343
344     DLOG("adding main content container\n");
345     Con *content = con_new(NULL, NULL);
346     content->type = CT_CON;
347     content->layout = L_SPLITH;
348     FREE(content->name);
349     content->name = sstrdup("content");
350
351     sasprintf(&name, "[i3 con] content %s", con->name);
352     x_set_name(content, name);
353     FREE(name);
354     con_attach(content, con, false);
355
356     /* bottom dock container */
357     Con *bottomdock = con_new(NULL, NULL);
358     bottomdock->type = CT_DOCKAREA;
359     bottomdock->layout = L_DOCKAREA;
360     /* this container swallows dock clients */
361     match = scalloc(1, sizeof(Match));
362     match_init(match);
363     match->dock = M_DOCK_BOTTOM;
364     match->insert_where = M_BELOW;
365     TAILQ_INSERT_TAIL(&(bottomdock->swallow_head), match, matches);
366
367     FREE(bottomdock->name);
368     bottomdock->name = sstrdup("bottomdock");
369
370     sasprintf(&name, "[i3 con] bottom dockarea %s", con->name);
371     x_set_name(bottomdock, name);
372     FREE(name);
373     DLOG("attaching\n");
374     con_attach(bottomdock, con, false);
375 }
376
377 /*
378  * Initializes at least one workspace for this output, trying the following
379  * steps until there is at least one workspace:
380  *
381  * • Move existing workspaces, which are assigned to be on the given output, to
382  *   the output.
383  * • Create the first assigned workspace for this output.
384  * • Create the first unused workspace.
385  *
386  */
387 void init_ws_for_output(Output *output, Con *content) {
388     /* go through all assignments and move the existing workspaces to this output */
389     struct Workspace_Assignment *assignment;
390     TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
391         if (strcmp(assignment->output, output_primary_name(output)) != 0)
392             continue;
393
394         /* check if this workspace actually exists */
395         Con *workspace = NULL, *out;
396         TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
397         GREP_FIRST(workspace, output_get_content(out),
398                    !strcasecmp(child->name, assignment->name));
399         if (workspace == NULL)
400             continue;
401
402         /* check that this workspace is not already attached (that means the
403          * user configured this assignment twice) */
404         Con *workspace_out = con_get_output(workspace);
405         if (workspace_out == output->con) {
406             LOG("Workspace \"%s\" assigned to output \"%s\", but it is already "
407                 "there. Do you have two assignment directives for the same "
408                 "workspace in your configuration file?\n",
409                 workspace->name, output_primary_name(output));
410             continue;
411         }
412
413         /* if so, move it over */
414         LOG("Moving workspace \"%s\" from output \"%s\" to \"%s\" due to assignment\n",
415             workspace->name, workspace_out->name, output_primary_name(output));
416
417         /* if the workspace is currently visible on that output, we need to
418          * switch to a different workspace - otherwise the output would end up
419          * with no active workspace */
420         bool visible = workspace_is_visible(workspace);
421         Con *previous = NULL;
422         if (visible && (previous = TAILQ_NEXT(workspace, focused))) {
423             LOG("Switching to previously used workspace \"%s\" on output \"%s\"\n",
424                 previous->name, workspace_out->name);
425             workspace_show(previous);
426         }
427
428         /* Render the output on which the workspace was to get correct Rects.
429          * Then, we need to work with the "content" container, since we cannot
430          * be sure that the workspace itself was rendered at all (in case it’s
431          * invisible, it won’t be rendered). */
432         render_con(workspace_out, false);
433         Con *ws_out_content = output_get_content(workspace_out);
434
435         Con *floating_con;
436         TAILQ_FOREACH(floating_con, &(workspace->floating_head), floating_windows)
437         /* NB: We use output->con here because content is not yet rendered,
438              * so it has a rect of {0, 0, 0, 0}. */
439         floating_fix_coordinates(floating_con, &(ws_out_content->rect), &(output->con->rect));
440
441         con_detach(workspace);
442         con_attach(workspace, content, false);
443
444         /* In case the workspace we just moved was visible but there was no
445          * other workspace to switch to, we need to initialize the source
446          * output as well */
447         if (visible && previous == NULL) {
448             LOG("There is no workspace left on \"%s\", re-initializing\n",
449                 workspace_out->name);
450             init_ws_for_output(get_output_by_name(workspace_out->name, true),
451                                output_get_content(workspace_out));
452             DLOG("Done re-initializing, continuing with \"%s\"\n", output_primary_name(output));
453         }
454     }
455
456     /* if a workspace exists, we are done now */
457     if (!TAILQ_EMPTY(&(content->nodes_head))) {
458         /* ensure that one of the workspaces is actually visible (in fullscreen
459          * mode), if they were invisible before, this might not be the case. */
460         Con *visible = NULL;
461         GREP_FIRST(visible, content, child->fullscreen_mode == CF_OUTPUT);
462         if (!visible) {
463             visible = TAILQ_FIRST(&(content->nodes_head));
464             focused = content;
465             workspace_show(visible);
466         }
467         return;
468     }
469
470     /* otherwise, we create the first assigned ws for this output */
471     TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
472         if (strcmp(assignment->output, output_primary_name(output)) != 0)
473             continue;
474
475         LOG("Initializing first assigned workspace \"%s\" for output \"%s\"\n",
476             assignment->name, assignment->output);
477         focused = content;
478         workspace_show_by_name(assignment->name);
479         return;
480     }
481
482     /* if there is still no workspace, we create the first free workspace */
483     DLOG("Now adding a workspace\n");
484     Con *ws = create_workspace_on_output(output, content);
485
486     /* TODO: Set focus in main.c */
487     con_focus(ws);
488 }
489
490 /*
491  * This function needs to be called when changing the mode of an output when
492  * it already has some workspaces (or a bar window) assigned.
493  *
494  * It reconfigures the bar window for the new mode, copies the new rect into
495  * each workspace on this output and forces all windows on the affected
496  * workspaces to be reconfigured.
497  *
498  * It is necessary to call render_layout() afterwards.
499  *
500  */
501 static void output_change_mode(xcb_connection_t *conn, Output *output) {
502     DLOG("Output mode changed, updating rect\n");
503     assert(output->con != NULL);
504     output->con->rect = output->rect;
505
506     Con *content, *workspace, *child;
507
508     /* Point content to the container of the workspaces */
509     content = output_get_content(output->con);
510
511     /* Fix the position of all floating windows on this output.
512      * The 'rect' of each workspace will be updated in src/render.c. */
513     TAILQ_FOREACH(workspace, &(content->nodes_head), nodes) {
514         TAILQ_FOREACH(child, &(workspace->floating_head), floating_windows) {
515             floating_fix_coordinates(child, &(workspace->rect), &(output->con->rect));
516         }
517     }
518
519     /* If default_orientation is NO_ORIENTATION, we change the orientation of
520      * the workspaces and their childs depending on output resolution. This is
521      * only done for workspaces with maximum one child. */
522     if (config.default_orientation == NO_ORIENTATION) {
523         TAILQ_FOREACH(workspace, &(content->nodes_head), nodes) {
524             /* Workspaces with more than one child are left untouched because
525              * we do not want to change an existing layout. */
526             if (con_num_children(workspace) > 1)
527                 continue;
528
529             workspace->layout = (output->rect.height > output->rect.width) ? L_SPLITV : L_SPLITH;
530             DLOG("Setting workspace [%d,%s]'s layout to %d.\n", workspace->num, workspace->name, workspace->layout);
531             if ((child = TAILQ_FIRST(&(workspace->nodes_head)))) {
532                 if (child->layout == L_SPLITV || child->layout == L_SPLITH)
533                     child->layout = workspace->layout;
534                 DLOG("Setting child [%d,%s]'s layout to %d.\n", child->num, child->name, child->layout);
535             }
536         }
537     }
538 }
539
540 /*
541  * randr_query_outputs_15 uses RandR ≥ 1.5 to update outputs.
542  *
543  */
544 static bool randr_query_outputs_15(void) {
545 #if XCB_RANDR_MINOR_VERSION < 5
546     return false;
547 #else
548     /* RandR 1.5 available at compile-time, i.e. libxcb is new enough */
549     if (!has_randr_1_5) {
550         return false;
551     }
552     /* RandR 1.5 available at run-time (supported by the server and not
553      * disabled by the user) */
554     DLOG("Querying outputs using RandR 1.5\n");
555     xcb_generic_error_t *err;
556     xcb_randr_get_monitors_reply_t *monitors =
557         xcb_randr_get_monitors_reply(
558             conn, xcb_randr_get_monitors(conn, root, true), &err);
559     if (err != NULL) {
560         ELOG("Could not get RandR monitors: X11 error code %d\n", err->error_code);
561         free(err);
562         /* Fall back to RandR ≤ 1.4 */
563         return false;
564     }
565
566     /* Mark all outputs as to_be_disabled, since xcb_randr_get_monitors() will
567      * only return active outputs. */
568     Output *output;
569     TAILQ_FOREACH(output, &outputs, outputs) {
570         if (output != root_output) {
571             output->to_be_disabled = true;
572         }
573     }
574
575     DLOG("%d RandR monitors found (timestamp %d)\n",
576          xcb_randr_get_monitors_monitors_length(monitors),
577          monitors->timestamp);
578
579     xcb_randr_monitor_info_iterator_t iter;
580     for (iter = xcb_randr_get_monitors_monitors_iterator(monitors);
581          iter.rem;
582          xcb_randr_monitor_info_next(&iter)) {
583         const xcb_randr_monitor_info_t *monitor_info = iter.data;
584         xcb_get_atom_name_reply_t *atom_reply =
585             xcb_get_atom_name_reply(
586                 conn, xcb_get_atom_name(conn, monitor_info->name), &err);
587         if (err != NULL) {
588             ELOG("Could not get RandR monitor name: X11 error code %d\n", err->error_code);
589             free(err);
590             continue;
591         }
592         char *name;
593         sasprintf(&name, "%.*s",
594                   xcb_get_atom_name_name_length(atom_reply),
595                   xcb_get_atom_name_name(atom_reply));
596         free(atom_reply);
597
598         Output *new = get_output_by_name(name, false);
599         if (new == NULL) {
600             new = scalloc(1, sizeof(Output));
601
602             struct output_name *output_name = scalloc(1, sizeof(struct output_name));
603             output_name->name = sstrdup(name);
604             SLIST_INIT(&new->names_head);
605             SLIST_INSERT_HEAD(&new->names_head, output_name, names);
606
607             if (monitor_info->primary) {
608                 TAILQ_INSERT_HEAD(&outputs, new, outputs);
609             } else {
610                 TAILQ_INSERT_TAIL(&outputs, new, outputs);
611             }
612         }
613         /* We specified get_active == true in xcb_randr_get_monitors(), so we
614          * will only receive active outputs. */
615         new->active = true;
616         new->to_be_disabled = false;
617
618         new->primary = monitor_info->primary;
619
620         new->changed =
621             update_if_necessary(&(new->rect.x), monitor_info->x) |
622             update_if_necessary(&(new->rect.y), monitor_info->y) |
623             update_if_necessary(&(new->rect.width), monitor_info->width) |
624             update_if_necessary(&(new->rect.height), monitor_info->height);
625
626         DLOG("name %s, x %d, y %d, width %d px, height %d px, width %d mm, height %d mm, primary %d, automatic %d\n",
627              name,
628              monitor_info->x, monitor_info->y, monitor_info->width, monitor_info->height,
629              monitor_info->width_in_millimeters, monitor_info->height_in_millimeters,
630              monitor_info->primary, monitor_info->automatic);
631         free(name);
632     }
633     free(monitors);
634     return true;
635 #endif
636 }
637
638 /*
639  * Gets called by randr_query_outputs_14() for each output. The function adds
640  * new outputs to the list of outputs, checks if the mode of existing outputs
641  * has been changed or if an existing output has been disabled. It will then
642  * change either the "changed" or the "to_be_deleted" flag of the output, if
643  * appropriate.
644  *
645  */
646 static void handle_output(xcb_connection_t *conn, xcb_randr_output_t id,
647                           xcb_randr_get_output_info_reply_t *output,
648                           xcb_timestamp_t cts,
649                           xcb_randr_get_screen_resources_current_reply_t *res) {
650     /* each CRT controller has a position in which we are interested in */
651     xcb_randr_get_crtc_info_reply_t *crtc;
652
653     Output *new = get_output_by_id(id);
654     bool existing = (new != NULL);
655     if (!existing) {
656         new = scalloc(1, sizeof(Output));
657         SLIST_INIT(&new->names_head);
658     }
659     new->id = id;
660     new->primary = (primary && primary->output == id);
661     while (!SLIST_EMPTY(&new->names_head)) {
662         FREE(SLIST_FIRST(&new->names_head)->name);
663         struct output_name *old_head = SLIST_FIRST(&new->names_head);
664         SLIST_REMOVE_HEAD(&new->names_head, names);
665         FREE(old_head);
666     }
667     struct output_name *output_name = scalloc(1, sizeof(struct output_name));
668     sasprintf(&output_name->name, "%.*s",
669               xcb_randr_get_output_info_name_length(output),
670               xcb_randr_get_output_info_name(output));
671     SLIST_INSERT_HEAD(&new->names_head, output_name, names);
672
673     DLOG("found output with name %s\n", output_primary_name(new));
674
675     /* Even if no CRTC is used at the moment, we store the output so that
676      * we do not need to change the list ever again (we only update the
677      * position/size) */
678     if (output->crtc == XCB_NONE) {
679         if (!existing) {
680             if (new->primary)
681                 TAILQ_INSERT_HEAD(&outputs, new, outputs);
682             else
683                 TAILQ_INSERT_TAIL(&outputs, new, outputs);
684         } else if (new->active)
685             new->to_be_disabled = true;
686         return;
687     }
688
689     xcb_randr_get_crtc_info_cookie_t icookie;
690     icookie = xcb_randr_get_crtc_info(conn, output->crtc, cts);
691     if ((crtc = xcb_randr_get_crtc_info_reply(conn, icookie, NULL)) == NULL) {
692         DLOG("Skipping output %s: could not get CRTC (%p)\n",
693              output_primary_name(new), crtc);
694         free(new);
695         return;
696     }
697
698     bool updated = update_if_necessary(&(new->rect.x), crtc->x) |
699                    update_if_necessary(&(new->rect.y), crtc->y) |
700                    update_if_necessary(&(new->rect.width), crtc->width) |
701                    update_if_necessary(&(new->rect.height), crtc->height);
702     free(crtc);
703     new->active = (new->rect.width != 0 && new->rect.height != 0);
704     if (!new->active) {
705         DLOG("width/height 0/0, disabling output\n");
706         return;
707     }
708
709     DLOG("mode: %dx%d+%d+%d\n", new->rect.width, new->rect.height,
710          new->rect.x, new->rect.y);
711
712     /* If we don’t need to change an existing output or if the output
713      * does not exist in the first place, the case is simple: we either
714      * need to insert the new output or we are done. */
715     if (!updated || !existing) {
716         if (!existing) {
717             if (new->primary)
718                 TAILQ_INSERT_HEAD(&outputs, new, outputs);
719             else
720                 TAILQ_INSERT_TAIL(&outputs, new, outputs);
721         }
722         return;
723     }
724
725     new->changed = true;
726 }
727
728 /*
729  * randr_query_outputs_14 uses RandR ≤ 1.4 to update outputs.
730  *
731  */
732 static void randr_query_outputs_14(void) {
733     DLOG("Querying outputs using RandR ≤ 1.4\n");
734
735     /* Get screen resources (primary output, crtcs, outputs, modes) */
736     xcb_randr_get_screen_resources_current_cookie_t rcookie;
737     rcookie = xcb_randr_get_screen_resources_current(conn, root);
738     xcb_randr_get_output_primary_cookie_t pcookie;
739     pcookie = xcb_randr_get_output_primary(conn, root);
740
741     if ((primary = xcb_randr_get_output_primary_reply(conn, pcookie, NULL)) == NULL)
742         ELOG("Could not get RandR primary output\n");
743     else
744         DLOG("primary output is %08x\n", primary->output);
745
746     xcb_randr_get_screen_resources_current_reply_t *res =
747         xcb_randr_get_screen_resources_current_reply(conn, rcookie, NULL);
748     if (res == NULL) {
749         ELOG("Could not query screen resources.\n");
750         return;
751     }
752
753     /* timestamp of the configuration so that we get consistent replies to all
754      * requests (if the configuration changes between our different calls) */
755     const xcb_timestamp_t cts = res->config_timestamp;
756
757     const int len = xcb_randr_get_screen_resources_current_outputs_length(res);
758
759     /* an output is VGA-1, LVDS-1, etc. (usually physical video outputs) */
760     xcb_randr_output_t *randr_outputs = xcb_randr_get_screen_resources_current_outputs(res);
761
762     /* Request information for each output */
763     xcb_randr_get_output_info_cookie_t ocookie[len];
764     for (int i = 0; i < len; i++)
765         ocookie[i] = xcb_randr_get_output_info(conn, randr_outputs[i], cts);
766
767     /* Loop through all outputs available for this X11 screen */
768     for (int i = 0; i < len; i++) {
769         xcb_randr_get_output_info_reply_t *output;
770
771         if ((output = xcb_randr_get_output_info_reply(conn, ocookie[i], NULL)) == NULL)
772             continue;
773
774         handle_output(conn, randr_outputs[i], output, cts, res);
775         free(output);
776     }
777
778     FREE(res);
779 }
780
781 /*
782  * (Re-)queries the outputs via RandR and stores them in the list of outputs.
783  *
784  * If no outputs are found use the root window.
785  *
786  */
787 void randr_query_outputs(void) {
788     Output *output, *other;
789
790     if (!randr_query_outputs_15()) {
791         randr_query_outputs_14();
792     }
793
794     /* If there's no randr output, enable the output covering the root window. */
795     if (any_randr_output_active()) {
796         DLOG("Active RandR output found. Disabling root output.\n");
797         if (root_output->active)
798             root_output->to_be_disabled = true;
799     } else {
800         DLOG("No active RandR output found. Enabling root output.\n");
801         root_output->active = true;
802     }
803
804     /* Check for clones, disable the clones and reduce the mode to the
805      * lowest common mode */
806     TAILQ_FOREACH(output, &outputs, outputs) {
807         if (!output->active || output->to_be_disabled)
808             continue;
809         DLOG("output %p / %s, position (%d, %d), checking for clones\n",
810              output, output_primary_name(output), output->rect.x, output->rect.y);
811
812         for (other = output;
813              other != TAILQ_END(&outputs);
814              other = TAILQ_NEXT(other, outputs)) {
815             if (other == output || !other->active || other->to_be_disabled)
816                 continue;
817
818             if (other->rect.x != output->rect.x ||
819                 other->rect.y != output->rect.y)
820                 continue;
821
822             DLOG("output %p has the same position, his mode = %d x %d\n",
823                  other, other->rect.width, other->rect.height);
824             uint32_t width = min(other->rect.width, output->rect.width);
825             uint32_t height = min(other->rect.height, output->rect.height);
826
827             if (update_if_necessary(&(output->rect.width), width) |
828                 update_if_necessary(&(output->rect.height), height))
829                 output->changed = true;
830
831             update_if_necessary(&(other->rect.width), width);
832             update_if_necessary(&(other->rect.height), height);
833
834             DLOG("disabling output %p (%s)\n", other, output_primary_name(other));
835             other->to_be_disabled = true;
836
837             DLOG("new output mode %d x %d, other mode %d x %d\n",
838                  output->rect.width, output->rect.height,
839                  other->rect.width, other->rect.height);
840         }
841     }
842
843     /* Ensure that all outputs which are active also have a con. This is
844      * necessary because in the next step, a clone might get disabled. Example:
845      * LVDS1 active, VGA1 gets activated as a clone of LVDS1 (has no con).
846      * LVDS1 gets disabled. */
847     TAILQ_FOREACH(output, &outputs, outputs) {
848         if (output->active && output->con == NULL) {
849             DLOG("Need to initialize a Con for output %s\n", output_primary_name(output));
850             output_init_con(output);
851             output->changed = false;
852         }
853     }
854
855     /* Handle outputs which have a new mode or are disabled now (either
856      * because the user disabled them or because they are clones) */
857     TAILQ_FOREACH(output, &outputs, outputs) {
858         if (output->to_be_disabled) {
859             randr_disable_output(output);
860         }
861
862         if (output->changed) {
863             output_change_mode(conn, output);
864             output->changed = false;
865         }
866     }
867
868     /* Just go through each active output and assign one workspace */
869     TAILQ_FOREACH(output, &outputs, outputs) {
870         if (!output->active)
871             continue;
872         Con *content = output_get_content(output->con);
873         if (!TAILQ_EMPTY(&(content->nodes_head)))
874             continue;
875         DLOG("Should add ws for output %s\n", output_primary_name(output));
876         init_ws_for_output(output, content);
877     }
878
879     /* Focus the primary screen, if possible */
880     TAILQ_FOREACH(output, &outputs, outputs) {
881         if (!output->primary || !output->con)
882             continue;
883
884         DLOG("Focusing primary output %s\n", output_primary_name(output));
885         con_focus(con_descend_focused(output->con));
886     }
887
888     /* render_layout flushes */
889     tree_render();
890
891     FREE(primary);
892 }
893
894 /*
895  * Disables the output and moves its content.
896  *
897  */
898 void randr_disable_output(Output *output) {
899     assert(output->to_be_disabled);
900
901     output->active = false;
902     DLOG("Output %s disabled, re-assigning workspaces/docks\n", output_primary_name(output));
903
904     Output *first = get_first_output();
905
906     /* TODO: refactor the following code into a nice function. maybe
907      * use an on_destroy callback which is implement differently for
908      * different container types (CT_CONTENT vs. CT_DOCKAREA)? */
909     Con *first_content = output_get_content(first->con);
910
911     if (output->con != NULL) {
912         /* We need to move the workspaces from the disappearing output to the first output */
913         /* 1: Get the con to focus next, if the disappearing ws is focused */
914         Con *next = NULL;
915         if (TAILQ_FIRST(&(croot->focus_head)) == output->con) {
916             DLOG("This output (%p) was focused! Getting next\n", output->con);
917             next = focused;
918             DLOG("next = %p\n", next);
919         }
920
921         /* 2: iterate through workspaces and re-assign them, fixing the coordinates
922          * of floating containers as we go */
923         Con *current;
924         Con *old_content = output_get_content(output->con);
925         while (!TAILQ_EMPTY(&(old_content->nodes_head))) {
926             current = TAILQ_FIRST(&(old_content->nodes_head));
927             if (current != next && TAILQ_EMPTY(&(current->focus_head))) {
928                 /* the workspace is empty and not focused, get rid of it */
929                 DLOG("Getting rid of current = %p / %s (empty, unfocused)\n", current, current->name);
930                 tree_close_internal(current, DONT_KILL_WINDOW, false, false);
931                 continue;
932             }
933             DLOG("Detaching current = %p / %s\n", current, current->name);
934             con_detach(current);
935             DLOG("Re-attaching current = %p / %s\n", current, current->name);
936             con_attach(current, first_content, false);
937             DLOG("Fixing the coordinates of floating containers\n");
938             Con *floating_con;
939             TAILQ_FOREACH(floating_con, &(current->floating_head), floating_windows) {
940                 floating_fix_coordinates(floating_con, &(output->con->rect), &(first->con->rect));
941             }
942             DLOG("Done, next\n");
943         }
944         DLOG("re-attached all workspaces\n");
945
946         if (next) {
947             DLOG("now focusing next = %p\n", next);
948             con_focus(next);
949             workspace_show(con_get_workspace(next));
950         }
951
952         /* 3: move the dock clients to the first output */
953         Con *child;
954         TAILQ_FOREACH(child, &(output->con->nodes_head), nodes) {
955             if (child->type != CT_DOCKAREA)
956                 continue;
957             DLOG("Handling dock con %p\n", child);
958             Con *dock;
959             while (!TAILQ_EMPTY(&(child->nodes_head))) {
960                 dock = TAILQ_FIRST(&(child->nodes_head));
961                 Con *nc;
962                 Match *match;
963                 nc = con_for_window(first->con, dock->window, &match);
964                 DLOG("Moving dock client %p to nc %p\n", dock, nc);
965                 con_detach(dock);
966                 DLOG("Re-attaching\n");
967                 con_attach(dock, nc, false);
968                 DLOG("Done\n");
969             }
970         }
971
972         DLOG("destroying disappearing con %p\n", output->con);
973         Con *con = output->con;
974         /* clear the pointer before calling tree_close_internal in which the memory is freed */
975         output->con = NULL;
976         tree_close_internal(con, DONT_KILL_WINDOW, true, false);
977         DLOG("Done. Should be fine now\n");
978     }
979
980     output->to_be_disabled = false;
981     output->changed = false;
982 }
983
984 static void fallback_to_root_output(void) {
985     root_output->active = true;
986     output_init_con(root_output);
987     init_ws_for_output(root_output, output_get_content(root_output->con));
988 }
989
990 /*
991  * We have just established a connection to the X server and need the initial
992  * XRandR information to setup workspaces for each screen.
993  *
994  */
995 void randr_init(int *event_base, const bool disable_randr15) {
996     const xcb_query_extension_reply_t *extreply;
997
998     root_output = create_root_output(conn);
999     TAILQ_INSERT_TAIL(&outputs, root_output, outputs);
1000
1001     extreply = xcb_get_extension_data(conn, &xcb_randr_id);
1002     if (!extreply->present) {
1003         DLOG("RandR is not present, activating root output.\n");
1004         fallback_to_root_output();
1005         return;
1006     }
1007
1008     xcb_generic_error_t *err;
1009     xcb_randr_query_version_reply_t *randr_version =
1010         xcb_randr_query_version_reply(
1011             conn, xcb_randr_query_version(conn, XCB_RANDR_MAJOR_VERSION, XCB_RANDR_MINOR_VERSION), &err);
1012     if (err != NULL) {
1013         free(err);
1014         ELOG("Could not query RandR version: X11 error code %d\n", err->error_code);
1015         fallback_to_root_output();
1016         return;
1017     }
1018
1019     has_randr_1_5 = (randr_version->major_version >= 1) &&
1020                     (randr_version->minor_version >= 5) &&
1021                     !disable_randr15;
1022
1023     free(randr_version);
1024
1025     randr_query_outputs();
1026
1027     if (event_base != NULL)
1028         *event_base = extreply->first_event;
1029
1030     xcb_randr_select_input(conn, root,
1031                            XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE |
1032                                XCB_RANDR_NOTIFY_MASK_OUTPUT_CHANGE |
1033                                XCB_RANDR_NOTIFY_MASK_CRTC_CHANGE |
1034                                XCB_RANDR_NOTIFY_MASK_OUTPUT_PROPERTY);
1035
1036     xcb_flush(conn);
1037 }