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