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