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