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