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