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