]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/generic/graphicc.cpp
Ensure there is valid context for DrawRectangle
[wxWidgets.git] / src / generic / graphicc.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/generic/graphicc.cpp
3// Purpose: cairo device context class
4// Author: Stefan Csomor
5// Modified by:
6// Created: 2006-10-03
7// RCS-ID: $Id$
8// Copyright: (c) 2006 Stefan Csomor
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12#include "wx/wxprec.h"
13
14#ifdef __BORLANDC__
15 #pragma hdrstop
16#endif
17
18#if wxUSE_GRAPHICS_CONTEXT
19
20#include "wx/graphics.h"
21
22#if wxUSE_CAIRO
23
24// keep cairo.h from defining dllimport as we're defining the symbols inside
25// the wx dll in order to load them dynamically.
26#define cairo_public
27
28#include <cairo.h>
29
30bool wxCairoInit();
31
32#ifndef WX_PRECOMP
33 #include "wx/bitmap.h"
34 #include "wx/icon.h"
35 #include "wx/dcclient.h"
36 #include "wx/dcmemory.h"
37 #include "wx/dcprint.h"
38 #include "wx/window.h"
39#endif
40
41#include "wx/private/graphics.h"
42#include "wx/rawbmp.h"
43#include "wx/vector.h"
44
45using namespace std;
46
47//-----------------------------------------------------------------------------
48// device context implementation
49//
50// more and more of the dc functionality should be implemented by calling
51// the appropricate wxCairoContext, but we will have to do that step by step
52// also coordinate conversions should be moved to native matrix ops
53//-----------------------------------------------------------------------------
54
55// we always stock two context states, one at entry, to be able to preserve the
56// state we were called with, the other one after changing to HI Graphics orientation
57// (this one is used for getting back clippings etc)
58
59//-----------------------------------------------------------------------------
60// wxGraphicsPath implementation
61//-----------------------------------------------------------------------------
62
63// TODO remove this dependency (gdiplus needs the macros)
64
65#ifndef max
66#define max(a,b) (((a) > (b)) ? (a) : (b))
67#endif
68
69#ifndef min
70#define min(a,b) (((a) < (b)) ? (a) : (b))
71#endif
72
73#include <cairo.h>
74#ifdef __WXMSW__
75#include <cairo-win32.h>
76// Notice that the order is important: cairo-win32.h includes windows.h which
77// pollutes the global name space with macros so include our own header which
78// #undefines them after it.
79#include "wx/msw/private.h"
80#endif
81
82#ifdef __WXGTK__
83#include <gtk/gtk.h>
84#include "wx/fontutil.h"
85#ifndef __WXGTK3__
86#include "wx/gtk/dc.h"
87#endif
88#endif
89
90#ifdef __WXMAC__
91#include "wx/osx/private.h"
92#include <cairo-quartz.h>
93#include <cairo-atsui.h>
94#endif
95
96class WXDLLIMPEXP_CORE wxCairoPathData : public wxGraphicsPathData
97{
98public :
99 wxCairoPathData(wxGraphicsRenderer* renderer, cairo_t* path = NULL);
100 ~wxCairoPathData();
101
102 virtual wxGraphicsObjectRefData *Clone() const;
103
104 //
105 // These are the path primitives from which everything else can be constructed
106 //
107
108 // begins a new subpath at (x,y)
109 virtual void MoveToPoint( wxDouble x, wxDouble y );
110
111 // adds a straight line from the current point to (x,y)
112 virtual void AddLineToPoint( wxDouble x, wxDouble y );
113
114 // adds a cubic Bezier curve from the current point, using two control points and an end point
115 virtual void AddCurveToPoint( wxDouble cx1, wxDouble cy1, wxDouble cx2, wxDouble cy2, wxDouble x, wxDouble y );
116
117
118 // adds an arc of a circle centering at (x,y) with radius (r) from startAngle to endAngle
119 virtual void AddArc( wxDouble x, wxDouble y, wxDouble r, wxDouble startAngle, wxDouble endAngle, bool clockwise ) ;
120
121 // gets the last point of the current path, (0,0) if not yet set
122 virtual void GetCurrentPoint( wxDouble* x, wxDouble* y) const;
123
124 // adds another path
125 virtual void AddPath( const wxGraphicsPathData* path );
126
127 // closes the current sub-path
128 virtual void CloseSubpath();
129
130 //
131 // These are convenience functions which - if not available natively will be assembled
132 // using the primitives from above
133 //
134
135 /*
136
137 // appends a rectangle as a new closed subpath
138 virtual void AddRectangle( wxDouble x, wxDouble y, wxDouble w, wxDouble h ) ;
139 // appends an ellipsis as a new closed subpath fitting the passed rectangle
140 virtual void AddEllipsis( wxDouble x, wxDouble y, wxDouble w , wxDouble h ) ;
141
142 // draws a an arc to two tangents connecting (current) to (x1,y1) and (x1,y1) to (x2,y2), also a straight line from (current) to (x1,y1)
143 virtual void AddArcToPoint( wxDouble x1, wxDouble y1 , wxDouble x2, wxDouble y2, wxDouble r ) ;
144 */
145
146 // returns the native path
147 virtual void * GetNativePath() const ;
148
149 // give the native path returned by GetNativePath() back (there might be some deallocations necessary)
150 virtual void UnGetNativePath(void *p) const;
151
152 // transforms each point of this path by the matrix
153 virtual void Transform( const wxGraphicsMatrixData* matrix ) ;
154
155 // gets the bounding box enclosing all points (possibly including control points)
156 virtual void GetBox(wxDouble *x, wxDouble *y, wxDouble *w, wxDouble *h) const;
157
158 virtual bool Contains( wxDouble x, wxDouble y, wxPolygonFillMode fillStyle = wxWINDING_RULE) const;
159
160private :
161 cairo_t* m_pathContext;
162};
163
164class WXDLLIMPEXP_CORE wxCairoMatrixData : public wxGraphicsMatrixData
165{
166public :
167 wxCairoMatrixData(wxGraphicsRenderer* renderer, const cairo_matrix_t* matrix = NULL ) ;
168 virtual ~wxCairoMatrixData() ;
169
170 virtual wxGraphicsObjectRefData *Clone() const ;
171
172 // concatenates the matrix
173 virtual void Concat( const wxGraphicsMatrixData *t );
174
175 // sets the matrix to the respective values
176 virtual void Set(wxDouble a=1.0, wxDouble b=0.0, wxDouble c=0.0, wxDouble d=1.0,
177 wxDouble tx=0.0, wxDouble ty=0.0);
178
179 // gets the component valuess of the matrix
180 virtual void Get(wxDouble* a=NULL, wxDouble* b=NULL, wxDouble* c=NULL,
181 wxDouble* d=NULL, wxDouble* tx=NULL, wxDouble* ty=NULL) const;
182
183 // makes this the inverse matrix
184 virtual void Invert();
185
186 // returns true if the elements of the transformation matrix are equal ?
187 virtual bool IsEqual( const wxGraphicsMatrixData* t) const ;
188
189 // return true if this is the identity matrix
190 virtual bool IsIdentity() const;
191
192 //
193 // transformation
194 //
195
196 // add the translation to this matrix
197 virtual void Translate( wxDouble dx , wxDouble dy );
198
199 // add the scale to this matrix
200 virtual void Scale( wxDouble xScale , wxDouble yScale );
201
202 // add the rotation to this matrix (radians)
203 virtual void Rotate( wxDouble angle );
204
205 //
206 // apply the transforms
207 //
208
209 // applies that matrix to the point
210 virtual void TransformPoint( wxDouble *x, wxDouble *y ) const;
211
212 // applies the matrix except for translations
213 virtual void TransformDistance( wxDouble *dx, wxDouble *dy ) const;
214
215 // returns the native representation
216 virtual void * GetNativeMatrix() const;
217private:
218 cairo_matrix_t m_matrix ;
219} ;
220
221// Common base class for pens and brushes.
222class wxCairoPenBrushBaseData : public wxGraphicsObjectRefData
223{
224public:
225 wxCairoPenBrushBaseData(wxGraphicsRenderer* renderer,
226 const wxColour& col,
227 bool isTransparent);
228 virtual ~wxCairoPenBrushBaseData();
229
230 virtual void Apply( wxGraphicsContext* context );
231
232protected:
233 // Call this to use the given bitmap as stipple. Bitmap must be non-null
234 // and valid.
235 void InitStipple(wxBitmap* bmp);
236
237 // Call this to use the given hatch style. Hatch style must be valid.
238 void InitHatch(wxHatchStyle hatchStyle);
239
240
241 double m_red;
242 double m_green;
243 double m_blue;
244 double m_alpha;
245
246 cairo_pattern_t* m_pattern;
247 class wxCairoBitmapData* m_bmpdata;
248
249private:
250 // Called once to allocate m_pattern if needed.
251 void InitHatchPattern(cairo_t* ctext);
252
253 wxHatchStyle m_hatchStyle;
254
255 wxDECLARE_NO_COPY_CLASS(wxCairoPenBrushBaseData);
256};
257
258class WXDLLIMPEXP_CORE wxCairoPenData : public wxCairoPenBrushBaseData
259{
260public:
261 wxCairoPenData( wxGraphicsRenderer* renderer, const wxPen &pen );
262 ~wxCairoPenData();
263
264 void Init();
265
266 virtual void Apply( wxGraphicsContext* context );
267 virtual wxDouble GetWidth() { return m_width; }
268
269private :
270 double m_width;
271
272 cairo_line_cap_t m_cap;
273 cairo_line_join_t m_join;
274
275 int m_count;
276 const double *m_lengths;
277 double *m_userLengths;
278
279 wxDECLARE_NO_COPY_CLASS(wxCairoPenData);
280};
281
282class WXDLLIMPEXP_CORE wxCairoBrushData : public wxCairoPenBrushBaseData
283{
284public:
285 wxCairoBrushData( wxGraphicsRenderer* renderer );
286 wxCairoBrushData( wxGraphicsRenderer* renderer, const wxBrush &brush );
287
288 void CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
289 wxDouble x2, wxDouble y2,
290 const wxGraphicsGradientStops& stops);
291 void CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
292 wxDouble xc, wxDouble yc, wxDouble radius,
293 const wxGraphicsGradientStops& stops);
294
295protected:
296 virtual void Init();
297
298 // common part of Create{Linear,Radial}GradientBrush()
299 void AddGradientStops(const wxGraphicsGradientStops& stops);
300};
301
302class wxCairoFontData : public wxGraphicsObjectRefData
303{
304public:
305 wxCairoFontData( wxGraphicsRenderer* renderer, const wxFont &font, const wxColour& col );
306 wxCairoFontData(wxGraphicsRenderer* renderer,
307 double sizeInPixels,
308 const wxString& facename,
309 int flags,
310 const wxColour& col);
311 ~wxCairoFontData();
312
313 virtual bool Apply( wxGraphicsContext* context );
314#ifdef __WXGTK__
315 const wxFont& GetFont() const { return m_wxfont; }
316#endif
317private :
318 void InitColour(const wxColour& col);
319 void InitFontComponents(const wxString& facename,
320 cairo_font_slant_t slant,
321 cairo_font_weight_t weight);
322
323 double m_size;
324 double m_red;
325 double m_green;
326 double m_blue;
327 double m_alpha;
328#ifdef __WXMAC__
329 cairo_font_face_t *m_font;
330#elif defined(__WXGTK__)
331 wxFont m_wxfont;
332#endif
333
334 // These members are used when the font is created from its face name and
335 // flags (and not from wxFont) and also even when creating it from wxFont
336 // on the platforms not covered above.
337 //
338 // Notice that we can't use cairo_font_face_t instead of storing those,
339 // even though it would be simpler and need less #ifdefs, because
340 // cairo_toy_font_face_create() that we'd need to create it is only
341 // available in Cairo 1.8 and we require just 1.2 currently. If we do drop
342 // support for < 1.8 versions in the future it would be definitely better
343 // to use cairo_toy_font_face_create() instead.
344 wxCharBuffer m_fontName;
345 cairo_font_slant_t m_slant;
346 cairo_font_weight_t m_weight;
347};
348
349class wxCairoBitmapData : public wxGraphicsBitmapData
350{
351public:
352 wxCairoBitmapData( wxGraphicsRenderer* renderer, const wxBitmap& bmp );
353#if wxUSE_IMAGE
354 wxCairoBitmapData(wxGraphicsRenderer* renderer, const wxImage& image);
355#endif // wxUSE_IMAGE
356 wxCairoBitmapData( wxGraphicsRenderer* renderer, cairo_surface_t* bitmap );
357 ~wxCairoBitmapData();
358
359 virtual cairo_surface_t* GetCairoSurface() { return m_surface; }
360 virtual cairo_pattern_t* GetCairoPattern() { return m_pattern; }
361 virtual void* GetNativeBitmap() const { return m_surface; }
362 virtual wxSize GetSize() { return wxSize(m_width, m_height); }
363
364#if wxUSE_IMAGE
365 wxImage ConvertToImage() const;
366#endif // wxUSE_IMAGE
367
368private :
369 // Allocate m_buffer for the bitmap of the given size in the given format.
370 //
371 // Returns the stride used for the buffer.
372 int InitBuffer(int width, int height, cairo_format_t format);
373
374 // Really create the surface using the buffer (which was supposed to be
375 // filled since InitBuffer() call).
376 void InitSurface(cairo_format_t format, int stride);
377
378
379 cairo_surface_t* m_surface;
380 cairo_pattern_t* m_pattern;
381 int m_width;
382 int m_height;
383 unsigned char* m_buffer;
384};
385
386class WXDLLIMPEXP_CORE wxCairoContext : public wxGraphicsContext
387{
388public:
389 wxCairoContext( wxGraphicsRenderer* renderer, const wxWindowDC& dc );
390 wxCairoContext( wxGraphicsRenderer* renderer, const wxMemoryDC& dc );
391 wxCairoContext( wxGraphicsRenderer* renderer, const wxPrinterDC& dc );
392#ifdef __WXGTK__
393 wxCairoContext( wxGraphicsRenderer* renderer, GdkWindow *window );
394#endif
395#ifdef __WXMSW__
396 wxCairoContext( wxGraphicsRenderer* renderer, HDC context );
397#endif
398 wxCairoContext( wxGraphicsRenderer* renderer, cairo_t *context );
399 wxCairoContext( wxGraphicsRenderer* renderer, wxWindow *window);
400
401 // If this ctor is used, Init() must be called by the derived class later.
402 wxCairoContext( wxGraphicsRenderer* renderer );
403
404 virtual ~wxCairoContext();
405
406 virtual bool ShouldOffset() const
407 {
408 if ( !m_enableOffset )
409 return false;
410
411 int penwidth = 0 ;
412 if ( !m_pen.IsNull() )
413 {
414 penwidth = (int)((wxCairoPenData*)m_pen.GetRefData())->GetWidth();
415 if ( penwidth == 0 )
416 penwidth = 1;
417 }
418 return ( penwidth % 2 ) == 1;
419 }
420
421 virtual void Clip( const wxRegion &region );
422#ifdef __WXMSW__
423 cairo_surface_t* m_mswSurface;
424 WindowHDC m_mswWindowHDC;
425#endif
426
427 // clips drawings to the rect
428 virtual void Clip( wxDouble x, wxDouble y, wxDouble w, wxDouble h );
429
430 // resets the clipping to original extent
431 virtual void ResetClip();
432
433 virtual void * GetNativeContext();
434
435 virtual bool SetAntialiasMode(wxAntialiasMode antialias);
436
437 virtual bool SetInterpolationQuality(wxInterpolationQuality interpolation);
438
439 virtual bool SetCompositionMode(wxCompositionMode op);
440
441 virtual void BeginLayer(wxDouble opacity);
442
443 virtual void EndLayer();
444
445 virtual void StrokePath( const wxGraphicsPath& p );
446 virtual void FillPath( const wxGraphicsPath& p , wxPolygonFillMode fillStyle = wxWINDING_RULE );
447
448 virtual void Translate( wxDouble dx , wxDouble dy );
449 virtual void Scale( wxDouble xScale , wxDouble yScale );
450 virtual void Rotate( wxDouble angle );
451
452 // concatenates this transform with the current transform of this context
453 virtual void ConcatTransform( const wxGraphicsMatrix& matrix );
454
455 // sets the transform of this context
456 virtual void SetTransform( const wxGraphicsMatrix& matrix );
457
458 // gets the matrix of this context
459 virtual wxGraphicsMatrix GetTransform() const;
460
461 virtual void DrawBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
462 virtual void DrawBitmap( const wxBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
463 virtual void DrawIcon( const wxIcon &icon, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
464 virtual void PushState();
465 virtual void PopState();
466
467 virtual void GetTextExtent( const wxString &str, wxDouble *width, wxDouble *height,
468 wxDouble *descent, wxDouble *externalLeading ) const;
469 virtual void GetPartialTextExtents(const wxString& text, wxArrayDouble& widths) const;
470
471protected:
472 virtual void DoDrawText( const wxString &str, wxDouble x, wxDouble y );
473
474 void Init(cairo_t *context);
475
476private:
477 cairo_t* m_context;
478
479 wxVector<float> m_layerOpacities;
480
481 wxDECLARE_NO_COPY_CLASS(wxCairoContext);
482};
483
484#if wxUSE_IMAGE
485// ----------------------------------------------------------------------------
486// wxCairoImageContext: context associated with a wxImage.
487// ----------------------------------------------------------------------------
488
489class wxCairoImageContext : public wxCairoContext
490{
491public:
492 wxCairoImageContext(wxGraphicsRenderer* renderer, wxImage& image) :
493 wxCairoContext(renderer),
494 m_image(image),
495 m_data(renderer, image)
496 {
497 Init(cairo_create(m_data.GetCairoSurface()));
498 }
499
500 virtual ~wxCairoImageContext()
501 {
502 m_image = m_data.ConvertToImage();
503 }
504
505private:
506 wxImage& m_image;
507 wxCairoBitmapData m_data;
508
509 wxDECLARE_NO_COPY_CLASS(wxCairoImageContext);
510};
511#endif // wxUSE_IMAGE
512
513// ----------------------------------------------------------------------------
514// wxCairoPenBrushBaseData implementation
515//-----------------------------------------------------------------------------
516
517wxCairoPenBrushBaseData::wxCairoPenBrushBaseData(wxGraphicsRenderer* renderer,
518 const wxColour& col,
519 bool isTransparent)
520 : wxGraphicsObjectRefData(renderer)
521{
522 m_hatchStyle = wxHATCHSTYLE_INVALID;
523 m_pattern = NULL;
524 m_bmpdata = NULL;
525
526 if ( isTransparent )
527 {
528 m_red =
529 m_green =
530 m_blue =
531 m_alpha = 0;
532 }
533 else // non-transparent
534 {
535 m_red = col.Red()/255.0;
536 m_green = col.Green()/255.0;
537 m_blue = col.Blue()/255.0;
538 m_alpha = col.Alpha()/255.0;
539 }
540}
541
542wxCairoPenBrushBaseData::~wxCairoPenBrushBaseData()
543{
544 if (m_bmpdata)
545 {
546 // Deleting the bitmap data also deletes the pattern referenced by
547 // m_pattern, so set it to NULL to avoid deleting it twice.
548 delete m_bmpdata;
549 m_pattern = NULL;
550 }
551 if (m_pattern)
552 cairo_pattern_destroy(m_pattern);
553}
554
555void wxCairoPenBrushBaseData::InitHatchPattern(cairo_t* ctext)
556{
557 cairo_surface_t* const
558 surface = cairo_surface_create_similar(
559 cairo_get_target(ctext), CAIRO_CONTENT_COLOR_ALPHA, 10, 10
560 );
561
562 cairo_t* const cr = cairo_create(surface);
563 cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);
564 cairo_set_line_width(cr, 1);
565 cairo_set_line_join(cr,CAIRO_LINE_JOIN_MITER);
566
567 switch ( m_hatchStyle )
568 {
569 case wxHATCHSTYLE_CROSS:
570 cairo_move_to(cr, 5, 0);
571 cairo_line_to(cr, 5, 10);
572 cairo_move_to(cr, 0, 5);
573 cairo_line_to(cr, 10, 5);
574 break;
575
576 case wxHATCHSTYLE_BDIAGONAL:
577 cairo_move_to(cr, 0, 10);
578 cairo_line_to(cr, 10, 0);
579 break;
580
581 case wxHATCHSTYLE_FDIAGONAL:
582 cairo_move_to(cr, 0, 0);
583 cairo_line_to(cr, 10, 10);
584 break;
585
586 case wxHATCHSTYLE_CROSSDIAG:
587 cairo_move_to(cr, 0, 0);
588 cairo_line_to(cr, 10, 10);
589 cairo_move_to(cr, 10, 0);
590 cairo_line_to(cr, 0, 10);
591 break;
592
593 case wxHATCHSTYLE_HORIZONTAL:
594 cairo_move_to(cr, 0, 5);
595 cairo_line_to(cr, 10, 5);
596 break;
597
598 case wxHATCHSTYLE_VERTICAL:
599 cairo_move_to(cr, 5, 0);
600 cairo_line_to(cr, 5, 10);
601 break;
602
603 default:
604 wxFAIL_MSG(wxS("Invalid hatch pattern style."));
605 }
606
607 cairo_set_source_rgba(cr, m_red, m_green, m_blue, m_alpha);
608 cairo_stroke(cr);
609
610 cairo_destroy(cr);
611
612 m_pattern = cairo_pattern_create_for_surface(surface);
613 cairo_surface_destroy(surface);
614 cairo_pattern_set_extend(m_pattern, CAIRO_EXTEND_REPEAT);
615}
616
617void wxCairoPenBrushBaseData::InitStipple(wxBitmap* bmp)
618{
619 wxCHECK_RET( bmp && bmp->IsOk(), wxS("Invalid stippled bitmap") );
620
621 m_bmpdata = new wxCairoBitmapData(GetRenderer(), *bmp);
622 m_pattern = m_bmpdata->GetCairoPattern();
623 cairo_pattern_set_extend(m_pattern, CAIRO_EXTEND_REPEAT);
624}
625
626void wxCairoPenBrushBaseData::InitHatch(wxHatchStyle hatchStyle)
627{
628 // We can't create m_pattern right now as we don't have the Cairo context
629 // needed for it, so just remember that we need to do it.
630 m_hatchStyle = hatchStyle;
631}
632
633void wxCairoPenBrushBaseData::Apply( wxGraphicsContext* context )
634{
635 cairo_t* const ctext = (cairo_t*) context->GetNativeContext();
636
637 if ( m_hatchStyle != wxHATCHSTYLE_INVALID && !m_pattern )
638 InitHatchPattern(ctext);
639
640 if ( m_pattern )
641 cairo_set_source(ctext, m_pattern);
642 else
643 cairo_set_source_rgba(ctext, m_red, m_green, m_blue, m_alpha);
644}
645
646//-----------------------------------------------------------------------------
647// wxCairoPenData implementation
648//-----------------------------------------------------------------------------
649
650wxCairoPenData::~wxCairoPenData()
651{
652 delete[] m_userLengths;
653}
654
655void wxCairoPenData::Init()
656{
657 m_lengths = NULL;
658 m_userLengths = NULL;
659 m_width = 0;
660 m_count = 0;
661}
662
663wxCairoPenData::wxCairoPenData( wxGraphicsRenderer* renderer, const wxPen &pen )
664 : wxCairoPenBrushBaseData(renderer, pen.GetColour(), pen.IsTransparent())
665{
666 Init();
667 m_width = pen.GetWidth();
668 if (m_width <= 0.0)
669 m_width = 0.1;
670
671 switch ( pen.GetCap() )
672 {
673 case wxCAP_ROUND :
674 m_cap = CAIRO_LINE_CAP_ROUND;
675 break;
676
677 case wxCAP_PROJECTING :
678 m_cap = CAIRO_LINE_CAP_SQUARE;
679 break;
680
681 case wxCAP_BUTT :
682 m_cap = CAIRO_LINE_CAP_BUTT;
683 break;
684
685 default :
686 m_cap = CAIRO_LINE_CAP_BUTT;
687 break;
688 }
689
690 switch ( pen.GetJoin() )
691 {
692 case wxJOIN_BEVEL :
693 m_join = CAIRO_LINE_JOIN_BEVEL;
694 break;
695
696 case wxJOIN_MITER :
697 m_join = CAIRO_LINE_JOIN_MITER;
698 break;
699
700 case wxJOIN_ROUND :
701 m_join = CAIRO_LINE_JOIN_ROUND;
702 break;
703
704 default :
705 m_join = CAIRO_LINE_JOIN_MITER;
706 break;
707 }
708
709 const double dashUnit = m_width < 1.0 ? 1.0 : m_width;
710 const double dotted[] =
711 {
712 dashUnit , dashUnit + 2.0
713 };
714 static const double short_dashed[] =
715 {
716 9.0 , 6.0
717 };
718 static const double dashed[] =
719 {
720 19.0 , 9.0
721 };
722 static const double dotted_dashed[] =
723 {
724 9.0 , 6.0 , 3.0 , 3.0
725 };
726
727 switch ( pen.GetStyle() )
728 {
729 case wxPENSTYLE_SOLID :
730 break;
731
732 case wxPENSTYLE_DOT :
733 m_count = WXSIZEOF(dotted);
734 m_userLengths = new double[ m_count ] ;
735 memcpy( m_userLengths, dotted, sizeof(dotted) );
736 m_lengths = m_userLengths;
737 break;
738
739 case wxPENSTYLE_LONG_DASH :
740 m_lengths = dashed ;
741 m_count = WXSIZEOF(dashed);
742 break;
743
744 case wxPENSTYLE_SHORT_DASH :
745 m_lengths = short_dashed ;
746 m_count = WXSIZEOF(short_dashed);
747 break;
748
749 case wxPENSTYLE_DOT_DASH :
750 m_lengths = dotted_dashed ;
751 m_count = WXSIZEOF(dotted_dashed);
752 break;
753
754 case wxPENSTYLE_USER_DASH :
755 {
756 wxDash *wxdashes ;
757 m_count = pen.GetDashes( &wxdashes ) ;
758 if ((wxdashes != NULL) && (m_count > 0))
759 {
760 m_userLengths = new double[m_count] ;
761 for ( int i = 0 ; i < m_count ; ++i )
762 {
763 m_userLengths[i] = wxdashes[i] * dashUnit ;
764
765 if ( i % 2 == 1 && m_userLengths[i] < dashUnit + 2.0 )
766 m_userLengths[i] = dashUnit + 2.0 ;
767 else if ( i % 2 == 0 && m_userLengths[i] < dashUnit )
768 m_userLengths[i] = dashUnit ;
769 }
770 }
771 m_lengths = m_userLengths ;
772 }
773 break;
774
775 case wxPENSTYLE_STIPPLE :
776 case wxPENSTYLE_STIPPLE_MASK :
777 case wxPENSTYLE_STIPPLE_MASK_OPAQUE :
778 InitStipple(pen.GetStipple());
779 break;
780
781 default :
782 if ( pen.GetStyle() >= wxPENSTYLE_FIRST_HATCH
783 && pen.GetStyle() <= wxPENSTYLE_LAST_HATCH )
784 {
785 InitHatch(static_cast<wxHatchStyle>(pen.GetStyle()));
786 }
787 break;
788 }
789}
790
791void wxCairoPenData::Apply( wxGraphicsContext* context )
792{
793 wxCairoPenBrushBaseData::Apply(context);
794
795 cairo_t * ctext = (cairo_t*) context->GetNativeContext();
796 cairo_set_line_width(ctext,m_width);
797 cairo_set_line_cap(ctext,m_cap);
798 cairo_set_line_join(ctext,m_join);
799 cairo_set_dash(ctext,(double*)m_lengths,m_count,0.0);
800}
801
802//-----------------------------------------------------------------------------
803// wxCairoBrushData implementation
804//-----------------------------------------------------------------------------
805
806wxCairoBrushData::wxCairoBrushData( wxGraphicsRenderer* renderer )
807 : wxCairoPenBrushBaseData(renderer, wxColour(), true /* transparent */)
808{
809 Init();
810}
811
812wxCairoBrushData::wxCairoBrushData( wxGraphicsRenderer* renderer,
813 const wxBrush &brush )
814 : wxCairoPenBrushBaseData(renderer, brush.GetColour(), brush.IsTransparent())
815{
816 Init();
817
818 switch ( brush.GetStyle() )
819 {
820 case wxBRUSHSTYLE_STIPPLE:
821 case wxBRUSHSTYLE_STIPPLE_MASK:
822 case wxBRUSHSTYLE_STIPPLE_MASK_OPAQUE:
823 InitStipple(brush.GetStipple());
824 break;
825
826 default:
827 if ( brush.IsHatch() )
828 InitHatch(static_cast<wxHatchStyle>(brush.GetStyle()));
829 break;
830 }
831}
832
833void wxCairoBrushData::AddGradientStops(const wxGraphicsGradientStops& stops)
834{
835 // loop over all the stops, they include the beginning and ending ones
836 const unsigned numStops = stops.GetCount();
837 for ( unsigned n = 0; n < numStops; n++ )
838 {
839 const wxGraphicsGradientStop stop = stops.Item(n);
840
841 const wxColour col = stop.GetColour();
842
843 cairo_pattern_add_color_stop_rgba
844 (
845 m_pattern,
846 stop.GetPosition(),
847 col.Red()/255.0,
848 col.Green()/255.0,
849 col.Blue()/255.0,
850 col.Alpha()/255.0
851 );
852 }
853
854 wxASSERT_MSG(cairo_pattern_status(m_pattern) == CAIRO_STATUS_SUCCESS,
855 wxT("Couldn't create cairo pattern"));
856}
857
858void
859wxCairoBrushData::CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
860 wxDouble x2, wxDouble y2,
861 const wxGraphicsGradientStops& stops)
862{
863 m_pattern = cairo_pattern_create_linear(x1,y1,x2,y2);
864
865 AddGradientStops(stops);
866}
867
868void
869wxCairoBrushData::CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
870 wxDouble xc, wxDouble yc,
871 wxDouble radius,
872 const wxGraphicsGradientStops& stops)
873{
874 m_pattern = cairo_pattern_create_radial(xo,yo,0.0,xc,yc,radius);
875
876 AddGradientStops(stops);
877}
878
879void wxCairoBrushData::Init()
880{
881 m_pattern = NULL;
882 m_bmpdata = NULL;
883}
884
885//-----------------------------------------------------------------------------
886// wxCairoFontData implementation
887//-----------------------------------------------------------------------------
888
889void wxCairoFontData::InitColour(const wxColour& col)
890{
891 m_red = col.Red()/255.0;
892 m_green = col.Green()/255.0;
893 m_blue = col.Blue()/255.0;
894 m_alpha = col.Alpha()/255.0;
895}
896
897void
898wxCairoFontData::InitFontComponents(const wxString& facename,
899 cairo_font_slant_t slant,
900 cairo_font_weight_t weight)
901{
902 m_fontName = facename.mb_str(wxConvUTF8);
903 m_slant = slant;
904 m_weight = weight;
905}
906
907wxCairoFontData::wxCairoFontData( wxGraphicsRenderer* renderer, const wxFont &font,
908 const wxColour& col )
909 : wxGraphicsObjectRefData(renderer)
910#ifdef __WXGTK__
911 , m_wxfont(font)
912#endif
913{
914 InitColour(col);
915
916 m_size = font.GetPointSize();
917
918#ifdef __WXMAC__
919 m_font = cairo_quartz_font_face_create_for_cgfont( font.OSXGetCGFont() );
920#elif defined(__WXGTK__)
921#else
922 InitFontComponents
923 (
924 font.GetFaceName(),
925 font.GetStyle() == wxFONTSTYLE_ITALIC ? CAIRO_FONT_SLANT_ITALIC
926 : CAIRO_FONT_SLANT_NORMAL,
927 font.GetWeight() == wxFONTWEIGHT_BOLD ? CAIRO_FONT_WEIGHT_BOLD
928 : CAIRO_FONT_WEIGHT_NORMAL
929 );
930#endif
931}
932
933wxCairoFontData::wxCairoFontData(wxGraphicsRenderer* renderer,
934 double sizeInPixels,
935 const wxString& facename,
936 int flags,
937 const wxColour& col) :
938 wxGraphicsObjectRefData(renderer)
939{
940 InitColour(col);
941
942 // Resolution for Cairo image surfaces is 72 DPI meaning that the sizes in
943 // points and pixels are identical, so we can just pass the size in pixels
944 // directly to cairo_set_font_size().
945 m_size = sizeInPixels;
946
947#if defined(__WXMAC__)
948 m_font = NULL;
949#endif
950
951 // There is no need to set m_underlined under wxGTK in this case, it can
952 // only be used if m_font != NULL.
953
954 InitFontComponents
955 (
956 facename,
957 flags & wxFONTFLAG_ITALIC ? CAIRO_FONT_SLANT_ITALIC
958 : CAIRO_FONT_SLANT_NORMAL,
959 flags & wxFONTFLAG_BOLD ? CAIRO_FONT_WEIGHT_BOLD
960 : CAIRO_FONT_WEIGHT_NORMAL
961 );
962}
963
964wxCairoFontData::~wxCairoFontData()
965{
966#ifdef __WXMAC__
967 if ( m_font )
968 cairo_font_face_destroy( m_font );
969#endif
970}
971
972bool wxCairoFontData::Apply( wxGraphicsContext* context )
973{
974 cairo_t * ctext = (cairo_t*) context->GetNativeContext();
975 cairo_set_source_rgba(ctext,m_red,m_green, m_blue,m_alpha);
976#ifdef __WXGTK__
977 if (m_wxfont.IsOk())
978 {
979 // Nothing to do, the caller uses Pango layout functions to do
980 // everything.
981 return true;
982 }
983#elif defined(__WXMAC__)
984 if ( m_font )
985 {
986 cairo_set_font_face(ctext, m_font);
987 cairo_set_font_size(ctext, m_size );
988 return true;
989 }
990#endif
991
992 // If we get here, we must be on a platform without native font support or
993 // we're using toy Cairo API even under wxGTK/wxMac.
994 cairo_select_font_face(ctext, m_fontName, m_slant, m_weight );
995 cairo_set_font_size(ctext, m_size );
996
997 // Indicate that we don't use native fonts for the platforms which care
998 // about this (currently only wxGTK).
999 return false;
1000}
1001
1002//-----------------------------------------------------------------------------
1003// wxCairoPathData implementation
1004//-----------------------------------------------------------------------------
1005
1006wxCairoPathData::wxCairoPathData( wxGraphicsRenderer* renderer, cairo_t* pathcontext)
1007 : wxGraphicsPathData(renderer)
1008{
1009 if (pathcontext)
1010 {
1011 m_pathContext = pathcontext;
1012 }
1013 else
1014 {
1015 cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,1,1);
1016 m_pathContext = cairo_create(surface);
1017 cairo_surface_destroy (surface);
1018 }
1019}
1020
1021wxCairoPathData::~wxCairoPathData()
1022{
1023 cairo_destroy(m_pathContext);
1024}
1025
1026wxGraphicsObjectRefData *wxCairoPathData::Clone() const
1027{
1028 cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,1,1);
1029 cairo_t* pathcontext = cairo_create(surface);
1030 cairo_surface_destroy (surface);
1031
1032 cairo_path_t* path = cairo_copy_path(m_pathContext);
1033 cairo_append_path(pathcontext, path);
1034 cairo_path_destroy(path);
1035 return new wxCairoPathData( GetRenderer() ,pathcontext);
1036}
1037
1038
1039void* wxCairoPathData::GetNativePath() const
1040{
1041 return cairo_copy_path(m_pathContext) ;
1042}
1043
1044void wxCairoPathData::UnGetNativePath(void *p) const
1045{
1046 cairo_path_destroy((cairo_path_t*)p);
1047}
1048
1049//
1050// The Primitives
1051//
1052
1053void wxCairoPathData::MoveToPoint( wxDouble x , wxDouble y )
1054{
1055 cairo_move_to(m_pathContext,x,y);
1056}
1057
1058void wxCairoPathData::AddLineToPoint( wxDouble x , wxDouble y )
1059{
1060 cairo_line_to(m_pathContext,x,y);
1061}
1062
1063void wxCairoPathData::AddPath( const wxGraphicsPathData* path )
1064{
1065 cairo_path_t* p = (cairo_path_t*)path->GetNativePath();
1066 cairo_append_path(m_pathContext, p);
1067 UnGetNativePath(p);
1068}
1069
1070void wxCairoPathData::CloseSubpath()
1071{
1072 cairo_close_path(m_pathContext);
1073}
1074
1075void wxCairoPathData::AddCurveToPoint( wxDouble cx1, wxDouble cy1, wxDouble cx2, wxDouble cy2, wxDouble x, wxDouble y )
1076{
1077 cairo_curve_to(m_pathContext,cx1,cy1,cx2,cy2,x,y);
1078}
1079
1080// gets the last point of the current path, (0,0) if not yet set
1081void wxCairoPathData::GetCurrentPoint( wxDouble* x, wxDouble* y) const
1082{
1083 double dx,dy;
1084 cairo_get_current_point(m_pathContext,&dx,&dy);
1085 if (x)
1086 *x = dx;
1087 if (y)
1088 *y = dy;
1089}
1090
1091void wxCairoPathData::AddArc( wxDouble x, wxDouble y, wxDouble r, double startAngle, double endAngle, bool clockwise )
1092{
1093 // as clockwise means positive in our system (y pointing downwards)
1094 // TODO make this interpretation dependent of the
1095 // real device trans
1096 if ( clockwise||(endAngle-startAngle)>=2*M_PI)
1097 cairo_arc(m_pathContext,x,y,r,startAngle,endAngle);
1098 else
1099 cairo_arc_negative(m_pathContext,x,y,r,startAngle,endAngle);
1100}
1101
1102// transforms each point of this path by the matrix
1103void wxCairoPathData::Transform( const wxGraphicsMatrixData* matrix )
1104{
1105 // as we don't have a true path object, we have to apply the inverse
1106 // matrix to the context
1107 cairo_matrix_t m = *((cairo_matrix_t*) matrix->GetNativeMatrix());
1108 cairo_matrix_invert( &m );
1109 cairo_transform(m_pathContext,&m);
1110}
1111
1112// gets the bounding box enclosing all points (possibly including control points)
1113void wxCairoPathData::GetBox(wxDouble *x, wxDouble *y, wxDouble *w, wxDouble *h) const
1114{
1115 double x1,y1,x2,y2;
1116
1117 cairo_stroke_extents( m_pathContext, &x1, &y1, &x2, &y2 );
1118 if ( x2 < x1 )
1119 {
1120 *x = x2;
1121 *w = x1-x2;
1122 }
1123 else
1124 {
1125 *x = x1;
1126 *w = x2-x1;
1127 }
1128
1129 if( y2 < y1 )
1130 {
1131 *y = y2;
1132 *h = y1-y2;
1133 }
1134 else
1135 {
1136 *y = y1;
1137 *h = y2-y1;
1138 }
1139}
1140
1141bool wxCairoPathData::Contains( wxDouble x, wxDouble y, wxPolygonFillMode fillStyle ) const
1142{
1143 cairo_set_fill_rule(m_pathContext,fillStyle==wxODDEVEN_RULE ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
1144 return cairo_in_fill( m_pathContext, x, y) != 0;
1145}
1146
1147//-----------------------------------------------------------------------------
1148// wxCairoMatrixData implementation
1149//-----------------------------------------------------------------------------
1150
1151wxCairoMatrixData::wxCairoMatrixData(wxGraphicsRenderer* renderer, const cairo_matrix_t* matrix )
1152 : wxGraphicsMatrixData(renderer)
1153{
1154 if ( matrix )
1155 m_matrix = *matrix;
1156}
1157
1158wxCairoMatrixData::~wxCairoMatrixData()
1159{
1160 // nothing to do
1161}
1162
1163wxGraphicsObjectRefData *wxCairoMatrixData::Clone() const
1164{
1165 return new wxCairoMatrixData(GetRenderer(),&m_matrix);
1166}
1167
1168// concatenates the matrix
1169void wxCairoMatrixData::Concat( const wxGraphicsMatrixData *t )
1170{
1171 cairo_matrix_multiply( &m_matrix, &m_matrix, (cairo_matrix_t*) t->GetNativeMatrix());
1172}
1173
1174// sets the matrix to the respective values
1175void wxCairoMatrixData::Set(wxDouble a, wxDouble b, wxDouble c, wxDouble d,
1176 wxDouble tx, wxDouble ty)
1177{
1178 cairo_matrix_init( &m_matrix, a, b, c, d, tx, ty);
1179}
1180
1181// gets the component valuess of the matrix
1182void wxCairoMatrixData::Get(wxDouble* a, wxDouble* b, wxDouble* c,
1183 wxDouble* d, wxDouble* tx, wxDouble* ty) const
1184{
1185 if (a) *a = m_matrix.xx;
1186 if (b) *b = m_matrix.yx;
1187 if (c) *c = m_matrix.xy;
1188 if (d) *d = m_matrix.yy;
1189 if (tx) *tx= m_matrix.x0;
1190 if (ty) *ty= m_matrix.y0;
1191}
1192
1193// makes this the inverse matrix
1194void wxCairoMatrixData::Invert()
1195{
1196 cairo_matrix_invert( &m_matrix );
1197}
1198
1199// returns true if the elements of the transformation matrix are equal ?
1200bool wxCairoMatrixData::IsEqual( const wxGraphicsMatrixData* t) const
1201{
1202 const cairo_matrix_t* tm = (cairo_matrix_t*) t->GetNativeMatrix();
1203 return (
1204 m_matrix.xx == tm->xx &&
1205 m_matrix.yx == tm->yx &&
1206 m_matrix.xy == tm->xy &&
1207 m_matrix.yy == tm->yy &&
1208 m_matrix.x0 == tm->x0 &&
1209 m_matrix.y0 == tm->y0 ) ;
1210}
1211
1212// return true if this is the identity matrix
1213bool wxCairoMatrixData::IsIdentity() const
1214{
1215 return ( m_matrix.xx == 1 && m_matrix.yy == 1 &&
1216 m_matrix.yx == 0 && m_matrix.xy == 0 && m_matrix.x0 == 0 && m_matrix.y0 == 0);
1217}
1218
1219//
1220// transformation
1221//
1222
1223// add the translation to this matrix
1224void wxCairoMatrixData::Translate( wxDouble dx , wxDouble dy )
1225{
1226 cairo_matrix_translate( &m_matrix, dx, dy) ;
1227}
1228
1229// add the scale to this matrix
1230void wxCairoMatrixData::Scale( wxDouble xScale , wxDouble yScale )
1231{
1232 cairo_matrix_scale( &m_matrix, xScale, yScale) ;
1233}
1234
1235// add the rotation to this matrix (radians)
1236void wxCairoMatrixData::Rotate( wxDouble angle )
1237{
1238 cairo_matrix_rotate( &m_matrix, angle) ;
1239}
1240
1241//
1242// apply the transforms
1243//
1244
1245// applies that matrix to the point
1246void wxCairoMatrixData::TransformPoint( wxDouble *x, wxDouble *y ) const
1247{
1248 double lx = *x, ly = *y ;
1249 cairo_matrix_transform_point( &m_matrix, &lx, &ly);
1250 *x = lx;
1251 *y = ly;
1252}
1253
1254// applies the matrix except for translations
1255void wxCairoMatrixData::TransformDistance( wxDouble *dx, wxDouble *dy ) const
1256{
1257 double lx = *dx, ly = *dy ;
1258 cairo_matrix_transform_distance( &m_matrix, &lx, &ly);
1259 *dx = lx;
1260 *dy = ly;
1261}
1262
1263// returns the native representation
1264void * wxCairoMatrixData::GetNativeMatrix() const
1265{
1266 return (void*) &m_matrix;
1267}
1268
1269// ----------------------------------------------------------------------------
1270// wxCairoBitmap implementation
1271// ----------------------------------------------------------------------------
1272
1273int wxCairoBitmapData::InitBuffer(int width, int height, cairo_format_t format)
1274{
1275 wxUnusedVar(format); // Only really unused with Cairo < 1.6.
1276
1277 // Determine the stride: use cairo_format_stride_for_width() if available
1278 // but fall back to 4*width for the earlier versions as this is what that
1279 // function always returns, even in latest Cairo, anyhow.
1280 int stride;
1281#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 6, 0)
1282 if ( cairo_version() >= CAIRO_VERSION_ENCODE(1, 6, 0) )
1283 {
1284 stride = cairo_format_stride_for_width(format, width);
1285
1286 // All our code would totally break if stride were not a multiple of 4
1287 // so ensure this is the case.
1288 if ( stride % 4 )
1289 {
1290 wxFAIL_MSG("Unexpected Cairo image surface stride.");
1291
1292 stride += 4 - stride % 4;
1293 }
1294 }
1295 else
1296#endif
1297 stride = 4*width;
1298
1299 m_width = width;
1300 m_height = height;
1301 m_buffer = new unsigned char[height*stride];
1302
1303 return stride;
1304}
1305
1306void wxCairoBitmapData::InitSurface(cairo_format_t format, int stride)
1307{
1308 m_surface = cairo_image_surface_create_for_data(
1309 m_buffer, format, m_width, m_height, stride);
1310 m_pattern = cairo_pattern_create_for_surface(m_surface);
1311}
1312
1313wxCairoBitmapData::wxCairoBitmapData( wxGraphicsRenderer* renderer, cairo_surface_t* bitmap ) :
1314 wxGraphicsBitmapData( renderer )
1315{
1316 m_surface = bitmap;
1317 m_pattern = cairo_pattern_create_for_surface(m_surface);
1318}
1319
1320wxCairoBitmapData::wxCairoBitmapData( wxGraphicsRenderer* renderer, const wxBitmap& bmp ) : wxGraphicsBitmapData( renderer )
1321{
1322 wxCHECK_RET( bmp.IsOk(), wxT("Invalid bitmap in wxCairoContext::DrawBitmap"));
1323
1324#ifdef wxHAS_RAW_BITMAP
1325 // Create a surface object and copy the bitmap pixel data to it. if the
1326 // image has alpha (or a mask represented as alpha) then we'll use a
1327 // different format and iterator than if it doesn't...
1328 cairo_format_t bufferFormat = bmp.GetDepth() == 32
1329#if defined(__WXGTK__) && !defined(__WXGTK3__)
1330 || bmp.GetMask()
1331#endif
1332 ? CAIRO_FORMAT_ARGB32
1333 : CAIRO_FORMAT_RGB24;
1334
1335 int stride = InitBuffer(bmp.GetWidth(), bmp.GetHeight(), bufferFormat);
1336
1337 wxBitmap bmpSource = bmp; // we need a non-const instance
1338 wxUint32* data = (wxUint32*)m_buffer;
1339
1340 if ( bufferFormat == CAIRO_FORMAT_ARGB32 )
1341 {
1342 // use the bitmap's alpha
1343 wxAlphaPixelData
1344 pixData(bmpSource, wxPoint(0, 0), wxSize(m_width, m_height));
1345 wxCHECK_RET( pixData, wxT("Failed to gain raw access to bitmap data."));
1346
1347 wxAlphaPixelData::Iterator p(pixData);
1348 for (int y=0; y<m_height; y++)
1349 {
1350 wxAlphaPixelData::Iterator rowStart = p;
1351 wxUint32* const rowStartDst = data;
1352 for (int x=0; x<m_width; x++)
1353 {
1354 // Each pixel in CAIRO_FORMAT_ARGB32 is a 32-bit quantity,
1355 // with alpha in the upper 8 bits, then red, then green, then
1356 // blue. The 32-bit quantities are stored native-endian.
1357 // Pre-multiplied alpha is used.
1358 unsigned char alpha = p.Alpha();
1359 if (alpha == 0)
1360 *data = 0;
1361 else
1362 *data = ( alpha << 24
1363 | (p.Red() * alpha/255) << 16
1364 | (p.Green() * alpha/255) << 8
1365 | (p.Blue() * alpha/255) );
1366 ++data;
1367 ++p;
1368 }
1369
1370 data = rowStartDst + stride / 4;
1371 p = rowStart;
1372 p.OffsetY(pixData, 1);
1373 }
1374 }
1375 else // no alpha
1376 {
1377 wxNativePixelData
1378 pixData(bmpSource, wxPoint(0, 0), wxSize(m_width, m_height));
1379 wxCHECK_RET( pixData, wxT("Failed to gain raw access to bitmap data."));
1380
1381 wxNativePixelData::Iterator p(pixData);
1382 for (int y=0; y<m_height; y++)
1383 {
1384 wxNativePixelData::Iterator rowStart = p;
1385 wxUint32* const rowStartDst = data;
1386 for (int x=0; x<m_width; x++)
1387 {
1388 // Each pixel in CAIRO_FORMAT_RGB24 is a 32-bit quantity, with
1389 // the upper 8 bits unused. Red, Green, and Blue are stored in
1390 // the remaining 24 bits in that order. The 32-bit quantities
1391 // are stored native-endian.
1392 *data = ( p.Red() << 16 | p.Green() << 8 | p.Blue() );
1393 ++data;
1394 ++p;
1395 }
1396
1397 data = rowStartDst + stride / 4;
1398 p = rowStart;
1399 p.OffsetY(pixData, 1);
1400 }
1401 }
1402#if defined(__WXMSW__) || defined(__WXGTK3__)
1403 // if there is a mask, set the alpha bytes in the target buffer to
1404 // fully transparent or fully opaque
1405 if (bmpSource.GetMask())
1406 {
1407 wxBitmap bmpMask = bmpSource.GetMask()->GetBitmap();
1408 bufferFormat = CAIRO_FORMAT_ARGB32;
1409 data = (wxUint32*)m_buffer;
1410 wxNativePixelData
1411 pixData(bmpMask, wxPoint(0, 0), wxSize(m_width, m_height));
1412 wxCHECK_RET( pixData, wxT("Failed to gain raw access to mask data."));
1413
1414 wxNativePixelData::Iterator p(pixData);
1415 for (int y=0; y<m_height; y++)
1416 {
1417 wxNativePixelData::Iterator rowStart = p;
1418 wxUint32* const rowStartDst = data;
1419 for (int x=0; x<m_width; x++)
1420 {
1421 if (p.Red()+p.Green()+p.Blue() == 0)
1422 *data = 0;
1423 else
1424 *data = (wxALPHA_OPAQUE << 24) | (*data & 0x00FFFFFF);
1425 ++data;
1426 ++p;
1427 }
1428
1429 data = rowStartDst + stride / 4;
1430 p = rowStart;
1431 p.OffsetY(pixData, 1);
1432 }
1433 }
1434#endif
1435
1436 InitSurface(bufferFormat, stride);
1437#endif // wxHAS_RAW_BITMAP
1438}
1439
1440#if wxUSE_IMAGE
1441
1442// Helper functions for dealing with alpha pre-multiplication.
1443namespace
1444{
1445
1446inline unsigned char Premultiply(unsigned char alpha, unsigned char data)
1447{
1448 return alpha ? (data * alpha)/0xff : data;
1449}
1450
1451inline unsigned char Unpremultiply(unsigned char alpha, unsigned char data)
1452{
1453 return alpha ? (data * 0xff)/alpha : data;
1454}
1455
1456} // anonymous namespace
1457
1458wxCairoBitmapData::wxCairoBitmapData(wxGraphicsRenderer* renderer,
1459 const wxImage& image)
1460 : wxGraphicsBitmapData(renderer)
1461{
1462 const cairo_format_t bufferFormat = image.HasAlpha()
1463 ? CAIRO_FORMAT_ARGB32
1464 : CAIRO_FORMAT_RGB24;
1465
1466 int stride = InitBuffer(image.GetWidth(), image.GetHeight(), bufferFormat);
1467
1468 // Copy wxImage data into the buffer. Notice that we work with wxUint32
1469 // values and not bytes becase Cairo always works with buffers in native
1470 // endianness.
1471 wxUint32* dst = reinterpret_cast<wxUint32*>(m_buffer);
1472 const unsigned char* src = image.GetData();
1473
1474 if ( bufferFormat == CAIRO_FORMAT_ARGB32 )
1475 {
1476 const unsigned char* alpha = image.GetAlpha();
1477
1478 for ( int y = 0; y < m_height; y++ )
1479 {
1480 wxUint32* const rowStartDst = dst;
1481
1482 for ( int x = 0; x < m_width; x++ )
1483 {
1484 const unsigned char a = *alpha++;
1485
1486 *dst++ = a << 24 |
1487 Premultiply(a, src[0]) << 16 |
1488 Premultiply(a, src[1]) << 8 |
1489 Premultiply(a, src[2]);
1490 src += 3;
1491 }
1492
1493 dst = rowStartDst + stride / 4;
1494 }
1495 }
1496 else // RGB
1497 {
1498 for ( int y = 0; y < m_height; y++ )
1499 {
1500 wxUint32* const rowStartDst = dst;
1501
1502 for ( int x = 0; x < m_width; x++ )
1503 {
1504 *dst++ = src[0] << 16 |
1505 src[1] << 8 |
1506 src[2];
1507 src += 3;
1508 }
1509
1510 dst = rowStartDst + stride / 4;
1511 }
1512 }
1513
1514 InitSurface(bufferFormat, stride);
1515}
1516
1517wxImage wxCairoBitmapData::ConvertToImage() const
1518{
1519 wxImage image(m_width, m_height, false /* don't clear */);
1520
1521 // Get the surface type and format.
1522 wxCHECK_MSG( cairo_surface_get_type(m_surface) == CAIRO_SURFACE_TYPE_IMAGE,
1523 wxNullImage,
1524 wxS("Can't convert non-image surface to image.") );
1525
1526 switch ( cairo_image_surface_get_format(m_surface) )
1527 {
1528 case CAIRO_FORMAT_ARGB32:
1529 image.SetAlpha();
1530 break;
1531
1532 case CAIRO_FORMAT_RGB24:
1533 // Nothing to do, we don't use alpha by default.
1534 break;
1535
1536 case CAIRO_FORMAT_A8:
1537 case CAIRO_FORMAT_A1:
1538 wxFAIL_MSG(wxS("Unsupported Cairo image surface type."));
1539 return wxNullImage;
1540
1541 default:
1542 wxFAIL_MSG(wxS("Unknown Cairo image surface type."));
1543 return wxNullImage;
1544 }
1545
1546 // Prepare for copying data.
1547 const wxUint32* src = (wxUint32*)cairo_image_surface_get_data(m_surface);
1548 wxCHECK_MSG( src, wxNullImage, wxS("Failed to get Cairo surface data.") );
1549
1550 int stride = cairo_image_surface_get_stride(m_surface);
1551 wxCHECK_MSG( stride > 0, wxNullImage,
1552 wxS("Failed to get Cairo surface stride.") );
1553
1554 // As we work with wxUint32 pointers and not char ones, we need to adjust
1555 // the stride accordingly. This should be lossless as the stride must be a
1556 // multiple of pixel size.
1557 wxASSERT_MSG( !(stride % sizeof(wxUint32)), wxS("Unexpected stride.") );
1558 stride /= sizeof(wxUint32);
1559
1560 unsigned char* dst = image.GetData();
1561 unsigned char *alpha = image.GetAlpha();
1562 if ( alpha )
1563 {
1564 // We need to also copy alpha and undo the pre-multiplication as Cairo
1565 // stores pre-multiplied values in this format while wxImage does not.
1566 for ( int y = 0; y < m_height; y++ )
1567 {
1568 const wxUint32* const rowStart = src;
1569 for ( int x = 0; x < m_width; x++ )
1570 {
1571 const wxUint32 argb = *src++;
1572
1573 *alpha++ = (argb & 0xff000000) >> 24;
1574
1575 // Copy the RGB data undoing the pre-multiplication.
1576 *dst++ = Unpremultiply(*alpha, (argb & 0x00ff0000) >> 16);
1577 *dst++ = Unpremultiply(*alpha, (argb & 0x0000ff00) >> 8);
1578 *dst++ = Unpremultiply(*alpha, (argb & 0x000000ff));
1579 }
1580
1581 src = rowStart + stride;
1582 }
1583 }
1584 else // RGB
1585 {
1586 // Things are pretty simple in this case, just copy RGB bytes.
1587 for ( int y = 0; y < m_height; y++ )
1588 {
1589 const wxUint32* const rowStart = src;
1590 for ( int x = 0; x < m_width; x++ )
1591 {
1592 const wxUint32 argb = *src++;
1593
1594 *dst++ = (argb & 0x00ff0000) >> 16;
1595 *dst++ = (argb & 0x0000ff00) >> 8;
1596 *dst++ = (argb & 0x000000ff);
1597 }
1598
1599 src = rowStart + stride;
1600 }
1601 }
1602
1603 return image;
1604}
1605
1606#endif // wxUSE_IMAGE
1607
1608wxCairoBitmapData::~wxCairoBitmapData()
1609{
1610 if (m_pattern)
1611 cairo_pattern_destroy(m_pattern);
1612
1613 if (m_surface)
1614 cairo_surface_destroy(m_surface);
1615
1616 delete [] m_buffer;
1617}
1618
1619//-----------------------------------------------------------------------------
1620// wxCairoContext implementation
1621//-----------------------------------------------------------------------------
1622
1623class wxCairoOffsetHelper
1624{
1625public :
1626 wxCairoOffsetHelper( cairo_t* ctx , bool offset )
1627 {
1628 m_ctx = ctx;
1629 m_offset = offset;
1630 if ( m_offset )
1631 cairo_translate( m_ctx, 0.5, 0.5 );
1632 }
1633 ~wxCairoOffsetHelper( )
1634 {
1635 if ( m_offset )
1636 cairo_translate( m_ctx, -0.5, -0.5 );
1637 }
1638public :
1639 cairo_t* m_ctx;
1640 bool m_offset;
1641} ;
1642
1643wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, const wxPrinterDC& dc )
1644: wxGraphicsContext(renderer)
1645{
1646#ifdef __WXMSW__
1647 // wxMSW contexts always use MM_ANISOTROPIC, which messes up
1648 // text rendering when printing using Cairo. Switch it to MM_TEXT
1649 // map mode to avoid this problem.
1650 HDC hdc = (HDC)dc.GetHDC();
1651 ::SetMapMode(hdc, MM_TEXT);
1652 m_mswSurface = cairo_win32_printing_surface_create(hdc);
1653 Init( cairo_create(m_mswSurface) );
1654#endif
1655
1656#ifdef __WXGTK20__
1657 const wxDCImpl *impl = dc.GetImpl();
1658 Init( (cairo_t*) impl->GetCairoContext() );
1659#endif
1660 wxSize sz = dc.GetSize();
1661 m_width = sz.x;
1662 m_height = sz.y;
1663
1664 wxPoint org = dc.GetDeviceOrigin();
1665 cairo_translate( m_context, org.x, org.y );
1666
1667 double sx,sy;
1668 dc.GetUserScale( &sx, &sy );
1669
1670// TODO: Determine if these fixes are needed on other platforms too.
1671// On MSW, without this the printer context will not respect wxDC SetMapMode calls.
1672// For example, using dc.SetMapMode(wxMM_POINTS) can let us share printer and screen
1673// drawing code
1674#ifdef __WXMSW__
1675 double lsx,lsy;
1676 dc.GetLogicalScale( &lsx, &lsy );
1677 sx *= lsx;
1678 sy *= lsy;
1679#endif
1680 cairo_scale( m_context, sx, sy );
1681
1682 org = dc.GetLogicalOrigin();
1683 cairo_translate( m_context, -org.x, -org.y );
1684}
1685
1686wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, const wxWindowDC& dc )
1687: wxGraphicsContext(renderer)
1688{
1689 int width, height;
1690 dc.GetSize( &width, &height );
1691 m_width = width;
1692 m_height = height;
1693
1694 m_enableOffset = true;
1695
1696#ifdef __WXMSW__
1697 m_mswSurface = cairo_win32_surface_create((HDC)dc.GetHDC());
1698 Init( cairo_create(m_mswSurface) );
1699#endif
1700
1701#ifdef __WXGTK3__
1702 cairo_t* cr = static_cast<cairo_t*>(dc.GetImpl()->GetCairoContext());
1703 if (cr)
1704 Init(cr);
1705#elif defined __WXGTK20__
1706 wxGTKDCImpl *impldc = (wxGTKDCImpl*) dc.GetImpl();
1707 Init( gdk_cairo_create( impldc->GetGDKWindow() ) );
1708
1709#if 0
1710 wxGraphicsMatrix matrix = CreateMatrix();
1711
1712 wxPoint org = dc.GetDeviceOrigin();
1713 matrix.Translate( org.x, org.y );
1714
1715 org = dc.GetLogicalOrigin();
1716 matrix.Translate( -org.x, -org.y );
1717
1718 double sx,sy;
1719 dc.GetUserScale( &sx, &sy );
1720 matrix.Scale( sx, sy );
1721
1722 ConcatTransform( matrix );
1723#endif
1724#endif
1725
1726#ifdef __WXMAC__
1727 CGContextRef cgcontext = (CGContextRef)dc.GetWindow()->MacGetCGContextRef();
1728 cairo_surface_t* surface = cairo_quartz_surface_create_for_cg_context(cgcontext, width, height);
1729 Init( cairo_create( surface ) );
1730 cairo_surface_destroy( surface );
1731#endif
1732}
1733
1734wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, const wxMemoryDC& dc )
1735: wxGraphicsContext(renderer)
1736{
1737 int width, height;
1738 dc.GetSize( &width, &height );
1739 m_width = width;
1740 m_height = height;
1741
1742 m_enableOffset = true;
1743
1744#ifdef __WXMSW__
1745
1746 HDC hdc = (HDC)dc.GetHDC();
1747
1748 HBITMAP bitmap = (HBITMAP)GetCurrentObject(hdc, OBJ_BITMAP);
1749
1750 BITMAP info;
1751 bool hasBitmap = false;
1752
1753 // cairo_win32_surface_create creates a 24-bit bitmap,
1754 // so if we have alpha, we need to create a 32-bit surface instead.
1755 if (!GetObject(bitmap, sizeof(info), &info) || info.bmBitsPixel < 32)
1756 m_mswSurface = cairo_win32_surface_create(hdc);
1757 else {
1758 hasBitmap = true;
1759 m_mswSurface = cairo_image_surface_create_for_data((unsigned char*)info.bmBits,
1760 CAIRO_FORMAT_ARGB32,
1761 info.bmWidth,
1762 info.bmHeight,
1763 info.bmWidthBytes);
1764 }
1765
1766 Init( cairo_create(m_mswSurface) );
1767 // If we've created a image surface, we need to flip the Y axis so that
1768 // all drawing will appear right side up.
1769 if (hasBitmap) {
1770 cairo_matrix_t matrix;
1771 cairo_matrix_init(&matrix, 1.0, 0.0, 0.0, -1.0, 0.0, height);
1772 cairo_set_matrix(m_context, &matrix);
1773 }
1774#endif
1775
1776#ifdef __WXGTK3__
1777 cairo_t* cr = static_cast<cairo_t*>(dc.GetImpl()->GetCairoContext());
1778 if (cr)
1779 Init(cr);
1780#elif defined __WXGTK20__
1781 wxGTKDCImpl *impldc = (wxGTKDCImpl*) dc.GetImpl();
1782 Init( gdk_cairo_create( impldc->GetGDKWindow() ) );
1783
1784#if 0
1785 wxGraphicsMatrix matrix = CreateMatrix();
1786
1787 wxPoint org = dc.GetDeviceOrigin();
1788 matrix.Translate( org.x, org.y );
1789
1790 org = dc.GetLogicalOrigin();
1791 matrix.Translate( -org.x, -org.y );
1792
1793 double sx,sy;
1794 dc.GetUserScale( &sx, &sy );
1795 matrix.Scale( sx, sy );
1796
1797 ConcatTransform( matrix );
1798#endif
1799#endif
1800
1801#ifdef __WXMAC__
1802 CGContextRef cgcontext = (CGContextRef)dc.GetWindow()->MacGetCGContextRef();
1803 cairo_surface_t* surface = cairo_quartz_surface_create_for_cg_context(cgcontext, width, height);
1804 Init( cairo_create( surface ) );
1805 cairo_surface_destroy( surface );
1806#endif
1807}
1808
1809#ifdef __WXGTK20__
1810wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, GdkWindow *window )
1811: wxGraphicsContext(renderer)
1812{
1813 Init( gdk_cairo_create( window ) );
1814
1815#ifdef __WXGTK3__
1816 m_width = gdk_window_get_width(window);
1817 m_height = gdk_window_get_height(window);
1818#else
1819 int width, height;
1820 gdk_drawable_get_size(window, &width, &height);
1821 m_width = width;
1822 m_height = height;
1823#endif
1824}
1825#endif
1826
1827#ifdef __WXMSW__
1828wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, HDC handle )
1829: wxGraphicsContext(renderer)
1830{
1831 m_mswSurface = cairo_win32_surface_create(handle);
1832 Init( cairo_create(m_mswSurface) );
1833 m_width =
1834 m_height = 0;
1835}
1836#endif
1837
1838
1839wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, cairo_t *context )
1840: wxGraphicsContext(renderer)
1841{
1842 Init( context );
1843 m_width =
1844 m_height = 0;
1845}
1846
1847wxCairoContext::wxCairoContext( wxGraphicsRenderer* renderer, wxWindow *window)
1848 : wxGraphicsContext(renderer)
1849#ifdef __WXMSW__
1850 , m_mswWindowHDC(GetHwndOf(window))
1851#endif
1852{
1853 m_enableOffset = true;
1854#ifdef __WXGTK__
1855 // something along these lines (copied from dcclient)
1856
1857 // Some controls don't have m_wxwindow - like wxStaticBox, but the user
1858 // code should still be able to create wxClientDCs for them, so we will
1859 // use the parent window here then.
1860 if (window->m_wxwindow == NULL)
1861 {
1862 window = window->GetParent();
1863 }
1864
1865 wxASSERT_MSG( window->m_wxwindow, wxT("wxCairoContext needs a widget") );
1866
1867 Init(gdk_cairo_create(window->GTKGetDrawingWindow()));
1868
1869 wxSize sz = window->GetSize();
1870 m_width = sz.x;
1871 m_height = sz.y;
1872#endif
1873
1874#ifdef __WXMSW__
1875 m_mswSurface = cairo_win32_surface_create((HDC)m_mswWindowHDC);
1876 Init(cairo_create(m_mswSurface));
1877#endif
1878
1879}
1880
1881wxCairoContext::wxCairoContext(wxGraphicsRenderer* renderer) :
1882 wxGraphicsContext(renderer)
1883{
1884 m_context = NULL;
1885}
1886
1887wxCairoContext::~wxCairoContext()
1888{
1889 if ( m_context )
1890 {
1891 PopState();
1892 PopState();
1893 cairo_destroy(m_context);
1894 }
1895#ifdef __WXMSW__
1896 if ( m_mswSurface )
1897 cairo_surface_destroy(m_mswSurface);
1898#endif
1899}
1900
1901void wxCairoContext::Init(cairo_t *context)
1902{
1903 m_context = context ;
1904 PushState();
1905 PushState();
1906}
1907
1908
1909void wxCairoContext::Clip( const wxRegion& region )
1910{
1911 // Create a path with all the rectangles in the region
1912 wxGraphicsPath path = GetRenderer()->CreatePath();
1913 wxRegionIterator ri(region);
1914 while (ri)
1915 {
1916 path.AddRectangle(ri.GetX(), ri.GetY(), ri.GetW(), ri.GetH());
1917 ++ri;
1918 }
1919
1920 // Put it in the context
1921 cairo_path_t* cp = (cairo_path_t*) path.GetNativePath() ;
1922 cairo_append_path(m_context, cp);
1923
1924 // clip to that path
1925 cairo_clip(m_context);
1926 path.UnGetNativePath(cp);
1927}
1928
1929void wxCairoContext::Clip( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1930{
1931 // Create a path with this rectangle
1932 wxGraphicsPath path = GetRenderer()->CreatePath();
1933 path.AddRectangle(x,y,w,h);
1934
1935 // Put it in the context
1936 cairo_path_t* cp = (cairo_path_t*) path.GetNativePath() ;
1937 cairo_append_path(m_context, cp);
1938
1939 // clip to that path
1940 cairo_clip(m_context);
1941 path.UnGetNativePath(cp);
1942}
1943
1944void wxCairoContext::ResetClip()
1945{
1946 cairo_reset_clip(m_context);
1947}
1948
1949
1950void wxCairoContext::StrokePath( const wxGraphicsPath& path )
1951{
1952 if ( !m_pen.IsNull() )
1953 {
1954 wxCairoOffsetHelper helper( m_context, ShouldOffset() ) ;
1955 cairo_path_t* cp = (cairo_path_t*) path.GetNativePath() ;
1956 cairo_append_path(m_context,cp);
1957 ((wxCairoPenData*)m_pen.GetRefData())->Apply(this);
1958 cairo_stroke(m_context);
1959 path.UnGetNativePath(cp);
1960 }
1961}
1962
1963void wxCairoContext::FillPath( const wxGraphicsPath& path , wxPolygonFillMode fillStyle )
1964{
1965 if ( !m_brush.IsNull() )
1966 {
1967 wxCairoOffsetHelper helper( m_context, ShouldOffset() ) ;
1968 cairo_path_t* cp = (cairo_path_t*) path.GetNativePath() ;
1969 cairo_append_path(m_context,cp);
1970 ((wxCairoBrushData*)m_brush.GetRefData())->Apply(this);
1971 cairo_set_fill_rule(m_context,fillStyle==wxODDEVEN_RULE ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
1972 cairo_fill(m_context);
1973 path.UnGetNativePath(cp);
1974 }
1975}
1976
1977void wxCairoContext::Rotate( wxDouble angle )
1978{
1979 cairo_rotate(m_context,angle);
1980}
1981
1982void wxCairoContext::Translate( wxDouble dx , wxDouble dy )
1983{
1984 cairo_translate(m_context,dx,dy);
1985}
1986
1987void wxCairoContext::Scale( wxDouble xScale , wxDouble yScale )
1988{
1989 cairo_scale(m_context,xScale,yScale);
1990}
1991
1992// concatenates this transform with the current transform of this context
1993void wxCairoContext::ConcatTransform( const wxGraphicsMatrix& matrix )
1994{
1995 cairo_transform(m_context,(const cairo_matrix_t *) matrix.GetNativeMatrix());
1996}
1997
1998// sets the transform of this context
1999void wxCairoContext::SetTransform( const wxGraphicsMatrix& matrix )
2000{
2001 cairo_set_matrix(m_context,(const cairo_matrix_t*) matrix.GetNativeMatrix());
2002}
2003
2004// gets the matrix of this context
2005wxGraphicsMatrix wxCairoContext::GetTransform() const
2006{
2007 wxGraphicsMatrix matrix = CreateMatrix();
2008 cairo_get_matrix(m_context,(cairo_matrix_t*) matrix.GetNativeMatrix());
2009 return matrix;
2010}
2011
2012
2013
2014void wxCairoContext::PushState()
2015{
2016 cairo_save(m_context);
2017}
2018
2019void wxCairoContext::PopState()
2020{
2021 cairo_restore(m_context);
2022}
2023
2024void wxCairoContext::DrawBitmap( const wxBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2025{
2026 wxGraphicsBitmap bitmap = GetRenderer()->CreateBitmap(bmp);
2027 DrawBitmap(bitmap, x, y, w, h);
2028
2029}
2030
2031void wxCairoContext::DrawBitmap(const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2032{
2033 PushState();
2034
2035 // In case we're scaling the image by using a width and height different
2036 // than the bitmap's size create a pattern transformation on the surface and
2037 // draw the transformed pattern.
2038 wxCairoBitmapData* data = static_cast<wxCairoBitmapData*>(bmp.GetRefData());
2039 cairo_pattern_t* pattern = data->GetCairoPattern();
2040 wxSize size = data->GetSize();
2041
2042 wxDouble scaleX = w / size.GetWidth();
2043 wxDouble scaleY = h / size.GetHeight();
2044
2045 // prepare to draw the image
2046 cairo_translate(m_context, x, y);
2047 cairo_scale(m_context, scaleX, scaleY);
2048 cairo_set_source(m_context, pattern);
2049 // use the original size here since the context is scaled already...
2050 cairo_rectangle(m_context, 0, 0, size.GetWidth(), size.GetHeight());
2051 // fill the rectangle using the pattern
2052 cairo_fill(m_context);
2053
2054 PopState();
2055}
2056
2057void wxCairoContext::DrawIcon( const wxIcon &icon, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2058{
2059 // An icon is a bitmap on wxGTK, so do this the easy way. When we want to
2060 // start using the Cairo backend on other platforms then we may need to
2061 // fiddle with this...
2062 DrawBitmap(icon, x, y, w, h);
2063}
2064
2065
2066void wxCairoContext::DoDrawText(const wxString& str, wxDouble x, wxDouble y)
2067{
2068 wxCHECK_RET( !m_font.IsNull(),
2069 wxT("wxCairoContext::DrawText - no valid font set") );
2070
2071 if ( str.empty())
2072 return;
2073
2074 const wxCharBuffer data = str.utf8_str();
2075 if ( !data )
2076 return;
2077
2078 if ( ((wxCairoFontData*)m_font.GetRefData())->Apply(this) )
2079 {
2080#ifdef __WXGTK__
2081 PangoLayout *layout = pango_cairo_create_layout (m_context);
2082 const wxFont& font = static_cast<wxCairoFontData*>(m_font.GetRefData())->GetFont();
2083 pango_layout_set_font_description(layout, font.GetNativeFontInfo()->description);
2084 pango_layout_set_text(layout, data, data.length());
2085 font.GTKSetPangoAttrs(layout);
2086
2087 cairo_move_to(m_context, x, y);
2088 pango_cairo_show_layout (m_context, layout);
2089
2090 g_object_unref (layout);
2091
2092 // Don't use Cairo text API, we already did everything.
2093 return;
2094#endif
2095 }
2096
2097 // Cairo's x,y for drawing text is at the baseline, so we need to adjust
2098 // the position we move to by the ascent.
2099 cairo_font_extents_t fe;
2100 cairo_font_extents(m_context, &fe);
2101 cairo_move_to(m_context, x, y+fe.ascent);
2102
2103 cairo_show_text(m_context, data);
2104}
2105
2106void wxCairoContext::GetTextExtent( const wxString &str, wxDouble *width, wxDouble *height,
2107 wxDouble *descent, wxDouble *externalLeading ) const
2108{
2109 wxCHECK_RET( !m_font.IsNull(), wxT("wxCairoContext::GetTextExtent - no valid font set") );
2110
2111 if ( width )
2112 *width = 0;
2113 if ( height )
2114 *height = 0;
2115 if ( descent )
2116 *descent = 0;
2117 if ( externalLeading )
2118 *externalLeading = 0;
2119
2120 if ( str.empty())
2121 return;
2122
2123 if ( ((wxCairoFontData*)m_font.GetRefData())->Apply((wxCairoContext*)this) )
2124 {
2125#ifdef __WXGTK__
2126 int w, h;
2127
2128 PangoLayout *layout = pango_cairo_create_layout (m_context);
2129 const wxFont& font = static_cast<wxCairoFontData*>(m_font.GetRefData())->GetFont();
2130 pango_layout_set_font_description(layout, font.GetNativeFontInfo()->description);
2131 const wxCharBuffer data = str.utf8_str();
2132 if ( !data )
2133 {
2134 return;
2135 }
2136 pango_layout_set_text(layout, data, data.length());
2137 pango_layout_get_pixel_size (layout, &w, &h);
2138 if ( width )
2139 *width = w;
2140 if ( height )
2141 *height = h;
2142 if (descent)
2143 {
2144 PangoLayoutIter *iter = pango_layout_get_iter(layout);
2145 int baseline = pango_layout_iter_get_baseline(iter);
2146 pango_layout_iter_free(iter);
2147 *descent = h - PANGO_PIXELS(baseline);
2148 }
2149 g_object_unref (layout);
2150 return;
2151#endif
2152 }
2153
2154 if (width)
2155 {
2156 const wxWX2MBbuf buf(str.mb_str(wxConvUTF8));
2157 cairo_text_extents_t te;
2158 cairo_text_extents(m_context, buf, &te);
2159 *width = te.width;
2160 }
2161
2162 if (height || descent || externalLeading)
2163 {
2164 cairo_font_extents_t fe;
2165 cairo_font_extents(m_context, &fe);
2166
2167 // some backends have negative descents
2168
2169 if ( fe.descent < 0 )
2170 fe.descent = -fe.descent;
2171
2172 if ( fe.height < (fe.ascent + fe.descent ) )
2173 {
2174 // some backends are broken re height ... (eg currently ATSUI)
2175 fe.height = fe.ascent + fe.descent;
2176 }
2177
2178 if (height)
2179 *height = fe.height;
2180 if ( descent )
2181 *descent = fe.descent;
2182 if ( externalLeading )
2183 *externalLeading = wxMax(0, fe.height - (fe.ascent + fe.descent));
2184 }
2185}
2186
2187void wxCairoContext::GetPartialTextExtents(const wxString& text, wxArrayDouble& widths) const
2188{
2189 widths.Empty();
2190 wxCHECK_RET( !m_font.IsNull(), wxT("wxCairoContext::GetPartialTextExtents - no valid font set") );
2191#ifdef __WXGTK__
2192 const wxCharBuffer data = text.utf8_str();
2193 int w = 0;
2194 if (data.length())
2195 {
2196 PangoLayout* layout = pango_cairo_create_layout(m_context);
2197 const wxFont& font = static_cast<wxCairoFontData*>(m_font.GetRefData())->GetFont();
2198 pango_layout_set_font_description(layout, font.GetNativeFontInfo()->description);
2199 pango_layout_set_text(layout, data, data.length());
2200 PangoLayoutIter* iter = pango_layout_get_iter(layout);
2201 PangoRectangle rect;
2202 do {
2203 pango_layout_iter_get_cluster_extents(iter, NULL, &rect);
2204 w += rect.width;
2205 widths.Add(PANGO_PIXELS(w));
2206 } while (pango_layout_iter_next_cluster(iter));
2207 pango_layout_iter_free(iter);
2208 g_object_unref(layout);
2209 }
2210 size_t i = widths.GetCount();
2211 const size_t len = text.length();
2212 while (i++ < len)
2213 widths.Add(PANGO_PIXELS(w));
2214#else
2215 // TODO
2216#endif
2217}
2218
2219void * wxCairoContext::GetNativeContext()
2220{
2221 return m_context;
2222}
2223
2224bool wxCairoContext::SetAntialiasMode(wxAntialiasMode antialias)
2225{
2226 if (m_antialias == antialias)
2227 return true;
2228
2229 m_antialias = antialias;
2230
2231 cairo_antialias_t antialiasMode;
2232 switch (antialias)
2233 {
2234 case wxANTIALIAS_DEFAULT:
2235 antialiasMode = CAIRO_ANTIALIAS_DEFAULT;
2236 break;
2237 case wxANTIALIAS_NONE:
2238 antialiasMode = CAIRO_ANTIALIAS_NONE;
2239 break;
2240 default:
2241 return false;
2242 }
2243 cairo_set_antialias(m_context, antialiasMode);
2244 return true;
2245}
2246
2247bool wxCairoContext::SetInterpolationQuality(wxInterpolationQuality WXUNUSED(interpolation))
2248{
2249 // placeholder
2250 return false;
2251}
2252
2253bool wxCairoContext::SetCompositionMode(wxCompositionMode op)
2254{
2255 if ( m_composition == op )
2256 return true;
2257
2258 m_composition = op;
2259 cairo_operator_t cop;
2260 switch (op)
2261 {
2262 case wxCOMPOSITION_CLEAR:
2263 cop = CAIRO_OPERATOR_CLEAR;
2264 break;
2265 case wxCOMPOSITION_SOURCE:
2266 cop = CAIRO_OPERATOR_SOURCE;
2267 break;
2268 case wxCOMPOSITION_OVER:
2269 cop = CAIRO_OPERATOR_OVER;
2270 break;
2271 case wxCOMPOSITION_IN:
2272 cop = CAIRO_OPERATOR_IN;
2273 break;
2274 case wxCOMPOSITION_OUT:
2275 cop = CAIRO_OPERATOR_OUT;
2276 break;
2277 case wxCOMPOSITION_ATOP:
2278 cop = CAIRO_OPERATOR_ATOP;
2279 break;
2280 case wxCOMPOSITION_DEST:
2281 cop = CAIRO_OPERATOR_DEST;
2282 break;
2283 case wxCOMPOSITION_DEST_OVER:
2284 cop = CAIRO_OPERATOR_DEST_OVER;
2285 break;
2286 case wxCOMPOSITION_DEST_IN:
2287 cop = CAIRO_OPERATOR_DEST_IN;
2288 break;
2289 case wxCOMPOSITION_DEST_OUT:
2290 cop = CAIRO_OPERATOR_DEST_OUT;
2291 break;
2292 case wxCOMPOSITION_DEST_ATOP:
2293 cop = CAIRO_OPERATOR_DEST_ATOP;
2294 break;
2295 case wxCOMPOSITION_XOR:
2296 cop = CAIRO_OPERATOR_XOR;
2297 break;
2298 case wxCOMPOSITION_ADD:
2299 cop = CAIRO_OPERATOR_ADD;
2300 break;
2301 default:
2302 return false;
2303 }
2304 cairo_set_operator(m_context, cop);
2305 return true;
2306}
2307
2308void wxCairoContext::BeginLayer(wxDouble opacity)
2309{
2310 m_layerOpacities.push_back(opacity);
2311 cairo_push_group(m_context);
2312}
2313
2314void wxCairoContext::EndLayer()
2315{
2316 float opacity = m_layerOpacities.back();
2317 m_layerOpacities.pop_back();
2318 cairo_pop_group_to_source(m_context);
2319 cairo_paint_with_alpha(m_context,opacity);
2320}
2321
2322//-----------------------------------------------------------------------------
2323// wxCairoRenderer declaration
2324//-----------------------------------------------------------------------------
2325
2326class WXDLLIMPEXP_CORE wxCairoRenderer : public wxGraphicsRenderer
2327{
2328public :
2329 wxCairoRenderer() {}
2330
2331 virtual ~wxCairoRenderer() {}
2332
2333 // Context
2334
2335 virtual wxGraphicsContext * CreateContext( const wxWindowDC& dc);
2336 virtual wxGraphicsContext * CreateContext( const wxMemoryDC& dc);
2337 virtual wxGraphicsContext * CreateContext( const wxPrinterDC& dc);
2338
2339 virtual wxGraphicsContext * CreateContextFromNativeContext( void * context );
2340
2341 virtual wxGraphicsContext * CreateContextFromNativeWindow( void * window );
2342#if wxUSE_IMAGE
2343 virtual wxGraphicsContext * CreateContextFromImage(wxImage& image);
2344#endif // wxUSE_IMAGE
2345
2346 virtual wxGraphicsContext * CreateContext( wxWindow* window );
2347
2348 virtual wxGraphicsContext * CreateMeasuringContext();
2349#ifdef __WXMSW__
2350#if wxUSE_ENH_METAFILE
2351 virtual wxGraphicsContext * CreateContext( const wxEnhMetaFileDC& dc);
2352#endif
2353#endif
2354 // Path
2355
2356 virtual wxGraphicsPath CreatePath();
2357
2358 // Matrix
2359
2360 virtual wxGraphicsMatrix CreateMatrix( wxDouble a=1.0, wxDouble b=0.0, wxDouble c=0.0, wxDouble d=1.0,
2361 wxDouble tx=0.0, wxDouble ty=0.0);
2362
2363
2364 virtual wxGraphicsPen CreatePen(const wxPen& pen) ;
2365
2366 virtual wxGraphicsBrush CreateBrush(const wxBrush& brush ) ;
2367
2368 virtual wxGraphicsBrush
2369 CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
2370 wxDouble x2, wxDouble y2,
2371 const wxGraphicsGradientStops& stops);
2372
2373 virtual wxGraphicsBrush
2374 CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
2375 wxDouble xc, wxDouble yc,
2376 wxDouble radius,
2377 const wxGraphicsGradientStops& stops);
2378
2379 // sets the font
2380 virtual wxGraphicsFont CreateFont( const wxFont &font , const wxColour &col = *wxBLACK ) ;
2381 virtual wxGraphicsFont CreateFont(double sizeInPixels,
2382 const wxString& facename,
2383 int flags = wxFONTFLAG_DEFAULT,
2384 const wxColour& col = *wxBLACK);
2385
2386 // create a native bitmap representation
2387 virtual wxGraphicsBitmap CreateBitmap( const wxBitmap &bitmap );
2388#if wxUSE_IMAGE
2389 virtual wxGraphicsBitmap CreateBitmapFromImage(const wxImage& image);
2390 virtual wxImage CreateImageFromBitmap(const wxGraphicsBitmap& bmp);
2391#endif // wxUSE_IMAGE
2392
2393 // create a graphics bitmap from a native bitmap
2394 virtual wxGraphicsBitmap CreateBitmapFromNativeBitmap( void* bitmap );
2395
2396 // create a subimage from a native image representation
2397 virtual wxGraphicsBitmap CreateSubBitmap( const wxGraphicsBitmap &bitmap, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
2398
2399 DECLARE_DYNAMIC_CLASS_NO_COPY(wxCairoRenderer)
2400} ;
2401
2402//-----------------------------------------------------------------------------
2403// wxCairoRenderer implementation
2404//-----------------------------------------------------------------------------
2405
2406IMPLEMENT_DYNAMIC_CLASS(wxCairoRenderer,wxGraphicsRenderer)
2407
2408static wxCairoRenderer gs_cairoGraphicsRenderer;
2409
2410#ifdef __WXGTK__
2411 #define ENSURE_LOADED_OR_RETURN(returnOnFail)
2412#else
2413 #define ENSURE_LOADED_OR_RETURN(returnOnFail) \
2414 if (!wxCairoInit()) \
2415 return returnOnFail
2416#endif
2417
2418wxGraphicsContext * wxCairoRenderer::CreateContext( const wxWindowDC& dc)
2419{
2420 ENSURE_LOADED_OR_RETURN(NULL);
2421 return new wxCairoContext(this,dc);
2422}
2423
2424wxGraphicsContext * wxCairoRenderer::CreateContext( const wxMemoryDC& dc)
2425{
2426 ENSURE_LOADED_OR_RETURN(NULL);
2427 return new wxCairoContext(this,dc);
2428}
2429
2430wxGraphicsContext * wxCairoRenderer::CreateContext( const wxPrinterDC& dc)
2431{
2432 ENSURE_LOADED_OR_RETURN(NULL);
2433 return new wxCairoContext(this, dc);
2434}
2435
2436#ifdef __WXMSW__
2437#if wxUSE_ENH_METAFILE
2438wxGraphicsContext * wxCairoRenderer::CreateContext( const wxEnhMetaFileDC& WXUNUSED(dc) )
2439{
2440 return NULL;
2441}
2442#endif
2443#endif
2444
2445wxGraphicsContext * wxCairoRenderer::CreateContextFromNativeContext( void * context )
2446{
2447 ENSURE_LOADED_OR_RETURN(NULL);
2448#ifdef __WXMSW__
2449 return new wxCairoContext(this,(HDC)context);
2450#else
2451 return new wxCairoContext(this,(cairo_t*)context);
2452#endif
2453}
2454
2455
2456wxGraphicsContext * wxCairoRenderer::CreateContextFromNativeWindow( void * window )
2457{
2458#ifdef __WXGTK__
2459 return new wxCairoContext(this, static_cast<GdkWindow*>(window));
2460#else
2461 wxUnusedVar(window);
2462 return NULL;
2463#endif
2464}
2465
2466#if wxUSE_IMAGE
2467wxGraphicsContext * wxCairoRenderer::CreateContextFromImage(wxImage& image)
2468{
2469 ENSURE_LOADED_OR_RETURN(NULL);
2470 return new wxCairoImageContext(this, image);
2471}
2472#endif // wxUSE_IMAGE
2473
2474wxGraphicsContext * wxCairoRenderer::CreateMeasuringContext()
2475{
2476#ifdef __WXGTK__
2477 return CreateContextFromNativeWindow(gdk_get_default_root_window());
2478#else
2479 return NULL;
2480 // TODO
2481#endif
2482}
2483
2484wxGraphicsContext * wxCairoRenderer::CreateContext( wxWindow* window )
2485{
2486 ENSURE_LOADED_OR_RETURN(NULL);
2487 return new wxCairoContext(this, window );
2488}
2489
2490// Path
2491
2492wxGraphicsPath wxCairoRenderer::CreatePath()
2493{
2494 wxGraphicsPath path;
2495 ENSURE_LOADED_OR_RETURN(path);
2496 path.SetRefData( new wxCairoPathData(this) );
2497 return path;
2498}
2499
2500
2501// Matrix
2502
2503wxGraphicsMatrix wxCairoRenderer::CreateMatrix( wxDouble a, wxDouble b, wxDouble c, wxDouble d,
2504 wxDouble tx, wxDouble ty)
2505
2506{
2507 wxGraphicsMatrix m;
2508 ENSURE_LOADED_OR_RETURN(m);
2509 wxCairoMatrixData* data = new wxCairoMatrixData( this );
2510 data->Set( a,b,c,d,tx,ty ) ;
2511 m.SetRefData(data);
2512 return m;
2513}
2514
2515wxGraphicsPen wxCairoRenderer::CreatePen(const wxPen& pen)
2516{
2517 wxGraphicsPen p;
2518 ENSURE_LOADED_OR_RETURN(p);
2519 if (pen.IsOk() && pen.GetStyle() != wxPENSTYLE_TRANSPARENT)
2520 {
2521 p.SetRefData(new wxCairoPenData( this, pen ));
2522 }
2523 return p;
2524}
2525
2526wxGraphicsBrush wxCairoRenderer::CreateBrush(const wxBrush& brush )
2527{
2528 wxGraphicsBrush p;
2529 ENSURE_LOADED_OR_RETURN(p);
2530 if (brush.IsOk() && brush.GetStyle() != wxBRUSHSTYLE_TRANSPARENT)
2531 {
2532 p.SetRefData(new wxCairoBrushData( this, brush ));
2533 }
2534 return p;
2535}
2536
2537wxGraphicsBrush
2538wxCairoRenderer::CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
2539 wxDouble x2, wxDouble y2,
2540 const wxGraphicsGradientStops& stops)
2541{
2542 wxGraphicsBrush p;
2543 ENSURE_LOADED_OR_RETURN(p);
2544 wxCairoBrushData* d = new wxCairoBrushData( this );
2545 d->CreateLinearGradientBrush(x1, y1, x2, y2, stops);
2546 p.SetRefData(d);
2547 return p;
2548}
2549
2550wxGraphicsBrush
2551wxCairoRenderer::CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
2552 wxDouble xc, wxDouble yc, wxDouble r,
2553 const wxGraphicsGradientStops& stops)
2554{
2555 wxGraphicsBrush p;
2556 ENSURE_LOADED_OR_RETURN(p);
2557 wxCairoBrushData* d = new wxCairoBrushData( this );
2558 d->CreateRadialGradientBrush(xo, yo, xc, yc, r, stops);
2559 p.SetRefData(d);
2560 return p;
2561}
2562
2563wxGraphicsFont wxCairoRenderer::CreateFont( const wxFont &font , const wxColour &col )
2564{
2565 wxGraphicsFont p;
2566 ENSURE_LOADED_OR_RETURN(p);
2567 if ( font.IsOk() )
2568 {
2569 p.SetRefData(new wxCairoFontData( this , font, col ));
2570 }
2571 return p;
2572}
2573
2574wxGraphicsFont
2575wxCairoRenderer::CreateFont(double sizeInPixels,
2576 const wxString& facename,
2577 int flags,
2578 const wxColour& col)
2579{
2580 wxGraphicsFont font;
2581 ENSURE_LOADED_OR_RETURN(font);
2582 font.SetRefData(new wxCairoFontData(this, sizeInPixels, facename, flags, col));
2583 return font;
2584}
2585
2586wxGraphicsBitmap wxCairoRenderer::CreateBitmap( const wxBitmap& bmp )
2587{
2588 wxGraphicsBitmap p;
2589 ENSURE_LOADED_OR_RETURN(p);
2590 if ( bmp.IsOk() )
2591 {
2592 p.SetRefData(new wxCairoBitmapData( this , bmp ));
2593 }
2594 return p;
2595}
2596
2597#if wxUSE_IMAGE
2598
2599wxGraphicsBitmap wxCairoRenderer::CreateBitmapFromImage(const wxImage& image)
2600{
2601 wxGraphicsBitmap bmp;
2602
2603 ENSURE_LOADED_OR_RETURN(bmp);
2604
2605 if ( image.IsOk() )
2606 {
2607 bmp.SetRefData(new wxCairoBitmapData(this, image));
2608 }
2609
2610 return bmp;
2611}
2612
2613wxImage wxCairoRenderer::CreateImageFromBitmap(const wxGraphicsBitmap& bmp)
2614{
2615 wxImage image;
2616 ENSURE_LOADED_OR_RETURN(image);
2617
2618 const wxCairoBitmapData* const
2619 data = static_cast<wxCairoBitmapData*>(bmp.GetGraphicsData());
2620 if (data)
2621 image = data->ConvertToImage();
2622
2623 return image;
2624}
2625
2626#endif // wxUSE_IMAGE
2627
2628
2629wxGraphicsBitmap wxCairoRenderer::CreateBitmapFromNativeBitmap( void* bitmap )
2630{
2631 wxGraphicsBitmap p;
2632 ENSURE_LOADED_OR_RETURN(p);
2633 if ( bitmap != NULL )
2634 {
2635 p.SetRefData(new wxCairoBitmapData( this , (cairo_surface_t*) bitmap ));
2636 }
2637 return p;
2638}
2639
2640wxGraphicsBitmap
2641wxCairoRenderer::CreateSubBitmap(const wxGraphicsBitmap& WXUNUSED(bitmap),
2642 wxDouble WXUNUSED(x),
2643 wxDouble WXUNUSED(y),
2644 wxDouble WXUNUSED(w),
2645 wxDouble WXUNUSED(h))
2646{
2647 wxGraphicsBitmap p;
2648 wxFAIL_MSG("wxCairoRenderer::CreateSubBitmap is not implemented.");
2649 return p;
2650}
2651
2652wxGraphicsRenderer* wxGraphicsRenderer::GetCairoRenderer()
2653{
2654 return &gs_cairoGraphicsRenderer;
2655}
2656
2657#else // !wxUSE_CAIRO
2658
2659wxGraphicsRenderer* wxGraphicsRenderer::GetCairoRenderer()
2660{
2661 return NULL;
2662}
2663
2664#endif // wxUSE_CAIRO/!wxUSE_CAIRO
2665
2666// MSW and OS X have their own native default renderers, but the other ports
2667// use Cairo by default
2668#if !(defined(__WXMSW__) || defined(__WXOSX__))
2669wxGraphicsRenderer* wxGraphicsRenderer::GetDefaultRenderer()
2670{
2671 return GetCairoRenderer();
2672}
2673#endif // !(__WXMSW__ || __WXOSX__)
2674
2675#endif // wxUSE_GRAPHICS_CONTEXT