xrandr.c revision 62770414
1/*
2 * Copyright © 2001 Keith Packard, member of The XFree86 Project, Inc.
3 * Copyright © 2002 Hewlett Packard Company, Inc.
4 * Copyright © 2006 Intel Corporation
5 *
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that copyright
9 * notice and this permission notice appear in supporting documentation, and
10 * that the name of the copyright holders not be used in advertising or
11 * publicity pertaining to distribution of the software without specific,
12 * written prior permission.  The copyright holders make no representations
13 * about the suitability of this software for any purpose.  It is provided "as
14 * is" without express or implied warranty.
15 *
16 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
17 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
18 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
19 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
20 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22 * OF THIS SOFTWARE.
23 *
24 * Thanks to Jim Gettys who wrote most of the client side code,
25 * and part of the server code for randr.
26 */
27
28#include <stdio.h>
29#include <X11/Xlib.h>
30#include <X11/Xlibint.h>
31#include <X11/Xproto.h>
32#include <X11/Xatom.h>
33#include <X11/extensions/Xrandr.h>
34#include <X11/extensions/Xrender.h>	/* we share subpixel information */
35#include <string.h>
36#include <stdlib.h>
37#include <stdarg.h>
38#include <math.h>
39
40#include "config.h"
41
42#if RANDR_MAJOR > 1 || (RANDR_MAJOR == 1 && RANDR_MINOR >= 2)
43#define HAS_RANDR_1_2 1
44#endif
45
46static char	*program_name;
47static Display	*dpy;
48static Window	root;
49static int	screen = -1;
50static Bool	verbose = False;
51static Bool	automatic = False;
52static Bool	properties = False;
53static Bool	grab_server = True;
54static Bool	no_primary = False;
55
56static char *direction[5] = {
57    "normal",
58    "left",
59    "inverted",
60    "right",
61    "\n"};
62
63static char *reflections[5] = {
64    "normal",
65    "x",
66    "y",
67    "xy",
68    "\n"};
69
70/* subpixel order */
71static char *order[6] = {
72    "unknown",
73    "horizontal rgb",
74    "horizontal bgr",
75    "vertical rgb",
76    "vertical bgr",
77    "no subpixels"};
78
79static const struct {
80    char	    *string;
81    unsigned long   flag;
82} mode_flags[] = {
83    { "+HSync", RR_HSyncPositive },
84    { "-HSync", RR_HSyncNegative },
85    { "+VSync", RR_VSyncPositive },
86    { "-VSync", RR_VSyncNegative },
87    { "Interlace", RR_Interlace },
88    { "DoubleScan", RR_DoubleScan },
89    { "CSync",	    RR_CSync },
90    { "+CSync",	    RR_CSyncPositive },
91    { "-CSync",	    RR_CSyncNegative },
92    { NULL,	    0 }
93};
94
95static void
96usage(void)
97{
98    fprintf(stderr, "usage: %s [options]\n", program_name);
99    fprintf(stderr, "  where options are:\n");
100    fprintf(stderr, "  -display <display> or -d <display>\n");
101    fprintf(stderr, "  -help\n");
102    fprintf(stderr, "  -o <normal,inverted,left,right,0,1,2,3>\n");
103    fprintf(stderr, "            or --orientation <normal,inverted,left,right,0,1,2,3>\n");
104    fprintf(stderr, "  -q        or --query\n");
105    fprintf(stderr, "  -s <size>/<width>x<height> or --size <size>/<width>x<height>\n");
106    fprintf(stderr, "  -r <rate> or --rate <rate> or --refresh <rate>\n");
107    fprintf(stderr, "  -v        or --version\n");
108    fprintf(stderr, "  -x        (reflect in x)\n");
109    fprintf(stderr, "  -y        (reflect in y)\n");
110    fprintf(stderr, "  --screen <screen>\n");
111    fprintf(stderr, "  --verbose\n");
112    fprintf(stderr, "  --dryrun\n");
113    fprintf(stderr, "  --nograb\n");
114#if HAS_RANDR_1_2
115    fprintf(stderr, "  --prop or --properties\n");
116    fprintf(stderr, "  --fb <width>x<height>\n");
117    fprintf(stderr, "  --fbmm <width>x<height>\n");
118    fprintf(stderr, "  --dpi <dpi>/<output>\n");
119#if 0
120    fprintf(stderr, "  --clone\n");
121    fprintf(stderr, "  --extend\n");
122#endif
123    fprintf(stderr, "  --output <output>\n");
124    fprintf(stderr, "      --auto\n");
125    fprintf(stderr, "      --mode <mode>\n");
126    fprintf(stderr, "      --preferred\n");
127    fprintf(stderr, "      --pos <x>x<y>\n");
128    fprintf(stderr, "      --rate <rate> or --refresh <rate>\n");
129    fprintf(stderr, "      --reflect normal,x,y,xy\n");
130    fprintf(stderr, "      --rotate normal,inverted,left,right\n");
131    fprintf(stderr, "      --left-of <output>\n");
132    fprintf(stderr, "      --right-of <output>\n");
133    fprintf(stderr, "      --above <output>\n");
134    fprintf(stderr, "      --below <output>\n");
135    fprintf(stderr, "      --same-as <output>\n");
136    fprintf(stderr, "      --set <property> <value>\n");
137    fprintf(stderr, "      --scale <x>x<y>\n");
138    fprintf(stderr, "      --transform <a>,<b>,<c>,<d>,<e>,<f>,<g>,<h>,<i>\n");
139    fprintf(stderr, "      --off\n");
140    fprintf(stderr, "      --crtc <crtc>\n");
141    fprintf(stderr, "      --panning <w>x<h>[+<x>+<y>[/<track:w>x<h>+<x>+<y>[/<border:l>/<t>/<r>/<b>]]]\n");
142    fprintf(stderr, "      --gamma <r>:<g>:<b>\n");
143    fprintf(stderr, "      --primary\n");
144    fprintf(stderr, "  --noprimary\n");
145    fprintf(stderr, "  --newmode <name> <clock MHz>\n");
146    fprintf(stderr, "            <hdisp> <hsync-start> <hsync-end> <htotal>\n");
147    fprintf(stderr, "            <vdisp> <vsync-start> <vsync-end> <vtotal>\n");
148    fprintf(stderr, "            [+HSync] [-HSync] [+VSync] [-VSync]\n");
149    fprintf(stderr, "  --rmmode <name>\n");
150    fprintf(stderr, "  --addmode <output> <name>\n");
151    fprintf(stderr, "  --delmode <output> <name>\n");
152#endif
153
154    exit(1);
155    /*NOTREACHED*/
156}
157
158static void
159fatal (const char *format, ...)
160{
161    va_list ap;
162
163    va_start (ap, format);
164    fprintf (stderr, "%s: ", program_name);
165    vfprintf (stderr, format, ap);
166    va_end (ap);
167    exit (1);
168    /*NOTREACHED*/
169}
170
171static void
172warning (const char *format, ...)
173{
174    va_list ap;
175
176    va_start (ap, format);
177    fprintf (stderr, "%s: ", program_name);
178    vfprintf (stderr, format, ap);
179    va_end (ap);
180}
181
182static char *
183rotation_name (Rotation rotation)
184{
185    int	i;
186
187    if ((rotation & 0xf) == 0)
188	return "normal";
189    for (i = 0; i < 4; i++)
190	if (rotation & (1 << i))
191	    return direction[i];
192    return "invalid rotation";
193}
194
195static char *
196reflection_name (Rotation rotation)
197{
198    rotation &= (RR_Reflect_X|RR_Reflect_Y);
199    switch (rotation) {
200    case 0:
201	return "none";
202    case RR_Reflect_X:
203	return "X axis";
204    case RR_Reflect_Y:
205	return "Y axis";
206    case RR_Reflect_X|RR_Reflect_Y:
207	return "X and Y axis";
208    }
209    return "invalid reflection";
210}
211
212#if HAS_RANDR_1_2
213typedef enum _policy {
214    clone, extend
215} policy_t;
216
217typedef enum _relation {
218    left_of, right_of, above, below, same_as,
219} relation_t;
220
221typedef struct {
222    int	    x, y, width, height;
223} rectangle_t;
224
225typedef struct {
226    int	    x1, y1, x2, y2;
227} box_t;
228
229typedef struct {
230    int	    x, y;
231} point_t;
232
233typedef enum _changes {
234    changes_none = 0,
235    changes_crtc = (1 << 0),
236    changes_mode = (1 << 1),
237    changes_relation = (1 << 2),
238    changes_position = (1 << 3),
239    changes_rotation = (1 << 4),
240    changes_reflection = (1 << 5),
241    changes_automatic = (1 << 6),
242    changes_refresh = (1 << 7),
243    changes_property = (1 << 8),
244    changes_transform = (1 << 9),
245    changes_panning = (1 << 10),
246    changes_gamma = (1 << 11),
247    changes_primary = (1 << 12),
248} changes_t;
249
250typedef enum _name_kind {
251    name_none = 0,
252    name_string = (1 << 0),
253    name_xid = (1 << 1),
254    name_index = (1 << 2),
255    name_preferred = (1 << 3),
256} name_kind_t;
257
258typedef struct {
259    name_kind_t	    kind;
260    char    	    *string;
261    XID	    	    xid;
262    int		    index;
263} name_t;
264
265typedef struct _crtc crtc_t;
266typedef struct _output	output_t;
267typedef struct _transform transform_t;
268typedef struct _umode	umode_t;
269typedef struct _output_prop output_prop_t;
270
271struct _transform {
272    XTransform	    transform;
273    char	    *filter;
274    int		    nparams;
275    XFixed	    *params;
276};
277
278struct _crtc {
279    name_t	    crtc;
280    Bool	    changing;
281    XRRCrtcInfo	    *crtc_info;
282
283    XRRModeInfo	    *mode_info;
284    XRRPanning      *panning_info;
285    int		    x;
286    int		    y;
287    Rotation	    rotation;
288    output_t	    **outputs;
289    int		    noutput;
290    transform_t	    current_transform, pending_transform;
291};
292
293struct _output_prop {
294    struct _output_prop	*next;
295    char		*name;
296    char		*value;
297};
298
299struct _output {
300    struct _output   *next;
301
302    changes_t	    changes;
303
304    output_prop_t   *props;
305
306    name_t	    output;
307    XRROutputInfo   *output_info;
308
309    name_t	    crtc;
310    crtc_t	    *crtc_info;
311    crtc_t	    *current_crtc_info;
312
313    name_t	    mode;
314    float	    refresh;
315    XRRModeInfo	    *mode_info;
316
317    name_t	    addmode;
318
319    relation_t	    relation;
320    char	    *relative_to;
321
322    int		    x, y;
323    Rotation	    rotation;
324
325    XRRPanning      panning;
326
327    Bool    	    automatic;
328    transform_t	    transform;
329
330    struct {
331	float red;
332	float green;
333	float blue;
334    } gamma;
335
336    Bool	    primary;
337};
338
339typedef enum _umode_action {
340    umode_create, umode_destroy, umode_add, umode_delete
341} umode_action_t;
342
343
344struct _umode {
345    struct _umode   *next;
346
347    umode_action_t  action;
348    XRRModeInfo	    mode;
349    name_t	    output;
350    name_t	    name;
351};
352
353static char *connection[3] = {
354    "connected",
355    "disconnected",
356    "unknown connection"};
357
358#define OUTPUT_NAME 1
359
360#define CRTC_OFF    2
361#define CRTC_UNSET  3
362#define CRTC_INDEX  0x40000000
363
364#define MODE_NAME   1
365#define MODE_OFF    2
366#define MODE_UNSET  3
367#define MODE_PREF   4
368
369#define POS_UNSET   -1
370
371static output_t	*outputs = NULL;
372static output_t	**outputs_tail = &outputs;
373static crtc_t	*crtcs;
374static umode_t	*umodes;
375static int	num_crtcs;
376static XRRScreenResources  *res;
377static int	fb_width = 0, fb_height = 0;
378static int	fb_width_mm = 0, fb_height_mm = 0;
379static float	dpi = 0;
380static char	*dpi_output = NULL;
381static Bool	dryrun = False;
382static int	minWidth, maxWidth, minHeight, maxHeight;
383static Bool    	has_1_2 = False;
384static Bool    	has_1_3 = False;
385
386static int
387mode_height (XRRModeInfo *mode_info, Rotation rotation)
388{
389    switch (rotation & 0xf) {
390    case RR_Rotate_0:
391    case RR_Rotate_180:
392	return mode_info->height;
393    case RR_Rotate_90:
394    case RR_Rotate_270:
395	return mode_info->width;
396    default:
397	return 0;
398    }
399}
400
401static int
402mode_width (XRRModeInfo *mode_info, Rotation rotation)
403{
404    switch (rotation & 0xf) {
405    case RR_Rotate_0:
406    case RR_Rotate_180:
407	return mode_info->width;
408    case RR_Rotate_90:
409    case RR_Rotate_270:
410	return mode_info->height;
411    default:
412	return 0;
413    }
414}
415
416static Bool
417transform_point (XTransform *transform, double *xp, double *yp)
418{
419    double  vector[3];
420    double  result[3];
421    int	    i, j;
422    double  v;
423
424    vector[0] = *xp;
425    vector[1] = *yp;
426    vector[2] = 1;
427    for (j = 0; j < 3; j++)
428    {
429	v = 0;
430	for (i = 0; i < 3; i++)
431	    v += (XFixedToDouble (transform->matrix[j][i]) * vector[i]);
432	if (v > 32767 || v < -32767)
433	    return False;
434	result[j] = v;
435    }
436    if (!result[2])
437	return False;
438    for (j = 0; j < 2; j++)
439	vector[j] = result[j] / result[2];
440    *xp = vector[0];
441    *yp = vector[1];
442    return True;
443}
444
445static void
446path_bounds (XTransform *transform, point_t *points, int npoints, box_t *box)
447{
448    int	    i;
449    box_t   point;
450
451    for (i = 0; i < npoints; i++) {
452	double	x, y;
453	x = points[i].x;
454	y = points[i].y;
455	transform_point (transform, &x, &y);
456	point.x1 = floor (x);
457	point.y1 = floor (y);
458	point.x2 = ceil (x);
459	point.y2 = ceil (y);
460	if (i == 0)
461	    *box = point;
462	else {
463	    if (point.x1 < box->x1) box->x1 = point.x1;
464	    if (point.y1 < box->y1) box->y1 = point.y1;
465	    if (point.x2 > box->x2) box->x2 = point.x2;
466	    if (point.y2 > box->y2) box->y2 = point.y2;
467	}
468    }
469}
470
471static void
472mode_geometry (XRRModeInfo *mode_info, Rotation rotation,
473	       XTransform *transform,
474	       box_t *bounds)
475{
476    point_t rect[4];
477    int	width = mode_width (mode_info, rotation);
478    int height = mode_height (mode_info, rotation);
479
480    rect[0].x = 0;
481    rect[0].y = 0;
482    rect[1].x = width;
483    rect[1].y = 0;
484    rect[2].x = width;
485    rect[2].y = height;
486    rect[3].x = 0;
487    rect[3].y = height;
488    path_bounds (transform, rect, 4, bounds);
489}
490
491/* v refresh frequency in Hz */
492static float
493mode_refresh (XRRModeInfo *mode_info)
494{
495    float rate;
496
497    if (mode_info->hTotal && mode_info->vTotal)
498	rate = ((float) mode_info->dotClock /
499		((float) mode_info->hTotal * (float) mode_info->vTotal));
500    else
501    	rate = 0;
502    return rate;
503}
504
505/* h sync frequency in Hz */
506static float
507mode_hsync (XRRModeInfo *mode_info)
508{
509    float rate;
510
511    if (mode_info->hTotal)
512	rate = (float) mode_info->dotClock / (float) mode_info->hTotal;
513    else
514    	rate = 0;
515    return rate;
516}
517
518static void
519init_name (name_t *name)
520{
521    name->kind = name_none;
522}
523
524static void
525set_name_string (name_t *name, char *string)
526{
527    name->kind |= name_string;
528    name->string = string;
529}
530
531static void
532set_name_xid (name_t *name, XID xid)
533{
534    name->kind |= name_xid;
535    name->xid = xid;
536}
537
538static void
539set_name_index (name_t *name, int index)
540{
541    name->kind |= name_index;
542    name->index = index;
543}
544
545static void
546set_name_preferred (name_t *name)
547{
548    name->kind |= name_preferred;
549}
550
551static void
552set_name_all (name_t *name, name_t *old)
553{
554    if (old->kind & name_xid)
555	name->xid = old->xid;
556    if (old->kind & name_string)
557	name->string = old->string;
558    if (old->kind & name_index)
559	name->index = old->index;
560    name->kind |= old->kind;
561}
562
563static void
564set_name (name_t *name, char *string, name_kind_t valid)
565{
566    unsigned int xid; /* don't make it XID (which is unsigned long):
567			 scanf() takes unsigned int */
568    int index;
569
570    if ((valid & name_xid) && sscanf (string, "0x%x", &xid) == 1)
571	set_name_xid (name, xid);
572    else if ((valid & name_index) && sscanf (string, "%d", &index) == 1)
573	set_name_index (name, index);
574    else if (valid & name_string)
575	set_name_string (name, string);
576    else
577	usage ();
578}
579
580static void
581init_transform (transform_t *transform)
582{
583    int x;
584    memset (&transform->transform, '\0', sizeof (transform->transform));
585    for (x = 0; x < 3; x++)
586	transform->transform.matrix[x][x] = XDoubleToFixed (1.0);
587    transform->filter = "";
588    transform->nparams = 0;
589    transform->params = NULL;
590}
591
592static void
593set_transform (transform_t  *dest,
594	       XTransform   *transform,
595	       char	    *filter,
596	       XFixed	    *params,
597	       int	    nparams)
598{
599    dest->transform = *transform;
600    dest->filter = strdup (filter);
601    dest->nparams = nparams;
602    dest->params = malloc (nparams * sizeof (XFixed));
603    memcpy (dest->params, params, nparams * sizeof (XFixed));
604}
605
606static void
607copy_transform (transform_t *dest, transform_t *src)
608{
609    set_transform (dest, &src->transform,
610		   src->filter, src->params, src->nparams);
611}
612
613static Bool
614equal_transform (transform_t *a, transform_t *b)
615{
616    if (memcmp (&a->transform, &b->transform, sizeof (XTransform)) != 0)
617	return False;
618    if (strcmp (a->filter, b->filter) != 0)
619	return False;
620    if (a->nparams != b->nparams)
621	return False;
622    if (memcmp (a->params, b->params, a->nparams * sizeof (XFixed)) != 0)
623	return False;
624    return True;
625}
626
627static output_t *
628add_output (void)
629{
630    output_t *output = calloc (1, sizeof (output_t));
631
632    if (!output)
633	fatal ("out of memory\n");
634    output->next = NULL;
635    *outputs_tail = output;
636    outputs_tail = &output->next;
637    return output;
638}
639
640static output_t *
641find_output (name_t *name)
642{
643    output_t *output;
644
645    for (output = outputs; output; output = output->next)
646    {
647	name_kind_t common = name->kind & output->output.kind;
648
649	if ((common & name_xid) && name->xid == output->output.xid)
650	    break;
651	if ((common & name_string) && !strcmp (name->string, output->output.string))
652	    break;
653	if ((common & name_index) && name->index == output->output.index)
654	    break;
655    }
656    return output;
657}
658
659static output_t *
660find_output_by_xid (RROutput output)
661{
662    name_t  output_name;
663
664    init_name (&output_name);
665    set_name_xid (&output_name, output);
666    return find_output (&output_name);
667}
668
669static output_t *
670find_output_by_name (char *name)
671{
672    name_t  output_name;
673
674    init_name (&output_name);
675    set_name_string (&output_name, name);
676    return find_output (&output_name);
677}
678
679static crtc_t *
680find_crtc (name_t *name)
681{
682    int	    c;
683    crtc_t  *crtc = NULL;
684
685    for (c = 0; c < num_crtcs; c++)
686    {
687	name_kind_t common;
688
689	crtc = &crtcs[c];
690	common = name->kind & crtc->crtc.kind;
691
692	if ((common & name_xid) && name->xid == crtc->crtc.xid)
693	    break;
694	if ((common & name_string) && !strcmp (name->string, crtc->crtc.string))
695	    break;
696	if ((common & name_index) && name->index == crtc->crtc.index)
697	    break;
698	crtc = NULL;
699    }
700    return crtc;
701}
702
703static crtc_t *
704find_crtc_by_xid (RRCrtc crtc)
705{
706    name_t  crtc_name;
707
708    init_name (&crtc_name);
709    set_name_xid (&crtc_name, crtc);
710    return find_crtc (&crtc_name);
711}
712
713static XRRModeInfo *
714find_mode (name_t *name, float refresh)
715{
716    int		m;
717    XRRModeInfo	*best = NULL;
718    float	bestDist = 0;
719
720    for (m = 0; m < res->nmode; m++)
721    {
722	XRRModeInfo *mode = &res->modes[m];
723	if ((name->kind & name_xid) && name->xid == mode->id)
724	{
725	    best = mode;
726	    break;
727	}
728	if ((name->kind & name_string) && !strcmp (name->string, mode->name))
729	{
730	    float   dist;
731
732	    if (refresh)
733		dist = fabs (mode_refresh (mode) - refresh);
734	    else
735		dist = 0;
736	    if (!best || dist < bestDist)
737	    {
738		bestDist = dist;
739		best = mode;
740	    }
741	    break;
742	}
743    }
744    return best;
745}
746
747static XRRModeInfo *
748find_mode_by_xid (RRMode mode)
749{
750    name_t  mode_name;
751
752    init_name (&mode_name);
753    set_name_xid (&mode_name, mode);
754    return find_mode (&mode_name, 0);
755}
756
757#if 0
758static XRRModeInfo *
759find_mode_by_name (char *name)
760{
761    name_t  mode_name;
762    init_name (&mode_name);
763    set_name_string (&mode_name, name);
764    return find_mode (&mode_name, 0);
765}
766#endif
767
768static
769XRRModeInfo *
770find_mode_for_output (output_t *output, name_t *name)
771{
772    XRROutputInfo   *output_info = output->output_info;
773    int		    m;
774    XRRModeInfo	    *best = NULL;
775    float	    bestDist = 0;
776
777    for (m = 0; m < output_info->nmode; m++)
778    {
779	XRRModeInfo	    *mode;
780
781	mode = find_mode_by_xid (output_info->modes[m]);
782	if (!mode) continue;
783	if ((name->kind & name_xid) && name->xid == mode->id)
784	{
785	    best = mode;
786	    break;
787	}
788	if ((name->kind & name_string) && !strcmp (name->string, mode->name))
789	{
790	    float   dist;
791
792	    /* Stay away from doublescan modes unless refresh rate is specified. */
793	    if (!output->refresh && (mode->modeFlags & RR_DoubleScan))
794		continue;
795
796	    if (output->refresh)
797		dist = fabs (mode_refresh (mode) - output->refresh);
798	    else
799		dist = 0;
800	    if (!best || dist < bestDist)
801	    {
802		bestDist = dist;
803		best = mode;
804	    }
805	}
806    }
807    return best;
808}
809
810static XRRModeInfo *
811preferred_mode (output_t *output)
812{
813    XRROutputInfo   *output_info = output->output_info;
814    int		    m;
815    XRRModeInfo	    *best;
816    int		    bestDist;
817
818    best = NULL;
819    bestDist = 0;
820    for (m = 0; m < output_info->nmode; m++)
821    {
822	XRRModeInfo *mode_info = find_mode_by_xid (output_info->modes[m]);
823	int	    dist;
824
825	if (m < output_info->npreferred)
826	    dist = 0;
827	else if (output_info->mm_height)
828	    dist = (1000 * DisplayHeight(dpy, screen) / DisplayHeightMM(dpy, screen) -
829		    1000 * mode_info->height / output_info->mm_height);
830	else
831	    dist = DisplayHeight(dpy, screen) - mode_info->height;
832
833        if (dist < 0) dist = -dist;
834	if (!best || dist < bestDist)
835	{
836	    best = mode_info;
837	    bestDist = dist;
838	}
839    }
840    return best;
841}
842
843static Bool
844output_can_use_crtc (output_t *output, crtc_t *crtc)
845{
846    XRROutputInfo   *output_info = output->output_info;
847    int		    c;
848
849    for (c = 0; c < output_info->ncrtc; c++)
850	if (output_info->crtcs[c] == crtc->crtc.xid)
851	    return True;
852    return False;
853}
854
855static Bool
856output_can_use_mode (output_t *output, XRRModeInfo *mode)
857{
858    XRROutputInfo   *output_info = output->output_info;
859    int		    m;
860
861    for (m = 0; m < output_info->nmode; m++)
862	if (output_info->modes[m] == mode->id)
863	    return True;
864    return False;
865}
866
867static Bool
868crtc_can_use_rotation (crtc_t *crtc, Rotation rotation)
869{
870    Rotation	rotations = crtc->crtc_info->rotations;
871    Rotation	dir = rotation & (RR_Rotate_0|RR_Rotate_90|RR_Rotate_180|RR_Rotate_270);
872    Rotation	reflect = rotation & (RR_Reflect_X|RR_Reflect_Y);
873    if (((rotations & dir) != 0) && ((rotations & reflect) == reflect))
874	return True;
875    return False;
876}
877
878#if 0
879static Bool
880crtc_can_use_transform (crtc_t *crtc, XTransform *transform)
881{
882    int	major, minor;
883
884    XRRQueryVersion (dpy, &major, &minor);
885    if (major > 1 || (major == 1 && minor >= 3))
886	return True;
887    return False;
888}
889#endif
890
891/*
892 * Report only rotations that are supported by all crtcs
893 */
894static Rotation
895output_rotations (output_t *output)
896{
897    Bool	    found = False;
898    Rotation	    rotation = RR_Rotate_0;
899    XRROutputInfo   *output_info = output->output_info;
900    int		    c;
901
902    for (c = 0; c < output_info->ncrtc; c++)
903    {
904	crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[c]);
905	if (crtc)
906	{
907	    if (!found) {
908		rotation = crtc->crtc_info->rotations;
909		found = True;
910	    } else
911		rotation &= crtc->crtc_info->rotations;
912	}
913    }
914    return rotation;
915}
916
917static Bool
918output_can_use_rotation (output_t *output, Rotation rotation)
919{
920    XRROutputInfo   *output_info = output->output_info;
921    int		    c;
922
923    /* make sure all of the crtcs can use this rotation.
924     * yes, this is not strictly necessary, but it is
925     * simpler,and we expect most drivers to either
926     * support rotation everywhere or nowhere
927     */
928    for (c = 0; c < output_info->ncrtc; c++)
929    {
930	crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[c]);
931	if (crtc && !crtc_can_use_rotation (crtc, rotation))
932	    return False;
933    }
934    return True;
935}
936
937static Bool
938output_is_primary(output_t *output)
939{
940    if (has_1_3)
941	    return XRRGetOutputPrimary(dpy, root) == output->output.xid;
942    return False;
943}
944
945static void
946set_output_info (output_t *output, RROutput xid, XRROutputInfo *output_info)
947{
948    /* sanity check output info */
949    if (output_info->connection != RR_Disconnected && !output_info->nmode)
950	warning ("Output %s is not disconnected but has no modes\n",
951		 output_info->name);
952
953    /* set output name and info */
954    if (!(output->output.kind & name_xid))
955	set_name_xid (&output->output, xid);
956    if (!(output->output.kind & name_string))
957	set_name_string (&output->output, output_info->name);
958    output->output_info = output_info;
959
960    /* set crtc name and info */
961    if (!(output->changes & changes_crtc))
962	set_name_xid (&output->crtc, output_info->crtc);
963
964    if (output->crtc.kind == name_xid && output->crtc.xid == None)
965	output->crtc_info = NULL;
966    else
967    {
968	output->crtc_info = find_crtc (&output->crtc);
969	if (!output->crtc_info)
970	{
971	    if (output->crtc.kind & name_xid)
972		fatal ("cannot find crtc 0x%x\n", output->crtc.xid);
973	    if (output->crtc.kind & name_index)
974		fatal ("cannot find crtc %d\n", output->crtc.index);
975	}
976	if (!output_can_use_crtc (output, output->crtc_info))
977	    fatal ("output %s cannot use crtc 0x%x\n", output->output.string,
978		   output->crtc_info->crtc.xid);
979    }
980
981    /* set mode name and info */
982    if (!(output->changes & changes_mode))
983    {
984	if (output->crtc_info)
985	    set_name_xid (&output->mode, output->crtc_info->crtc_info->mode);
986	else
987	    set_name_xid (&output->mode, None);
988	if (output->mode.xid)
989	{
990	    output->mode_info = find_mode_by_xid (output->mode.xid);
991	    if (!output->mode_info)
992		fatal ("server did not report mode 0x%x for output %s\n",
993		       output->mode.xid, output->output.string);
994	}
995	else
996	    output->mode_info = NULL;
997    }
998    else if (output->mode.kind == name_xid && output->mode.xid == None)
999	output->mode_info = NULL;
1000    else
1001    {
1002	if (output->mode.kind == name_preferred)
1003	    output->mode_info = preferred_mode (output);
1004	else
1005	    output->mode_info = find_mode_for_output (output, &output->mode);
1006	if (!output->mode_info)
1007	{
1008	    if (output->mode.kind & name_preferred)
1009		fatal ("cannot find preferred mode\n");
1010	    if (output->mode.kind & name_string)
1011		fatal ("cannot find mode %s\n", output->mode.string);
1012	    if (output->mode.kind & name_xid)
1013		fatal ("cannot find mode 0x%x\n", output->mode.xid);
1014	}
1015	if (!output_can_use_mode (output, output->mode_info))
1016	    fatal ("output %s cannot use mode %s\n", output->output.string,
1017		   output->mode_info->name);
1018    }
1019
1020    /* set position */
1021    if (!(output->changes & changes_position))
1022    {
1023	if (output->crtc_info)
1024	{
1025	    output->x = output->crtc_info->crtc_info->x;
1026	    output->y = output->crtc_info->crtc_info->y;
1027	}
1028	else
1029	{
1030	    output->x = 0;
1031	    output->y = 0;
1032	}
1033    }
1034
1035    /* set rotation */
1036    if (!(output->changes & changes_rotation))
1037    {
1038	output->rotation &= ~0xf;
1039	if (output->crtc_info)
1040	    output->rotation |= (output->crtc_info->crtc_info->rotation & 0xf);
1041	else
1042	    output->rotation = RR_Rotate_0;
1043    }
1044    if (!(output->changes & changes_reflection))
1045    {
1046	output->rotation &= ~(RR_Reflect_X|RR_Reflect_Y);
1047	if (output->crtc_info)
1048	    output->rotation |= (output->crtc_info->crtc_info->rotation &
1049				 (RR_Reflect_X|RR_Reflect_Y));
1050    }
1051    if (!output_can_use_rotation (output, output->rotation))
1052	fatal ("output %s cannot use rotation \"%s\" reflection \"%s\"\n",
1053	       output->output.string,
1054	       rotation_name (output->rotation),
1055	       reflection_name (output->rotation));
1056
1057    /* set transformation */
1058    if (!(output->changes & changes_transform))
1059    {
1060	if (output->crtc_info)
1061	    copy_transform (&output->transform, &output->crtc_info->current_transform);
1062	else
1063	    init_transform (&output->transform);
1064    }
1065
1066    /* set primary */
1067    if (!(output->changes & changes_primary))
1068	output->primary = output_is_primary(output);
1069}
1070
1071static void
1072get_screen (Bool current)
1073{
1074    if (!has_1_2)
1075        fatal ("Server RandR version before 1.2\n");
1076
1077    XRRGetScreenSizeRange (dpy, root, &minWidth, &minHeight,
1078			   &maxWidth, &maxHeight);
1079
1080    if (current)
1081	res = XRRGetScreenResourcesCurrent (dpy, root);
1082    else
1083	res = XRRGetScreenResources (dpy, root);
1084    if (!res) fatal ("could not get screen resources");
1085}
1086
1087static void
1088get_crtcs (void)
1089{
1090    int		c;
1091
1092    num_crtcs = res->ncrtc;
1093    crtcs = calloc (num_crtcs, sizeof (crtc_t));
1094    if (!crtcs) fatal ("out of memory\n");
1095
1096    for (c = 0; c < res->ncrtc; c++)
1097    {
1098	XRRCrtcInfo *crtc_info = XRRGetCrtcInfo (dpy, res, res->crtcs[c]);
1099#if RANDR_MAJOR > 1 || RANDR_MINOR >= 3
1100	XRRCrtcTransformAttributes  *attr;
1101#endif
1102	XRRPanning  *panning_info = NULL;
1103
1104	if (has_1_3) {
1105	    XRRPanning zero;
1106	    memset(&zero, 0, sizeof(zero));
1107	    panning_info = XRRGetPanning  (dpy, res, res->crtcs[c]);
1108	    zero.timestamp = panning_info->timestamp;
1109	    if (!memcmp(panning_info, &zero, sizeof(zero))) {
1110		Xfree(panning_info);
1111		panning_info = NULL;
1112	    }
1113	}
1114
1115	set_name_xid (&crtcs[c].crtc, res->crtcs[c]);
1116	set_name_index (&crtcs[c].crtc, c);
1117	if (!crtc_info) fatal ("could not get crtc 0x%x information\n", res->crtcs[c]);
1118	crtcs[c].crtc_info = crtc_info;
1119	crtcs[c].panning_info = panning_info;
1120	if (crtc_info->mode == None)
1121	{
1122	    crtcs[c].mode_info = NULL;
1123	    crtcs[c].x = 0;
1124	    crtcs[c].y = 0;
1125	    crtcs[c].rotation = RR_Rotate_0;
1126	}
1127#if RANDR_MAJOR > 1 || RANDR_MINOR >= 3
1128	if (XRRGetCrtcTransform (dpy, res->crtcs[c], &attr) && attr) {
1129	    set_transform (&crtcs[c].current_transform,
1130			   &attr->currentTransform,
1131			   attr->currentFilter,
1132			   attr->currentParams,
1133			   attr->currentNparams);
1134	    XFree (attr);
1135	}
1136	else
1137#endif
1138	{
1139	    init_transform (&crtcs[c].current_transform);
1140	}
1141	copy_transform (&crtcs[c].pending_transform, &crtcs[c].current_transform);
1142   }
1143}
1144
1145static void
1146crtc_add_output (crtc_t *crtc, output_t *output)
1147{
1148    if (crtc->outputs)
1149	crtc->outputs = realloc (crtc->outputs, (crtc->noutput + 1) * sizeof (output_t *));
1150    else
1151    {
1152	crtc->outputs = malloc (sizeof (output_t *));
1153	crtc->x = output->x;
1154	crtc->y = output->y;
1155	crtc->rotation = output->rotation;
1156	crtc->mode_info = output->mode_info;
1157	copy_transform (&crtc->pending_transform, &output->transform);
1158   }
1159    if (!crtc->outputs) fatal ("out of memory\n");
1160    crtc->outputs[crtc->noutput++] = output;
1161}
1162
1163static void
1164set_crtcs (void)
1165{
1166    output_t	*output;
1167
1168    for (output = outputs; output; output = output->next)
1169    {
1170	if (!output->mode_info) continue;
1171	crtc_add_output (output->crtc_info, output);
1172    }
1173}
1174
1175static void
1176set_panning (void)
1177{
1178    output_t	*output;
1179
1180    for (output = outputs; output; output = output->next)
1181    {
1182	if (! output->crtc_info)
1183	    continue;
1184	if (! (output->changes & changes_panning))
1185	    continue;
1186	if (! output->crtc_info->panning_info)
1187	    output->crtc_info->panning_info = malloc (sizeof(XRRPanning));
1188	memcpy (output->crtc_info->panning_info, &output->panning, sizeof(XRRPanning));
1189	output->crtc_info->changing = 1;
1190    }
1191}
1192
1193static void
1194set_gamma(void)
1195{
1196    output_t	*output;
1197
1198    for (output = outputs; output; output = output->next) {
1199	int i, size;
1200	crtc_t *crtc;
1201	XRRCrtcGamma *gamma;
1202
1203	if (!(output->changes & changes_gamma))
1204	    continue;
1205
1206	if (!output->crtc_info) {
1207	    fatal("Need crtc to set gamma on.\n");
1208	    continue;
1209	}
1210
1211	crtc = output->crtc_info;
1212
1213	size = XRRGetCrtcGammaSize(dpy, crtc->crtc.xid);
1214
1215	if (!size) {
1216	    fatal("Gamma size is 0.\n");
1217	    continue;
1218	}
1219
1220	gamma = XRRAllocGamma(size);
1221	if (!gamma) {
1222	    fatal("Gamma allocation failed.\n");
1223	    continue;
1224	}
1225
1226	for (i = 0; i < size; i++) {
1227	    if (output->gamma.red == 1.0)
1228		gamma->red[i] = i << 8;
1229	    else
1230		gamma->red[i] = (CARD16)(pow((double)i/(double)(size - 1),
1231			    (double)output->gamma.red) * (double)(size - 1) * 256);
1232
1233	    if (output->gamma.green == 1.0)
1234		gamma->green[i] = i << 8;
1235	    else
1236		gamma->green[i] = (CARD16)(pow((double)i/(double)(size - 1),
1237			    (double)output->gamma.green) * (double)(size - 1) * 256);
1238
1239	    if (output->gamma.blue == 1.0)
1240		gamma->blue[i] = i << 8;
1241	    else
1242		gamma->blue[i] = (CARD16)(pow((double)i/(double)(size - 1),
1243			    (double)output->gamma.blue) * (double)(size - 1) * 256);
1244	}
1245
1246	XRRSetCrtcGamma(dpy, crtc->crtc.xid, gamma);
1247
1248	free(gamma);
1249    }
1250}
1251
1252static void
1253set_primary(void)
1254{
1255    output_t *output;
1256
1257    if (no_primary) {
1258	XRRSetOutputPrimary(dpy, root, None);
1259    } else {
1260	for (output = outputs; output; output = output->next) {
1261	    if (!(output->changes & changes_primary))
1262		continue;
1263	    if (output->primary)
1264		XRRSetOutputPrimary(dpy, root, output->output.xid);
1265	}
1266    }
1267}
1268
1269static Status
1270crtc_disable (crtc_t *crtc)
1271{
1272    if (verbose)
1273    	printf ("crtc %d: disable\n", crtc->crtc.index);
1274
1275    if (dryrun)
1276	return RRSetConfigSuccess;
1277    return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
1278			     0, 0, None, RR_Rotate_0, NULL, 0);
1279}
1280
1281static void
1282crtc_set_transform (crtc_t *crtc, transform_t *transform)
1283{
1284    int	major, minor;
1285
1286    XRRQueryVersion (dpy, &major, &minor);
1287    if (major > 1 || (major == 1 && minor >= 3))
1288	XRRSetCrtcTransform (dpy, crtc->crtc.xid,
1289			     &transform->transform,
1290			     transform->filter,
1291			     transform->params,
1292			     transform->nparams);
1293}
1294
1295static Status
1296crtc_revert (crtc_t *crtc)
1297{
1298    XRRCrtcInfo	*crtc_info = crtc->crtc_info;
1299
1300    if (verbose)
1301    	printf ("crtc %d: revert\n", crtc->crtc.index);
1302
1303    if (dryrun)
1304	return RRSetConfigSuccess;
1305
1306    if (!equal_transform (&crtc->current_transform, &crtc->pending_transform))
1307	crtc_set_transform (crtc, &crtc->current_transform);
1308    return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
1309			    crtc_info->x, crtc_info->y,
1310			    crtc_info->mode, crtc_info->rotation,
1311			    crtc_info->outputs, crtc_info->noutput);
1312}
1313
1314static Status
1315crtc_apply (crtc_t *crtc)
1316{
1317    RROutput	*rr_outputs;
1318    int		o;
1319    Status	s;
1320    RRMode	mode = None;
1321
1322    if (!crtc->changing || !crtc->mode_info)
1323	return RRSetConfigSuccess;
1324
1325    rr_outputs = calloc (crtc->noutput, sizeof (RROutput));
1326    if (!rr_outputs)
1327	return BadAlloc;
1328    for (o = 0; o < crtc->noutput; o++)
1329	rr_outputs[o] = crtc->outputs[o]->output.xid;
1330    mode = crtc->mode_info->id;
1331    if (verbose) {
1332	printf ("crtc %d: %12s %6.1f +%d+%d", crtc->crtc.index,
1333		crtc->mode_info->name, mode_refresh (crtc->mode_info),
1334		crtc->x, crtc->y);
1335	for (o = 0; o < crtc->noutput; o++)
1336	    printf (" \"%s\"", crtc->outputs[o]->output.string);
1337	printf ("\n");
1338    }
1339
1340    if (dryrun)
1341	s = RRSetConfigSuccess;
1342    else
1343    {
1344	if (!equal_transform (&crtc->current_transform, &crtc->pending_transform))
1345	    crtc_set_transform (crtc, &crtc->pending_transform);
1346	s = XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
1347			      crtc->x, crtc->y, mode, crtc->rotation,
1348			      rr_outputs, crtc->noutput);
1349	if (s == RRSetConfigSuccess && crtc->panning_info) {
1350	    if (has_1_3)
1351		s = XRRSetPanning (dpy, res, crtc->crtc.xid, crtc->panning_info);
1352	    else
1353		fatal ("panning needs RandR 1.3\n");
1354	}
1355    }
1356    free (rr_outputs);
1357    return s;
1358}
1359
1360static void
1361screen_revert (void)
1362{
1363    if (verbose)
1364	printf ("screen %d: revert\n", screen);
1365
1366    if (dryrun)
1367	return;
1368    XRRSetScreenSize (dpy, root,
1369		      DisplayWidth (dpy, screen),
1370		      DisplayHeight (dpy, screen),
1371		      DisplayWidthMM (dpy, screen),
1372		      DisplayHeightMM (dpy, screen));
1373}
1374
1375static void
1376screen_apply (void)
1377{
1378    if (fb_width == DisplayWidth (dpy, screen) &&
1379	fb_height == DisplayHeight (dpy, screen) &&
1380	fb_width_mm == DisplayWidthMM (dpy, screen) &&
1381	fb_height_mm == DisplayHeightMM (dpy, screen))
1382    {
1383	return;
1384    }
1385    if (verbose)
1386	printf ("screen %d: %dx%d %dx%d mm %6.2fdpi\n", screen,
1387		fb_width, fb_height, fb_width_mm, fb_height_mm, dpi);
1388    if (dryrun)
1389	return;
1390    XRRSetScreenSize (dpy, root, fb_width, fb_height,
1391		      fb_width_mm, fb_height_mm);
1392}
1393
1394static void
1395revert (void)
1396{
1397    int	c;
1398
1399    /* first disable all crtcs */
1400    for (c = 0; c < res->ncrtc; c++)
1401	crtc_disable (&crtcs[c]);
1402    /* next reset screen size */
1403    screen_revert ();
1404    /* now restore all crtcs */
1405    for (c = 0; c < res->ncrtc; c++)
1406	crtc_revert (&crtcs[c]);
1407}
1408
1409/*
1410 * uh-oh, something bad happened in the middle of changing
1411 * the configuration. Revert to the previous configuration
1412 * and bail
1413 */
1414static void
1415panic (Status s, crtc_t *crtc)
1416{
1417    int	    c = crtc->crtc.index;
1418    char    *message;
1419
1420    switch (s) {
1421    case RRSetConfigSuccess:		message = "succeeded";		    break;
1422    case BadAlloc:			message = "out of memory";	    break;
1423    case RRSetConfigFailed:		message = "failed";		    break;
1424    case RRSetConfigInvalidConfigTime:	message = "invalid config time";    break;
1425    case RRSetConfigInvalidTime:	message = "invalid time";	    break;
1426    default:				message = "unknown failure";	    break;
1427    }
1428
1429    fprintf (stderr, "%s: Configure crtc %d %s\n", program_name, c, message);
1430    revert ();
1431    exit (1);
1432}
1433
1434static void
1435apply (void)
1436{
1437    Status  s;
1438    int	    c;
1439
1440    /*
1441     * Hold the server grabbed while messing with
1442     * the screen so that apps which notice the resize
1443     * event and ask for xinerama information from the server
1444     * receive up-to-date information
1445     */
1446    if (grab_server)
1447	XGrabServer (dpy);
1448
1449    /*
1450     * Turn off any crtcs which are to be disabled or which are
1451     * larger than the target size
1452     */
1453    for (c = 0; c < res->ncrtc; c++)
1454    {
1455	crtc_t	    *crtc = &crtcs[c];
1456	XRRCrtcInfo *crtc_info = crtc->crtc_info;
1457
1458	/* if this crtc is already disabled, skip it */
1459	if (crtc_info->mode == None)
1460	    continue;
1461
1462	/*
1463	 * If this crtc is to be left enabled, make
1464	 * sure the old size fits then new screen
1465	 */
1466	if (crtc->mode_info)
1467	{
1468	    XRRModeInfo	*old_mode = find_mode_by_xid (crtc_info->mode);
1469	    int x, y, w, h;
1470	    box_t bounds;
1471
1472	    if (!old_mode)
1473		panic (RRSetConfigFailed, crtc);
1474
1475	    /* old position and size information */
1476	    mode_geometry (old_mode, crtc_info->rotation,
1477			   &crtc->current_transform.transform,
1478			   &bounds);
1479
1480	    x = crtc_info->x + bounds.x1;
1481	    y = crtc_info->y + bounds.y1;
1482	    w = bounds.x2 - bounds.x1;
1483	    h = bounds.y2 - bounds.y1;
1484
1485	    /* if it fits, skip it */
1486	    if (x + w <= fb_width && y + h <= fb_height)
1487		continue;
1488	    crtc->changing = True;
1489	}
1490	s = crtc_disable (crtc);
1491	if (s != RRSetConfigSuccess)
1492	    panic (s, crtc);
1493    }
1494
1495    /*
1496     * Set the screen size
1497     */
1498    screen_apply ();
1499
1500    /*
1501     * Set crtcs
1502     */
1503
1504    for (c = 0; c < res->ncrtc; c++)
1505    {
1506	crtc_t	*crtc = &crtcs[c];
1507
1508	s = crtc_apply (crtc);
1509	if (s != RRSetConfigSuccess)
1510	    panic (s, crtc);
1511    }
1512
1513    set_primary ();
1514
1515    /*
1516     * Release the server grab and let all clients
1517     * respond to the updated state
1518     */
1519    if (grab_server)
1520	XUngrabServer (dpy);
1521}
1522
1523/*
1524 * Use current output state to complete the output list
1525 */
1526static void
1527get_outputs (void)
1528{
1529    int		o;
1530
1531    for (o = 0; o < res->noutput; o++)
1532    {
1533	XRROutputInfo	*output_info = XRRGetOutputInfo (dpy, res, res->outputs[o]);
1534	output_t	*output;
1535	name_t		output_name;
1536	if (!output_info) fatal ("could not get output 0x%x information\n", res->outputs[o]);
1537	set_name_xid (&output_name, res->outputs[o]);
1538	set_name_index (&output_name, o);
1539	set_name_string (&output_name, output_info->name);
1540	output = find_output (&output_name);
1541	if (!output)
1542	{
1543	    output = add_output ();
1544	    set_name_all (&output->output, &output_name);
1545	    /*
1546	     * When global --automatic mode is set, turn on connected but off
1547	     * outputs, turn off disconnected but on outputs
1548	     */
1549	    if (automatic)
1550	    {
1551		switch (output_info->connection) {
1552		case RR_Connected:
1553		    if (!output_info->crtc) {
1554			output->changes |= changes_automatic;
1555			output->automatic = True;
1556		    }
1557		    break;
1558		case RR_Disconnected:
1559		    if (output_info->crtc)
1560		    {
1561			output->changes |= changes_automatic;
1562			output->automatic = True;
1563		    }
1564		    break;
1565		}
1566	    }
1567	}
1568
1569	/*
1570	 * Automatic mode -- track connection state and enable/disable outputs
1571	 * as necessary
1572	 */
1573	if (output->automatic)
1574	{
1575	    switch (output_info->connection) {
1576	    case RR_Connected:
1577	    case RR_UnknownConnection:
1578		if ((!(output->changes & changes_mode)))
1579		{
1580		    set_name_preferred (&output->mode);
1581		    output->changes |= changes_mode;
1582		}
1583		break;
1584	    case RR_Disconnected:
1585		if ((!(output->changes & changes_mode)))
1586		{
1587		    set_name_xid (&output->mode, None);
1588		    set_name_xid (&output->crtc, None);
1589		    output->changes |= changes_mode;
1590		    output->changes |= changes_crtc;
1591		}
1592		break;
1593	    }
1594	}
1595
1596	set_output_info (output, res->outputs[o], output_info);
1597    }
1598}
1599
1600static void
1601mark_changing_crtcs (void)
1602{
1603    int	c;
1604
1605    for (c = 0; c < num_crtcs; c++)
1606    {
1607	crtc_t	    *crtc = &crtcs[c];
1608	int	    o;
1609	output_t    *output;
1610
1611	/* walk old output list (to catch disables) */
1612	for (o = 0; o < crtc->crtc_info->noutput; o++)
1613	{
1614	    output = find_output_by_xid (crtc->crtc_info->outputs[o]);
1615	    if (!output) fatal ("cannot find output 0x%x\n",
1616				crtc->crtc_info->outputs[o]);
1617	    if (output->changes)
1618		crtc->changing = True;
1619	}
1620	/* walk new output list */
1621	for (o = 0; o < crtc->noutput; o++)
1622	{
1623	    output = crtc->outputs[o];
1624	    if (output->changes)
1625		crtc->changing = True;
1626	}
1627    }
1628}
1629
1630/*
1631 * Test whether 'crtc' can be used for 'output'
1632 */
1633static Bool
1634check_crtc_for_output (crtc_t *crtc, output_t *output)
1635{
1636    int		c;
1637    int		l;
1638    output_t    *other;
1639
1640    for (c = 0; c < output->output_info->ncrtc; c++)
1641	if (output->output_info->crtcs[c] == crtc->crtc.xid)
1642	    break;
1643    if (c == output->output_info->ncrtc)
1644	return False;
1645    for (other = outputs; other; other = other->next)
1646    {
1647	if (other == output)
1648	    continue;
1649
1650	if (other->mode_info == NULL)
1651	    continue;
1652
1653	if (other->crtc_info != crtc)
1654	    continue;
1655
1656	/* see if the output connected to the crtc can clone to this output */
1657	for (l = 0; l < output->output_info->nclone; l++)
1658	    if (output->output_info->clones[l] == other->output.xid)
1659		break;
1660	/* not on the list, can't clone */
1661	if (l == output->output_info->nclone)
1662	    return False;
1663    }
1664
1665    if (crtc->noutput)
1666    {
1667	/* make sure the state matches */
1668	if (crtc->mode_info != output->mode_info)
1669	    return False;
1670	if (crtc->x != output->x)
1671	    return False;
1672	if (crtc->y != output->y)
1673	    return False;
1674	if (crtc->rotation != output->rotation)
1675	    return False;
1676	if (!equal_transform (&crtc->current_transform, &output->transform))
1677	    return False;
1678    }
1679    else if (crtc->crtc_info->noutput)
1680    {
1681	/* make sure the state matches the already used state */
1682	XRRModeInfo *mode = find_mode_by_xid (crtc->crtc_info->mode);
1683
1684	if (mode != output->mode_info)
1685	    return False;
1686	if (crtc->crtc_info->x != output->x)
1687	    return False;
1688	if (crtc->crtc_info->y != output->y)
1689	    return False;
1690	if (crtc->crtc_info->rotation != output->rotation)
1691	    return False;
1692    }
1693    return True;
1694}
1695
1696static crtc_t *
1697find_crtc_for_output (output_t *output)
1698{
1699    int	    c;
1700
1701    for (c = 0; c < output->output_info->ncrtc; c++)
1702    {
1703	crtc_t	    *crtc;
1704
1705	crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
1706	if (!crtc) fatal ("cannot find crtc 0x%x\n", output->output_info->crtcs[c]);
1707
1708	if (check_crtc_for_output (crtc, output))
1709	    return crtc;
1710    }
1711    return NULL;
1712}
1713
1714static void
1715set_positions (void)
1716{
1717    output_t	*output;
1718    Bool	keep_going;
1719    Bool	any_set;
1720    int		min_x, min_y;
1721
1722    for (;;)
1723    {
1724	any_set = False;
1725	keep_going = False;
1726	for (output = outputs; output; output = output->next)
1727	{
1728	    output_t    *relation;
1729	    name_t	relation_name;
1730
1731	    if (!(output->changes & changes_relation)) continue;
1732
1733	    if (output->mode_info == NULL) continue;
1734
1735	    init_name (&relation_name);
1736	    set_name_string (&relation_name, output->relative_to);
1737	    relation = find_output (&relation_name);
1738	    if (!relation) fatal ("cannot find output \"%s\"\n", output->relative_to);
1739
1740	    if (relation->mode_info == NULL)
1741	    {
1742		output->x = 0;
1743		output->y = 0;
1744		output->changes |= changes_position;
1745		any_set = True;
1746		continue;
1747	    }
1748	    /*
1749	     * Make sure the dependent object has been set in place
1750	     */
1751	    if ((relation->changes & changes_relation) &&
1752		!(relation->changes & changes_position))
1753	    {
1754		keep_going = True;
1755		continue;
1756	    }
1757
1758	    switch (output->relation) {
1759	    case left_of:
1760		output->y = relation->y;
1761		output->x = relation->x - mode_width (output->mode_info, output->rotation);
1762		break;
1763	    case right_of:
1764		output->y = relation->y;
1765		output->x = relation->x + mode_width (relation->mode_info, relation->rotation);
1766		break;
1767	    case above:
1768		output->x = relation->x;
1769		output->y = relation->y - mode_height (output->mode_info, output->rotation);
1770		break;
1771	    case below:
1772		output->x = relation->x;
1773		output->y = relation->y + mode_height (relation->mode_info, relation->rotation);
1774		break;
1775	    case same_as:
1776		output->x = relation->x;
1777		output->y = relation->y;
1778	    }
1779	    output->changes |= changes_position;
1780	    any_set = True;
1781	}
1782	if (!keep_going)
1783	    break;
1784	if (!any_set)
1785	    fatal ("loop in relative position specifications\n");
1786    }
1787
1788    /*
1789     * Now normalize positions so the upper left corner of all outputs is at 0,0
1790     */
1791    min_x = 32768;
1792    min_y = 32768;
1793    for (output = outputs; output; output = output->next)
1794    {
1795	if (output->mode_info == NULL) continue;
1796
1797	if (output->x < min_x) min_x = output->x;
1798	if (output->y < min_y) min_y = output->y;
1799    }
1800    if (min_x || min_y)
1801    {
1802	/* move all outputs */
1803	for (output = outputs; output; output = output->next)
1804	{
1805	    if (output->mode_info == NULL) continue;
1806
1807	    output->x -= min_x;
1808	    output->y -= min_y;
1809	    output->changes |= changes_position;
1810	}
1811    }
1812}
1813
1814static void
1815set_screen_size (void)
1816{
1817    output_t	*output;
1818    Bool	fb_specified = fb_width != 0 && fb_height != 0;
1819
1820    for (output = outputs; output; output = output->next)
1821    {
1822	XRRModeInfo *mode_info = output->mode_info;
1823	int	    x, y, w, h;
1824	box_t	    bounds;
1825
1826	if (!mode_info) continue;
1827
1828	mode_geometry (mode_info, output->rotation,
1829		       &output->transform.transform,
1830		       &bounds);
1831	x = output->x + bounds.x1;
1832	y = output->y + bounds.y1;
1833	w = bounds.x2 - bounds.x1;
1834	h = bounds.y2 - bounds.y1;
1835	/* make sure output fits in specified size */
1836	if (fb_specified)
1837	{
1838	    if (x + w > fb_width || y + h > fb_height)
1839		warning ("specified screen %dx%d not large enough for output %s (%dx%d+%d+%d)\n",
1840			 fb_width, fb_height, output->output.string, w, h, x, y);
1841	}
1842	/* fit fb to output */
1843	else
1844	{
1845	    XRRPanning *pan;
1846	    if (x + w > fb_width)
1847		fb_width = x + w;
1848	    if (y + h > fb_height)
1849		fb_height = y + h;
1850	    if (output->changes & changes_panning)
1851		pan = &output->panning;
1852	    else
1853		pan = output->crtc_info ? output->crtc_info->panning_info : NULL;
1854	    if (pan && pan->left + pan->width > fb_width)
1855		fb_width = pan->left + pan->width;
1856	    if (pan && pan->top + pan->height > fb_height)
1857		fb_height = pan->top + pan->height;
1858	}
1859    }
1860
1861    if (fb_width > maxWidth || fb_height > maxHeight)
1862        fatal ("screen cannot be larger than %dx%d (desired size %dx%d)\n",
1863	       maxWidth, maxHeight, fb_width, fb_height);
1864    if (fb_specified)
1865    {
1866	if (fb_width < minWidth || fb_height < minHeight)
1867	    fatal ("screen must be at least %dx%d\n", minWidth, minHeight);
1868    }
1869    else
1870    {
1871	if (fb_width < minWidth) fb_width = minWidth;
1872	if (fb_height < minHeight) fb_height = minHeight;
1873    }
1874}
1875
1876#endif
1877
1878static void
1879disable_outputs (output_t *outputs)
1880{
1881    while (outputs)
1882    {
1883	outputs->crtc_info = NULL;
1884	outputs = outputs->next;
1885    }
1886}
1887
1888/*
1889 * find the best mapping from output to crtc available
1890 */
1891static int
1892pick_crtcs_score (output_t *outputs)
1893{
1894    output_t	*output;
1895    int		best_score;
1896    int		my_score;
1897    int		score;
1898    crtc_t	*best_crtc;
1899    int		c;
1900
1901    if (!outputs)
1902	return 0;
1903
1904    output = outputs;
1905    outputs = outputs->next;
1906    /*
1907     * Score with this output disabled
1908     */
1909    output->crtc_info = NULL;
1910    best_score = pick_crtcs_score (outputs);
1911    if (output->mode_info == NULL)
1912	return best_score;
1913
1914    best_crtc = NULL;
1915    /*
1916     * Now score with this output any valid crtc
1917     */
1918    for (c = 0; c < output->output_info->ncrtc; c++)
1919    {
1920	crtc_t	    *crtc;
1921
1922	crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
1923	if (!crtc)
1924	    fatal ("cannot find crtc 0x%x\n", output->output_info->crtcs[c]);
1925
1926	/* reset crtc allocation for following outputs */
1927	disable_outputs (outputs);
1928	if (!check_crtc_for_output (crtc, output))
1929	    continue;
1930
1931	my_score = 1000;
1932	/* slight preference for existing connections */
1933	if (crtc == output->current_crtc_info)
1934	    my_score++;
1935
1936	output->crtc_info = crtc;
1937	score = my_score + pick_crtcs_score (outputs);
1938	if (score > best_score)
1939	{
1940	    best_crtc = crtc;
1941	    best_score = score;
1942	}
1943    }
1944    if (output->crtc_info != best_crtc)
1945	output->crtc_info = best_crtc;
1946    /*
1947     * Reset other outputs based on this one using the best crtc
1948     */
1949    (void) pick_crtcs_score (outputs);
1950
1951    return best_score;
1952}
1953
1954/*
1955 * Pick crtcs for any changing outputs that don't have one
1956 */
1957static void
1958pick_crtcs (void)
1959{
1960    output_t	*output;
1961
1962    /*
1963     * First try to match up newly enabled outputs with spare crtcs
1964     */
1965    for (output = outputs; output; output = output->next)
1966    {
1967	if (output->changes && output->mode_info)
1968	{
1969	    if (output->crtc_info) {
1970		if (output->crtc_info->crtc_info->noutput > 0 &&
1971		    (output->crtc_info->crtc_info->noutput > 1 ||
1972		     output != find_output_by_xid (output->crtc_info->crtc_info->outputs[0])))
1973		    break;
1974	    } else {
1975		output->crtc_info = find_crtc_for_output (output);
1976		if (!output->crtc_info)
1977		    break;
1978	    }
1979	}
1980    }
1981    /*
1982     * Everyone is happy
1983     */
1984    if (!output)
1985	return;
1986    /*
1987     * When the simple way fails, see if there is a way
1988     * to swap crtcs around and make things work
1989     */
1990    for (output = outputs; output; output = output->next)
1991	output->current_crtc_info = output->crtc_info;
1992    pick_crtcs_score (outputs);
1993    for (output = outputs; output; output = output->next)
1994    {
1995	if (output->mode_info && !output->crtc_info)
1996	    fatal ("cannot find crtc for output %s\n", output->output.string);
1997	if (!output->changes && output->crtc_info != output->current_crtc_info)
1998	    output->changes |= changes_crtc;
1999    }
2000}
2001
2002int
2003main (int argc, char **argv)
2004{
2005    XRRScreenSize *sizes;
2006    XRRScreenConfiguration *sc;
2007    int		nsize;
2008    int		nrate;
2009    short		*rates;
2010    Status	status = RRSetConfigFailed;
2011    int		rot = -1;
2012    int		query = 0;
2013    Rotation	rotation, current_rotation, rotations;
2014    XEvent	event;
2015    XRRScreenChangeNotifyEvent *sce;
2016    char          *display_name = NULL;
2017    int 		i, j;
2018    SizeID	current_size;
2019    short	current_rate;
2020    float    	rate = -1;
2021    int		size = -1;
2022    int		dirind = 0;
2023    Bool	setit = False;
2024    Bool    	version = False;
2025    int		event_base, error_base;
2026    int		reflection = 0;
2027    int		width = 0, height = 0;
2028    Bool    	have_pixel_size = False;
2029    int		ret = 0;
2030#if HAS_RANDR_1_2
2031    output_t	*output = NULL;
2032    policy_t	policy = clone;
2033    Bool    	setit_1_2 = False;
2034    Bool    	query_1_2 = False;
2035    Bool	modeit = False;
2036    Bool	propit = False;
2037    Bool	query_1 = False;
2038    int		major, minor;
2039    Bool	current = False;
2040#endif
2041
2042    program_name = argv[0];
2043    if (argc == 1) query = True;
2044    for (i = 1; i < argc; i++) {
2045	if (!strcmp ("-display", argv[i]) || !strcmp ("-d", argv[i])) {
2046	    if (++i>=argc) usage ();
2047	    display_name = argv[i];
2048	    continue;
2049	}
2050	if (!strcmp("-help", argv[i])) {
2051	    usage();
2052	    continue;
2053	}
2054	if (!strcmp ("--verbose", argv[i])) {
2055	    verbose = True;
2056	    continue;
2057	}
2058	if (!strcmp ("--dryrun", argv[i])) {
2059	    dryrun = True;
2060	    verbose = True;
2061	    continue;
2062	}
2063	if (!strcmp ("--nograb", argv[i])) {
2064	    grab_server = False;
2065	    continue;
2066	}
2067	if (!strcmp("--current", argv[i])) {
2068	    current = True;
2069	    /* if --current was the only arg, then query */
2070	    if (argc == 2) query = True;
2071	    continue;
2072	}
2073
2074	if (!strcmp ("-s", argv[i]) || !strcmp ("--size", argv[i])) {
2075	    if (++i>=argc) usage ();
2076	    if (sscanf (argv[i], "%dx%d", &width, &height) == 2)
2077		have_pixel_size = True;
2078	    else {
2079		size = atoi (argv[i]);
2080		if (size < 0) usage();
2081	    }
2082	    setit = True;
2083	    continue;
2084	}
2085
2086	if (!strcmp ("-r", argv[i]) ||
2087	    !strcmp ("--rate", argv[i]) ||
2088	    !strcmp ("--refresh", argv[i]))
2089	{
2090	    if (++i>=argc) usage ();
2091	    if (sscanf (argv[i], "%f", &rate) != 1)
2092		usage ();
2093	    setit = True;
2094#if HAS_RANDR_1_2
2095	    if (output)
2096	    {
2097		output->refresh = rate;
2098		output->changes |= changes_refresh;
2099		setit_1_2 = True;
2100	    }
2101#endif
2102	    continue;
2103	}
2104
2105	if (!strcmp ("-v", argv[i]) || !strcmp ("--version", argv[i])) {
2106	    version = True;
2107	    continue;
2108	}
2109
2110	if (!strcmp ("-x", argv[i])) {
2111	    reflection |= RR_Reflect_X;
2112	    setit = True;
2113	    continue;
2114	}
2115	if (!strcmp ("-y", argv[i])) {
2116	    reflection |= RR_Reflect_Y;
2117	    setit = True;
2118	    continue;
2119	}
2120	if (!strcmp ("--screen", argv[i])) {
2121	    if (++i>=argc) usage ();
2122	    screen = atoi (argv[i]);
2123	    if (screen < 0) usage();
2124	    continue;
2125	}
2126	if (!strcmp ("-q", argv[i]) || !strcmp ("--query", argv[i])) {
2127	    query = True;
2128	    continue;
2129	}
2130	if (!strcmp ("-o", argv[i]) || !strcmp ("--orientation", argv[i])) {
2131	    char *endptr;
2132	    if (++i>=argc) usage ();
2133	    dirind = strtol(argv[i], &endptr, 0);
2134	    if (*endptr != '\0') {
2135		for (dirind = 0; dirind < 4; dirind++) {
2136		    if (strcmp (direction[dirind], argv[i]) == 0) break;
2137		}
2138		if ((dirind < 0) || (dirind > 3))  usage();
2139	    }
2140	    rot = dirind;
2141	    setit = True;
2142	    continue;
2143	}
2144#if HAS_RANDR_1_2
2145	if (!strcmp ("--prop", argv[i]) ||
2146	    !strcmp ("--props", argv[i]) ||
2147	    !strcmp ("--madprops", argv[i]) ||
2148	    !strcmp ("--properties", argv[i]))
2149	{
2150	    query_1_2 = True;
2151	    properties = True;
2152	    continue;
2153	}
2154	if (!strcmp ("--output", argv[i])) {
2155	    if (++i >= argc) usage();
2156
2157	    output = find_output_by_name (argv[i]);
2158	    if (!output) {
2159		output = add_output ();
2160		set_name (&output->output, argv[i], name_string|name_xid);
2161	    }
2162
2163	    setit_1_2 = True;
2164	    continue;
2165	}
2166	if (!strcmp ("--crtc", argv[i])) {
2167	    if (++i >= argc) usage();
2168	    if (!output) usage();
2169	    set_name (&output->crtc, argv[i], name_xid|name_index);
2170	    output->changes |= changes_crtc;
2171	    continue;
2172	}
2173	if (!strcmp ("--mode", argv[i])) {
2174	    if (++i >= argc) usage();
2175	    if (!output) usage();
2176	    set_name (&output->mode, argv[i], name_string|name_xid);
2177	    output->changes |= changes_mode;
2178	    continue;
2179	}
2180	if (!strcmp ("--preferred", argv[i])) {
2181	    if (!output) usage();
2182	    set_name_preferred (&output->mode);
2183	    output->changes |= changes_mode;
2184	    continue;
2185	}
2186	if (!strcmp ("--pos", argv[i])) {
2187	    if (++i>=argc) usage ();
2188	    if (!output) usage();
2189	    if (sscanf (argv[i], "%dx%d",
2190			&output->x, &output->y) != 2)
2191		usage ();
2192	    output->changes |= changes_position;
2193	    continue;
2194	}
2195	if (!strcmp ("--rotation", argv[i]) || !strcmp ("--rotate", argv[i])) {
2196	    if (++i>=argc) usage ();
2197	    if (!output) usage();
2198	    for (dirind = 0; dirind < 4; dirind++) {
2199		if (strcmp (direction[dirind], argv[i]) == 0) break;
2200	    }
2201	    if (dirind == 4)
2202		usage ();
2203	    output->rotation &= ~0xf;
2204	    output->rotation |= 1 << dirind;
2205	    output->changes |= changes_rotation;
2206	    continue;
2207	}
2208	if (!strcmp ("--reflect", argv[i]) || !strcmp ("--reflection", argv[i])) {
2209	    if (++i>=argc) usage ();
2210	    if (!output) usage();
2211	    for (dirind = 0; dirind < 4; dirind++) {
2212		if (strcmp (reflections[dirind], argv[i]) == 0) break;
2213	    }
2214	    if (dirind == 4)
2215		usage ();
2216	    output->rotation &= ~(RR_Reflect_X|RR_Reflect_Y);
2217	    output->rotation |= dirind * RR_Reflect_X;
2218	    output->changes |= changes_reflection;
2219	    continue;
2220	}
2221	if (!strcmp ("--left-of", argv[i])) {
2222	    if (++i>=argc) usage ();
2223	    if (!output) usage();
2224	    output->relation = left_of;
2225	    output->relative_to = argv[i];
2226	    output->changes |= changes_relation;
2227	    continue;
2228	}
2229	if (!strcmp ("--right-of", argv[i])) {
2230	    if (++i>=argc) usage ();
2231	    if (!output) usage();
2232	    output->relation = right_of;
2233	    output->relative_to = argv[i];
2234	    output->changes |= changes_relation;
2235	    continue;
2236	}
2237	if (!strcmp ("--above", argv[i])) {
2238	    if (++i>=argc) usage ();
2239	    if (!output) usage();
2240	    output->relation = above;
2241	    output->relative_to = argv[i];
2242	    output->changes |= changes_relation;
2243	    continue;
2244	}
2245	if (!strcmp ("--below", argv[i])) {
2246	    if (++i>=argc) usage ();
2247	    if (!output) usage();
2248	    output->relation = below;
2249	    output->relative_to = argv[i];
2250	    output->changes |= changes_relation;
2251	    continue;
2252	}
2253	if (!strcmp ("--same-as", argv[i])) {
2254	    if (++i>=argc) usage ();
2255	    if (!output) usage();
2256	    output->relation = same_as;
2257	    output->relative_to = argv[i];
2258	    output->changes |= changes_relation;
2259	    continue;
2260	}
2261	if (!strcmp ("--panning", argv[i])) {
2262	    XRRPanning *pan;
2263	    if (++i>=argc) usage ();
2264	    if (!output) usage();
2265	    pan = &output->panning;
2266	    switch (sscanf (argv[i], "%dx%d+%d+%d/%dx%d+%d+%d/%d/%d/%d/%d",
2267			    &pan->width, &pan->height, &pan->left, &pan->top,
2268			    &pan->track_width, &pan->track_height,
2269			    &pan->track_left, &pan->track_top,
2270			    &pan->border_left, &pan->border_top,
2271			    &pan->border_right, &pan->border_bottom)) {
2272	    case 2:
2273		pan->left = pan->top = 0;
2274		/* fall through */
2275	    case 4:
2276		pan->track_left = pan->track_top =
2277		    pan->track_width = pan->track_height = 0;
2278		/* fall through */
2279	    case 8:
2280		pan->border_left = pan->border_top =
2281		    pan->border_right = pan->border_bottom = 0;
2282		/* fall through */
2283	    case 12:
2284		break;
2285	    default:
2286		usage ();
2287	    }
2288	    output->changes |= changes_panning;
2289	    continue;
2290	}
2291	if (!strcmp ("--gamma", argv[i])) {
2292	    if (!output) usage();
2293	    if (++i>=argc) usage ();
2294	    if (sscanf(argv[i], "%f:%f:%f", &output->gamma.red,
2295		    &output->gamma.green, &output->gamma.blue) != 3)
2296		usage ();
2297	    output->changes |= changes_gamma;
2298	    setit_1_2 = True;
2299	    continue;
2300	}
2301	if (!strcmp ("--primary", argv[i])) {
2302	    if (!output) usage();
2303	    output->changes |= changes_primary;
2304	    output->primary = True;
2305	    setit_1_2 = True;
2306	    continue;
2307	}
2308	if (!strcmp ("--noprimary", argv[i])) {
2309	    no_primary = True;
2310	    setit_1_2 = True;
2311	    continue;
2312	}
2313	if (!strcmp ("--set", argv[i])) {
2314	    output_prop_t   *prop;
2315	    if (!output) usage();
2316	    prop = malloc (sizeof (output_prop_t));
2317	    prop->next = output->props;
2318	    output->props = prop;
2319	    if (++i>=argc) usage ();
2320	    prop->name = argv[i];
2321	    if (++i>=argc) usage ();
2322	    prop->value = argv[i];
2323	    propit = True;
2324	    output->changes |= changes_property;
2325	    setit_1_2 = True;
2326	    continue;
2327	}
2328	if (!strcmp ("--scale", argv[i]))
2329	{
2330	    double  sx, sy;
2331	    if (++i>=argc) usage();
2332	    if (sscanf (argv[i], "%lfx%lf", &sx, &sy) != 2)
2333		usage ();
2334	    init_transform (&output->transform);
2335	    output->transform.transform.matrix[0][0] = XDoubleToFixed (sx);
2336	    output->transform.transform.matrix[1][1] = XDoubleToFixed (sy);
2337	    output->transform.transform.matrix[2][2] = XDoubleToFixed (1.0);
2338	    if (sx != 1 || sy != 1)
2339		output->transform.filter = "bilinear";
2340	    else
2341		output->transform.filter = "nearest";
2342	    output->transform.nparams = 0;
2343	    output->transform.params = NULL;
2344	    output->changes |= changes_transform;
2345	    continue;
2346	}
2347	if (!strcmp ("--transform", argv[i])) {
2348	    double  transform[3][3];
2349	    int	    k, l;
2350	    if (++i>=argc) usage ();
2351	    init_transform (&output->transform);
2352	    if (strcmp (argv[i], "none") != 0)
2353	    {
2354		if (sscanf(argv[i], "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",
2355			   &transform[0][0],&transform[0][1],&transform[0][2],
2356			   &transform[1][0],&transform[1][1],&transform[1][2],
2357			   &transform[2][0],&transform[2][1],&transform[2][2])
2358		    != 9)
2359		    usage ();
2360		init_transform (&output->transform);
2361		for (k = 0; k < 3; k++)
2362		    for (l = 0; l < 3; l++) {
2363			output->transform.transform.matrix[k][l] = XDoubleToFixed (transform[k][l]);
2364		    }
2365		output->transform.filter = "bilinear";
2366		output->transform.nparams = 0;
2367		output->transform.params = NULL;
2368	    }
2369	    output->changes |= changes_transform;
2370	    continue;
2371	}
2372	if (!strcmp ("--off", argv[i])) {
2373	    if (!output) usage();
2374	    set_name_xid (&output->mode, None);
2375	    set_name_xid (&output->crtc, None);
2376	    output->changes |= changes_mode;
2377	    continue;
2378	}
2379	if (!strcmp ("--fb", argv[i])) {
2380	    if (++i>=argc) usage ();
2381	    if (sscanf (argv[i], "%dx%d",
2382			&fb_width, &fb_height) != 2)
2383		usage ();
2384	    setit_1_2 = True;
2385	    continue;
2386	}
2387	if (!strcmp ("--fbmm", argv[i])) {
2388	    if (++i>=argc) usage ();
2389	    if (sscanf (argv[i], "%dx%d",
2390			&fb_width_mm, &fb_height_mm) != 2)
2391		usage ();
2392	    setit_1_2 = True;
2393	    continue;
2394	}
2395	if (!strcmp ("--dpi", argv[i])) {
2396	    if (++i>=argc) usage ();
2397	    if (sscanf (argv[i], "%f", &dpi) != 1)
2398	    {
2399		dpi = 0.0;
2400		dpi_output = argv[i];
2401	    }
2402	    setit_1_2 = True;
2403	    continue;
2404	}
2405	if (!strcmp ("--clone", argv[i])) {
2406	    policy = clone;
2407	    setit_1_2 = True;
2408	    continue;
2409	}
2410	if (!strcmp ("--extend", argv[i])) {
2411	    policy = extend;
2412	    setit_1_2 = True;
2413	    continue;
2414	}
2415	if (!strcmp ("--auto", argv[i])) {
2416	    if (output)
2417	    {
2418		output->automatic = True;
2419		output->changes |= changes_automatic;
2420	    }
2421	    else
2422		automatic = True;
2423	    setit_1_2 = True;
2424	    continue;
2425	}
2426	if (!strcmp ("--q12", argv[i]))
2427	{
2428	    query_1_2 = True;
2429	    continue;
2430	}
2431	if (!strcmp ("--q1", argv[i]))
2432	{
2433	    query_1 = True;
2434	    continue;
2435	}
2436	if (!strcmp ("--newmode", argv[i]))
2437	{
2438	    umode_t  *m = malloc (sizeof (umode_t));
2439	    float   clock;
2440
2441	    ++i;
2442	    if (i + 9 >= argc) usage ();
2443	    m->mode.name = argv[i];
2444	    m->mode.nameLength = strlen (argv[i]);
2445	    i++;
2446	    if (sscanf (argv[i++], "%f", &clock) != 1)
2447		usage ();
2448	    m->mode.dotClock = clock * 1e6;
2449
2450	    if (sscanf (argv[i++], "%d", &m->mode.width) != 1) usage();
2451	    if (sscanf (argv[i++], "%d", &m->mode.hSyncStart) != 1) usage();
2452	    if (sscanf (argv[i++], "%d", &m->mode.hSyncEnd) != 1) usage();
2453	    if (sscanf (argv[i++], "%d", &m->mode.hTotal) != 1) usage();
2454	    if (sscanf (argv[i++], "%d", &m->mode.height) != 1) usage();
2455	    if (sscanf (argv[i++], "%d", &m->mode.vSyncStart) != 1) usage();
2456	    if (sscanf (argv[i++], "%d", &m->mode.vSyncEnd) != 1) usage();
2457	    if (sscanf (argv[i++], "%d", &m->mode.vTotal) != 1) usage();
2458	    m->mode.modeFlags = 0;
2459	    while (i < argc) {
2460		int f;
2461
2462		for (f = 0; mode_flags[f].string; f++)
2463		    if (!strcasecmp (mode_flags[f].string, argv[i]))
2464			break;
2465
2466		if (!mode_flags[f].string)
2467		    break;
2468    		m->mode.modeFlags |= mode_flags[f].flag;
2469    		i++;
2470	    }
2471	    m->next = umodes;
2472	    m->action = umode_create;
2473	    umodes = m;
2474	    modeit = True;
2475	    continue;
2476	}
2477	if (!strcmp ("--rmmode", argv[i]))
2478	{
2479	    umode_t  *m = malloc (sizeof (umode_t));
2480
2481	    if (++i>=argc) usage ();
2482	    set_name (&m->name, argv[i], name_string|name_xid);
2483	    m->action = umode_destroy;
2484	    m->next = umodes;
2485	    umodes = m;
2486	    modeit = True;
2487	    continue;
2488	}
2489	if (!strcmp ("--addmode", argv[i]))
2490	{
2491	    umode_t  *m = malloc (sizeof (umode_t));
2492
2493	    if (++i>=argc) usage ();
2494	    set_name (&m->output, argv[i], name_string|name_xid);
2495	    if (++i>=argc) usage();
2496	    set_name (&m->name, argv[i], name_string|name_xid);
2497	    m->action = umode_add;
2498	    m->next = umodes;
2499	    umodes = m;
2500	    modeit = True;
2501	    continue;
2502	}
2503	if (!strcmp ("--delmode", argv[i]))
2504	{
2505	    umode_t  *m = malloc (sizeof (umode_t));
2506
2507	    if (++i>=argc) usage ();
2508	    set_name (&m->output, argv[i], name_string|name_xid);
2509	    if (++i>=argc) usage();
2510	    set_name (&m->name, argv[i], name_string|name_xid);
2511	    m->action = umode_delete;
2512	    m->next = umodes;
2513	    umodes = m;
2514	    modeit = True;
2515	    continue;
2516	}
2517#endif
2518	usage();
2519    }
2520    if (verbose)
2521    {
2522	query = True;
2523	if (setit && !setit_1_2)
2524	    query_1 = True;
2525    }
2526    if (version)
2527	printf("xrandr program version       " VERSION "\n");
2528
2529    dpy = XOpenDisplay (display_name);
2530
2531    if (dpy == NULL) {
2532	fprintf (stderr, "Can't open display %s\n", XDisplayName(display_name));
2533	exit (1);
2534    }
2535    if (screen < 0)
2536	screen = DefaultScreen (dpy);
2537    if (screen >= ScreenCount (dpy)) {
2538	fprintf (stderr, "Invalid screen number %d (display has %d)\n",
2539		 screen, ScreenCount (dpy));
2540	exit (1);
2541    }
2542
2543    root = RootWindow (dpy, screen);
2544
2545#if HAS_RANDR_1_2
2546    if (!XRRQueryVersion (dpy, &major, &minor))
2547    {
2548	fprintf (stderr, "RandR extension missing\n");
2549	exit (1);
2550    }
2551    if (major > 1 || (major == 1 && minor >= 2))
2552	has_1_2 = True;
2553    if (major > 1 || (major == 1 && minor >= 3))
2554	has_1_3 = True;
2555
2556    if (has_1_2 && modeit)
2557    {
2558	umode_t	*m;
2559
2560        get_screen (current);
2561	get_crtcs();
2562	get_outputs();
2563
2564	for (m = umodes; m; m = m->next)
2565	{
2566	    XRRModeInfo *e;
2567	    output_t	*o;
2568
2569	    switch (m->action) {
2570	    case umode_create:
2571		XRRCreateMode (dpy, root, &m->mode);
2572		break;
2573	    case umode_destroy:
2574		e = find_mode (&m->name, 0);
2575		if (!e)
2576		    fatal ("cannot find mode \"%s\"\n", m->name.string);
2577		XRRDestroyMode (dpy, e->id);
2578		break;
2579	    case umode_add:
2580		o = find_output (&m->output);
2581		if (!o)
2582		    fatal ("cannot find output \"%s\"\n", m->output.string);
2583		e = find_mode (&m->name, 0);
2584		if (!e)
2585		    fatal ("cannot find mode \"%s\"\n", m->name.string);
2586		XRRAddOutputMode (dpy, o->output.xid, e->id);
2587		break;
2588	    case umode_delete:
2589		o = find_output (&m->output);
2590		if (!o)
2591		    fatal ("cannot find output \"%s\"\n", m->output.string);
2592		e = find_mode (&m->name, 0);
2593		if (!e)
2594		    fatal ("cannot find mode \"%s\"\n", m->name.string);
2595		XRRDeleteOutputMode (dpy, o->output.xid, e->id);
2596		break;
2597	    }
2598	}
2599	if (!setit_1_2)
2600	{
2601	    XSync (dpy, False);
2602	    exit (0);
2603	}
2604    }
2605    if (has_1_2 && propit)
2606    {
2607
2608        get_screen (current);
2609	get_crtcs();
2610	get_outputs();
2611
2612	for (output = outputs; output; output = output->next)
2613	{
2614	    output_prop_t   *prop;
2615
2616	    for (prop = output->props; prop; prop = prop->next)
2617	    {
2618		Atom		name = XInternAtom (dpy, prop->name, False);
2619		Atom		type;
2620		int		format;
2621		unsigned char	*data;
2622		int		nelements;
2623		int		int_value;
2624		unsigned long	ulong_value;
2625		unsigned char	*prop_data;
2626		int		actual_format;
2627		unsigned long	nitems, bytes_after;
2628		Atom		actual_type;
2629		XRRPropertyInfo *propinfo;
2630
2631		type = AnyPropertyType;
2632		format=0;
2633
2634		if (XRRGetOutputProperty (dpy, output->output.xid, name,
2635					  0, 100, False, False,
2636					  AnyPropertyType,
2637					  &actual_type, &actual_format,
2638					  &nitems, &bytes_after, &prop_data) == Success &&
2639
2640		    (propinfo = XRRQueryOutputProperty(dpy, output->output.xid,
2641						      name)))
2642		{
2643		    type = actual_type;
2644		    format = actual_format;
2645		}
2646
2647		if ((type == XA_INTEGER || type == AnyPropertyType) &&
2648		    (sscanf (prop->value, "%d", &int_value) == 1 ||
2649		     sscanf (prop->value, "0x%x", &int_value) == 1))
2650		{
2651		    type = XA_INTEGER;
2652		    ulong_value = int_value;
2653		    data = (unsigned char *) &ulong_value;
2654		    nelements = 1;
2655		    format = 32;
2656		}
2657		else if ((type == XA_ATOM))
2658		{
2659		    ulong_value = XInternAtom (dpy, prop->value, False);
2660		    data = (unsigned char *) &ulong_value;
2661		    nelements = 1;
2662		    format = 32;
2663		}
2664		else if ((type == XA_STRING || type == AnyPropertyType))
2665		{
2666		    type = XA_STRING;
2667		    data = (unsigned char *) prop->value;
2668		    nelements = strlen (prop->value);
2669		    format = 8;
2670		}
2671		else
2672		    continue;
2673		XRRChangeOutputProperty (dpy, output->output.xid,
2674					 name, type, format, PropModeReplace,
2675					 data, nelements);
2676	    }
2677	}
2678	if (!setit_1_2)
2679	{
2680	    XSync (dpy, False);
2681	    exit (0);
2682	}
2683    }
2684    if (setit_1_2)
2685    {
2686	get_screen (current);
2687	get_crtcs ();
2688	get_outputs ();
2689	set_positions ();
2690	set_screen_size ();
2691
2692	pick_crtcs ();
2693
2694	/*
2695	 * Assign outputs to crtcs
2696	 */
2697	set_crtcs ();
2698
2699	/*
2700	 * Mark changing crtcs
2701	 */
2702	mark_changing_crtcs ();
2703
2704	/*
2705	 * If an output was specified to track dpi, use it
2706	 */
2707	if (dpi_output)
2708	{
2709	    output_t	*output = find_output_by_name (dpi_output);
2710	    XRROutputInfo	*output_info;
2711	    XRRModeInfo	*mode_info;
2712	    if (!output)
2713		fatal ("Cannot find output %s\n", dpi_output);
2714	    output_info = output->output_info;
2715	    mode_info = output->mode_info;
2716	    if (output_info && mode_info && output_info->mm_height)
2717	    {
2718		/*
2719		 * When this output covers the whole screen, just use
2720		 * the known physical size
2721		 */
2722		if (fb_width == mode_info->width &&
2723		    fb_height == mode_info->height)
2724		{
2725		    fb_width_mm = output_info->mm_width;
2726		    fb_height_mm = output_info->mm_height;
2727		}
2728		else
2729		{
2730		    dpi = (25.4 * mode_info->height) / output_info->mm_height;
2731		}
2732	    }
2733	}
2734
2735	/*
2736	 * Compute physical screen size
2737	 */
2738	if (fb_width_mm == 0 || fb_height_mm == 0)
2739	{
2740	    if (fb_width != DisplayWidth (dpy, screen) ||
2741		fb_height != DisplayHeight (dpy, screen) || dpi != 0.0)
2742	    {
2743		if (dpi <= 0)
2744		    dpi = (25.4 * DisplayHeight (dpy, screen)) / DisplayHeightMM(dpy, screen);
2745
2746		fb_width_mm = (25.4 * fb_width) / dpi;
2747		fb_height_mm = (25.4 * fb_height) / dpi;
2748	    }
2749	    else
2750	    {
2751		fb_width_mm = DisplayWidthMM (dpy, screen);
2752		fb_height_mm = DisplayHeightMM (dpy, screen);
2753	    }
2754	}
2755
2756	/*
2757	 * Set panning
2758	 */
2759	set_panning ();
2760
2761	/*
2762	 * Set gamma on crtc's that belong to the outputs.
2763	 */
2764	set_gamma ();
2765
2766	/*
2767	 * Now apply all of the changes
2768	 */
2769	apply ();
2770
2771	XSync (dpy, False);
2772	exit (0);
2773    }
2774    if (query_1_2 || (query && has_1_2 && !query_1))
2775    {
2776	output_t    *output;
2777	int	    m;
2778
2779#define ModeShown   0x80000000
2780
2781	get_screen (current);
2782	get_crtcs ();
2783	get_outputs ();
2784
2785        printf ("Screen %d: minimum %d x %d, current %d x %d, maximum %d x %d\n",
2786		screen, minWidth, minHeight,
2787		DisplayWidth (dpy, screen), DisplayHeight(dpy, screen),
2788		maxWidth, maxHeight);
2789
2790	for (output = outputs; output; output = output->next)
2791	{
2792	    XRROutputInfo   *output_info = output->output_info;
2793	    crtc_t	    *crtc = output->crtc_info;
2794	    XRRCrtcInfo	    *crtc_info = crtc ? crtc->crtc_info : NULL;
2795	    XRRModeInfo	    *mode = output->mode_info;
2796	    Atom	    *props;
2797	    int		    j, k, nprop;
2798	    Bool	    *mode_shown;
2799	    Rotation	    rotations = output_rotations (output);
2800
2801	    printf ("%s %s", output_info->name, connection[output_info->connection]);
2802	    if (mode)
2803	    {
2804		if (crtc_info) {
2805		    printf (" %dx%d+%d+%d",
2806			    crtc_info->width, crtc_info->height,
2807			    crtc_info->x, crtc_info->y);
2808		} else {
2809		    printf (" %dx%d+%d+%d",
2810			    mode->width, mode->height, output->x, output->y);
2811		}
2812		if (verbose)
2813		    printf (" (0x%x)", (int)mode->id);
2814		if (output->rotation != RR_Rotate_0 || verbose)
2815		{
2816		    printf (" %s",
2817			    rotation_name (output->rotation));
2818		    if (output->rotation & (RR_Reflect_X|RR_Reflect_Y))
2819			printf (" %s", reflection_name (output->rotation));
2820		}
2821	    }
2822	    if (rotations != RR_Rotate_0 || verbose)
2823	    {
2824		Bool    first = True;
2825		printf (" (");
2826		for (i = 0; i < 4; i ++) {
2827		    if ((rotations >> i) & 1) {
2828			if (!first) printf (" "); first = False;
2829			printf("%s", direction[i]);
2830			first = False;
2831		    }
2832		}
2833		if (rotations & RR_Reflect_X)
2834		{
2835		    if (!first) printf (" "); first = False;
2836		    printf ("x axis");
2837		}
2838		if (rotations & RR_Reflect_Y)
2839		{
2840		    if (!first) printf (" "); first = False;
2841		    printf ("y axis");
2842		}
2843		printf (")");
2844	    }
2845
2846	    if (mode)
2847	    {
2848		printf (" %dmm x %dmm",
2849			(int)output_info->mm_width, (int)output_info->mm_height);
2850	    }
2851
2852	    if (crtc && crtc->panning_info && crtc->panning_info->width > 0)
2853	    {
2854		XRRPanning *pan = crtc->panning_info;
2855		printf (" panning %dx%d+%d+%d",
2856			pan->width, pan->height, pan->left, pan->top);
2857		if ((pan->track_width    != 0 &&
2858		     (pan->track_left    != pan->left		||
2859		      pan->track_width   != pan->width		||
2860		      pan->border_left   != 0			||
2861		      pan->border_right  != 0))			||
2862		    (pan->track_height   != 0 &&
2863		     (pan->track_top     != pan->top		||
2864		      pan->track_height  != pan->height		||
2865		      pan->border_top    != 0			||
2866		      pan->border_bottom != 0)))
2867		    printf (" tracking %dx%d+%d+%d border %d/%d/%d/%d",
2868			    pan->track_width,  pan->track_height,
2869			    pan->track_left,   pan->track_top,
2870			    pan->border_left,  pan->border_top,
2871			    pan->border_right, pan->border_bottom);
2872	    }
2873	    printf ("\n");
2874
2875	    if (verbose)
2876	    {
2877		printf ("\tIdentifier: 0x%x\n", (int)output->output.xid);
2878		printf ("\tTimestamp:  %d\n", (int)output_info->timestamp);
2879		printf ("\tSubpixel:   %s\n", order[output_info->subpixel_order]);
2880		printf ("\tClones:    ");
2881		for (j = 0; j < output_info->nclone; j++)
2882		{
2883		    output_t	*clone = find_output_by_xid (output_info->clones[j]);
2884
2885		    if (clone) printf (" %s", clone->output.string);
2886		}
2887		printf ("\n");
2888		if (output->crtc_info)
2889		    printf ("\tCRTC:       %d\n", output->crtc_info->crtc.index);
2890		printf ("\tCRTCs:     ");
2891		for (j = 0; j < output_info->ncrtc; j++)
2892		{
2893		    crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[j]);
2894		    if (crtc)
2895			printf (" %d", crtc->crtc.index);
2896		}
2897		printf ("\n");
2898		if (output->crtc_info && output->crtc_info->panning_info) {
2899		    XRRPanning *pan = output->crtc_info->panning_info;
2900		    printf ("\tPanning:    %dx%d+%d+%d\n",
2901			    pan->width, pan->height, pan->left, pan->top);
2902		    printf ("\tTracking:   %dx%d+%d+%d\n",
2903			    pan->track_width,  pan->track_height,
2904			    pan->track_left,   pan->track_top);
2905		    printf ("\tBorder:     %d/%d/%d/%d\n",
2906			    pan->border_left,  pan->border_top,
2907			    pan->border_right, pan->border_bottom);
2908		}
2909	    }
2910	    if (verbose)
2911	    {
2912		int x, y;
2913
2914		printf ("\tTransform: ");
2915		for (y = 0; y < 3; y++)
2916		{
2917		    for (x = 0; x < 3; x++)
2918			printf (" %f", XFixedToDouble (output->transform.transform.matrix[y][x]));
2919		    if (y < 2)
2920			printf ("\n\t           ");
2921		}
2922		if (output->transform.filter)
2923		    printf ("\n\t           filter: %s", output->transform.filter);
2924		printf ("\n");
2925	    }
2926	    if (verbose || properties)
2927	    {
2928		props = XRRListOutputProperties (dpy, output->output.xid,
2929						 &nprop);
2930		for (j = 0; j < nprop; j++) {
2931		    unsigned char *prop;
2932		    int actual_format;
2933		    unsigned long nitems, bytes_after;
2934		    Atom actual_type;
2935		    XRRPropertyInfo *propinfo;
2936
2937		    XRRGetOutputProperty (dpy, output->output.xid, props[j],
2938					  0, 100, False, False,
2939					  AnyPropertyType,
2940					  &actual_type, &actual_format,
2941					  &nitems, &bytes_after, &prop);
2942
2943		    propinfo = XRRQueryOutputProperty(dpy, output->output.xid,
2944						      props[j]);
2945
2946		    if (actual_type == XA_INTEGER && actual_format == 8) {
2947			int k;
2948
2949			printf("\t%s:\n", XGetAtomName (dpy, props[j]));
2950			for (k = 0; k < nitems; k++) {
2951			    if (k % 16 == 0)
2952				printf ("\t\t");
2953			    printf("%02x", (unsigned char)prop[k]);
2954			    if (k % 16 == 15)
2955				printf("\n");
2956			}
2957		    } else if (actual_type == XA_INTEGER &&
2958			       actual_format == 32)
2959		    {
2960			printf("\t%s: ", XGetAtomName (dpy, props[j]));
2961			for (k = 0; k < nitems; k++) {
2962			    if (k > 0)
2963				printf ("\n\t\t\t");
2964			    printf("%d (0x%08x)",
2965				   (int)((INT32 *)prop)[k], (int)((INT32 *)prop)[k]);
2966			}
2967
2968 			if (propinfo->range && propinfo->num_values > 0) {
2969			    if (nitems > 1)
2970				printf ("\n\t\t");
2971			    printf("\trange%s: ",
2972				   (propinfo->num_values == 2) ? "" : "s");
2973
2974			    for (k = 0; k < propinfo->num_values / 2; k++)
2975				printf(" (%d,%d)", (int)propinfo->values[k * 2],
2976				       (int)propinfo->values[k * 2 + 1]);
2977			}
2978
2979			printf("\n");
2980		    } else if (actual_type == XA_ATOM &&
2981			       actual_format == 32)
2982		    {
2983			printf("\t%s:", XGetAtomName (dpy, props[j]));
2984			for (k = 0; k < nitems; k++) {
2985			    if (k > 0 && (k & 1) == 0)
2986				printf ("\n\t\t");
2987			    printf("\t%s", XGetAtomName (dpy, ((Atom *)prop)[k]));
2988			}
2989
2990 			if (!propinfo->range && propinfo->num_values > 0) {
2991			    printf("\n\t\tsupported:");
2992
2993			    for (k = 0; k < propinfo->num_values; k++)
2994			    {
2995				printf(" %-12.12s", XGetAtomName (dpy,
2996							    propinfo->values[k]));
2997				if (k % 4 == 3 && k < propinfo->num_values - 1)
2998				    printf ("\n\t\t          ");
2999			    }
3000			}
3001			printf("\n");
3002		    } else if (actual_format == 8) {
3003			printf ("\t%s: %s%s\n", XGetAtomName (dpy, props[j]),
3004				prop, bytes_after ? "..." : "");
3005		    } else {
3006			char	*type = actual_type ? XGetAtomName (dpy, actual_type) : "none";
3007			printf ("\t%s: %s(%d) (format %d items %d) ????\n",
3008				XGetAtomName (dpy, props[j]),
3009				type, (int)actual_type, actual_format, (int)nitems);
3010		    }
3011
3012		    free(propinfo);
3013		}
3014	    }
3015
3016	    if (verbose)
3017	    {
3018		for (j = 0; j < output_info->nmode; j++)
3019		{
3020		    XRRModeInfo	*mode = find_mode_by_xid (output_info->modes[j]);
3021		    int		f;
3022
3023		    printf ("  %s (0x%x) %6.1fMHz",
3024			    mode->name, (int)mode->id,
3025			    (float)mode->dotClock / 1000000.0);
3026		    for (f = 0; mode_flags[f].flag; f++)
3027			if (mode->modeFlags & mode_flags[f].flag)
3028			    printf (" %s", mode_flags[f].string);
3029		    if (mode == output->mode_info)
3030			printf (" *current");
3031		    if (j < output_info->npreferred)
3032			printf (" +preferred");
3033		    printf ("\n");
3034		    printf ("        h: width  %4d start %4d end %4d total %4d skew %4d clock %6.1fKHz\n",
3035			    mode->width, mode->hSyncStart, mode->hSyncEnd,
3036			    mode->hTotal, mode->hSkew, mode_hsync (mode) / 1000);
3037		    printf ("        v: height %4d start %4d end %4d total %4d           clock %6.1fHz\n",
3038			    mode->height, mode->vSyncStart, mode->vSyncEnd, mode->vTotal,
3039			    mode_refresh (mode));
3040		    mode->modeFlags |= ModeShown;
3041		}
3042	    }
3043	    else
3044	    {
3045		mode_shown = calloc (output_info->nmode, sizeof (Bool));
3046		if (!mode_shown) fatal ("out of memory\n");
3047		for (j = 0; j < output_info->nmode; j++)
3048		{
3049		    XRRModeInfo *jmode, *kmode;
3050
3051		    if (mode_shown[j]) continue;
3052
3053		    jmode = find_mode_by_xid (output_info->modes[j]);
3054		    printf (" ");
3055		    printf ("  %-12s", jmode->name);
3056		    for (k = j; k < output_info->nmode; k++)
3057		    {
3058			if (mode_shown[k]) continue;
3059			kmode = find_mode_by_xid (output_info->modes[k]);
3060			if (strcmp (jmode->name, kmode->name) != 0) continue;
3061			mode_shown[k] = True;
3062			kmode->modeFlags |= ModeShown;
3063			printf (" %6.1f", mode_refresh (kmode));
3064			if (kmode == output->mode_info)
3065			    printf ("*");
3066			else
3067			    printf (" ");
3068			if (k < output_info->npreferred)
3069			    printf ("+");
3070			else
3071			    printf (" ");
3072		    }
3073		    printf ("\n");
3074		}
3075		free (mode_shown);
3076	    }
3077	}
3078	for (m = 0; m < res->nmode; m++)
3079	{
3080	    XRRModeInfo	*mode = &res->modes[m];
3081
3082	    if (!(mode->modeFlags & ModeShown))
3083	    {
3084		printf ("  %s (0x%x) %6.1fMHz\n",
3085			mode->name, (int)mode->id,
3086			(float)mode->dotClock / 1000000.0);
3087		printf ("        h: width  %4d start %4d end %4d total %4d skew %4d clock %6.1fKHz\n",
3088			mode->width, mode->hSyncStart, mode->hSyncEnd,
3089			mode->hTotal, mode->hSkew, mode_hsync (mode) / 1000);
3090		printf ("        v: height %4d start %4d end %4d total %4d           clock %6.1fHz\n",
3091			mode->height, mode->vSyncStart, mode->vSyncEnd, mode->vTotal,
3092			mode_refresh (mode));
3093	    }
3094	}
3095	exit (0);
3096    }
3097#endif
3098
3099    sc = XRRGetScreenInfo (dpy, root);
3100
3101    if (sc == NULL)
3102	exit (1);
3103
3104    current_size = XRRConfigCurrentConfiguration (sc, &current_rotation);
3105
3106    sizes = XRRConfigSizes(sc, &nsize);
3107
3108    if (have_pixel_size) {
3109	for (size = 0; size < nsize; size++)
3110	{
3111	    if (sizes[size].width == width && sizes[size].height == height)
3112		break;
3113	}
3114	if (size >= nsize) {
3115	    fprintf (stderr,
3116		     "Size %dx%d not found in available modes\n", width, height);
3117	    exit (1);
3118	}
3119    }
3120    else if (size < 0)
3121	size = current_size;
3122    else if (size >= nsize) {
3123	fprintf (stderr,
3124		 "Size index %d is too large, there are only %d sizes\n",
3125		 size, nsize);
3126	exit (1);
3127    }
3128
3129    if (rot < 0)
3130    {
3131	for (rot = 0; rot < 4; rot++)
3132	    if (1 << rot == (current_rotation & 0xf))
3133		break;
3134    }
3135
3136    current_rate = XRRConfigCurrentRate (sc);
3137
3138    if (rate < 0)
3139    {
3140	if (size == current_size)
3141	    rate = current_rate;
3142	else
3143	    rate = 0;
3144    }
3145    else
3146    {
3147	rates = XRRConfigRates (sc, size, &nrate);
3148	for (i = 0; i < nrate; i++)
3149	    if (rate == rates[i])
3150		break;
3151	if (i == nrate) {
3152	    fprintf (stderr, "Rate %.1f Hz not available for this size\n", rate);
3153	    exit (1);
3154	}
3155    }
3156
3157    if (version) {
3158	int major_version, minor_version;
3159	XRRQueryVersion (dpy, &major_version, &minor_version);
3160	printf("Server reports RandR version %d.%d\n",
3161	       major_version, minor_version);
3162    }
3163
3164    if (query || query_1) {
3165	printf(" SZ:    Pixels          Physical       Refresh\n");
3166	for (i = 0; i < nsize; i++) {
3167	    printf ("%c%-2d %5d x %-5d  (%4dmm x%4dmm )",
3168		    i == current_size ? '*' : ' ',
3169		    i, sizes[i].width, sizes[i].height,
3170		    sizes[i].mwidth, sizes[i].mheight);
3171	    rates = XRRConfigRates (sc, i, &nrate);
3172	    if (nrate) printf ("  ");
3173	    for (j = 0; j < nrate; j++)
3174		printf ("%c%-4d",
3175			i == current_size && rates[j] == current_rate ? '*' : ' ',
3176			rates[j]);
3177	    printf ("\n");
3178	}
3179    }
3180
3181    rotations = XRRConfigRotations(sc, &current_rotation);
3182
3183    rotation = 1 << rot ;
3184    if (query) {
3185    	printf("Current rotation - %s\n",
3186	       rotation_name (current_rotation));
3187
3188	printf("Current reflection - %s\n",
3189	       reflection_name (current_rotation));
3190
3191	printf ("Rotations possible - ");
3192	for (i = 0; i < 4; i ++) {
3193	    if ((rotations >> i) & 1)  printf("%s ", direction[i]);
3194	}
3195	printf ("\n");
3196
3197	printf ("Reflections possible - ");
3198	if (rotations & (RR_Reflect_X|RR_Reflect_Y))
3199	{
3200	    if (rotations & RR_Reflect_X) printf ("X Axis ");
3201	    if (rotations & RR_Reflect_Y) printf ("Y Axis");
3202	}
3203	else
3204	    printf ("none");
3205	printf ("\n");
3206    }
3207
3208    if (verbose) {
3209	printf("Setting size to %d, rotation to %s\n",  size, direction[rot]);
3210
3211	printf ("Setting reflection on ");
3212	if (reflection)
3213	{
3214	    if (reflection & RR_Reflect_X) printf ("X Axis ");
3215	    if (reflection & RR_Reflect_Y) printf ("Y Axis");
3216	}
3217	else
3218	    printf ("neither axis");
3219	printf ("\n");
3220
3221	if (reflection & RR_Reflect_X) printf("Setting reflection on X axis\n");
3222
3223	if (reflection & RR_Reflect_Y) printf("Setting reflection on Y axis\n");
3224    }
3225
3226    /* we should test configureNotify on the root window */
3227    XSelectInput (dpy, root, StructureNotifyMask);
3228
3229    if (setit && !dryrun) XRRSelectInput (dpy, root,
3230			       RRScreenChangeNotifyMask);
3231    if (setit && !dryrun) status = XRRSetScreenConfigAndRate (dpy, sc,
3232						   root,
3233						   (SizeID) size, (Rotation) (rotation | reflection), rate, CurrentTime);
3234
3235    XRRQueryExtension(dpy, &event_base, &error_base);
3236
3237    if (setit && !dryrun && status == RRSetConfigFailed) {
3238	printf ("Failed to change the screen configuration!\n");
3239	ret = 1;
3240    }
3241
3242    if (verbose && setit && !dryrun && size != current_size) {
3243	if (status == RRSetConfigSuccess)
3244	{
3245	    Bool    seen_screen = False;
3246	    while (!seen_screen) {
3247		int spo;
3248		XNextEvent(dpy, (XEvent *) &event);
3249
3250		printf ("Event received, type = %d\n", event.type);
3251		/* update Xlib's knowledge of the event */
3252		XRRUpdateConfiguration (&event);
3253		if (event.type == ConfigureNotify)
3254		    printf("Received ConfigureNotify Event!\n");
3255
3256		switch (event.type - event_base) {
3257		case RRScreenChangeNotify:
3258		    sce = (XRRScreenChangeNotifyEvent *) &event;
3259
3260		    printf("Got a screen change notify event!\n");
3261		    printf(" window = %d\n root = %d\n size_index = %d\n rotation %d\n",
3262			   (int) sce->window, (int) sce->root,
3263			   sce->size_index,  sce->rotation);
3264		    printf(" timestamp = %ld, config_timestamp = %ld\n",
3265			   sce->timestamp, sce->config_timestamp);
3266		    printf(" Rotation = %x\n", sce->rotation);
3267		    printf(" %d X %d pixels, %d X %d mm\n",
3268			   sce->width, sce->height, sce->mwidth, sce->mheight);
3269		    printf("Display width   %d, height   %d\n",
3270			   DisplayWidth(dpy, screen), DisplayHeight(dpy, screen));
3271		    printf("Display widthmm %d, heightmm %d\n",
3272			   DisplayWidthMM(dpy, screen), DisplayHeightMM(dpy, screen));
3273		    spo = sce->subpixel_order;
3274		    if ((spo < 0) || (spo > 5))
3275			printf ("Unknown subpixel order, value = %d\n", spo);
3276		    else printf ("new Subpixel rendering model is %s\n", order[spo]);
3277		    seen_screen = True;
3278		    break;
3279		default:
3280		    if (event.type != ConfigureNotify)
3281			printf("unknown event received, type = %d!\n", event.type);
3282		}
3283	    }
3284	}
3285    }
3286    XRRFreeScreenConfigInfo(sc);
3287    return(ret);
3288}
3289