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