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