1806e64b2f2835ec8464f49a212d23b5b0e23a85
[framework/graphics/cairo.git] / src / cairo-xlib-surface.c
1 /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright © 2002 University of Southern California
5  * Copyright © 2005 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it either under the terms of the GNU Lesser General Public
9  * License version 2.1 as published by the Free Software Foundation
10  * (the "LGPL") or, at your option, under the terms of the Mozilla
11  * Public License Version 1.1 (the "MPL"). If you do not alter this
12  * notice, a recipient may use your version of this file under either
13  * the MPL or the LGPL.
14  *
15  * You should have received a copy of the LGPL along with this library
16  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
18  * You should have received a copy of the MPL along with this library
19  * in the file COPYING-MPL-1.1
20  *
21  * The contents of this file are subject to the Mozilla Public License
22  * Version 1.1 (the "License"); you may not use this file except in
23  * compliance with the License. You may obtain a copy of the License at
24  * http://www.mozilla.org/MPL/
25  *
26  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
27  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
28  * the specific language governing rights and limitations.
29  *
30  * The Original Code is the cairo graphics library.
31  *
32  * The Initial Developer of the Original Code is University of Southern
33  * California.
34  *
35  * Contributor(s):
36  *      Carl D. Worth <cworth@cworth.org>
37  *      Behdad Esfahbod <behdad@behdad.org>
38  *      Chris Wilson <chris@chris-wilson.co.uk>
39  *      Karl Tomlinson <karlt+@karlt.net>, Mozilla Corporation
40  */
41
42 /* Heed well the words of Owen Taylor:
43  * "Any patch that works around a render bug, or claims to, without a
44  * specific reference to the bug filed in bugzilla.freedesktop.org will
45  * never pass approval."
46  */
47
48 #include "cairoint.h"
49
50 #if !CAIRO_HAS_XLIB_XCB_FUNCTIONS
51
52 #include "cairo-xlib-private.h"
53 #include "cairo-xlib-surface-private.h"
54
55 #include "cairo-compositor-private.h"
56 #include "cairo-clip-private.h"
57 #include "cairo-default-context-private.h"
58 #include "cairo-error-private.h"
59 #include "cairo-image-surface-private.h"
60 #include "cairo-pattern-private.h"
61 #include "cairo-region-private.h"
62 #include "cairo-scaled-font-private.h"
63 #include "cairo-surface-snapshot-private.h"
64 #include "cairo-surface-subsurface-private.h"
65
66 #include <X11/Xutil.h> /* for XDestroyImage */
67
68 #define XLIB_COORD_MAX 32767
69
70 #define DEBUG 0
71
72 #if DEBUG
73 #define UNSUPPORTED(reason) \
74     fprintf (stderr, \
75              "cairo-xlib: hit unsupported operation %s(), line %d: %s\n", \
76              __FUNCTION__, __LINE__, reason), \
77     CAIRO_INT_STATUS_UNSUPPORTED
78 #else
79 #define UNSUPPORTED(reason) CAIRO_INT_STATUS_UNSUPPORTED
80 #endif
81
82 #if DEBUG
83 #include <X11/Xlibint.h>
84 static void CAIRO_PRINTF_FORMAT (2, 3)
85 _x_bread_crumb (Display *dpy,
86                 const char *fmt,
87                 ...)
88 {
89     xReq *req;
90     char buf[2048];
91     unsigned int len, len_dwords;
92     va_list ap;
93
94     va_start (ap, fmt);
95     len = vsnprintf (buf, sizeof (buf), fmt, ap);
96     va_end (ap);
97
98     buf[len++] = '\0';
99     while (len & 3)
100         buf[len++] = '\0';
101
102     LockDisplay (dpy);
103     GetEmptyReq (NoOperation, req);
104
105     len_dwords = len >> 2;
106     SetReqLen (req, len_dwords, len_dwords);
107     Data (dpy, buf, len);
108
109     UnlockDisplay (dpy);
110     SyncHandle ();
111 }
112 #define X_DEBUG(x) _x_bread_crumb x
113 #else
114 #define X_DEBUG(x)
115 #endif
116
117 /**
118  * SECTION:cairo-xlib
119  * @Title: XLib Surfaces
120  * @Short_Description: X Window System rendering using XLib
121  * @See_Also: #cairo_surface_t
122  *
123  * The XLib surface is used to render cairo graphics to X Window System
124  * windows and pixmaps using the XLib library.
125  *
126  * Note that the XLib surface automatically takes advantage of X render extension
127  * if it is available.
128  */
129
130 /**
131  * CAIRO_HAS_XLIB_SURFACE:
132  *
133  * Defined if the Xlib surface backend is available.
134  * This macro can be used to conditionally compile backend-specific code.
135  */
136
137 /**
138  * SECTION:cairo-xlib-xrender
139  * @Title: XLib/XRender Backend
140  * @Short_Description: X Window System rendering using XLib and the X Render extension
141  * @See_Also: #cairo_surface_t
142  *
143  * The XLib surface is used to render cairo graphics to X Window System
144  * windows and pixmaps using the XLib and Xrender libraries.
145  *
146  * Note that the XLib surface automatically takes advantage of X Render extension
147  * if it is available.
148  */
149
150 /**
151  * CAIRO_HAS_XLIB_XRENDER_SURFACE:
152  *
153  * Defined if the XLib/XRender surface functions are available.
154  * This macro can be used to conditionally compile backend-specific code.
155  */
156
157 /* Xlib doesn't define a typedef, so define one ourselves */
158 typedef int (*cairo_xlib_error_func_t) (Display     *display,
159                                         XErrorEvent *event);
160
161 static cairo_surface_t *
162 _cairo_xlib_surface_create_internal (cairo_xlib_screen_t        *screen,
163                                      Drawable                   drawable,
164                                      Visual                    *visual,
165                                      XRenderPictFormat         *xrender_format,
166                                      int                        width,
167                                      int                        height,
168                                      int                        depth);
169
170 static cairo_bool_t
171 _cairo_surface_is_xlib (cairo_surface_t *surface);
172
173 /*
174  * Instead of taking two round trips for each blending request,
175  * assume that if a particular drawable fails GetImage that it will
176  * fail for a "while"; use temporary pixmaps to avoid the errors
177  */
178
179 #define CAIRO_ASSUME_PIXMAP     20
180
181 static const XTransform identity = { {
182     { 1 << 16, 0x00000, 0x00000 },
183     { 0x00000, 1 << 16, 0x00000 },
184     { 0x00000, 0x00000, 1 << 16 },
185 } };
186
187 static Visual *
188 _visual_for_xrender_format(Screen *screen,
189                            XRenderPictFormat *xrender_format)
190 {
191     int d, v;
192
193     /* XXX Consider searching through the list of known cairo_visual_t for
194      * the reverse mapping.
195      */
196
197     for (d = 0; d < screen->ndepths; d++) {
198         Depth *d_info = &screen->depths[d];
199
200         if (d_info->depth != xrender_format->depth)
201             continue;
202
203         for (v = 0; v < d_info->nvisuals; v++) {
204             Visual *visual = &d_info->visuals[v];
205
206             switch (visual->class) {
207             case TrueColor:
208                 if (xrender_format->type != PictTypeDirect)
209                     continue;
210                 break;
211
212             case DirectColor:
213                 /* Prefer TrueColor to DirectColor.
214                  * (XRenderFindVisualFormat considers both TrueColor and DirectColor
215                  * Visuals to match the same PictFormat.)
216                  */
217                 continue;
218
219             case StaticGray:
220             case GrayScale:
221             case StaticColor:
222             case PseudoColor:
223                 if (xrender_format->type != PictTypeIndexed)
224                     continue;
225                 break;
226             }
227
228             if (xrender_format ==
229                 XRenderFindVisualFormat (DisplayOfScreen(screen), visual))
230                 return visual;
231         }
232     }
233
234     return NULL;
235 }
236
237 static cairo_content_t
238 _xrender_format_to_content (XRenderPictFormat *xrender_format)
239 {
240     cairo_bool_t xrender_format_has_alpha;
241     cairo_bool_t xrender_format_has_color;
242
243     /* This only happens when using a non-Render server. Let's punt
244      * and say there's no alpha here. */
245     if (xrender_format == NULL)
246         return CAIRO_CONTENT_COLOR;
247
248     xrender_format_has_alpha = (xrender_format->direct.alphaMask != 0);
249     xrender_format_has_color = (xrender_format->direct.redMask   != 0 ||
250                                 xrender_format->direct.greenMask != 0 ||
251                                 xrender_format->direct.blueMask  != 0);
252
253     if (xrender_format_has_alpha)
254         if (xrender_format_has_color)
255             return CAIRO_CONTENT_COLOR_ALPHA;
256         else
257             return CAIRO_CONTENT_ALPHA;
258     else
259         return CAIRO_CONTENT_COLOR;
260 }
261
262 static cairo_surface_t *
263 _cairo_xlib_surface_create_similar (void               *abstract_src,
264                                     cairo_content_t     content,
265                                     int                 width,
266                                     int                 height)
267 {
268     cairo_xlib_surface_t *src = abstract_src;
269     XRenderPictFormat *xrender_format;
270     cairo_xlib_surface_t *surface;
271     cairo_xlib_display_t *display;
272     Pixmap pix;
273
274     if (width > XLIB_COORD_MAX || height > XLIB_COORD_MAX)
275         return NULL;
276
277     if (width == 0 || height == 0)
278         return NULL;
279
280     if (_cairo_xlib_display_acquire (src->base.device, &display))
281         return NULL;
282
283     /* If we never found an XRenderFormat or if it isn't compatible
284      * with the content being requested, then we fallback to just
285      * constructing a cairo_format_t instead, (which will fairly
286      * arbitrarily pick a visual/depth for the similar surface.
287      */
288     xrender_format = NULL;
289     if (src->xrender_format &&
290         _xrender_format_to_content (src->xrender_format) == content)
291     {
292         xrender_format = src->xrender_format;
293     }
294     if (xrender_format == NULL) {
295         xrender_format =
296             _cairo_xlib_display_get_xrender_format (display,
297                                                     _cairo_format_from_content (content));
298     }
299     if (xrender_format) {
300         Visual *visual;
301
302         /* We've got a compatible XRenderFormat now, which means the
303          * similar surface will match the existing surface as closely in
304          * visual/depth etc. as possible. */
305         pix = XCreatePixmap (display->display, src->drawable,
306                              width, height, xrender_format->depth);
307
308         if (xrender_format == src->xrender_format)
309             visual = src->visual;
310         else
311             visual = _visual_for_xrender_format(src->screen->screen,
312                                                 xrender_format);
313
314         surface = (cairo_xlib_surface_t *)
315                   _cairo_xlib_surface_create_internal (src->screen, pix, visual,
316                                                        xrender_format,
317                                                        width, height,
318                                                        xrender_format->depth);
319     }
320     else
321     {
322         Screen *screen = src->screen->screen;
323         int depth;
324
325         /* No compatabile XRenderFormat, see if we can make an ordinary pixmap,
326          * so that we can still accelerate blits with XCopyArea(). */
327         if (content != CAIRO_CONTENT_COLOR) {
328             cairo_device_release (&display->base);
329             return NULL;
330         }
331
332         depth = DefaultDepthOfScreen (screen);
333
334         pix = XCreatePixmap (display->display, RootWindowOfScreen (screen),
335                              width <= 0 ? 1 : width, height <= 0 ? 1 : height,
336                              depth);
337
338         surface = (cairo_xlib_surface_t *)
339                   _cairo_xlib_surface_create_internal (src->screen, pix,
340                                                        DefaultVisualOfScreen (screen),
341                                                        NULL,
342                                                        width, height, depth);
343     }
344
345     if (likely (surface->base.status == CAIRO_STATUS_SUCCESS))
346         surface->owns_pixmap = TRUE;
347     else
348         XFreePixmap (display->display, pix);
349
350     cairo_device_release (&display->base);
351
352     return &surface->base;
353 }
354
355 static cairo_status_t
356 _cairo_xlib_surface_finish (void *abstract_surface)
357 {
358     cairo_xlib_surface_t *surface = abstract_surface;
359     cairo_status_t        status;
360     cairo_xlib_display_t *display;
361
362     X_DEBUG ((display->display, "finish (drawable=%x)", (unsigned int) surface->drawable));
363
364     cairo_list_del (&surface->link);
365
366     status = _cairo_xlib_display_acquire (surface->base.device, &display);
367     if (unlikely (status))
368         return status;
369
370     if (surface->embedded_source.picture)
371         XRenderFreePicture (display->display, surface->embedded_source.picture);
372     if (surface->picture)
373         XRenderFreePicture (display->display, surface->picture);
374     if (surface->owns_pixmap)
375         XFreePixmap (display->display, surface->drawable);
376
377     cairo_device_release (&display->base);
378
379     return status;
380 }
381
382 cairo_status_t
383 _cairo_xlib_surface_get_gc (cairo_xlib_display_t *display,
384                             cairo_xlib_surface_t *surface,
385                             GC                   *gc)
386 {
387     *gc = _cairo_xlib_screen_get_gc (display,
388                                      surface->screen,
389                                      surface->depth,
390                                      surface->drawable);
391     if (unlikely (*gc == NULL))
392         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
393
394     return CAIRO_STATUS_SUCCESS;
395 }
396
397 static int
398 _noop_error_handler (Display     *display,
399                      XErrorEvent *event)
400 {
401     return False;               /* return value is ignored */
402 }
403
404 static void
405 _swap_ximage_2bytes (XImage *ximage)
406 {
407     int i, j;
408     char *line = ximage->data;
409
410     for (j = ximage->height; j; j--) {
411         uint16_t *p = (uint16_t *) line;
412         for (i = ximage->width; i; i--) {
413             *p = bswap_16 (*p);
414             p++;
415         }
416
417         line += ximage->bytes_per_line;
418     }
419 }
420
421 static void
422 _swap_ximage_3bytes (XImage *ximage)
423 {
424     int i, j;
425     char *line = ximage->data;
426
427     for (j = ximage->height; j; j--) {
428         uint8_t *p = (uint8_t *) line;
429         for (i = ximage->width; i; i--) {
430             uint8_t tmp;
431             tmp = p[2];
432             p[2] = p[0];
433             p[0] = tmp;
434             p += 3;
435         }
436
437         line += ximage->bytes_per_line;
438     }
439 }
440
441 static void
442 _swap_ximage_4bytes (XImage *ximage)
443 {
444     int i, j;
445     char *line = ximage->data;
446
447     for (j = ximage->height; j; j--) {
448         uint32_t *p = (uint32_t *) line;
449         for (i = ximage->width; i; i--) {
450             *p = bswap_32 (*p);
451             p++;
452         }
453
454         line += ximage->bytes_per_line;
455     }
456 }
457
458 static void
459 _swap_ximage_nibbles (XImage *ximage)
460 {
461     int i, j;
462     char *line = ximage->data;
463
464     for (j = ximage->height; j; j--) {
465         uint8_t *p = (uint8_t *) line;
466         for (i = (ximage->width + 1) / 2; i; i--) {
467             *p = ((*p >> 4) & 0xf) | ((*p << 4) & ~0xf);
468             p++;
469         }
470
471         line += ximage->bytes_per_line;
472     }
473 }
474
475 static void
476 _swap_ximage_bits (XImage *ximage)
477 {
478     int i, j;
479     char *line = ximage->data;
480     int unit = ximage->bitmap_unit;
481     int line_bytes = ((ximage->width + unit - 1) & ~(unit - 1)) / 8;
482
483     for (j = ximage->height; j; j--) {
484         char *p = line;
485
486         for (i = line_bytes; i; i--) {
487             char b = *p;
488             b = ((b << 1) & 0xaa) | ((b >> 1) & 0x55);
489             b = ((b << 2) & 0xcc) | ((b >> 2) & 0x33);
490             b = ((b << 4) & 0xf0) | ((b >> 4) & 0x0f);
491             *p = b;
492
493             p++;
494         }
495
496         line += ximage->bytes_per_line;
497     }
498 }
499
500 static void
501 _swap_ximage_to_native (XImage *ximage)
502 {
503     int unit_bytes = 0;
504     int native_byte_order = _cairo_is_little_endian () ? LSBFirst : MSBFirst;
505
506     if (ximage->bits_per_pixel == 1 &&
507         ximage->bitmap_bit_order != native_byte_order)
508     {
509         _swap_ximage_bits (ximage);
510         if (ximage->bitmap_bit_order == ximage->byte_order)
511             return;
512     }
513
514     if (ximage->byte_order == native_byte_order)
515         return;
516
517     switch (ximage->bits_per_pixel) {
518     case 1:
519         unit_bytes = ximage->bitmap_unit / 8;
520         break;
521     case 4:
522         _swap_ximage_nibbles (ximage);
523         /* fall-through */
524     case 8:
525     case 16:
526     case 20:
527     case 24:
528     case 28:
529     case 30:
530     case 32:
531         unit_bytes = (ximage->bits_per_pixel + 7) / 8;
532         break;
533     default:
534         /* This could be hit on some rare but possible cases. */
535         ASSERT_NOT_REACHED;
536     }
537
538     switch (unit_bytes) {
539     case 1:
540         break;
541     case 2:
542         _swap_ximage_2bytes (ximage);
543         break;
544     case 3:
545         _swap_ximage_3bytes (ximage);
546         break;
547     case 4:
548         _swap_ximage_4bytes (ximage);
549         break;
550     default:
551         ASSERT_NOT_REACHED;
552     }
553 }
554
555
556 /* Given a mask, (with a single sequence of contiguous 1 bits), return
557  * the number of 1 bits in 'width' and the number of 0 bits to its
558  * right in 'shift'. */
559 static void
560 _characterize_field (uint32_t mask, int *width, int *shift)
561 {
562     *width = _cairo_popcount (mask);
563     /* The final '& 31' is to force a 0 mask to result in 0 shift. */
564     *shift = _cairo_popcount ((mask - 1) & ~mask) & 31;
565 }
566
567 /* Convert a field of 'width' bits to 'new_width' bits with correct
568  * rounding. */
569 static inline uint32_t
570 _resize_field (uint32_t field, int width, int new_width)
571 {
572     if (width == 0)
573         return 0;
574
575     if (width >= new_width) {
576         return field >> (width - new_width);
577     } else {
578         uint32_t result = field << (new_width - width);
579
580         while (width < new_width) {
581             result |= result >> width;
582             width <<= 1;
583         }
584         return result;
585     }
586 }
587
588 static inline uint32_t
589 _adjust_field (uint32_t field, int adjustment)
590 {
591     return MIN (255, MAX(0, (int)field + adjustment));
592 }
593
594 /* Given a shifted field value, (described by 'width' and 'shift),
595  * resize it 8-bits and return that value.
596  *
597  * Note that the original field value must not have any non-field bits
598  * set.
599  */
600 static inline uint32_t
601 _field_to_8 (uint32_t field, int width, int shift)
602 {
603     return _resize_field (field >> shift, width, 8);
604 }
605
606 static inline uint32_t
607 _field_to_8_undither (uint32_t field, int width, int shift,
608                       int dither_adjustment)
609 {
610     return _adjust_field (_field_to_8 (field, width, shift), - dither_adjustment>>width);
611 }
612
613 /* Given an 8-bit value, convert it to a field of 'width', shift it up
614  *  to 'shift, and return it. */
615 static inline uint32_t
616 _field_from_8 (uint32_t field, int width, int shift)
617 {
618     return _resize_field (field, 8, width) << shift;
619 }
620
621 static inline uint32_t
622 _field_from_8_dither (uint32_t field, int width, int shift,
623                       int8_t dither_adjustment)
624 {
625     return _field_from_8 (_adjust_field (field, dither_adjustment>>width), width, shift);
626 }
627
628 static inline uint32_t
629 _pseudocolor_from_rgb888_dither (cairo_xlib_visual_info_t *visual_info,
630                                  uint32_t r, uint32_t g, uint32_t b,
631                                  int8_t dither_adjustment)
632 {
633     if (r == g && g == b) {
634         dither_adjustment /= RAMP_SIZE;
635         return visual_info->gray8_to_pseudocolor[_adjust_field (r, dither_adjustment)];
636     } else {
637         dither_adjustment = visual_info->dither8_to_cube[dither_adjustment+128];
638         return visual_info->cube_to_pseudocolor[visual_info->field8_to_cube[_adjust_field (r, dither_adjustment)]]
639                                                [visual_info->field8_to_cube[_adjust_field (g, dither_adjustment)]]
640                                                [visual_info->field8_to_cube[_adjust_field (b, dither_adjustment)]];
641     }
642 }
643
644 static inline uint32_t
645 _pseudocolor_to_rgb888 (cairo_xlib_visual_info_t *visual_info,
646                         uint32_t pixel)
647 {
648     uint32_t r, g, b;
649     pixel &= 0xff;
650     r = visual_info->colors[pixel].r;
651     g = visual_info->colors[pixel].g;
652     b = visual_info->colors[pixel].b;
653     return (r << 16) |
654            (g <<  8) |
655            (b      );
656 }
657
658 /* should range from -128 to 127 */
659 #define X 16
660 static const int8_t dither_pattern[4][4] = {
661     {-8*X, +0*X, -6*X, +2*X},
662     {+4*X, -4*X, +6*X, -2*X},
663     {-5*X, +4*X, -7*X, +1*X},
664     {+7*X, -1*X, +5*X, -3*X}
665 };
666 #undef X
667
668 static cairo_surface_t *
669 _get_image_surface (cairo_xlib_surface_t    *surface,
670                     const cairo_rectangle_int_t *extents)
671 {
672     cairo_int_status_t status;
673     cairo_image_surface_t *image = NULL;
674     XImage *ximage;
675     pixman_format_code_t pixman_format;
676     cairo_format_masks_t xlib_masks;
677     cairo_xlib_display_t *display;
678
679     assert (extents->x >= 0);
680     assert (extents->y >= 0);
681     assert (extents->x + extents->width <= surface->width);
682     assert (extents->y + extents->height <= surface->height);
683
684     if (surface->base.serial == 0) {
685         xlib_masks.bpp = (surface->depth + 7) & ~7;
686         xlib_masks.alpha_mask = surface->a_mask;
687         xlib_masks.red_mask = surface->r_mask;
688         xlib_masks.green_mask = surface->g_mask;
689         xlib_masks.blue_mask = surface->b_mask;
690         _pixman_format_from_masks (&xlib_masks, &pixman_format);
691         return _cairo_image_surface_create_with_pixman_format (NULL,
692                                                                pixman_format,
693                                                                extents->width,
694                                                                extents->height,
695                                                                0);
696     }
697
698     status = _cairo_xlib_display_acquire (surface->base.device, &display);
699     if (status)
700         return _cairo_surface_create_in_error (status);
701
702     /* XXX: This should try to use the XShm extension if available */
703
704     if (surface->use_pixmap == 0) {
705         cairo_xlib_error_func_t old_handler;
706
707         old_handler = XSetErrorHandler (_noop_error_handler);
708
709         ximage = XGetImage (display->display,
710                             surface->drawable,
711                             extents->x, extents->y,
712                             extents->width, extents->height,
713                             AllPlanes, ZPixmap);
714
715         XSetErrorHandler (old_handler);
716
717         /* If we get an error, the surface must have been a window,
718          * so retry with the safe code path.
719          */
720         if (!ximage)
721             surface->use_pixmap = CAIRO_ASSUME_PIXMAP;
722     } else {
723         surface->use_pixmap--;
724         ximage = NULL;
725     }
726
727     if (ximage == NULL) {
728         /* XGetImage from a window is dangerous because it can
729          * produce errors if the window is unmapped or partially
730          * outside the screen. We could check for errors and
731          * retry, but to keep things simple, we just create a
732          * temporary pixmap
733          */
734         Pixmap pixmap;
735         GC gc;
736
737         status = _cairo_xlib_surface_get_gc (display, surface, &gc);
738         if (unlikely (status))
739             goto BAIL;
740
741         pixmap = XCreatePixmap (display->display,
742                                 surface->drawable,
743                                 extents->width, extents->height,
744                                 surface->depth);
745         if (pixmap) {
746             XCopyArea (display->display, surface->drawable, pixmap, gc,
747                        extents->x, extents->y,
748                        extents->width, extents->height,
749                        0, 0);
750
751             ximage = XGetImage (display->display,
752                                 pixmap,
753                                 0, 0,
754                                 extents->width, extents->height,
755                                 AllPlanes, ZPixmap);
756
757             XFreePixmap (display->display, pixmap);
758         }
759
760         _cairo_xlib_surface_put_gc (display, surface, gc);
761
762         if (ximage == NULL) {
763             status =  _cairo_error (CAIRO_STATUS_NO_MEMORY);
764             goto BAIL;
765         }
766     }
767
768     _swap_ximage_to_native (ximage);
769
770     xlib_masks.bpp = ximage->bits_per_pixel;
771     xlib_masks.alpha_mask = surface->a_mask;
772     xlib_masks.red_mask = surface->r_mask;
773     xlib_masks.green_mask = surface->g_mask;
774     xlib_masks.blue_mask = surface->b_mask;
775
776     /* We can't use pixman to simply write to image if:
777      *   (a) the pixels are not appropriately aligned,
778      *   (b) pixman does not the pixel format, or
779      *   (c) if the image is palettized and we need to convert.
780      */
781     if (ximage->bitmap_unit == 32 && ximage->bitmap_pad == 32 &&
782         _pixman_format_from_masks (&xlib_masks, &pixman_format) &&
783         (surface->visual == NULL || surface->visual->class == TrueColor))
784     {
785         image = (cairo_image_surface_t*)
786             _cairo_image_surface_create_with_pixman_format ((unsigned char *) ximage->data,
787                                                             pixman_format,
788                                                             ximage->width,
789                                                             ximage->height,
790                                                             ximage->bytes_per_line);
791         status = image->base.status;
792         if (unlikely (status))
793             goto BAIL;
794
795         /* Let the surface take ownership of the data */
796         _cairo_image_surface_assume_ownership_of_data (image);
797         ximage->data = NULL;
798     } else {
799         /* The visual we are dealing with is not supported by the
800          * standard pixman formats. So we must first convert the data
801          * to a supported format. */
802
803         cairo_format_t format;
804         unsigned char *data;
805         uint32_t *row;
806         uint32_t in_pixel, out_pixel;
807         unsigned int rowstride;
808         uint32_t a_mask=0, r_mask=0, g_mask=0, b_mask=0;
809         int a_width=0, r_width=0, g_width=0, b_width=0;
810         int a_shift=0, r_shift=0, g_shift=0, b_shift=0;
811         int x, y, x0, y0, x_off, y_off;
812         cairo_xlib_visual_info_t *visual_info = NULL;
813
814         if (surface->visual == NULL || surface->visual->class == TrueColor) {
815             cairo_bool_t has_alpha;
816             cairo_bool_t has_color;
817
818             has_alpha =  surface->a_mask;
819             has_color = (surface->r_mask ||
820                          surface->g_mask ||
821                          surface->b_mask);
822
823             if (has_color) {
824                 if (has_alpha) {
825                     format = CAIRO_FORMAT_ARGB32;
826                 } else {
827                     format = CAIRO_FORMAT_RGB24;
828                 }
829             } else {
830                 /* XXX: Using CAIRO_FORMAT_A8 here would be more
831                  * efficient, but would require slightly different code in
832                  * the image conversion to put the alpha channel values
833                  * into the right place. */
834                 format = CAIRO_FORMAT_ARGB32;
835             }
836
837             a_mask = surface->a_mask;
838             r_mask = surface->r_mask;
839             g_mask = surface->g_mask;
840             b_mask = surface->b_mask;
841
842             _characterize_field (a_mask, &a_width, &a_shift);
843             _characterize_field (r_mask, &r_width, &r_shift);
844             _characterize_field (g_mask, &g_width, &g_shift);
845             _characterize_field (b_mask, &b_width, &b_shift);
846
847         } else {
848             format = CAIRO_FORMAT_RGB24;
849
850             status = _cairo_xlib_screen_get_visual_info (display,
851                                                          surface->screen,
852                                                          surface->visual,
853                                                          &visual_info);
854             if (unlikely (status))
855                 goto BAIL;
856         }
857
858         image = (cairo_image_surface_t *) cairo_image_surface_create
859             (format, ximage->width, ximage->height);
860         status = image->base.status;
861         if (unlikely (status))
862             goto BAIL;
863
864         data = cairo_image_surface_get_data (&image->base);
865         rowstride = cairo_image_surface_get_stride (&image->base) >> 2;
866         row = (uint32_t *) data;
867         x0 = extents->x + surface->base.device_transform.x0;
868         y0 = extents->y + surface->base.device_transform.y0;
869         for (y = 0, y_off = y0 % ARRAY_LENGTH (dither_pattern);
870              y < ximage->height;
871              y++, y_off = (y_off+1) % ARRAY_LENGTH (dither_pattern)) {
872             const int8_t *dither_row = dither_pattern[y_off];
873             for (x = 0, x_off = x0 % ARRAY_LENGTH (dither_pattern[0]);
874                  x < ximage->width;
875                  x++, x_off = (x_off+1) % ARRAY_LENGTH (dither_pattern[0])) {
876                 int dither_adjustment = dither_row[x_off];
877
878                 in_pixel = XGetPixel (ximage, x, y);
879                 if (visual_info == NULL) {
880                     out_pixel = (
881                         _field_to_8 (in_pixel & a_mask, a_width, a_shift) << 24 |
882                         _field_to_8_undither (in_pixel & r_mask, r_width, r_shift, dither_adjustment) << 16 |
883                         _field_to_8_undither (in_pixel & g_mask, g_width, g_shift, dither_adjustment) << 8 |
884                         _field_to_8_undither (in_pixel & b_mask, b_width, b_shift, dither_adjustment));
885                 } else {
886                     /* Undithering pseudocolor does not look better */
887                     out_pixel = _pseudocolor_to_rgb888 (visual_info, in_pixel);
888                 }
889                 row[x] = out_pixel;
890             }
891             row += rowstride;
892         }
893         cairo_surface_mark_dirty (&image->base);
894     }
895
896  BAIL:
897     if (ximage)
898         XDestroyImage (ximage);
899
900     cairo_device_release (&display->base);
901
902     if (unlikely (status)) {
903         cairo_surface_destroy (&image->base);
904         return _cairo_surface_create_in_error (status);
905     }
906
907     return &image->base;
908 }
909
910 void
911 _cairo_xlib_surface_set_precision (cairo_xlib_surface_t *surface,
912                                    cairo_antialias_t     antialias)
913 {
914     cairo_xlib_display_t        *display = surface->display;
915     int precision;
916
917     if (display->force_precision != -1)
918             precision = display->force_precision;
919     else switch (antialias) {
920     default:
921     case CAIRO_ANTIALIAS_DEFAULT:
922     case CAIRO_ANTIALIAS_GRAY:
923     case CAIRO_ANTIALIAS_NONE:
924     case CAIRO_ANTIALIAS_FAST:
925     case CAIRO_ANTIALIAS_GOOD:
926         precision = PolyModeImprecise;
927         break;
928     case CAIRO_ANTIALIAS_BEST:
929     case CAIRO_ANTIALIAS_SUBPIXEL:
930         precision = PolyModePrecise;
931         break;
932     }
933
934     if (surface->precision != precision) {
935         XRenderPictureAttributes pa;
936
937         pa.poly_mode = precision;
938         XRenderChangePicture (display->display, surface->picture,
939                               CPPolyMode, &pa);
940
941         surface->precision = precision;
942     }
943 }
944
945 void
946 _cairo_xlib_surface_ensure_picture (cairo_xlib_surface_t    *surface)
947 {
948     cairo_xlib_display_t *display = surface->display;
949     XRenderPictureAttributes pa;
950     int mask = 0;
951
952     if (surface->picture)
953         return;
954
955     if (display->force_precision != -1)
956         pa.poly_mode = display->force_precision;
957     else
958         pa.poly_mode = PolyModeImprecise;
959     if (pa.poly_mode)
960             mask |= CPPolyMode;
961
962     surface->precision = pa.poly_mode;
963     surface->picture = XRenderCreatePicture (display->display,
964                                              surface->drawable,
965                                              surface->xrender_format,
966                                              mask, &pa);
967 }
968
969 cairo_status_t
970 _cairo_xlib_surface_draw_image (cairo_xlib_surface_t   *surface,
971                                 cairo_image_surface_t  *image,
972                                 int                    src_x,
973                                 int                    src_y,
974                                 int                    width,
975                                 int                    height,
976                                 int                    dst_x,
977                                 int                    dst_y)
978 {
979     cairo_xlib_display_t *display;
980     XImage ximage;
981     cairo_format_masks_t image_masks;
982     int native_byte_order = _cairo_is_little_endian () ? LSBFirst : MSBFirst;
983     pixman_image_t *pixman_image = NULL;
984     cairo_status_t status;
985     cairo_bool_t own_data;
986     cairo_bool_t is_rgb_image;
987     GC gc;
988
989     ximage.width = image->width;
990     ximage.height = image->height;
991     ximage.format = ZPixmap;
992     ximage.byte_order = native_byte_order;
993     ximage.bitmap_unit = 32;    /* always for libpixman */
994     ximage.bitmap_bit_order = native_byte_order;
995     ximage.bitmap_pad = 32;     /* always for libpixman */
996     ximage.depth = surface->depth;
997     ximage.red_mask = surface->r_mask;
998     ximage.green_mask = surface->g_mask;
999     ximage.blue_mask = surface->b_mask;
1000     ximage.xoffset = 0;
1001
1002     status = _cairo_xlib_display_acquire (surface->base.device, &display);
1003     if (unlikely (status))
1004         return status;
1005
1006     is_rgb_image = _pixman_format_to_masks (image->pixman_format, &image_masks);
1007
1008     if (is_rgb_image &&
1009         (image_masks.alpha_mask == surface->a_mask || surface->a_mask == 0) &&
1010         (image_masks.red_mask   == surface->r_mask || surface->r_mask == 0) &&
1011         (image_masks.green_mask == surface->g_mask || surface->g_mask == 0) &&
1012         (image_masks.blue_mask  == surface->b_mask || surface->b_mask == 0))
1013     {
1014         int ret;
1015
1016         ximage.bits_per_pixel = image_masks.bpp;
1017         ximage.bytes_per_line = image->stride;
1018         ximage.data = (char *)image->data;
1019         own_data = FALSE;
1020
1021         ret = XInitImage (&ximage);
1022         assert (ret != 0);
1023     }
1024     else if (!is_rgb_image ||
1025              (surface->visual == NULL || surface->visual->class == TrueColor))
1026     {
1027         pixman_format_code_t intermediate_format;
1028         int ret;
1029
1030         image_masks.alpha_mask = surface->a_mask;
1031         image_masks.red_mask   = surface->r_mask;
1032         image_masks.green_mask = surface->g_mask;
1033         image_masks.blue_mask  = surface->b_mask;
1034         image_masks.bpp        = surface->depth;
1035         ret = _pixman_format_from_masks (&image_masks, &intermediate_format);
1036         assert (ret);
1037
1038         own_data = FALSE;
1039
1040         pixman_image = pixman_image_create_bits (intermediate_format,
1041                                                  image->width,
1042                                                  image->height,
1043                                                  NULL,
1044                                                  0);
1045         if (pixman_image == NULL) {
1046             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1047             goto BAIL;
1048         }
1049
1050         pixman_image_composite32 (PIXMAN_OP_SRC,
1051                                   image->pixman_image,
1052                                   NULL,
1053                                   pixman_image,
1054                                   0, 0,
1055                                   0, 0,
1056                                   0, 0,
1057                                   image->width, image->height);
1058
1059         ximage.bits_per_pixel = image_masks.bpp;
1060         ximage.data = (char *) pixman_image_get_data (pixman_image);
1061         ximage.bytes_per_line = pixman_image_get_stride (pixman_image);
1062
1063         ret = XInitImage (&ximage);
1064         assert (ret != 0);
1065     }
1066     else
1067     {
1068         unsigned int stride, rowstride;
1069         int x, y, x0, y0, x_off, y_off;
1070         uint32_t in_pixel, out_pixel, *row;
1071         int i_a_width=0, i_r_width=0, i_g_width=0, i_b_width=0;
1072         int i_a_shift=0, i_r_shift=0, i_g_shift=0, i_b_shift=0;
1073         int o_a_width=0, o_r_width=0, o_g_width=0, o_b_width=0;
1074         int o_a_shift=0, o_r_shift=0, o_g_shift=0, o_b_shift=0;
1075         cairo_xlib_visual_info_t *visual_info = NULL;
1076         cairo_bool_t true_color;
1077         int ret;
1078
1079         if (surface->depth > 16)
1080             ximage.bits_per_pixel = 32;
1081         else if (surface->depth > 8)
1082             ximage.bits_per_pixel = 16;
1083         else if (surface->depth > 1)
1084             ximage.bits_per_pixel = 8;
1085         else
1086             ximage.bits_per_pixel = 1;
1087         stride = CAIRO_STRIDE_FOR_WIDTH_BPP (ximage.width,
1088                                              ximage.bits_per_pixel);
1089         ximage.bytes_per_line = stride;
1090         ximage.data = _cairo_malloc_ab (stride, ximage.height);
1091         if (unlikely (ximage.data == NULL)) {
1092             own_data = FALSE;
1093             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1094             goto BAIL;
1095         }
1096
1097         own_data = TRUE;
1098
1099         ret = XInitImage (&ximage);
1100         assert (ret != 0);
1101
1102         _characterize_field (image_masks.alpha_mask, &i_a_width, &i_a_shift);
1103         _characterize_field (image_masks.red_mask  , &i_r_width, &i_r_shift);
1104         _characterize_field (image_masks.green_mask, &i_g_width, &i_g_shift);
1105         _characterize_field (image_masks.blue_mask , &i_b_width, &i_b_shift);
1106
1107         true_color = surface->visual == NULL ||
1108                      surface->visual->class == TrueColor;
1109         if (true_color) {
1110             _characterize_field (surface->a_mask, &o_a_width, &o_a_shift);
1111             _characterize_field (surface->r_mask, &o_r_width, &o_r_shift);
1112             _characterize_field (surface->g_mask, &o_g_width, &o_g_shift);
1113             _characterize_field (surface->b_mask, &o_b_width, &o_b_shift);
1114         } else {
1115             status = _cairo_xlib_screen_get_visual_info (display,
1116                                                          surface->screen,
1117                                                          surface->visual,
1118                                                          &visual_info);
1119             if (unlikely (status))
1120                 goto BAIL;
1121         }
1122
1123         rowstride = image->stride >> 2;
1124         row = (uint32_t *) image->data;
1125         x0 = dst_x + surface->base.device_transform.x0;
1126         y0 = dst_y + surface->base.device_transform.y0;
1127         for (y = 0, y_off = y0 % ARRAY_LENGTH (dither_pattern);
1128              y < ximage.height;
1129              y++, y_off = (y_off+1) % ARRAY_LENGTH (dither_pattern))
1130         {
1131             const int8_t *dither_row = dither_pattern[y_off];
1132
1133             for (x = 0, x_off = x0 % ARRAY_LENGTH (dither_pattern[0]);
1134                  x < ximage.width;
1135                  x++, x_off = (x_off+1) % ARRAY_LENGTH (dither_pattern[0]))
1136             {
1137                 int dither_adjustment = dither_row[x_off];
1138                 int a, r, g, b;
1139
1140                 if (image_masks.bpp == 1)
1141                     in_pixel = !! (((uint8_t*)row)[x/8] & (1 << (x & 7)));
1142                 else if (image_masks.bpp <= 8)
1143                     in_pixel = ((uint8_t*)row)[x];
1144                 else if (image_masks.bpp <= 16)
1145                     in_pixel = ((uint16_t*)row)[x];
1146                 else if (image_masks.bpp <= 24)
1147 #ifdef WORDS_BIGENDIAN
1148                     in_pixel = ((uint8_t*)row)[3 * x]     << 16 |
1149                                ((uint8_t*)row)[3 * x + 1] << 8  |
1150                                ((uint8_t*)row)[3 * x + 2];
1151 #else
1152                     in_pixel = ((uint8_t*)row)[3 * x]           |
1153                                ((uint8_t*)row)[3 * x + 1] << 8  |
1154                                ((uint8_t*)row)[3 * x + 2] << 16;
1155 #endif
1156                 else
1157                     in_pixel = row[x];
1158
1159                 /* If the incoming image has no alpha channel, then the input
1160                  * is opaque and the output should have the maximum alpha value.
1161                  * For all other channels, their absence implies 0.
1162                  */
1163                 if (image_masks.alpha_mask == 0x0)
1164                     a = 0xff;
1165                 else
1166                     a = _field_to_8 (in_pixel & image_masks.alpha_mask, i_a_width, i_a_shift);
1167                 r = _field_to_8 (in_pixel & image_masks.red_mask  , i_r_width, i_r_shift);
1168                 g = _field_to_8 (in_pixel & image_masks.green_mask, i_g_width, i_g_shift);
1169                 b = _field_to_8 (in_pixel & image_masks.blue_mask , i_b_width, i_b_shift);
1170
1171                 if (true_color) {
1172                     out_pixel = _field_from_8        (a, o_a_width, o_a_shift) |
1173                                 _field_from_8_dither (r, o_r_width, o_r_shift, dither_adjustment) |
1174                                 _field_from_8_dither (g, o_g_width, o_g_shift, dither_adjustment) |
1175                                 _field_from_8_dither (b, o_b_width, o_b_shift, dither_adjustment);
1176                 } else {
1177                     out_pixel = _pseudocolor_from_rgb888_dither (visual_info, r, g, b, dither_adjustment);
1178                 }
1179
1180                 XPutPixel (&ximage, x, y, out_pixel);
1181             }
1182
1183             row += rowstride;
1184         }
1185     }
1186
1187     status = _cairo_xlib_surface_get_gc (display, surface, &gc);
1188     if (unlikely (status))
1189         goto BAIL;
1190
1191     XPutImage (display->display, surface->drawable, gc,
1192                &ximage, src_x, src_y, dst_x, dst_y,
1193                width, height);
1194
1195     _cairo_xlib_surface_put_gc (display, surface, gc);
1196
1197   BAIL:
1198
1199     cairo_device_release (&display->base);
1200
1201     if (own_data)
1202         free (ximage.data);
1203     if (pixman_image)
1204         pixman_image_unref (pixman_image);
1205
1206     return CAIRO_STATUS_SUCCESS;
1207 }
1208
1209 static cairo_status_t
1210 _cairo_xlib_surface_acquire_source_image (void                    *abstract_surface,
1211                                           cairo_image_surface_t  **image_out,
1212                                           void                   **image_extra)
1213 {
1214     cairo_xlib_surface_t *surface = abstract_surface;
1215     cairo_rectangle_int_t extents;
1216
1217     extents.x = extents.y = 0;
1218     extents.width = surface->width;
1219     extents.height = surface->height;
1220
1221     *image_extra = NULL;
1222     *image_out = (cairo_image_surface_t*)_get_image_surface (surface, &extents);
1223     return (*image_out)->base.status;
1224 }
1225
1226 static cairo_surface_t *
1227 _cairo_xlib_surface_snapshot (void *abstract_surface)
1228 {
1229     cairo_xlib_surface_t *surface = abstract_surface;
1230     cairo_rectangle_int_t extents;
1231
1232     extents.x = extents.y = 0;
1233     extents.width = surface->width;
1234     extents.height = surface->height;
1235
1236     /* XXX notice the duplication with acquire source */
1237     return _get_image_surface (surface, &extents);
1238 }
1239
1240 static void
1241 _cairo_xlib_surface_release_source_image (void                   *abstract_surface,
1242                                           cairo_image_surface_t  *image,
1243                                           void                   *image_extra)
1244 {
1245     cairo_surface_destroy (&image->base);
1246 }
1247
1248 static cairo_surface_t *
1249 _cairo_xlib_surface_map_to_image (void                    *abstract_surface,
1250                                   const cairo_rectangle_int_t   *extents)
1251 {
1252     cairo_surface_t *image;
1253
1254     image = _get_image_surface (abstract_surface, extents);
1255     cairo_surface_set_device_offset (image, -extents->y, -extents->y);
1256
1257     return image;
1258 }
1259
1260 static cairo_int_status_t
1261 _cairo_xlib_surface_unmap_image (void *abstract_surface,
1262                                  cairo_image_surface_t *image)
1263 {
1264     return _cairo_xlib_surface_draw_image (abstract_surface, image,
1265                                            0, 0,
1266                                            image->width, image->height,
1267                                            image->base.device_transform_inverse.x0,
1268                                            image->base.device_transform_inverse.y0);
1269 }
1270
1271 static cairo_bool_t
1272 _cairo_xlib_surface_get_extents (void                    *abstract_surface,
1273                                  cairo_rectangle_int_t   *rectangle)
1274 {
1275     cairo_xlib_surface_t *surface = abstract_surface;
1276
1277     rectangle->x = 0;
1278     rectangle->y = 0;
1279
1280     rectangle->width  = surface->width;
1281     rectangle->height = surface->height;
1282
1283     return TRUE;
1284 }
1285
1286 static void
1287 _cairo_xlib_surface_get_font_options (void                  *abstract_surface,
1288                                       cairo_font_options_t  *options)
1289 {
1290     cairo_xlib_surface_t *surface = abstract_surface;
1291
1292     *options = *_cairo_xlib_screen_get_font_options (surface->screen);
1293 }
1294
1295
1296 static cairo_int_status_t
1297 _cairo_xlib_surface_paint (void                         *_surface,
1298                            cairo_operator_t              op,
1299                            const cairo_pattern_t        *source,
1300                            const cairo_clip_t           *clip)
1301 {
1302     cairo_xlib_surface_t *surface = _surface;
1303     return _cairo_compositor_paint (surface->compositor,
1304                                     &surface->base, op, source,
1305                                     clip);
1306 }
1307
1308 static cairo_int_status_t
1309 _cairo_xlib_surface_mask (void                  *_surface,
1310                           cairo_operator_t       op,
1311                           const cairo_pattern_t *source,
1312                           const cairo_pattern_t *mask,
1313                           const cairo_clip_t    *clip)
1314 {
1315     cairo_xlib_surface_t *surface = _surface;
1316     return _cairo_compositor_mask (surface->compositor,
1317                                    &surface->base, op, source, mask,
1318                                    clip);
1319 }
1320
1321 static cairo_int_status_t
1322 _cairo_xlib_surface_stroke (void                        *_surface,
1323                             cairo_operator_t             op,
1324                             const cairo_pattern_t       *source,
1325                             const cairo_path_fixed_t    *path,
1326                             const cairo_stroke_style_t  *style,
1327                             const cairo_matrix_t        *ctm,
1328                             const cairo_matrix_t        *ctm_inverse,
1329                             double                       tolerance,
1330                             cairo_antialias_t            antialias,
1331                             const cairo_clip_t          *clip)
1332 {
1333     cairo_xlib_surface_t *surface = _surface;
1334     return _cairo_compositor_stroke (surface->compositor,
1335                                      &surface->base, op, source,
1336                                      path, style, ctm, ctm_inverse,
1337                                      tolerance, antialias,
1338                                      clip);
1339 }
1340
1341 static cairo_int_status_t
1342 _cairo_xlib_surface_fill (void                          *_surface,
1343                           cairo_operator_t               op,
1344                           const cairo_pattern_t         *source,
1345                           const cairo_path_fixed_t      *path,
1346                           cairo_fill_rule_t              fill_rule,
1347                           double                         tolerance,
1348                           cairo_antialias_t              antialias,
1349                           const cairo_clip_t            *clip)
1350 {
1351     cairo_xlib_surface_t *surface = _surface;
1352     return _cairo_compositor_fill (surface->compositor,
1353                                    &surface->base, op, source,
1354                                    path, fill_rule, tolerance, antialias,
1355                                    clip);
1356 }
1357
1358 static cairo_int_status_t
1359 _cairo_xlib_surface_glyphs (void                        *_surface,
1360                             cairo_operator_t             op,
1361                             const cairo_pattern_t       *source,
1362                             cairo_glyph_t               *glyphs,
1363                             int                          num_glyphs,
1364                             cairo_scaled_font_t         *scaled_font,
1365                             const cairo_clip_t          *clip)
1366 {
1367     cairo_xlib_surface_t *surface = _surface;
1368     return _cairo_compositor_glyphs (surface->compositor,
1369                                      &surface->base, op, source,
1370                                      glyphs, num_glyphs, scaled_font,
1371                                      clip);
1372 }
1373
1374 static const cairo_surface_backend_t cairo_xlib_surface_backend = {
1375     CAIRO_SURFACE_TYPE_XLIB,
1376     _cairo_xlib_surface_finish,
1377
1378     _cairo_default_context_create,
1379
1380     _cairo_xlib_surface_create_similar,
1381     NULL, //_cairo_xlib_surface_create_similar_image, /* XXX shm */
1382     _cairo_xlib_surface_map_to_image,
1383     _cairo_xlib_surface_unmap_image,
1384
1385     _cairo_xlib_surface_acquire_source_image,
1386     _cairo_xlib_surface_release_source_image,
1387     _cairo_xlib_surface_snapshot,
1388
1389     NULL, /* copy_page */
1390     NULL, /* show_page */
1391
1392     _cairo_xlib_surface_get_extents,
1393     _cairo_xlib_surface_get_font_options,
1394
1395     NULL, /* flush */
1396     NULL, /* mark_dirty_rectangle */
1397
1398     _cairo_xlib_surface_paint,
1399     _cairo_xlib_surface_mask,
1400     _cairo_xlib_surface_stroke,
1401     _cairo_xlib_surface_fill,
1402     NULL, /* fill-stroke */
1403     _cairo_xlib_surface_glyphs,
1404 };
1405
1406 /**
1407  * _cairo_surface_is_xlib:
1408  * @surface: a #cairo_surface_t
1409  *
1410  * Checks if a surface is a #cairo_xlib_surface_t
1411  *
1412  * Return value: True if the surface is an xlib surface
1413  **/
1414 static cairo_bool_t
1415 _cairo_surface_is_xlib (cairo_surface_t *surface)
1416 {
1417     return surface->backend == &cairo_xlib_surface_backend;
1418 }
1419
1420 static cairo_surface_t *
1421 _cairo_xlib_surface_create_internal (cairo_xlib_screen_t        *screen,
1422                                      Drawable                    drawable,
1423                                      Visual                     *visual,
1424                                      XRenderPictFormat          *xrender_format,
1425                                      int                         width,
1426                                      int                         height,
1427                                      int                         depth)
1428 {
1429     cairo_xlib_surface_t *surface;
1430     cairo_xlib_display_t *display;
1431     cairo_status_t status;
1432
1433     if (depth == 0) {
1434         if (xrender_format) {
1435             depth = xrender_format->depth;
1436
1437             /* XXX find matching visual for core/dithering fallbacks? */
1438         } else if (visual) {
1439             Screen *scr = screen->screen;
1440
1441             if (visual == DefaultVisualOfScreen (scr)) {
1442                 depth = DefaultDepthOfScreen (scr);
1443             } else  {
1444                 int j, k;
1445
1446                 /* This is ugly, but we have to walk over all visuals
1447                  * for the display to find the correct depth.
1448                  */
1449                 depth = 0;
1450                 for (j = 0; j < scr->ndepths; j++) {
1451                     Depth *d = &scr->depths[j];
1452                     for (k = 0; k < d->nvisuals; k++) {
1453                         if (&d->visuals[k] == visual) {
1454                             depth = d->depth;
1455                             goto found;
1456                         }
1457                     }
1458                 }
1459             }
1460         }
1461
1462         if (depth == 0)
1463             return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_VISUAL));
1464
1465 found:
1466         ;
1467     }
1468
1469     surface = malloc (sizeof (cairo_xlib_surface_t));
1470     if (unlikely (surface == NULL))
1471         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
1472
1473     status = _cairo_xlib_display_acquire (screen->device, &display);
1474     if (unlikely (status)) {
1475         free (surface);
1476         return _cairo_surface_create_in_error (_cairo_error (status));
1477     }
1478
1479     surface->display = display;
1480     if (CAIRO_RENDER_HAS_CREATE_PICTURE (display)) {
1481         if (!xrender_format) {
1482             if (visual) {
1483                 xrender_format = XRenderFindVisualFormat (display->display, visual);
1484             } else if (depth == 1) {
1485                 xrender_format =
1486                     _cairo_xlib_display_get_xrender_format (display,
1487                                                             CAIRO_FORMAT_A1);
1488             }
1489         }
1490     }
1491
1492     cairo_device_release (&display->base);
1493
1494     _cairo_surface_init (&surface->base,
1495                          &cairo_xlib_surface_backend,
1496                          screen->device,
1497                          _xrender_format_to_content (xrender_format));
1498
1499     surface->screen = screen;
1500     surface->compositor = display->compositor;
1501
1502     surface->drawable = drawable;
1503     surface->owns_pixmap = FALSE;
1504     surface->use_pixmap = 0;
1505     surface->width = width;
1506     surface->height = height;
1507
1508     surface->picture = None;
1509     surface->precision = PolyModePrecise;
1510
1511     surface->embedded_source.picture = None;
1512
1513     surface->visual = visual;
1514     surface->xrender_format = xrender_format;
1515     surface->depth = depth;
1516
1517     /*
1518      * Compute the pixel format masks from either a XrenderFormat or
1519      * else from a visual; failing that we assume the drawable is an
1520      * alpha-only pixmap as it could only have been created that way
1521      * through the cairo_xlib_surface_create_for_bitmap function.
1522      */
1523     if (xrender_format) {
1524         surface->a_mask = (unsigned long)
1525             surface->xrender_format->direct.alphaMask
1526             << surface->xrender_format->direct.alpha;
1527         surface->r_mask = (unsigned long)
1528             surface->xrender_format->direct.redMask
1529             << surface->xrender_format->direct.red;
1530         surface->g_mask = (unsigned long)
1531             surface->xrender_format->direct.greenMask
1532             << surface->xrender_format->direct.green;
1533         surface->b_mask = (unsigned long)
1534             surface->xrender_format->direct.blueMask
1535             << surface->xrender_format->direct.blue;
1536     } else if (visual) {
1537         surface->a_mask = 0;
1538         surface->r_mask = visual->red_mask;
1539         surface->g_mask = visual->green_mask;
1540         surface->b_mask = visual->blue_mask;
1541     } else {
1542         if (depth < 32)
1543             surface->a_mask = (1 << depth) - 1;
1544         else
1545             surface->a_mask = 0xffffffff;
1546         surface->r_mask = 0;
1547         surface->g_mask = 0;
1548         surface->b_mask = 0;
1549     }
1550
1551     cairo_list_add (&surface->link, &screen->surfaces);
1552
1553     return &surface->base;
1554 }
1555
1556 static Screen *
1557 _cairo_xlib_screen_from_visual (Display *dpy, Visual *visual)
1558 {
1559     int s, d, v;
1560
1561     for (s = 0; s < ScreenCount (dpy); s++) {
1562         Screen *screen;
1563
1564         screen = ScreenOfDisplay (dpy, s);
1565         if (visual == DefaultVisualOfScreen (screen))
1566             return screen;
1567
1568         for (d = 0; d < screen->ndepths; d++) {
1569             Depth  *depth;
1570
1571             depth = &screen->depths[d];
1572             for (v = 0; v < depth->nvisuals; v++)
1573                 if (visual == &depth->visuals[v])
1574                     return screen;
1575         }
1576     }
1577
1578     return NULL;
1579 }
1580
1581 static cairo_bool_t valid_size (int width, int height)
1582 {
1583     return width > 0 && width <= XLIB_COORD_MAX && height > 0 && height <= XLIB_COORD_MAX;
1584 }
1585
1586 /**
1587  * cairo_xlib_surface_create:
1588  * @dpy: an X Display
1589  * @drawable: an X Drawable, (a Pixmap or a Window)
1590  * @visual: the visual to use for drawing to @drawable. The depth
1591  *          of the visual must match the depth of the drawable.
1592  *          Currently, only TrueColor visuals are fully supported.
1593  * @width: the current width of @drawable.
1594  * @height: the current height of @drawable.
1595  *
1596  * Creates an Xlib surface that draws to the given drawable.
1597  * The way that colors are represented in the drawable is specified
1598  * by the provided visual.
1599  *
1600  * Note: If @drawable is a Window, then the function
1601  * cairo_xlib_surface_set_size() must be called whenever the size of the
1602  * window changes.
1603  *
1604  * When @drawable is a Window containing child windows then drawing to
1605  * the created surface will be clipped by those child windows.  When
1606  * the created surface is used as a source, the contents of the
1607  * children will be included.
1608  *
1609  * Return value: the newly created surface
1610  **/
1611 cairo_surface_t *
1612 cairo_xlib_surface_create (Display     *dpy,
1613                            Drawable     drawable,
1614                            Visual      *visual,
1615                            int          width,
1616                            int          height)
1617 {
1618     Screen *scr;
1619     cairo_xlib_screen_t *screen;
1620     cairo_status_t status;
1621
1622     if (! valid_size (width, height)) {
1623         /* you're lying, and you know it! */
1624         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_SIZE));
1625     }
1626
1627     scr = _cairo_xlib_screen_from_visual (dpy, visual);
1628     if (scr == NULL)
1629         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_VISUAL));
1630
1631     status = _cairo_xlib_screen_get (dpy, scr, &screen);
1632     if (unlikely (status))
1633         return _cairo_surface_create_in_error (status);
1634
1635     X_DEBUG ((dpy, "create (drawable=%x)", (unsigned int) drawable));
1636
1637     return _cairo_xlib_surface_create_internal (screen, drawable,
1638                                                 visual, NULL,
1639                                                 width, height, 0);
1640 }
1641
1642 /**
1643  * cairo_xlib_surface_create_for_bitmap:
1644  * @dpy: an X Display
1645  * @bitmap: an X Drawable, (a depth-1 Pixmap)
1646  * @screen: the X Screen associated with @bitmap
1647  * @width: the current width of @bitmap.
1648  * @height: the current height of @bitmap.
1649  *
1650  * Creates an Xlib surface that draws to the given bitmap.
1651  * This will be drawn to as a %CAIRO_FORMAT_A1 object.
1652  *
1653  * Return value: the newly created surface
1654  **/
1655 cairo_surface_t *
1656 cairo_xlib_surface_create_for_bitmap (Display  *dpy,
1657                                       Pixmap    bitmap,
1658                                       Screen   *scr,
1659                                       int       width,
1660                                       int       height)
1661 {
1662     cairo_xlib_screen_t *screen;
1663     cairo_status_t status;
1664
1665     if (! valid_size (width, height))
1666         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_SIZE));
1667
1668     status = _cairo_xlib_screen_get (dpy, scr, &screen);
1669     if (unlikely (status))
1670         return _cairo_surface_create_in_error (status);
1671
1672     X_DEBUG ((dpy, "create_for_bitmap (drawable=%x)", (unsigned int) bitmap));
1673
1674     return _cairo_xlib_surface_create_internal (screen, bitmap,
1675                                                 NULL, NULL,
1676                                                 width, height, 1);
1677 }
1678
1679 #if CAIRO_HAS_XLIB_XRENDER_SURFACE
1680 /**
1681  * cairo_xlib_surface_create_with_xrender_format:
1682  * @dpy: an X Display
1683  * @drawable: an X Drawable, (a Pixmap or a Window)
1684  * @screen: the X Screen associated with @drawable
1685  * @format: the picture format to use for drawing to @drawable. The depth
1686  *          of @format must match the depth of the drawable.
1687  * @width: the current width of @drawable.
1688  * @height: the current height of @drawable.
1689  *
1690  * Creates an Xlib surface that draws to the given drawable.
1691  * The way that colors are represented in the drawable is specified
1692  * by the provided picture format.
1693  *
1694  * Note: If @drawable is a Window, then the function
1695  * cairo_xlib_surface_set_size() must be called whenever the size of the
1696  * window changes.
1697  *
1698  * Return value: the newly created surface
1699  **/
1700 cairo_surface_t *
1701 cairo_xlib_surface_create_with_xrender_format (Display              *dpy,
1702                                                Drawable             drawable,
1703                                                Screen               *scr,
1704                                                XRenderPictFormat    *format,
1705                                                int                  width,
1706                                                int                  height)
1707 {
1708     cairo_xlib_screen_t *screen;
1709     cairo_status_t status;
1710
1711     if (! valid_size (width, height))
1712         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_SIZE));
1713
1714     status = _cairo_xlib_screen_get (dpy, scr, &screen);
1715     if (unlikely (status))
1716         return _cairo_surface_create_in_error (status);
1717
1718     X_DEBUG ((dpy, "create_with_xrender_format (drawable=%x)", (unsigned int) drawable));
1719
1720     return _cairo_xlib_surface_create_internal (screen, drawable,
1721                                                 _visual_for_xrender_format (scr, format),
1722                                                 format, width, height, 0);
1723 }
1724
1725 /**
1726  * cairo_xlib_surface_get_xrender_format:
1727  * @surface: an xlib surface
1728  *
1729  * Gets the X Render picture format that @surface uses for rendering with the
1730  * X Render extension. If the surface was created by
1731  * cairo_xlib_surface_create_with_xrender_format() originally, the return
1732  * value is the format passed to that constructor.
1733  *
1734  * Return value: the XRenderPictFormat* associated with @surface,
1735  * or %NULL if the surface is not an xlib surface
1736  * or if the X Render extension is not available.
1737  *
1738  * Since: 1.6
1739  **/
1740 XRenderPictFormat *
1741 cairo_xlib_surface_get_xrender_format (cairo_surface_t *surface)
1742 {
1743     cairo_xlib_surface_t *xlib_surface = (cairo_xlib_surface_t *) surface;
1744
1745     /* Throw an error for a non-xlib surface */
1746     if (! _cairo_surface_is_xlib (surface)) {
1747         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1748         return NULL;
1749     }
1750
1751     return xlib_surface->xrender_format;
1752 }
1753 #endif
1754
1755 /**
1756  * cairo_xlib_surface_set_size:
1757  * @surface: a #cairo_surface_t for the XLib backend
1758  * @width: the new width of the surface
1759  * @height: the new height of the surface
1760  *
1761  * Informs cairo of the new size of the X Drawable underlying the
1762  * surface. For a surface created for a Window (rather than a Pixmap),
1763  * this function must be called each time the size of the window
1764  * changes. (For a subwindow, you are normally resizing the window
1765  * yourself, but for a toplevel window, it is necessary to listen for
1766  * ConfigureNotify events.)
1767  *
1768  * A Pixmap can never change size, so it is never necessary to call
1769  * this function on a surface created for a Pixmap.
1770  **/
1771 void
1772 cairo_xlib_surface_set_size (cairo_surface_t *abstract_surface,
1773                              int              width,
1774                              int              height)
1775 {
1776     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
1777
1778     if (unlikely (abstract_surface->status))
1779         return;
1780     if (unlikely (abstract_surface->finished)) {
1781         _cairo_surface_set_error (abstract_surface,
1782                                   _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
1783         return;
1784     }
1785
1786     if (! _cairo_surface_is_xlib (abstract_surface)) {
1787         _cairo_surface_set_error (abstract_surface,
1788                                   _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
1789         return;
1790     }
1791
1792     if (! valid_size (width, height)) {
1793         _cairo_surface_set_error (abstract_surface,
1794                                   _cairo_error (CAIRO_STATUS_INVALID_SIZE));
1795         return;
1796     }
1797
1798     surface->width = width;
1799     surface->height = height;
1800 }
1801 /**
1802  * cairo_xlib_surface_set_drawable:
1803  * @surface: a #cairo_surface_t for the XLib backend
1804  * @drawable: the new drawable for the surface
1805  * @width: the width of the new drawable
1806  * @height: the height of the new drawable
1807  *
1808  * Informs cairo of a new X Drawable underlying the
1809  * surface. The drawable must match the display, screen
1810  * and format of the existing drawable or the application
1811  * will get X protocol errors and will probably terminate.
1812  * No checks are done by this function to ensure this
1813  * compatibility.
1814  **/
1815 void
1816 cairo_xlib_surface_set_drawable (cairo_surface_t   *abstract_surface,
1817                                  Drawable           drawable,
1818                                  int                width,
1819                                  int                height)
1820 {
1821     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *)abstract_surface;
1822     cairo_status_t status;
1823
1824     if (unlikely (abstract_surface->status))
1825         return;
1826     if (unlikely (abstract_surface->finished)) {
1827         status = _cairo_surface_set_error (abstract_surface,
1828                                            _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
1829         return;
1830     }
1831
1832     if (! _cairo_surface_is_xlib (abstract_surface)) {
1833         status = _cairo_surface_set_error (abstract_surface,
1834                                            _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
1835         return;
1836     }
1837
1838     if (! valid_size (width, height)) {
1839         status = _cairo_surface_set_error (abstract_surface,
1840                                            _cairo_error (CAIRO_STATUS_INVALID_SIZE));
1841         return;
1842     }
1843
1844     /* XXX: and what about this case? */
1845     if (surface->owns_pixmap)
1846         return;
1847
1848     if (surface->drawable != drawable) {
1849         cairo_xlib_display_t *display;
1850
1851         status = _cairo_xlib_display_acquire (surface->base.device, &display);
1852         if (unlikely (status))
1853             return;
1854
1855         X_DEBUG ((display->display, "set_drawable (drawable=%x)", (unsigned int) drawable));
1856
1857         if (surface->picture != None) {
1858             XRenderFreePicture (display->display, surface->picture);
1859             if (unlikely (status)) {
1860                 status = _cairo_surface_set_error (&surface->base, status);
1861                 return;
1862             }
1863
1864             surface->picture = None;
1865         }
1866
1867         cairo_device_release (&display->base);
1868
1869         surface->drawable = drawable;
1870     }
1871     surface->width = width;
1872     surface->height = height;
1873 }
1874
1875 /**
1876  * cairo_xlib_surface_get_display:
1877  * @surface: a #cairo_xlib_surface_t
1878  *
1879  * Get the X Display for the underlying X Drawable.
1880  *
1881  * Return value: the display.
1882  *
1883  * Since: 1.2
1884  **/
1885 Display *
1886 cairo_xlib_surface_get_display (cairo_surface_t *abstract_surface)
1887 {
1888     if (! _cairo_surface_is_xlib (abstract_surface)) {
1889         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1890         return NULL;
1891     }
1892
1893     return ((cairo_xlib_display_t *) abstract_surface->device)->display;
1894 }
1895
1896 /**
1897  * cairo_xlib_surface_get_drawable:
1898  * @surface: a #cairo_xlib_surface_t
1899  *
1900  * Get the underlying X Drawable used for the surface.
1901  *
1902  * Return value: the drawable.
1903  *
1904  * Since: 1.2
1905  **/
1906 Drawable
1907 cairo_xlib_surface_get_drawable (cairo_surface_t *abstract_surface)
1908 {
1909     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
1910
1911     if (! _cairo_surface_is_xlib (abstract_surface)) {
1912         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1913         return 0;
1914     }
1915
1916     return surface->drawable;
1917 }
1918
1919 /**
1920  * cairo_xlib_surface_get_screen:
1921  * @surface: a #cairo_xlib_surface_t
1922  *
1923  * Get the X Screen for the underlying X Drawable.
1924  *
1925  * Return value: the screen.
1926  *
1927  * Since: 1.2
1928  **/
1929 Screen *
1930 cairo_xlib_surface_get_screen (cairo_surface_t *abstract_surface)
1931 {
1932     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
1933
1934     if (! _cairo_surface_is_xlib (abstract_surface)) {
1935         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1936         return NULL;
1937     }
1938
1939     return surface->screen->screen;
1940 }
1941
1942 /**
1943  * cairo_xlib_surface_get_visual:
1944  * @surface: a #cairo_xlib_surface_t
1945  *
1946  * Gets the X Visual associated with @surface, suitable for use with the
1947  * underlying X Drawable.  If @surface was created by
1948  * cairo_xlib_surface_create(), the return value is the Visual passed to that
1949  * constructor.
1950  *
1951  * Return value: the Visual or %NULL if there is no appropriate Visual for
1952  * @surface.
1953  *
1954  * Since: 1.2
1955  **/
1956 Visual *
1957 cairo_xlib_surface_get_visual (cairo_surface_t *surface)
1958 {
1959     cairo_xlib_surface_t *xlib_surface = (cairo_xlib_surface_t *) surface;
1960
1961     if (! _cairo_surface_is_xlib (surface)) {
1962         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1963         return NULL;
1964     }
1965
1966     return xlib_surface->visual;
1967 }
1968
1969 /**
1970  * cairo_xlib_surface_get_depth:
1971  * @surface: a #cairo_xlib_surface_t
1972  *
1973  * Get the number of bits used to represent each pixel value.
1974  *
1975  * Return value: the depth of the surface in bits.
1976  *
1977  * Since: 1.2
1978  **/
1979 int
1980 cairo_xlib_surface_get_depth (cairo_surface_t *abstract_surface)
1981 {
1982     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
1983
1984     if (! _cairo_surface_is_xlib (abstract_surface)) {
1985         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1986         return 0;
1987     }
1988
1989     return surface->depth;
1990 }
1991
1992 /**
1993  * cairo_xlib_surface_get_width:
1994  * @surface: a #cairo_xlib_surface_t
1995  *
1996  * Get the width of the X Drawable underlying the surface in pixels.
1997  *
1998  * Return value: the width of the surface in pixels.
1999  *
2000  * Since: 1.2
2001  **/
2002 int
2003 cairo_xlib_surface_get_width (cairo_surface_t *abstract_surface)
2004 {
2005     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
2006
2007     if (! _cairo_surface_is_xlib (abstract_surface)) {
2008         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
2009         return 0;
2010     }
2011
2012     return surface->width;
2013 }
2014
2015 /**
2016  * cairo_xlib_surface_get_height:
2017  * @surface: a #cairo_xlib_surface_t
2018  *
2019  * Get the height of the X Drawable underlying the surface in pixels.
2020  *
2021  * Return value: the height of the surface in pixels.
2022  *
2023  * Since: 1.2
2024  **/
2025 int
2026 cairo_xlib_surface_get_height (cairo_surface_t *abstract_surface)
2027 {
2028     cairo_xlib_surface_t *surface = (cairo_xlib_surface_t *) abstract_surface;
2029
2030     if (! _cairo_surface_is_xlib (abstract_surface)) {
2031         _cairo_error_throw (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
2032         return 0;
2033     }
2034
2035     return surface->height;
2036 }
2037
2038 #endif /* !CAIRO_HAS_XLIB_XCB_FUNCTIONS */