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