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