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