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