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