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