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