TINF-96: add cairo-gobject and cairo-gobject-devel; deps for gobject-introspection
[profile/ivi/cairo.git] / src / cairo-qt-surface.cpp
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 © 2008 Mozilla Corporation
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it either under the terms of the GNU Lesser General Public
8  * License version 2.1 as published by the Free Software Foundation
9  * (the "LGPL") or, at your option, under the terms of the Mozilla
10  * Public License Version 1.1 (the "MPL"). If you do not alter this
11  * notice, a recipient may use your version of this file under either
12  * the MPL or the LGPL.
13  *
14  * You should have received a copy of the LGPL along with this library
15  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17  * You should have received a copy of the MPL along with this library
18  * in the file COPYING-MPL-1.1
19  *
20  * The contents of this file are subject to the Mozilla Public License
21  * Version 1.1 (the "License"); you may not use this file except in
22  * compliance with the License. You may obtain a copy of the License at
23  * http://www.mozilla.org/MPL/
24  *
25  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27  * the specific language governing rights and limitations.
28  *
29  * The Original Code is the cairo graphics library.
30  *
31  * The Initial Developer of the Original Code is Mozilla Corporation.
32  *
33  * Contributor(s):
34  *      Vladimir Vukicevic <vladimir@mozilla.com>
35  */
36
37 /* Get INT16_MIN etc. as per C99 */
38 #define __STDC_LIMIT_MACROS
39
40 #include "cairoint.h"
41
42 #include "cairo-clip-private.h"
43 #include "cairo-default-context-private.h"
44 #include "cairo-error-private.h"
45 #include "cairo-region-private.h"
46 #include "cairo-surface-clipper-private.h"
47 #include "cairo-types-private.h"
48 #include "cairo-image-surface-private.h"
49 #include "cairo-pattern-private.h"
50 #include "cairo-surface-backend-private.h"
51
52 #include "cairo-ft.h"
53 #include "cairo-qt.h"
54
55 #include <memory>
56
57 #include <QtGui/QPainter>
58 #include <QtGui/QPaintEngine>
59 #include <QtGui/QPaintDevice>
60 #include <QtGui/QImage>
61 #include <QtGui/QPixmap>
62 #include <QtGui/QBrush>
63 #include <QtGui/QPen>
64 #include <QWidget>
65 #include <QtCore/QVarLengthArray>
66
67 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)) || defined(QT_GLYPHS_API_BACKPORT)
68 extern void qt_draw_glyphs(QPainter *, const quint32 *glyphs, const QPointF *positions, int count);
69 #endif
70
71 #include <sys/time.h>
72
73 /* Enable workaround slow regional Qt paths */
74 #define ENABLE_FAST_FILL 0
75 #define ENABLE_FAST_CLIP 0
76
77 #if 0
78 #define D(x)  x
79 static const char *
80 _opstr (cairo_operator_t op)
81 {
82     const char *ops[] = {
83         "CLEAR",
84         "SOURCE",
85         "OVER",
86         "IN",
87         "OUT",
88         "ATOP",
89         "DEST",
90         "DEST_OVER",
91         "DEST_IN",
92         "DEST_OUT",
93         "DEST_ATOP",
94         "XOR",
95         "ADD",
96         "SATURATE"
97     };
98
99     if (op < CAIRO_OPERATOR_CLEAR || op > CAIRO_OPERATOR_SATURATE)
100         return "(\?\?\?)";
101
102     return ops[op];
103 }
104 #else
105 #define D(x) do { } while(0)
106 #endif
107
108 #ifndef CAIRO_INT_STATUS_SUCCESS
109 #define CAIRO_INT_STATUS_SUCCESS ((cairo_int_status_t) CAIRO_STATUS_SUCCESS)
110 #endif
111
112 /* Qt::PenStyle optimization based on the assumption that dots are 1*w and dashes are 3*w. */
113 #define DOT_LENGTH  1.0
114 #define DASH_LENGTH 3.0
115
116 struct cairo_qt_surface_t {
117     cairo_surface_t base;
118
119     cairo_bool_t supports_porter_duff;
120
121     QPainter *p;
122
123     /* The pixmap/image constructors will store their objects here */
124     QPixmap *pixmap;
125     QImage *image;
126
127     QRect window;
128
129     cairo_surface_clipper_t clipper;
130
131     cairo_surface_t *image_equiv;
132 };
133
134 /* Will be true if we ever try to create a QPixmap and end
135  * up with one without an alpha channel.
136  */
137 static cairo_bool_t _qpixmaps_have_no_alpha = FALSE;
138
139 /*
140  * Helper methods
141  */
142
143 static QPainter::CompositionMode
144 _qpainter_compositionmode_from_cairo_op (cairo_operator_t op)
145 {
146     switch (op) {
147     case CAIRO_OPERATOR_CLEAR:
148         return QPainter::CompositionMode_Clear;
149
150     case CAIRO_OPERATOR_SOURCE:
151         return QPainter::CompositionMode_Source;
152     case CAIRO_OPERATOR_OVER:
153         return QPainter::CompositionMode_SourceOver;
154     case CAIRO_OPERATOR_IN:
155         return QPainter::CompositionMode_SourceIn;
156     case CAIRO_OPERATOR_OUT:
157         return QPainter::CompositionMode_SourceOut;
158     case CAIRO_OPERATOR_ATOP:
159         return QPainter::CompositionMode_SourceAtop;
160
161     case CAIRO_OPERATOR_DEST:
162         return QPainter::CompositionMode_Destination;
163     case CAIRO_OPERATOR_DEST_OVER:
164         return QPainter::CompositionMode_DestinationOver;
165     case CAIRO_OPERATOR_DEST_IN:
166         return QPainter::CompositionMode_DestinationIn;
167     case CAIRO_OPERATOR_DEST_OUT:
168         return QPainter::CompositionMode_DestinationOut;
169     case CAIRO_OPERATOR_DEST_ATOP:
170         return QPainter::CompositionMode_DestinationAtop;
171
172     case CAIRO_OPERATOR_XOR:
173         return QPainter::CompositionMode_Xor;
174
175     default:
176     case CAIRO_OPERATOR_ADD:
177     case CAIRO_OPERATOR_SATURATE:
178     case CAIRO_OPERATOR_MULTIPLY:
179     case CAIRO_OPERATOR_SCREEN:
180     case CAIRO_OPERATOR_OVERLAY:
181     case CAIRO_OPERATOR_DARKEN:
182     case CAIRO_OPERATOR_LIGHTEN:
183     case CAIRO_OPERATOR_COLOR_DODGE:
184     case CAIRO_OPERATOR_COLOR_BURN:
185     case CAIRO_OPERATOR_HARD_LIGHT:
186     case CAIRO_OPERATOR_SOFT_LIGHT:
187     case CAIRO_OPERATOR_DIFFERENCE:
188     case CAIRO_OPERATOR_EXCLUSION:
189     case CAIRO_OPERATOR_HSL_HUE:
190     case CAIRO_OPERATOR_HSL_SATURATION:
191     case CAIRO_OPERATOR_HSL_COLOR:
192     case CAIRO_OPERATOR_HSL_LUMINOSITY:
193         ASSERT_NOT_REACHED;
194     }
195 }
196
197 static bool
198 _op_is_supported (cairo_qt_surface_t *qs, cairo_operator_t op)
199 {
200     if (qs->supports_porter_duff) {
201         switch (op) {
202         case CAIRO_OPERATOR_CLEAR:
203         case CAIRO_OPERATOR_SOURCE:
204         case CAIRO_OPERATOR_OVER:
205         case CAIRO_OPERATOR_IN:
206         case CAIRO_OPERATOR_OUT:
207         case CAIRO_OPERATOR_ATOP:
208
209         case CAIRO_OPERATOR_DEST:
210         case CAIRO_OPERATOR_DEST_OVER:
211         case CAIRO_OPERATOR_DEST_IN:
212         case CAIRO_OPERATOR_DEST_OUT:
213         case CAIRO_OPERATOR_DEST_ATOP:
214
215         case CAIRO_OPERATOR_XOR:
216             return TRUE;
217
218         default:
219             ASSERT_NOT_REACHED;
220         case CAIRO_OPERATOR_ADD:
221         case CAIRO_OPERATOR_SATURATE:
222         case CAIRO_OPERATOR_MULTIPLY:
223         case CAIRO_OPERATOR_SCREEN:
224         case CAIRO_OPERATOR_OVERLAY:
225         case CAIRO_OPERATOR_DARKEN:
226         case CAIRO_OPERATOR_LIGHTEN:
227         case CAIRO_OPERATOR_COLOR_DODGE:
228         case CAIRO_OPERATOR_COLOR_BURN:
229         case CAIRO_OPERATOR_HARD_LIGHT:
230         case CAIRO_OPERATOR_SOFT_LIGHT:
231         case CAIRO_OPERATOR_DIFFERENCE:
232         case CAIRO_OPERATOR_EXCLUSION:
233         case CAIRO_OPERATOR_HSL_HUE:
234         case CAIRO_OPERATOR_HSL_SATURATION:
235         case CAIRO_OPERATOR_HSL_COLOR:
236         case CAIRO_OPERATOR_HSL_LUMINOSITY:
237             return FALSE;
238
239         }
240     } else {
241         return op == CAIRO_OPERATOR_OVER;
242     }
243 }
244
245 static cairo_format_t
246 _cairo_format_from_qimage_format (QImage::Format fmt)
247 {
248     switch (fmt) {
249     case QImage::Format_ARGB32_Premultiplied:
250         return CAIRO_FORMAT_ARGB32;
251     case QImage::Format_RGB32:
252         return CAIRO_FORMAT_RGB24;
253     case QImage::Format_Indexed8: // XXX not quite
254         return CAIRO_FORMAT_A8;
255 #ifdef WORDS_BIGENDIAN
256     case QImage::Format_Mono:
257 #else
258     case QImage::Format_MonoLSB:
259 #endif
260         return CAIRO_FORMAT_A1;
261
262     case QImage::Format_Invalid:
263 #ifdef WORDS_BIGENDIAN
264     case QImage::Format_MonoLSB:
265 #else
266     case QImage::Format_Mono:
267 #endif
268     case QImage::Format_ARGB32:
269     case QImage::Format_RGB16:
270     case QImage::Format_ARGB8565_Premultiplied:
271     case QImage::Format_RGB666:
272     case QImage::Format_ARGB6666_Premultiplied:
273     case QImage::Format_RGB555:
274     case QImage::Format_ARGB8555_Premultiplied:
275     case QImage::Format_RGB888:
276     case QImage::Format_RGB444:
277     case QImage::Format_ARGB4444_Premultiplied:
278     case QImage::NImageFormats:
279     default:
280         ASSERT_NOT_REACHED;
281         return (cairo_format_t) -1;
282     }
283 }
284
285 static QImage::Format
286 _qimage_format_from_cairo_format (cairo_format_t fmt)
287 {
288     switch (fmt) {
289     case CAIRO_FORMAT_INVALID:
290         ASSERT_NOT_REACHED;
291     case CAIRO_FORMAT_ARGB32:
292         return QImage::Format_ARGB32_Premultiplied;
293     case CAIRO_FORMAT_RGB24:
294         return QImage::Format_RGB32;
295     case CAIRO_FORMAT_RGB16_565:
296         return QImage::Format_RGB16;
297     case CAIRO_FORMAT_A8:
298         return QImage::Format_Indexed8; // XXX not quite
299     case CAIRO_FORMAT_A1:
300 #ifdef WORDS_BIGENDIAN
301         return QImage::Format_Mono; // XXX think we need to choose between this and LSB
302 #else
303         return QImage::Format_MonoLSB;
304 #endif
305     }
306
307     return QImage::Format_Mono;
308 }
309
310 static inline QMatrix
311 _qmatrix_from_cairo_matrix (const cairo_matrix_t& m)
312 {
313     return QMatrix(m.xx, m.yx, m.xy, m.yy, m.x0, m.y0);
314 }
315
316 /* Path conversion */
317 typedef struct _qpainter_path_transform {
318     QPainterPath path;
319     const cairo_matrix_t *ctm_inverse;
320 } qpainter_path_data;
321
322 /* cairo path -> execute in context */
323 static cairo_status_t
324 _cairo_path_to_qpainterpath_move_to (void *closure, const cairo_point_t *point)
325 {
326     qpainter_path_data *pdata = static_cast <qpainter_path_data *> (closure);
327     double x = _cairo_fixed_to_double (point->x);
328     double y = _cairo_fixed_to_double (point->y);
329
330     if (pdata->ctm_inverse)
331         cairo_matrix_transform_point (pdata->ctm_inverse, &x, &y);
332
333     pdata->path.moveTo(x, y);
334
335     return CAIRO_STATUS_SUCCESS;
336 }
337
338 static cairo_status_t
339 _cairo_path_to_qpainterpath_line_to (void *closure, const cairo_point_t *point)
340 {
341     qpainter_path_data *pdata = static_cast <qpainter_path_data *> (closure);
342     double x = _cairo_fixed_to_double (point->x);
343     double y = _cairo_fixed_to_double (point->y);
344
345     if (pdata->ctm_inverse)
346         cairo_matrix_transform_point (pdata->ctm_inverse, &x, &y);
347
348     pdata->path.lineTo(x, y);
349
350     return CAIRO_STATUS_SUCCESS;
351 }
352
353 static cairo_status_t
354 _cairo_path_to_qpainterpath_curve_to (void *closure, const cairo_point_t *p0, const cairo_point_t *p1, const cairo_point_t *p2)
355 {
356     qpainter_path_data *pdata = static_cast <qpainter_path_data *> (closure);
357     double x0 = _cairo_fixed_to_double (p0->x);
358     double y0 = _cairo_fixed_to_double (p0->y);
359     double x1 = _cairo_fixed_to_double (p1->x);
360     double y1 = _cairo_fixed_to_double (p1->y);
361     double x2 = _cairo_fixed_to_double (p2->x);
362     double y2 = _cairo_fixed_to_double (p2->y);
363
364     if (pdata->ctm_inverse) {
365         cairo_matrix_transform_point (pdata->ctm_inverse, &x0, &y0);
366         cairo_matrix_transform_point (pdata->ctm_inverse, &x1, &y1);
367         cairo_matrix_transform_point (pdata->ctm_inverse, &x2, &y2);
368     }
369
370     pdata->path.cubicTo (x0, y0, x1, y1, x2, y2);
371
372     return CAIRO_STATUS_SUCCESS;
373 }
374
375 static cairo_status_t
376 _cairo_path_to_qpainterpath_close_path (void *closure)
377 {
378     qpainter_path_data *pdata = static_cast <qpainter_path_data *> (closure);
379
380     pdata->path.closeSubpath();
381
382     return CAIRO_STATUS_SUCCESS;
383 }
384
385 static inline QPainterPath
386 path_to_qt (const cairo_path_fixed_t *path,
387             const cairo_matrix_t *ctm_inverse = NULL)
388 {
389     qpainter_path_data data;
390     cairo_status_t status;
391
392     if (ctm_inverse && _cairo_matrix_is_identity (ctm_inverse))
393         ctm_inverse = NULL;
394     data.ctm_inverse = ctm_inverse;
395
396     status = _cairo_path_fixed_interpret (path,
397                                           _cairo_path_to_qpainterpath_move_to,
398                                           _cairo_path_to_qpainterpath_line_to,
399                                           _cairo_path_to_qpainterpath_curve_to,
400                                           _cairo_path_to_qpainterpath_close_path,
401                                           &data);
402     assert (status == CAIRO_STATUS_SUCCESS);
403
404     return data.path;
405 }
406
407 static inline QPainterPath
408 path_to_qt (const cairo_path_fixed_t *path,
409             cairo_fill_rule_t fill_rule,
410             cairo_matrix_t *ctm_inverse = NULL)
411 {
412     QPainterPath qpath = path_to_qt (path, ctm_inverse);
413
414     qpath.setFillRule (fill_rule == CAIRO_FILL_RULE_WINDING ?
415                         Qt::WindingFill :
416                         Qt::OddEvenFill);
417
418     return qpath;
419 }
420
421 /*
422  * Surface backend methods
423  */
424 static cairo_surface_t *
425 _cairo_qt_surface_create_similar (void *abstract_surface,
426                                   cairo_content_t content,
427                                   int width,
428                                   int height)
429 {
430     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
431     bool use_pixmap;
432
433     D(fprintf(stderr, "q[%p] create_similar: %d %d [%d] -> ", abstract_surface, width, height, content));
434
435     use_pixmap = qs->image == NULL;
436     if (use_pixmap) {
437         switch (content) {
438         case CAIRO_CONTENT_ALPHA:
439             use_pixmap = FALSE;
440             break;
441         case CAIRO_CONTENT_COLOR:
442             break;
443         case CAIRO_CONTENT_COLOR_ALPHA:
444             use_pixmap = ! _qpixmaps_have_no_alpha;
445             break;
446         }
447     }
448
449     if (use_pixmap) {
450         cairo_surface_t *result =
451             cairo_qt_surface_create_with_qpixmap (content, width, height);
452
453         /* XXX result->content is always content. ??? */
454         if (result->content == content) {
455             D(fprintf(stderr, "qpixmap content: %d\n", content));
456             return result;
457         }
458
459         _qpixmaps_have_no_alpha = TRUE;
460         cairo_surface_destroy (result);
461     }
462
463     D(fprintf (stderr, "qimage\n"));
464     return cairo_qt_surface_create_with_qimage
465         (_cairo_format_from_content (content), width, height);
466 }
467
468 static cairo_status_t
469 _cairo_qt_surface_finish (void *abstract_surface)
470 {
471     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
472
473     D(fprintf(stderr, "q[%p] finish\n", abstract_surface));
474
475     /* Only delete p if we created it */
476     if (qs->image || qs->pixmap)
477         delete qs->p;
478     else
479         qs->p->restore ();
480
481     if (qs->image_equiv)
482         cairo_surface_destroy (qs->image_equiv);
483
484     _cairo_surface_clipper_reset (&qs->clipper);
485
486     if (qs->image)
487         delete qs->image;
488
489     if (qs->pixmap)
490         delete qs->pixmap;
491
492     return CAIRO_STATUS_SUCCESS;
493 }
494
495 static void
496 _qimg_destroy (void *closure)
497 {
498     QImage *qimg = (QImage *) closure;
499     delete qimg;
500 }
501
502 static cairo_status_t
503 _cairo_qt_surface_acquire_source_image (void *abstract_surface,
504                                         cairo_image_surface_t **image_out,
505                                         void **image_extra)
506 {
507     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
508
509     D(fprintf(stderr, "q[%p] acquire_source_image\n", abstract_surface));
510
511     *image_extra = NULL;
512
513     if (qs->image_equiv) {
514         *image_out = (cairo_image_surface_t*)
515                      cairo_surface_reference (qs->image_equiv);
516
517         return CAIRO_STATUS_SUCCESS;
518     }
519
520     if (qs->pixmap) {
521         QImage *qimg = new QImage(qs->pixmap->toImage());
522         cairo_surface_t *image;
523         cairo_status_t status;
524
525         image = cairo_image_surface_create_for_data (qimg->bits(),
526                                                      _cairo_format_from_qimage_format (qimg->format()),
527                                                      qimg->width(), qimg->height(),
528                                                      qimg->bytesPerLine());
529
530         status = _cairo_user_data_array_set_data (&image->user_data,
531                                                   (const cairo_user_data_key_t *)&_qimg_destroy,
532                                                   qimg,
533                                                   _qimg_destroy);
534         if (status) {
535             cairo_surface_destroy (image);
536             return status;
537         }
538
539         *image_out = (cairo_image_surface_t *) image;
540         return CAIRO_STATUS_SUCCESS;
541     }
542
543     return _cairo_error (CAIRO_STATUS_NO_MEMORY);
544 }
545
546 static void
547 _cairo_qt_surface_release_source_image (void *abstract_surface,
548                                         cairo_image_surface_t *image,
549                                         void *image_extra)
550 {
551     //cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
552
553     D(fprintf(stderr, "q[%p] release_source_image\n", abstract_surface));
554
555     cairo_surface_destroy (&image->base);
556 }
557
558 static cairo_status_t
559 _cairo_qt_surface_acquire_dest_image (void *abstract_surface,
560                                       cairo_rectangle_int_t *interest_rect,
561                                       cairo_image_surface_t **image_out,
562                                       cairo_rectangle_int_t *image_rect,
563                                       void **image_extra)
564 {
565     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
566     QImage *qimg = NULL;
567
568     D(fprintf(stderr, "q[%p] acquire_dest_image\n", abstract_surface));
569
570     *image_extra = NULL;
571
572     if (qs->image_equiv) {
573         *image_out = (cairo_image_surface_t*)
574                      cairo_surface_reference (qs->image_equiv);
575
576         image_rect->x = qs->window.x();
577         image_rect->y = qs->window.y();
578         image_rect->width = qs->window.width();
579         image_rect->height = qs->window.height();
580
581         return CAIRO_STATUS_SUCCESS;
582     }
583
584     QPoint offset;
585
586     if (qs->pixmap) {
587         qimg = new QImage(qs->pixmap->toImage());
588     } else {
589         // Try to figure out what kind of QPaintDevice we have, and
590         // how we can grab an image from it
591         QPaintDevice *pd = qs->p->device();
592         if (!pd)
593             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
594
595         QPaintDevice *rpd = QPainter::redirected(pd, &offset);
596         if (rpd)
597             pd = rpd;
598
599         if (pd->devType() == QInternal::Image) {
600             qimg = new QImage(((QImage*) pd)->copy());
601         } else if (pd->devType() == QInternal::Pixmap) {
602             qimg = new QImage(((QPixmap*) pd)->toImage());
603         } else if (pd->devType() == QInternal::Widget) {
604             qimg = new QImage(QPixmap::grabWindow(((QWidget*)pd)->winId()).toImage());
605         }
606     }
607
608     if (qimg == NULL)
609         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
610
611     *image_out = (cairo_image_surface_t*)
612                  cairo_image_surface_create_for_data (qimg->bits(),
613                                                       _cairo_format_from_qimage_format (qimg->format()),
614                                                       qimg->width(), qimg->height(),
615                                                       qimg->bytesPerLine());
616     *image_extra = qimg;
617
618     image_rect->x = qs->window.x() + offset.x();
619     image_rect->y = qs->window.y() + offset.y();
620     image_rect->width = qs->window.width() - offset.x();
621     image_rect->height = qs->window.height() - offset.y();
622
623     return CAIRO_STATUS_SUCCESS;
624 }
625
626 static void
627 _cairo_qt_surface_release_dest_image (void *abstract_surface,
628                                       cairo_rectangle_int_t *interest_rect,
629                                       cairo_image_surface_t *image,
630                                       cairo_rectangle_int_t *image_rect,
631                                       void *image_extra)
632 {
633     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
634     D(fprintf(stderr, "q[%p] release_dest_image\n", abstract_surface));
635
636     cairo_surface_destroy (&image->base);
637
638     if (image_extra) {
639         QImage *qimg = (QImage*) image_extra;
640
641         // XXX should I be using setBackgroundMode here instead of setCompositionMode?
642         if (qs->supports_porter_duff)
643             qs->p->setCompositionMode (QPainter::CompositionMode_Source);
644
645         qs->p->drawImage (image_rect->x, image_rect->y, *qimg);
646
647         if (qs->supports_porter_duff)
648             qs->p->setCompositionMode (QPainter::CompositionMode_SourceOver);
649
650         delete qimg;
651     }
652 }
653
654 static cairo_bool_t
655 _cairo_qt_surface_get_extents (void *abstract_surface,
656                                cairo_rectangle_int_t *extents)
657 {
658     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
659
660     extents->x = qs->window.x();
661     extents->y = qs->window.y();
662     extents->width  = qs->window.width();
663     extents->height = qs->window.height();
664
665     return TRUE;
666 }
667
668 static cairo_status_t
669 _cairo_qt_surface_clipper_intersect_clip_path (cairo_surface_clipper_t *clipper,
670                                                cairo_path_fixed_t *path,
671                                                cairo_fill_rule_t fill_rule,
672                                                double tolerance,
673                                                cairo_antialias_t antialias)
674 {
675     cairo_qt_surface_t *qs = cairo_container_of (clipper,
676                                                  cairo_qt_surface_t,
677                                                  clipper);
678
679     if (path == NULL) {
680         if (qs->pixmap || qs->image) {
681             // we own p
682             qs->p->setClipping (false);
683         } else {
684             qs->p->restore ();
685             qs->p->save ();
686         }
687     } else {
688         // XXX Antialiasing is ignored
689         qs->p->setClipPath (path_to_qt (path, fill_rule), Qt::IntersectClip);
690     }
691
692     return CAIRO_STATUS_SUCCESS;
693 }
694
695 static void
696 _cairo_qt_surface_set_clip_region (cairo_qt_surface_t *qs,
697                                    const cairo_region_t *clip_region)
698 {
699     _cairo_surface_clipper_reset (&qs->clipper);
700
701     if (clip_region == NULL) {
702         // How the clip path is reset depends on whether we own p or not
703         if (qs->pixmap || qs->image) {
704             // we own p
705             qs->p->setClipping (false);
706         } else {
707             qs->p->restore ();
708             qs->p->save ();
709         }
710     } else {
711         QRegion qr;
712         int num_rects = cairo_region_num_rectangles (clip_region);
713         for (int i = 0; i < num_rects; ++i) {
714             cairo_rectangle_int_t rect;
715
716             cairo_region_get_rectangle (clip_region, i, &rect);
717
718             QRect r(rect.x, rect.y, rect.width, rect.height);
719             qr = qr.unite(r);
720         }
721
722         qs->p->setClipRegion (qr, Qt::IntersectClip);
723     }
724 }
725
726 static cairo_int_status_t
727 _cairo_qt_surface_set_clip (cairo_qt_surface_t *qs,
728                             const cairo_clip_t *clip)
729 {
730     cairo_int_status_t status;
731
732     D(fprintf(stderr, "q[%p] intersect_clip_path %s\n", abstract_surface, path ? "(path)" : "(clear)"));
733
734     if (clip == NULL) {
735         _cairo_surface_clipper_reset (&qs->clipper);
736         // How the clip path is reset depends on whether we own p or not
737         if (qs->pixmap || qs->image) {
738             // we own p
739             qs->p->setClipping (false);
740         } else {
741             qs->p->restore ();
742             qs->p->save ();
743         }
744
745         return CAIRO_INT_STATUS_SUCCESS;
746     }
747
748 #if ENABLE_FAST_CLIP
749     // Qt will implicitly enable clipping, and will use ReplaceClip
750     // instead of IntersectClip if clipping was disabled before
751
752     // Note: Qt is really bad at dealing with clip paths.  It doesn't
753     // seem to usefully recognize rectangular paths, instead going down
754     // extremely slow paths whenever a clip path is set.  So,
755     // we do a bunch of work here to try to get rectangles or regions
756     // down to Qt for clipping.
757
758     cairo_region_t *clip_region = NULL;
759
760     status = _cairo_clip_get_region (clip, &clip_region);
761     if (status == CAIRO_INT_STATUS_UNSUPPORTED) {
762         // We weren't able to extract a region from the traps.
763         // Just hand the path down to QPainter.
764         status = (cairo_int_status_t)
765             _cairo_surface_clipper_set_clip (&qs->clipper, clip);
766     } else if (status == CAIRO_INT_STATUS_SUCCESS) {
767         _cairo_qt_surface_set_clip_region (qs, clip_region);
768         status = CAIRO_INT_STATUS_SUCCESS;
769     }
770 #else
771     status = (cairo_int_status_t)
772         _cairo_surface_clipper_set_clip (&qs->clipper, clip);
773 #endif
774
775     return status;
776 }
777
778 /*
779  * Brush conversion
780  */
781
782 struct PatternToBrushConverter {
783     PatternToBrushConverter (const cairo_pattern_t *pattern) :
784         mAcquiredImageParent(0),
785         mAcquiredImage(0),
786         mAcquiredImageExtra(0)
787     {
788         if (pattern->type == CAIRO_PATTERN_TYPE_SOLID) {
789             cairo_solid_pattern_t *solid = (cairo_solid_pattern_t*) pattern;
790             QColor color;
791             color.setRgbF(solid->color.red,
792                           solid->color.green,
793                           solid->color.blue,
794                           solid->color.alpha);
795
796             mBrush = QBrush(color);
797         } else if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
798             cairo_surface_pattern_t *spattern = (cairo_surface_pattern_t*) pattern;
799             cairo_surface_t *surface = spattern->surface;
800
801             if (surface->type == CAIRO_SURFACE_TYPE_QT) {
802                 cairo_qt_surface_t *qs = (cairo_qt_surface_t*) surface;
803
804                 if (qs->image) {
805                     mBrush = QBrush(*qs->image);
806                 } else if (qs->pixmap) {
807                     mBrush = QBrush(*qs->pixmap);
808                 } else {
809                     // do something smart
810                     mBrush = QBrush(0xff0000ff);
811                 }
812             } else {
813                 cairo_image_surface_t *isurf = NULL;
814
815                 if (surface->type == CAIRO_SURFACE_TYPE_IMAGE) {
816                     isurf = (cairo_image_surface_t*) surface;
817                 } else {
818                     void *image_extra;
819
820                     if (_cairo_surface_acquire_source_image (surface, &isurf, &image_extra) == CAIRO_STATUS_SUCCESS) {
821                         mAcquiredImageParent = surface;
822                         mAcquiredImage = isurf;
823                         mAcquiredImageExtra = image_extra;
824                     } else {
825                         isurf = NULL;
826                     }
827                 }
828
829                 if (isurf) {
830                     mBrush = QBrush (QImage ((const uchar *) isurf->data,
831                                                  isurf->width,
832                                                  isurf->height,
833                                                  isurf->stride,
834                                                  _qimage_format_from_cairo_format (isurf->format)));
835                 } else {
836                     mBrush = QBrush(0x0000ffff);
837                 }
838             }
839         } else if (pattern->type == CAIRO_PATTERN_TYPE_LINEAR ||
840                    pattern->type == CAIRO_PATTERN_TYPE_RADIAL)
841         {
842             QGradient *grad;
843             cairo_bool_t reverse_stops = FALSE;
844             cairo_bool_t emulate_reflect = FALSE;
845             double offset = 0.0;
846
847             cairo_extend_t extend = pattern->extend;
848
849             cairo_gradient_pattern_t *gpat = (cairo_gradient_pattern_t *) pattern;
850
851             if (pattern->type == CAIRO_PATTERN_TYPE_LINEAR) {
852                 cairo_linear_pattern_t *lpat = (cairo_linear_pattern_t *) pattern;
853                 grad = new QLinearGradient (lpat->pd1.x, lpat->pd1.y,
854                                             lpat->pd2.x, lpat->pd2.y);
855             } else if (pattern->type == CAIRO_PATTERN_TYPE_RADIAL) {
856                 cairo_radial_pattern_t *rpat = (cairo_radial_pattern_t *) pattern;
857
858                 /* Based on the SVG surface code */
859
860                 cairo_circle_double_t *c0, *c1;
861                 double x0, y0, r0, x1, y1, r1;
862
863                 if (rpat->cd1.radius < rpat->cd2.radius) {
864                     c0 = &rpat->cd1;
865                     c1 = &rpat->cd2;
866                     reverse_stops = FALSE;
867                 } else {
868                     c0 = &rpat->cd2;
869                     c1 = &rpat->cd1;
870                     reverse_stops = TRUE;
871                 }
872
873                 x0 = c0->center.x;
874                 y0 = c0->center.y;
875                 r0 = c0->radius;
876                 x1 = c1->center.x;
877                 y1 = c1->center.y;
878                 r1 = c1->radius;
879
880                 if (r0 == r1) {
881                     grad = new QRadialGradient (x1, y1, r1, x1, y1);
882                 } else {
883                     double fx = (r1 * x0 - r0 * x1) / (r1 - r0);
884                     double fy = (r1 * y0 - r0 * y1) / (r1 - r0);
885
886                     /* QPainter doesn't support the inner circle and use instead a gradient focal.
887                      * That means we need to emulate the cairo behaviour by processing the
888                      * cairo gradient stops.
889                      * The CAIRO_EXTENT_NONE and CAIRO_EXTENT_PAD modes are quite easy to handle,
890                      * it's just a matter of stop position translation and calculation of
891                      * the corresponding SVG radial gradient focal.
892                      * The CAIRO_EXTENT_REFLECT and CAIRO_EXTEND_REPEAT modes require to compute a new
893                      * radial gradient, with an new outer circle, equal to r1 - r0 in the CAIRO_EXTEND_REPEAT
894                      * case, and 2 * (r1 - r0) in the CAIRO_EXTENT_REFLECT case, and a new gradient stop
895                      * list that maps to the original cairo stop list.
896                      */
897                     if ((extend == CAIRO_EXTEND_REFLECT || extend == CAIRO_EXTEND_REPEAT) && r0 > 0.0) {
898                         double r_org = r1;
899                         double r, x, y;
900
901                         if (extend == CAIRO_EXTEND_REFLECT) {
902                             r1 = 2 * r1 - r0;
903                             emulate_reflect = TRUE;
904                         }
905
906                         offset = fmod (r1, r1 - r0) / (r1 - r0) - 1.0;
907                         r = r1 - r0;
908
909                         /* New position of outer circle. */
910                         x = r * (x1 - fx) / r_org + fx;
911                         y = r * (y1 - fy) / r_org + fy;
912
913                         x1 = x;
914                         y1 = y;
915                         r1 = r;
916                         r0 = 0.0;
917                     } else {
918                         offset = r0 / r1;
919                     }
920
921                     grad = new QRadialGradient (x1, y1, r1, fx, fy);
922
923                     if (extend == CAIRO_EXTEND_NONE && r0 != 0.0)
924                         grad->setColorAt (r0 / r1, Qt::transparent);
925                 }
926             }
927
928             switch (extend) {
929                 case CAIRO_EXTEND_NONE:
930                 case CAIRO_EXTEND_PAD:
931                     grad->setSpread(QGradient::PadSpread);
932
933                     grad->setColorAt (0.0, Qt::transparent);
934                     grad->setColorAt (1.0, Qt::transparent);
935                     break;
936
937                 case CAIRO_EXTEND_REFLECT:
938                     grad->setSpread(QGradient::ReflectSpread);
939                     break;
940
941                 case CAIRO_EXTEND_REPEAT:
942                     grad->setSpread(QGradient::RepeatSpread);
943                     break;
944             }
945
946             for (unsigned int i = 0; i < gpat->n_stops; i++) {
947                 int index = i;
948                 if (reverse_stops)
949                     index = gpat->n_stops - i - 1;
950
951                 double offset = gpat->stops[i].offset;
952                 QColor color;
953                 color.setRgbF (gpat->stops[i].color.red,
954                                gpat->stops[i].color.green,
955                                gpat->stops[i].color.blue,
956                                gpat->stops[i].color.alpha);
957
958                 if (emulate_reflect) {
959                     offset = offset / 2.0;
960                     grad->setColorAt (1.0 - offset, color);
961                 }
962
963                 grad->setColorAt (offset, color);
964             }
965
966             mBrush = QBrush(*grad);
967
968             delete grad;
969         }
970
971         if (mBrush.style() != Qt::NoBrush  &&
972             pattern->type != CAIRO_PATTERN_TYPE_SOLID &&
973             ! _cairo_matrix_is_identity (&pattern->matrix))
974         {
975             cairo_matrix_t pm = pattern->matrix;
976             cairo_status_t status = cairo_matrix_invert (&pm);
977             assert (status == CAIRO_STATUS_SUCCESS);
978             mBrush.setMatrix (_qmatrix_from_cairo_matrix (pm));
979         }
980     }
981
982     ~PatternToBrushConverter () {
983         if (mAcquiredImageParent)
984             _cairo_surface_release_source_image (mAcquiredImageParent, mAcquiredImage, mAcquiredImageExtra);
985     }
986
987     operator QBrush& () {
988         return mBrush;
989     }
990
991     QBrush mBrush;
992
993     private:
994     cairo_surface_t *mAcquiredImageParent;
995     cairo_image_surface_t *mAcquiredImage;
996     void *mAcquiredImageExtra;
997 };
998
999 struct PatternToPenConverter {
1000     PatternToPenConverter (const cairo_pattern_t *source,
1001                            const cairo_stroke_style_t *style) :
1002         mBrushConverter(source)
1003     {
1004         Qt::PenJoinStyle join = Qt::MiterJoin;
1005         Qt::PenCapStyle cap = Qt::SquareCap;
1006
1007         switch (style->line_cap) {
1008         case CAIRO_LINE_CAP_BUTT:
1009             cap = Qt::FlatCap;
1010             break;
1011         case CAIRO_LINE_CAP_ROUND:
1012             cap = Qt::RoundCap;
1013             break;
1014         case CAIRO_LINE_CAP_SQUARE:
1015             cap = Qt::SquareCap;
1016             break;
1017         }
1018
1019         switch (style->line_join) {
1020         case CAIRO_LINE_JOIN_MITER:
1021             join = Qt::MiterJoin;
1022             break;
1023         case CAIRO_LINE_JOIN_ROUND:
1024             join = Qt::RoundJoin;
1025             break;
1026         case CAIRO_LINE_JOIN_BEVEL:
1027             join = Qt::BevelJoin;
1028             break;
1029         }
1030
1031         mPen = QPen(mBrushConverter, style->line_width, Qt::SolidLine, cap, join);
1032         mPen.setMiterLimit (style->miter_limit);
1033
1034         if (style->dash && style->num_dashes) {
1035             Qt::PenStyle pstyle = Qt::NoPen;
1036
1037             if (style->num_dashes == 2) {
1038                 if ((style->dash[0] == style->line_width &&
1039                         style->dash[1] == style->line_width && style->line_width <= 2.0) ||
1040                     (style->dash[0] == 0.0 &&
1041                         style->dash[1] == style->line_width * 2 && cap == Qt::RoundCap))
1042                 {
1043                     pstyle = Qt::DotLine;
1044                 } else if (style->dash[0] == style->line_width * DASH_LENGTH &&
1045                            style->dash[1] == style->line_width * DASH_LENGTH &&
1046                            cap == Qt::FlatCap)
1047                 {
1048                     pstyle = Qt::DashLine;
1049                 }
1050             }
1051
1052             if (pstyle != Qt::NoPen) {
1053                 mPen.setStyle(pstyle);
1054                 return;
1055             }
1056
1057             unsigned int odd_dash = style->num_dashes % 2;
1058
1059             QVector<qreal> dashes (odd_dash ? style->num_dashes * 2 : style->num_dashes);
1060             for (unsigned int i = 0; i < odd_dash+1; i++) {
1061                 for (unsigned int j = 0; j < style->num_dashes; j++) {
1062                     // In Qt, the dash lengths are given in units of line width, whereas
1063                     // in cairo, they are in user-space units.  We'll always apply the CTM,
1064                     // so all we have to do here is divide cairo's dash lengths by the line
1065                     // width.
1066                     dashes.append (style->dash[j] / style->line_width);
1067                 }
1068             }
1069
1070             mPen.setDashPattern(dashes);
1071             mPen.setDashOffset(style->dash_offset / style->line_width);
1072         }
1073     }
1074
1075     ~PatternToPenConverter() { }
1076
1077     operator QPen& () {
1078         return mPen;
1079     }
1080
1081     QPen mPen;
1082     PatternToBrushConverter mBrushConverter;
1083 };
1084
1085 /*
1086  * Core drawing operations
1087  */
1088
1089 static bool
1090 _cairo_qt_fast_fill (cairo_qt_surface_t *qs,
1091                      const cairo_pattern_t *source,
1092                      const cairo_path_fixed_t *path = NULL,
1093                      cairo_fill_rule_t fill_rule = CAIRO_FILL_RULE_WINDING,
1094                      double tolerance = 0.0,
1095                      cairo_antialias_t antialias = CAIRO_ANTIALIAS_NONE)
1096 {
1097 #if ENABLE_FAST_FILL
1098     QImage *qsSrc_image = NULL;
1099     QPixmap *qsSrc_pixmap = NULL;
1100     std::auto_ptr<QImage> qsSrc_image_d;
1101
1102
1103     if (source->type == CAIRO_PATTERN_TYPE_SURFACE) {
1104         cairo_surface_pattern_t *spattern = (cairo_surface_pattern_t*) source;
1105         if (spattern->surface->type == CAIRO_SURFACE_TYPE_QT) {
1106             cairo_qt_surface_t *p = (cairo_qt_surface_t*) spattern->surface;
1107
1108             qsSrc_image = p->image;
1109             qsSrc_pixmap = p->pixmap;
1110         } else if (spattern->surface->type == CAIRO_SURFACE_TYPE_IMAGE) {
1111             cairo_image_surface_t *p = (cairo_image_surface_t*) spattern->surface;
1112             qsSrc_image = new QImage((const uchar*) p->data,
1113                                      p->width,
1114                                      p->height,
1115                                      p->stride,
1116                                      _qimage_format_from_cairo_format(p->format));
1117             qsSrc_image_d.reset(qsSrc_image);
1118         }
1119     }
1120
1121     if (!qsSrc_image && !qsSrc_pixmap)
1122         return false;
1123
1124     // We can only drawTiledPixmap; there's no drawTiledImage
1125     if (! qsSrc_pixmap &&
1126         (source->extend == CAIRO_EXTEND_REPEAT ||
1127          source->extend == CAIRO_EXTEND_REFLECT))
1128     {
1129         return false;
1130     }
1131
1132     QMatrix sourceMatrix = _qmatrix_from_cairo_matrix (source->matrix);
1133
1134     // We can draw this faster by clipping and calling drawImage/drawPixmap.
1135     // Use our own clipping function so that we can get the
1136     // region handling to end up with the fastest possible clip.
1137     //
1138     // XXX Antialiasing will fail pretty hard here, since we can't clip with AA
1139     // with QPainter.
1140     qs->p->save();
1141
1142     if (path) {
1143         cairo_int_status_t status;
1144
1145         cairo_clip_t clip, old_clip = qs->clipper.clip;
1146
1147         _cairo_clip_init_copy (&clip, &qs->clipper.clip);
1148         status = (cairo_int_status_t) _cairo_clip_clip (&clip,
1149                                                         path,
1150                                                         fill_rule,
1151                                                         tolerance,
1152                                                         antialias);
1153         if (unlikely (status)) {
1154             qs->p->restore();
1155             return false;
1156         }
1157
1158         status = _cairo_qt_surface_set_clip (qs, &clip);
1159         if (unlikely (status)) {
1160             qs->p->restore();
1161             return false;
1162         }
1163
1164         _cairo_clip_reset (&clip);
1165         qs->clipper.clip = old_clip;
1166     }
1167
1168     qs->p->setWorldMatrix (sourceMatrix.inverted(), true);
1169
1170     switch (source->extend) {
1171     case CAIRO_EXTEND_REPEAT:
1172     // XXX handle reflect by tiling 4 times first
1173     case CAIRO_EXTEND_REFLECT: {
1174             assert (qsSrc_pixmap);
1175
1176             // Render the tiling to cover the entire destination window (because
1177             // it'll be clipped).  Transform the window rect by the inverse
1178             // of the current world transform so that the device coordinates
1179             // end up as the right thing.
1180             QRectF dest = qs->p->worldTransform().inverted().mapRect(QRectF(qs->window));
1181             QPointF origin = sourceMatrix.map(QPointF(0.0, 0.0));
1182
1183             qs->p->drawTiledPixmap (dest, *qsSrc_pixmap, origin);
1184         }
1185         break;
1186     case CAIRO_EXTEND_NONE:
1187     case CAIRO_EXTEND_PAD: // XXX not exactly right, but good enough
1188     default:
1189         if (qsSrc_image)
1190             qs->p->drawImage (0, 0, *qsSrc_image);
1191         else if (qsSrc_pixmap)
1192             qs->p->drawPixmap (0, 0, *qsSrc_pixmap);
1193         break;
1194     }
1195
1196     qs->p->restore();
1197
1198     return true;
1199 #else
1200     return false;
1201 #endif
1202 }
1203
1204 static cairo_int_status_t
1205 _cairo_qt_surface_paint (void *abstract_surface,
1206                          cairo_operator_t op,
1207                          const cairo_pattern_t *source,
1208                          const cairo_clip_t            *clip)
1209 {
1210     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1211     cairo_int_status_t status;
1212
1213     D(fprintf(stderr, "q[%p] paint op:%s\n", abstract_surface, _opstr(op)));
1214
1215     if (!qs->p)
1216         return CAIRO_INT_STATUS_UNSUPPORTED;
1217
1218     if (! _op_is_supported (qs, op))
1219         return CAIRO_INT_STATUS_UNSUPPORTED;
1220
1221     status = _cairo_qt_surface_set_clip (qs, clip);
1222     if (unlikely (status))
1223         return status;
1224
1225     if (qs->supports_porter_duff)
1226         qs->p->setCompositionMode (_qpainter_compositionmode_from_cairo_op (op));
1227
1228     if (! _cairo_qt_fast_fill (qs, source)) {
1229         PatternToBrushConverter brush (source);
1230         qs->p->fillRect (qs->window, brush);
1231     }
1232
1233     if (qs->supports_porter_duff)
1234         qs->p->setCompositionMode (QPainter::CompositionMode_SourceOver);
1235
1236     return CAIRO_INT_STATUS_SUCCESS;
1237 }
1238
1239 static cairo_int_status_t
1240 _cairo_qt_surface_fill (void *abstract_surface,
1241                         cairo_operator_t op,
1242                         const cairo_pattern_t *source,
1243                         const cairo_path_fixed_t *path,
1244                         cairo_fill_rule_t fill_rule,
1245                         double tolerance,
1246                         cairo_antialias_t antialias,
1247                         const cairo_clip_t *clip)
1248 {
1249     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1250
1251     D(fprintf(stderr, "q[%p] fill op:%s\n", abstract_surface, _opstr(op)));
1252
1253     if (!qs->p)
1254         return CAIRO_INT_STATUS_UNSUPPORTED;
1255
1256     if (! _op_is_supported (qs, op))
1257         return CAIRO_INT_STATUS_UNSUPPORTED;
1258
1259     cairo_int_status_t status = _cairo_qt_surface_set_clip (qs, clip);
1260     if (unlikely (status))
1261         return status;
1262
1263     if (qs->supports_porter_duff)
1264         qs->p->setCompositionMode (_qpainter_compositionmode_from_cairo_op (op));
1265
1266     // XXX Qt4.3, 4.4 misrenders some complex paths if antialiasing is
1267     // enabled
1268     //qs->p->setRenderHint (QPainter::Antialiasing, antialias == CAIRO_ANTIALIAS_NONE ? false : true);
1269     qs->p->setRenderHint (QPainter::SmoothPixmapTransform, source->filter != CAIRO_FILTER_FAST);
1270
1271     if (! _cairo_qt_fast_fill (qs, source,
1272                                path, fill_rule, tolerance, antialias))
1273     {
1274         PatternToBrushConverter brush(source);
1275         qs->p->fillPath (path_to_qt (path, fill_rule), brush);
1276     }
1277
1278     if (qs->supports_porter_duff)
1279         qs->p->setCompositionMode (QPainter::CompositionMode_SourceOver);
1280
1281     return CAIRO_INT_STATUS_SUCCESS;
1282 }
1283
1284 static cairo_int_status_t
1285 _cairo_qt_surface_stroke (void *abstract_surface,
1286                           cairo_operator_t op,
1287                           const cairo_pattern_t *source,
1288                           const cairo_path_fixed_t *path,
1289                           const cairo_stroke_style_t *style,
1290                           const cairo_matrix_t *ctm,
1291                           const cairo_matrix_t *ctm_inverse,
1292                           double tolerance,
1293                           cairo_antialias_t antialias,
1294                           const cairo_clip_t *clip)
1295 {
1296     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1297
1298     D(fprintf(stderr, "q[%p] stroke op:%s\n", abstract_surface, _opstr(op)));
1299
1300     if (!qs->p)
1301         return CAIRO_INT_STATUS_UNSUPPORTED;
1302
1303     if (! _op_is_supported (qs, op))
1304         return CAIRO_INT_STATUS_UNSUPPORTED;
1305
1306     cairo_int_status_t int_status = _cairo_qt_surface_set_clip (qs, clip);
1307     if (unlikely (int_status))
1308         return int_status;
1309
1310
1311     QMatrix savedMatrix = qs->p->worldMatrix();
1312
1313     if (qs->supports_porter_duff)
1314         qs->p->setCompositionMode (_qpainter_compositionmode_from_cairo_op (op));
1315
1316     qs->p->setWorldMatrix (_qmatrix_from_cairo_matrix (*ctm), true);
1317     // XXX Qt4.3, 4.4 misrenders some complex paths if antialiasing is
1318     // enabled
1319     //qs->p->setRenderHint (QPainter::Antialiasing, antialias == CAIRO_ANTIALIAS_NONE ? false : true);
1320     qs->p->setRenderHint (QPainter::SmoothPixmapTransform, source->filter != CAIRO_FILTER_FAST);
1321
1322     PatternToPenConverter pen(source, style);
1323
1324     qs->p->setPen(pen);
1325     qs->p->drawPath(path_to_qt (path, ctm_inverse));
1326     qs->p->setPen(Qt::black);
1327
1328     qs->p->setWorldMatrix (savedMatrix, false);
1329
1330     if (qs->supports_porter_duff)
1331         qs->p->setCompositionMode (QPainter::CompositionMode_SourceOver);
1332
1333     return CAIRO_INT_STATUS_SUCCESS;
1334 }
1335
1336 static cairo_int_status_t
1337 _cairo_qt_surface_show_glyphs (void *abstract_surface,
1338                                cairo_operator_t op,
1339                                const cairo_pattern_t *source,
1340                                cairo_glyph_t *glyphs,
1341                                int num_glyphs,
1342                                cairo_scaled_font_t *scaled_font,
1343                                const cairo_clip_t *clip)
1344 {
1345 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)) || defined(QT_GLYPHS_API_BACKPORT)
1346     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1347
1348     // pick out the colour to use from the cairo source
1349     cairo_solid_pattern_t *solid = (cairo_solid_pattern_t*) source;
1350     cairo_scaled_glyph_t* glyph;
1351     // documentation says you have to freeze the cache, but I don't believe it
1352     _cairo_scaled_font_freeze_cache(scaled_font);
1353
1354     QColor tempColour(solid->color.red * 255, solid->color.green * 255, solid->color.blue * 255);
1355     QVarLengthArray<QPointF> positions(num_glyphs);
1356     QVarLengthArray<unsigned int> glyphss(num_glyphs);
1357     FT_Face face = cairo_ft_scaled_font_lock_face (scaled_font);
1358     const FT_Size_Metrics& ftMetrics = face->size->metrics;
1359     QFont font(face->family_name);
1360     font.setStyleStrategy(QFont::NoFontMerging);
1361     font.setBold(face->style_flags & FT_STYLE_FLAG_BOLD);
1362     font.setItalic(face->style_flags & FT_STYLE_FLAG_ITALIC);
1363     font.setKerning(face->face_flags & FT_FACE_FLAG_KERNING);
1364     font.setPixelSize(ftMetrics.y_ppem);
1365     cairo_ft_scaled_font_unlock_face(scaled_font);
1366     qs->p->setFont(font);
1367     qs->p->setPen(tempColour);
1368     for (int currentGlyph = 0; currentGlyph < num_glyphs; currentGlyph++) {
1369         positions[currentGlyph].setX(glyphs[currentGlyph].x);
1370         positions[currentGlyph].setY(glyphs[currentGlyph].y);
1371         glyphss[currentGlyph] = glyphs[currentGlyph].index;
1372     }
1373     qt_draw_glyphs(qs->p, glyphss.data(), positions.data(), num_glyphs);
1374     _cairo_scaled_font_thaw_cache(scaled_font);
1375     return CAIRO_INT_STATUS_SUCCESS;
1376 #else
1377     return CAIRO_INT_STATUS_UNSUPPORTED;
1378 #endif
1379 }
1380
1381 static cairo_int_status_t
1382 _cairo_qt_surface_mask (void *abstract_surface,
1383                         cairo_operator_t op,
1384                         const cairo_pattern_t *source,
1385                         const cairo_pattern_t *mask,
1386                         const cairo_clip_t          *clip)
1387 {
1388     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1389
1390     D(fprintf(stderr, "q[%p] mask op:%s\n", abstract_surface, _opstr(op)));
1391
1392     if (!qs->p)
1393         return CAIRO_INT_STATUS_UNSUPPORTED;
1394
1395     if (mask->type == CAIRO_PATTERN_TYPE_SOLID) {
1396         cairo_solid_pattern_t *solid_mask = (cairo_solid_pattern_t *) mask;
1397         cairo_int_status_t result;
1398
1399         qs->p->setOpacity (solid_mask->color.alpha);
1400
1401         result = _cairo_qt_surface_paint (abstract_surface, op, source, clip);
1402
1403         qs->p->setOpacity (1.0);
1404
1405         return result;
1406     }
1407
1408     // otherwise skip for now
1409     return CAIRO_INT_STATUS_UNSUPPORTED;
1410 }
1411
1412 static cairo_status_t
1413 _cairo_qt_surface_mark_dirty (void *abstract_surface,
1414                               int x, int y,
1415                               int width, int height)
1416 {
1417     cairo_qt_surface_t *qs = (cairo_qt_surface_t *) abstract_surface;
1418
1419     if (qs->p && !(qs->image || qs->pixmap))
1420         qs->p->save ();
1421
1422     return CAIRO_STATUS_SUCCESS;
1423 }
1424
1425 /*
1426  * Backend struct
1427  */
1428
1429 static const cairo_surface_backend_t cairo_qt_surface_backend = {
1430     CAIRO_SURFACE_TYPE_QT,
1431     _cairo_qt_surface_finish,
1432     _cairo_default_context_create, /* XXX */
1433     _cairo_qt_surface_create_similar,
1434     NULL, /* similar image */
1435     NULL, /* map to image */
1436     NULL, /* unmap image */
1437     _cairo_surface_default_source,
1438     _cairo_qt_surface_acquire_source_image,
1439     _cairo_qt_surface_release_source_image,
1440     NULL, /* snapshot */
1441     NULL, /* copy_page */
1442     NULL, /* show_page */
1443     _cairo_qt_surface_get_extents,
1444     NULL, /* get_font_options */
1445     NULL, /* flush */
1446     _cairo_qt_surface_mark_dirty,
1447     _cairo_qt_surface_paint,
1448     _cairo_qt_surface_mask,
1449     _cairo_qt_surface_stroke,
1450     _cairo_qt_surface_fill,
1451     NULL, /* fill_stroke */
1452     _cairo_qt_surface_show_glyphs
1453 };
1454
1455 cairo_surface_t *
1456 cairo_qt_surface_create (QPainter *painter)
1457 {
1458     cairo_qt_surface_t *qs;
1459
1460     qs = (cairo_qt_surface_t *) malloc (sizeof(cairo_qt_surface_t));
1461     if (qs == NULL)
1462         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
1463
1464     memset (qs, 0, sizeof(cairo_qt_surface_t));
1465
1466     _cairo_surface_init (&qs->base,
1467                          &cairo_qt_surface_backend,
1468                          NULL, /* device */
1469                          CAIRO_CONTENT_COLOR_ALPHA);
1470
1471     _cairo_surface_clipper_init (&qs->clipper,
1472                                  _cairo_qt_surface_clipper_intersect_clip_path);
1473
1474     qs->p = painter;
1475     if (qs->p->paintEngine())
1476         qs->supports_porter_duff = qs->p->paintEngine()->hasFeature(QPaintEngine::PorterDuff);
1477     else
1478         qs->supports_porter_duff = FALSE;
1479
1480     // Save so that we can always get back to the original state
1481     qs->p->save();
1482
1483     qs->window = painter->window();
1484
1485     D(fprintf(stderr, "qpainter_surface_create: window: [%d %d %d %d] pd:%d\n",
1486               qs->window.x(), qs->window.y(), qs->window.width(), qs->window.height(),
1487               qs->supports_porter_duff));
1488
1489     return &qs->base;
1490 }
1491
1492 cairo_surface_t *
1493 cairo_qt_surface_create_with_qimage (cairo_format_t format,
1494                                      int width,
1495                                      int height)
1496 {
1497     cairo_qt_surface_t *qs;
1498
1499     qs = (cairo_qt_surface_t *) malloc (sizeof(cairo_qt_surface_t));
1500     if (qs == NULL)
1501         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
1502
1503     memset (qs, 0, sizeof(cairo_qt_surface_t));
1504
1505     _cairo_surface_init (&qs->base,
1506                          &cairo_qt_surface_backend,
1507                          NULL, /* device */
1508                          _cairo_content_from_format (format));
1509
1510     _cairo_surface_clipper_init (&qs->clipper,
1511                                  _cairo_qt_surface_clipper_intersect_clip_path);
1512
1513
1514     QImage *image = new QImage (width, height,
1515                                 _qimage_format_from_cairo_format (format));
1516
1517     qs->image = image;
1518
1519     if (!image->isNull()) {
1520         qs->p = new QPainter(image);
1521         qs->supports_porter_duff = qs->p->paintEngine()->hasFeature(QPaintEngine::PorterDuff);
1522     }
1523
1524     qs->image_equiv = cairo_image_surface_create_for_data (image->bits(),
1525                                                            format,
1526                                                            width, height,
1527                                                            image->bytesPerLine());
1528
1529     qs->window = QRect(0, 0, width, height);
1530
1531     D(fprintf(stderr, "qpainter_surface_create: qimage: [%d %d %d %d] pd:%d\n",
1532               qs->window.x(), qs->window.y(), qs->window.width(), qs->window.height(),
1533               qs->supports_porter_duff));
1534
1535     return &qs->base;
1536 }
1537
1538 cairo_surface_t *
1539 cairo_qt_surface_create_with_qpixmap (cairo_content_t content,
1540                                       int width,
1541                                       int height)
1542 {
1543     cairo_qt_surface_t *qs;
1544
1545     if ((content & CAIRO_CONTENT_COLOR) == 0)
1546         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_CONTENT));
1547
1548     qs = (cairo_qt_surface_t *) malloc (sizeof(cairo_qt_surface_t));
1549     if (qs == NULL)
1550         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
1551
1552     memset (qs, 0, sizeof(cairo_qt_surface_t));
1553
1554     QPixmap *pixmap = new QPixmap (width, height);
1555     if (pixmap == NULL) {
1556         free (qs);
1557         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
1558     }
1559
1560     // By default, a QPixmap is opaque; however, if it's filled
1561     // with a color with a transparency component, it is converted
1562     // to a format that preserves transparency.
1563     if (content == CAIRO_CONTENT_COLOR_ALPHA)
1564         pixmap->fill(Qt::transparent);
1565
1566     _cairo_surface_init (&qs->base,
1567                          &cairo_qt_surface_backend,
1568                          NULL, /* device */
1569                          content);
1570
1571     _cairo_surface_clipper_init (&qs->clipper,
1572                                  _cairo_qt_surface_clipper_intersect_clip_path);
1573
1574     qs->pixmap = pixmap;
1575
1576     if (!pixmap->isNull()) {
1577         qs->p = new QPainter(pixmap);
1578         qs->supports_porter_duff = qs->p->paintEngine()->hasFeature(QPaintEngine::PorterDuff);
1579     }
1580
1581     qs->window = QRect(0, 0, width, height);
1582
1583     D(fprintf(stderr, "qpainter_surface_create: qpixmap: [%d %d %d %d] pd:%d\n",
1584               qs->window.x(), qs->window.y(), qs->window.width(), qs->window.height(),
1585               qs->supports_porter_duff));
1586
1587     return &qs->base;
1588 }
1589
1590 QPainter *
1591 cairo_qt_surface_get_qpainter (cairo_surface_t *surface)
1592 {
1593     cairo_qt_surface_t *qs = (cairo_qt_surface_t*) surface;
1594
1595     if (surface->type != CAIRO_SURFACE_TYPE_QT)
1596         return NULL;
1597
1598     return qs->p;
1599 }
1600
1601 QImage *
1602 cairo_qt_surface_get_qimage (cairo_surface_t *surface)
1603 {
1604     cairo_qt_surface_t *qs = (cairo_qt_surface_t*) surface;
1605
1606     if (surface->type != CAIRO_SURFACE_TYPE_QT)
1607         return NULL;
1608
1609     return qs->image;
1610 }
1611
1612 cairo_surface_t *
1613 cairo_qt_surface_get_image (cairo_surface_t *surface)
1614 {
1615     cairo_qt_surface_t *qs = (cairo_qt_surface_t*) surface;
1616
1617     if (surface->type != CAIRO_SURFACE_TYPE_QT)
1618         return NULL;
1619
1620     return qs->image_equiv;
1621 }
1622
1623 /*
1624  * TODO:
1625  *
1626  * - Figure out why QBrush isn't working with non-repeated images
1627  *
1628  * - Correct repeat mode; right now, every surface source is EXTEND_REPEAT
1629  *   - implement EXTEND_NONE (?? probably need to clip to the extents of the source)
1630  *   - implement EXTEND_REFLECT (create temporary and copy 4x, then EXTEND_REPEAT that)
1631  *
1632  * - stroke-image failure
1633  *
1634  * - Implement mask() with non-solid masks (probably will need to use a temporary and use IN)
1635  *
1636  * - Implement gradient sources
1637  *
1638  * - Make create_similar smarter -- create QPixmaps in more circumstances
1639  *   (e.g. if the pixmap can have alpha)
1640  *
1641  * - Implement show_glyphs() in terms of Qt
1642  *
1643  */