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