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