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