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