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