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