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