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