]> git.saurik.com Git - wxWidgets.git/blob - src/osx/carbon/graphics.cpp
Fix wxHTMLDataObject compilation and memory leaks.
[wxWidgets.git] / src / osx / carbon / graphics.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/carbon/graphics.cpp
3 // Purpose: wxDC class
4 // Author: Stefan Csomor
5 // Modified by:
6 // Created: 01/02/97
7 // RCS-ID: $Id$
8 // copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #include "wx/graphics.h"
15 #include "wx/private/graphics.h"
16
17 #ifndef WX_PRECOMP
18 #include "wx/dcclient.h"
19 #include "wx/dcmemory.h"
20 #include "wx/dcprint.h"
21 #include "wx/log.h"
22 #include "wx/region.h"
23 #include "wx/image.h"
24 #include "wx/icon.h"
25 #endif
26
27
28 #ifdef __MSL__
29 #if __MSL__ >= 0x6000
30 #include "math.h"
31 // in case our functions were defined outside std, we make it known all the same
32 namespace std { }
33 using namespace std;
34 #endif
35 #endif
36
37 #ifdef __WXMAC__
38 #include "wx/osx/private.h"
39 #include "wx/osx/dcprint.h"
40 #include "wx/osx/dcclient.h"
41 #include "wx/osx/dcmemory.h"
42 #include "wx/osx/private.h"
43 #else
44 #include "CoreServices/CoreServices.h"
45 #include "ApplicationServices/ApplicationServices.h"
46 #include "wx/osx/core/cfstring.h"
47 #include "wx/cocoa/dcclient.h"
48 #endif
49
50 #ifdef __WXCOCOA__
51
52 CGColorSpaceRef wxMacGetGenericRGBColorSpace()
53 {
54 static wxCFRef<CGColorSpaceRef> genericRGBColorSpace;
55
56 if (genericRGBColorSpace == NULL)
57 {
58 genericRGBColorSpace.reset( CGColorSpaceCreateWithName( kCGColorSpaceGenericRGB ) );
59 }
60
61 return genericRGBColorSpace;
62 }
63
64 int UMAGetSystemVersion()
65 {
66 return 0x1050;
67 }
68
69
70 #define wxOSX_USE_CORE_TEXT 1
71
72 #endif
73
74 #if wxOSX_USE_COCOA_OR_IPHONE
75 extern CGContextRef wxOSXGetContextFromCurrentContext() ;
76 #if wxOSX_USE_COCOA
77 extern bool wxOSXLockFocus( WXWidget view) ;
78 extern void wxOSXUnlockFocus( WXWidget view) ;
79 #endif
80 #endif
81
82 #if 1 // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
83
84 // TODO test whether this private API also works under 10.3
85
86 // copying values from NSCompositingModes (see also webkit and cairo sources)
87
88 typedef enum CGCompositeOperation {
89 kCGCompositeOperationClear = 0,
90 kCGCompositeOperationCopy = 1,
91 kCGCompositeOperationSourceOver = 2,
92 kCGCompositeOperationSourceIn = 3,
93 kCGCompositeOperationSourceOut = 4,
94 kCGCompositeOperationSourceAtop = 5,
95 kCGCompositeOperationDestinationOver = 6,
96 kCGCompositeOperationDestinationIn = 7,
97 kCGCompositeOperationDestinationOut = 8,
98 kCGCompositeOperationDestinationAtop = 9,
99 kCGCompositeOperationXOR = 10,
100 kCGCompositeOperationPlusDarker = 11,
101 // NS only, unsupported by CG : Highlight
102 kCGCompositeOperationPlusLighter = 12
103 } CGCompositeOperation ;
104
105 extern "C"
106 {
107 CG_EXTERN void CGContextSetCompositeOperation (CGContextRef context, int operation);
108 } ;
109
110 #endif
111
112 //-----------------------------------------------------------------------------
113 // constants
114 //-----------------------------------------------------------------------------
115
116 #ifndef M_PI
117 const double M_PI = 3.14159265358979;
118 #endif
119
120 static const double RAD2DEG = 180.0 / M_PI;
121
122 //
123 // Pen, Brushes and Fonts
124 //
125
126 #pragma mark -
127 #pragma mark wxMacCoreGraphicsPattern, ImagePattern, HatchPattern classes
128
129 OSStatus wxMacDrawCGImage(
130 CGContextRef inContext,
131 const CGRect * inBounds,
132 CGImageRef inImage)
133 {
134 #if wxOSX_USE_CARBON
135 return HIViewDrawCGImage( inContext, inBounds, inImage );
136 #else
137 CGContextSaveGState(inContext);
138 CGContextTranslateCTM(inContext, inBounds->origin.x, inBounds->origin.y + inBounds->size.height);
139 CGRect r = *inBounds;
140 r.origin.x = r.origin.y = 0;
141 CGContextScaleCTM(inContext, 1, -1);
142 CGContextDrawImage(inContext, r, inImage );
143 CGContextRestoreGState(inContext);
144 return noErr;
145 #endif
146 }
147
148 CGColorRef wxMacCreateCGColor( const wxColour& col )
149 {
150 CGColorRef retval = 0;
151 #ifdef __WXMAC__
152 retval = col.CreateCGColor();
153 #else
154 // TODO add conversion NSColor - CGColorRef (obj-c)
155 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
156 if ( CGColorCreateGenericRGB )
157 retval = CGColorCreateGenericRGB( col.Red() / 255.0 , col.Green() / 255.0, col.Blue() / 255.0, col.Alpha() / 255.0 );
158 else
159 #endif
160 {
161 CGFloat components[4] = { col.Red() / 255.0, col.Green() / 255.0, col.Blue() / 255.0, col.Alpha() / 255.0 } ;
162 retval = CGColorCreate( wxMacGetGenericRGBColorSpace() , components ) ;
163 }
164
165 #endif
166 wxASSERT(retval != NULL);
167 return retval;
168 }
169
170 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 && wxOSX_USE_CORE_TEXT
171
172 CTFontRef wxMacCreateCTFont( const wxFont& font )
173 {
174 #ifdef __WXMAC__
175 return wxCFRetain((CTFontRef) font.OSXGetCTFont());
176 #else
177 return CTFontCreateWithName( wxCFStringRef( font.GetFaceName(), wxLocale::GetSystemEncoding() ) , font.GetPointSize() , NULL );
178 #endif
179 }
180
181 #endif
182
183 // CGPattern wrapper class: always allocate on heap, never call destructor
184
185 class wxMacCoreGraphicsPattern
186 {
187 public :
188 wxMacCoreGraphicsPattern() {}
189
190 // is guaranteed to be called only with a non-Null CGContextRef
191 virtual void Render( CGContextRef ctxRef ) = 0;
192
193 operator CGPatternRef() const { return m_patternRef; }
194
195 protected :
196 virtual ~wxMacCoreGraphicsPattern()
197 {
198 // as this is called only when the m_patternRef is been released;
199 // don't release it again
200 }
201
202 static void _Render( void *info, CGContextRef ctxRef )
203 {
204 wxMacCoreGraphicsPattern* self = (wxMacCoreGraphicsPattern*) info;
205 if ( self && ctxRef )
206 self->Render( ctxRef );
207 }
208
209 static void _Dispose( void *info )
210 {
211 wxMacCoreGraphicsPattern* self = (wxMacCoreGraphicsPattern*) info;
212 delete self;
213 }
214
215 CGPatternRef m_patternRef;
216
217 static const CGPatternCallbacks ms_Callbacks;
218 };
219
220 const CGPatternCallbacks wxMacCoreGraphicsPattern::ms_Callbacks = { 0, &wxMacCoreGraphicsPattern::_Render, &wxMacCoreGraphicsPattern::_Dispose };
221
222 class ImagePattern : public wxMacCoreGraphicsPattern
223 {
224 public :
225 ImagePattern( const wxBitmap* bmp , const CGAffineTransform& transform )
226 {
227 wxASSERT( bmp && bmp->IsOk() );
228 #ifdef __WXMAC__
229 Init( (CGImageRef) bmp->CreateCGImage() , transform );
230 #endif
231 }
232
233 // ImagePattern takes ownership of CGImageRef passed in
234 ImagePattern( CGImageRef image , const CGAffineTransform& transform )
235 {
236 if ( image )
237 CFRetain( image );
238
239 Init( image , transform );
240 }
241
242 virtual void Render( CGContextRef ctxRef )
243 {
244 if (m_image != NULL)
245 wxMacDrawCGImage( ctxRef, &m_imageBounds, m_image );
246 }
247
248 protected :
249 void Init( CGImageRef image, const CGAffineTransform& transform )
250 {
251 m_image = image;
252 if ( m_image )
253 {
254 m_imageBounds = CGRectMake( (CGFloat) 0.0, (CGFloat) 0.0, (CGFloat)CGImageGetWidth( m_image ), (CGFloat)CGImageGetHeight( m_image ) );
255 m_patternRef = CGPatternCreate(
256 this , m_imageBounds, transform ,
257 m_imageBounds.size.width, m_imageBounds.size.height,
258 kCGPatternTilingNoDistortion, true , &wxMacCoreGraphicsPattern::ms_Callbacks );
259 }
260 }
261
262 virtual ~ImagePattern()
263 {
264 if ( m_image )
265 CGImageRelease( m_image );
266 }
267
268 CGImageRef m_image;
269 CGRect m_imageBounds;
270 };
271
272 class HatchPattern : public wxMacCoreGraphicsPattern
273 {
274 public :
275 HatchPattern( int hatchstyle, const CGAffineTransform& transform )
276 {
277 m_hatch = hatchstyle;
278 m_imageBounds = CGRectMake( (CGFloat) 0.0, (CGFloat) 0.0, (CGFloat) 8.0 , (CGFloat) 8.0 );
279 m_patternRef = CGPatternCreate(
280 this , m_imageBounds, transform ,
281 m_imageBounds.size.width, m_imageBounds.size.height,
282 kCGPatternTilingNoDistortion, false , &wxMacCoreGraphicsPattern::ms_Callbacks );
283 }
284
285 void StrokeLineSegments( CGContextRef ctxRef , const CGPoint pts[] , size_t count )
286 {
287 CGContextStrokeLineSegments( ctxRef , pts , count );
288 }
289
290 virtual void Render( CGContextRef ctxRef )
291 {
292 switch ( m_hatch )
293 {
294 case wxBDIAGONAL_HATCH :
295 {
296 CGPoint pts[] =
297 {
298 { (CGFloat) 8.0 , (CGFloat) 0.0 } , { (CGFloat) 0.0 , (CGFloat) 8.0 }
299 };
300 StrokeLineSegments( ctxRef , pts , 2 );
301 }
302 break;
303
304 case wxCROSSDIAG_HATCH :
305 {
306 CGPoint pts[] =
307 {
308 { (CGFloat) 0.0 , (CGFloat) 0.0 } , { (CGFloat) 8.0 , (CGFloat) 8.0 } ,
309 { (CGFloat) 8.0 , (CGFloat) 0.0 } , { (CGFloat) 0.0 , (CGFloat) 8.0 }
310 };
311 StrokeLineSegments( ctxRef , pts , 4 );
312 }
313 break;
314
315 case wxFDIAGONAL_HATCH :
316 {
317 CGPoint pts[] =
318 {
319 { (CGFloat) 0.0 , (CGFloat) 0.0 } , { (CGFloat) 8.0 , (CGFloat) 8.0 }
320 };
321 StrokeLineSegments( ctxRef , pts , 2 );
322 }
323 break;
324
325 case wxCROSS_HATCH :
326 {
327 CGPoint pts[] =
328 {
329 { (CGFloat) 0.0 , (CGFloat) 4.0 } , { (CGFloat) 8.0 , (CGFloat) 4.0 } ,
330 { (CGFloat) 4.0 , (CGFloat) 0.0 } , { (CGFloat) 4.0 , (CGFloat) 8.0 } ,
331 };
332 StrokeLineSegments( ctxRef , pts , 4 );
333 }
334 break;
335
336 case wxHORIZONTAL_HATCH :
337 {
338 CGPoint pts[] =
339 {
340 { (CGFloat) 0.0 , (CGFloat) 4.0 } , { (CGFloat) 8.0 , (CGFloat) 4.0 } ,
341 };
342 StrokeLineSegments( ctxRef , pts , 2 );
343 }
344 break;
345
346 case wxVERTICAL_HATCH :
347 {
348 CGPoint pts[] =
349 {
350 { (CGFloat) 4.0 , (CGFloat) 0.0 } , { (CGFloat) 4.0 , (CGFloat) 8.0 } ,
351 };
352 StrokeLineSegments( ctxRef , pts , 2 );
353 }
354 break;
355
356 default:
357 break;
358 }
359 }
360
361 protected :
362 virtual ~HatchPattern() {}
363
364 CGRect m_imageBounds;
365 int m_hatch;
366 };
367
368 class wxMacCoreGraphicsPenData : public wxGraphicsObjectRefData
369 {
370 public:
371 wxMacCoreGraphicsPenData( wxGraphicsRenderer* renderer, const wxPen &pen );
372 ~wxMacCoreGraphicsPenData();
373
374 void Init();
375 virtual void Apply( wxGraphicsContext* context );
376 virtual wxDouble GetWidth() { return m_width; }
377
378 protected :
379 CGLineCap m_cap;
380 wxCFRef<CGColorRef> m_color;
381 wxCFRef<CGColorSpaceRef> m_colorSpace;
382
383 CGLineJoin m_join;
384 CGFloat m_width;
385
386 int m_count;
387 const CGFloat *m_lengths;
388 CGFloat *m_userLengths;
389
390
391 bool m_isPattern;
392 wxCFRef<CGPatternRef> m_pattern;
393 CGFloat* m_patternColorComponents;
394 };
395
396 wxMacCoreGraphicsPenData::wxMacCoreGraphicsPenData( wxGraphicsRenderer* renderer, const wxPen &pen ) :
397 wxGraphicsObjectRefData( renderer )
398 {
399 Init();
400
401 m_color.reset( wxMacCreateCGColor( pen.GetColour() ) ) ;
402
403 // TODO: * m_dc->m_scaleX
404 m_width = pen.GetWidth();
405 if (m_width <= 0.0)
406 m_width = (CGFloat) 0.1;
407
408 switch ( pen.GetCap() )
409 {
410 case wxCAP_ROUND :
411 m_cap = kCGLineCapRound;
412 break;
413
414 case wxCAP_PROJECTING :
415 m_cap = kCGLineCapSquare;
416 break;
417
418 case wxCAP_BUTT :
419 m_cap = kCGLineCapButt;
420 break;
421
422 default :
423 m_cap = kCGLineCapButt;
424 break;
425 }
426
427 switch ( pen.GetJoin() )
428 {
429 case wxJOIN_BEVEL :
430 m_join = kCGLineJoinBevel;
431 break;
432
433 case wxJOIN_MITER :
434 m_join = kCGLineJoinMiter;
435 break;
436
437 case wxJOIN_ROUND :
438 m_join = kCGLineJoinRound;
439 break;
440
441 default :
442 m_join = kCGLineJoinMiter;
443 break;
444 }
445
446 const CGFloat dashUnit = m_width < 1.0 ? (CGFloat) 1.0 : m_width;
447
448 const CGFloat dotted[] = { (CGFloat) dashUnit , (CGFloat) (dashUnit + 2.0) };
449 static const CGFloat short_dashed[] = { (CGFloat) 9.0 , (CGFloat) 6.0 };
450 static const CGFloat dashed[] = { (CGFloat) 19.0 , (CGFloat) 9.0 };
451 static const CGFloat dotted_dashed[] = { (CGFloat) 9.0 , (CGFloat) 6.0 , (CGFloat) 3.0 , (CGFloat) 3.0 };
452
453 switch ( pen.GetStyle() )
454 {
455 case wxPENSTYLE_SOLID:
456 break;
457
458 case wxPENSTYLE_DOT:
459 m_count = WXSIZEOF(dotted);
460 m_userLengths = new CGFloat[ m_count ] ;
461 memcpy( m_userLengths, dotted, sizeof(dotted) );
462 m_lengths = m_userLengths;
463 break;
464
465 case wxPENSTYLE_LONG_DASH:
466 m_count = WXSIZEOF(dashed);
467 m_lengths = dashed;
468 break;
469
470 case wxPENSTYLE_SHORT_DASH:
471 m_count = WXSIZEOF(short_dashed);
472 m_lengths = short_dashed;
473 break;
474
475 case wxPENSTYLE_DOT_DASH:
476 m_count = WXSIZEOF(dotted_dashed);
477 m_lengths = dotted_dashed;
478 break;
479
480 case wxPENSTYLE_USER_DASH:
481 wxDash *dashes;
482 m_count = pen.GetDashes( &dashes );
483 if ((dashes != NULL) && (m_count > 0))
484 {
485 m_userLengths = new CGFloat[m_count];
486 for ( int i = 0; i < m_count; ++i )
487 {
488 m_userLengths[i] = dashes[i] * dashUnit;
489
490 if ( i % 2 == 1 && m_userLengths[i] < dashUnit + 2.0 )
491 m_userLengths[i] = (CGFloat) (dashUnit + 2.0);
492 else if ( i % 2 == 0 && m_userLengths[i] < dashUnit )
493 m_userLengths[i] = dashUnit;
494 }
495 }
496 m_lengths = m_userLengths;
497 break;
498
499 case wxPENSTYLE_STIPPLE:
500 {
501 wxBitmap* bmp = pen.GetStipple();
502 if ( bmp && bmp->IsOk() )
503 {
504 m_colorSpace.reset( CGColorSpaceCreatePattern( NULL ) );
505 m_pattern.reset( (CGPatternRef) *( new ImagePattern( bmp , CGAffineTransformMakeScale( 1,-1 ) ) ) );
506 m_patternColorComponents = new CGFloat[1] ;
507 m_patternColorComponents[0] = (CGFloat) 1.0;
508 m_isPattern = true;
509 }
510 }
511 break;
512
513 default :
514 {
515 m_isPattern = true;
516 m_colorSpace.reset( CGColorSpaceCreatePattern( wxMacGetGenericRGBColorSpace() ) );
517 m_pattern.reset( (CGPatternRef) *( new HatchPattern( pen.GetStyle() , CGAffineTransformMakeScale( 1,-1 ) ) ) );
518 m_patternColorComponents = new CGFloat[4] ;
519 m_patternColorComponents[0] = (CGFloat) (pen.GetColour().Red() / 255.0);
520 m_patternColorComponents[1] = (CGFloat) (pen.GetColour().Green() / 255.0);
521 m_patternColorComponents[2] = (CGFloat) (pen.GetColour().Blue() / 255.0);
522 m_patternColorComponents[3] = (CGFloat) (pen.GetColour().Alpha() / 255.0);
523 }
524 break;
525 }
526 if ((m_lengths != NULL) && (m_count > 0))
527 {
528 // force the line cap, otherwise we get artifacts (overlaps) and just solid lines
529 m_cap = kCGLineCapButt;
530 }
531 }
532
533 wxMacCoreGraphicsPenData::~wxMacCoreGraphicsPenData()
534 {
535 delete[] m_userLengths;
536 delete[] m_patternColorComponents;
537 }
538
539 void wxMacCoreGraphicsPenData::Init()
540 {
541 m_lengths = NULL;
542 m_userLengths = NULL;
543 m_width = 0;
544 m_count = 0;
545 m_patternColorComponents = NULL;
546 m_isPattern = false;
547 }
548
549 void wxMacCoreGraphicsPenData::Apply( wxGraphicsContext* context )
550 {
551 CGContextRef cg = (CGContextRef) context->GetNativeContext();
552 CGContextSetLineWidth( cg , m_width );
553 CGContextSetLineJoin( cg , m_join );
554
555 CGContextSetLineDash( cg , 0 , m_lengths , m_count );
556 CGContextSetLineCap( cg , m_cap );
557
558 if ( m_isPattern )
559 {
560 CGAffineTransform matrix = CGContextGetCTM( cg );
561 CGContextSetPatternPhase( cg, CGSizeMake(matrix.tx, matrix.ty) );
562 CGContextSetStrokeColorSpace( cg , m_colorSpace );
563 CGContextSetStrokePattern( cg, m_pattern , m_patternColorComponents );
564 }
565 else
566 {
567 CGContextSetStrokeColorWithColor( cg , m_color );
568 }
569 }
570
571 //
572 // Brush
573 //
574
575 // make sure we all use one class for all conversions from wx to native colour
576
577 class wxMacCoreGraphicsColour
578 {
579 public:
580 wxMacCoreGraphicsColour();
581 wxMacCoreGraphicsColour(const wxBrush &brush);
582 ~wxMacCoreGraphicsColour();
583
584 void Apply( CGContextRef cgContext );
585 protected:
586 void Init();
587 wxCFRef<CGColorRef> m_color;
588 wxCFRef<CGColorSpaceRef> m_colorSpace;
589
590 bool m_isPattern;
591 wxCFRef<CGPatternRef> m_pattern;
592 CGFloat* m_patternColorComponents;
593 } ;
594
595 wxMacCoreGraphicsColour::~wxMacCoreGraphicsColour()
596 {
597 delete[] m_patternColorComponents;
598 }
599
600 void wxMacCoreGraphicsColour::Init()
601 {
602 m_isPattern = false;
603 m_patternColorComponents = NULL;
604 }
605
606 void wxMacCoreGraphicsColour::Apply( CGContextRef cgContext )
607 {
608 if ( m_isPattern )
609 {
610 CGAffineTransform matrix = CGContextGetCTM( cgContext );
611 CGContextSetPatternPhase( cgContext, CGSizeMake(matrix.tx, matrix.ty) );
612 CGContextSetFillColorSpace( cgContext , m_colorSpace );
613 CGContextSetFillPattern( cgContext, m_pattern , m_patternColorComponents );
614 }
615 else
616 {
617 CGContextSetFillColorWithColor( cgContext, m_color );
618 }
619 }
620
621 wxMacCoreGraphicsColour::wxMacCoreGraphicsColour()
622 {
623 Init();
624 }
625
626 wxMacCoreGraphicsColour::wxMacCoreGraphicsColour( const wxBrush &brush )
627 {
628 Init();
629 if ( brush.GetStyle() == wxSOLID )
630 {
631 m_color.reset( wxMacCreateCGColor( brush.GetColour() ));
632 }
633 else if ( brush.IsHatch() )
634 {
635 m_isPattern = true;
636 m_colorSpace.reset( CGColorSpaceCreatePattern( wxMacGetGenericRGBColorSpace() ) );
637 m_pattern.reset( (CGPatternRef) *( new HatchPattern( brush.GetStyle() , CGAffineTransformMakeScale( 1,-1 ) ) ) );
638
639 m_patternColorComponents = new CGFloat[4] ;
640 m_patternColorComponents[0] = (CGFloat) (brush.GetColour().Red() / 255.0);
641 m_patternColorComponents[1] = (CGFloat) (brush.GetColour().Green() / 255.0);
642 m_patternColorComponents[2] = (CGFloat) (brush.GetColour().Blue() / 255.0);
643 m_patternColorComponents[3] = (CGFloat) (brush.GetColour().Alpha() / 255.0);
644 }
645 else
646 {
647 // now brush is a bitmap
648 wxBitmap* bmp = brush.GetStipple();
649 if ( bmp && bmp->IsOk() )
650 {
651 m_isPattern = true;
652 m_patternColorComponents = new CGFloat[1] ;
653 m_patternColorComponents[0] = (CGFloat) 1.0;
654 m_colorSpace.reset( CGColorSpaceCreatePattern( NULL ) );
655 m_pattern.reset( (CGPatternRef) *( new ImagePattern( bmp , CGAffineTransformMakeScale( 1,-1 ) ) ) );
656 }
657 }
658 }
659
660 class wxMacCoreGraphicsBrushData : public wxGraphicsObjectRefData
661 {
662 public:
663 wxMacCoreGraphicsBrushData( wxGraphicsRenderer* renderer );
664 wxMacCoreGraphicsBrushData( wxGraphicsRenderer* renderer, const wxBrush &brush );
665 ~wxMacCoreGraphicsBrushData ();
666
667 virtual void Apply( wxGraphicsContext* context );
668 void CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
669 wxDouble x2, wxDouble y2,
670 const wxGraphicsGradientStops& stops);
671 void CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
672 wxDouble xc, wxDouble yc, wxDouble radius,
673 const wxGraphicsGradientStops& stops);
674
675 virtual bool IsShading() { return m_isShading; }
676 CGShadingRef GetShading() { return m_shading; }
677 protected:
678 CGFunctionRef CreateGradientFunction(const wxGraphicsGradientStops& stops);
679
680 static void CalculateShadingValues (void *info, const CGFloat *in, CGFloat *out);
681 virtual void Init();
682
683 wxMacCoreGraphicsColour m_cgColor;
684
685 bool m_isShading;
686 CGFunctionRef m_gradientFunction;
687 CGShadingRef m_shading;
688
689 // information about a single gradient component
690 struct GradientComponent
691 {
692 CGFloat pos;
693 CGFloat red;
694 CGFloat green;
695 CGFloat blue;
696 CGFloat alpha;
697 };
698
699 // and information about all of them
700 struct GradientComponents
701 {
702 GradientComponents()
703 {
704 count = 0;
705 comps = NULL;
706 }
707
708 void Init(unsigned count_)
709 {
710 count = count_;
711 comps = new GradientComponent[count];
712 }
713
714 ~GradientComponents()
715 {
716 delete [] comps;
717 }
718
719 unsigned count;
720 GradientComponent *comps;
721 };
722
723 GradientComponents m_gradientComponents;
724 };
725
726 wxMacCoreGraphicsBrushData::wxMacCoreGraphicsBrushData( wxGraphicsRenderer* renderer) : wxGraphicsObjectRefData( renderer )
727 {
728 Init();
729 }
730
731 void
732 wxMacCoreGraphicsBrushData::CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
733 wxDouble x2, wxDouble y2,
734 const wxGraphicsGradientStops& stops)
735 {
736 m_gradientFunction = CreateGradientFunction(stops);
737 m_shading = CGShadingCreateAxial( wxMacGetGenericRGBColorSpace(), CGPointMake((CGFloat) x1, (CGFloat) y1),
738 CGPointMake((CGFloat) x2,(CGFloat) y2), m_gradientFunction, true, true ) ;
739 m_isShading = true ;
740 }
741
742 void
743 wxMacCoreGraphicsBrushData::CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
744 wxDouble xc, wxDouble yc,
745 wxDouble radius,
746 const wxGraphicsGradientStops& stops)
747 {
748 m_gradientFunction = CreateGradientFunction(stops);
749 m_shading = CGShadingCreateRadial( wxMacGetGenericRGBColorSpace(), CGPointMake((CGFloat) xo,(CGFloat) yo), 0,
750 CGPointMake((CGFloat) xc,(CGFloat) yc), (CGFloat) radius, m_gradientFunction, true, true ) ;
751 m_isShading = true ;
752 }
753
754 wxMacCoreGraphicsBrushData::wxMacCoreGraphicsBrushData(wxGraphicsRenderer* renderer, const wxBrush &brush) : wxGraphicsObjectRefData( renderer ),
755 m_cgColor( brush )
756 {
757 Init();
758
759 }
760
761 wxMacCoreGraphicsBrushData::~wxMacCoreGraphicsBrushData()
762 {
763 if ( m_shading )
764 CGShadingRelease(m_shading);
765
766 if( m_gradientFunction )
767 CGFunctionRelease(m_gradientFunction);
768 }
769
770 void wxMacCoreGraphicsBrushData::Init()
771 {
772 m_gradientFunction = NULL;
773 m_shading = NULL;
774 m_isShading = false;
775 }
776
777 void wxMacCoreGraphicsBrushData::Apply( wxGraphicsContext* context )
778 {
779 CGContextRef cg = (CGContextRef) context->GetNativeContext();
780
781 if ( m_isShading )
782 {
783 // nothing to set as shades are processed by clipping using the path and filling
784 }
785 else
786 {
787 m_cgColor.Apply( cg );
788 }
789 }
790
791 void wxMacCoreGraphicsBrushData::CalculateShadingValues (void *info, const CGFloat *in, CGFloat *out)
792 {
793 const GradientComponents& stops = *(GradientComponents*) info ;
794
795 CGFloat f = *in;
796 if (f <= 0.0)
797 {
798 // Start
799 out[0] = stops.comps[0].red;
800 out[1] = stops.comps[0].green;
801 out[2] = stops.comps[0].blue;
802 out[3] = stops.comps[0].alpha;
803 }
804 else if (f >= 1.0)
805 {
806 // end
807 out[0] = stops.comps[stops.count - 1].red;
808 out[1] = stops.comps[stops.count - 1].green;
809 out[2] = stops.comps[stops.count - 1].blue;
810 out[3] = stops.comps[stops.count - 1].alpha;
811 }
812 else
813 {
814 // Find first component with position greater than f
815 unsigned i;
816 for ( i = 0; i < stops.count; i++ )
817 {
818 if (stops.comps[i].pos > f)
819 break;
820 }
821
822 // Interpolated between stops
823 CGFloat diff = (f - stops.comps[i-1].pos);
824 CGFloat range = (stops.comps[i].pos - stops.comps[i-1].pos);
825 CGFloat fact = diff / range;
826
827 out[0] = stops.comps[i - 1].red + (stops.comps[i].red - stops.comps[i - 1].red) * fact;
828 out[1] = stops.comps[i - 1].green + (stops.comps[i].green - stops.comps[i - 1].green) * fact;
829 out[2] = stops.comps[i - 1].blue + (stops.comps[i].blue - stops.comps[i - 1].blue) * fact;
830 out[3] = stops.comps[i - 1].alpha + (stops.comps[i].alpha - stops.comps[i - 1].alpha) * fact;
831 }
832 }
833
834 CGFunctionRef
835 wxMacCoreGraphicsBrushData::CreateGradientFunction(const wxGraphicsGradientStops& stops)
836 {
837
838 static const CGFunctionCallbacks callbacks = { 0, &CalculateShadingValues, NULL };
839 static const CGFloat input_value_range [2] = { 0, 1 };
840 static const CGFloat output_value_ranges [8] = { 0, 1, 0, 1, 0, 1, 0, 1 };
841
842 m_gradientComponents.Init(stops.GetCount());
843 for ( unsigned i = 0; i < m_gradientComponents.count; i++ )
844 {
845 const wxGraphicsGradientStop stop = stops.Item(i);
846
847 m_gradientComponents.comps[i].pos = stop.GetPosition();
848
849 const wxColour col = stop.GetColour();
850 m_gradientComponents.comps[i].red = (CGFloat) (col.Red() / 255.0);
851 m_gradientComponents.comps[i].green = (CGFloat) (col.Green() / 255.0);
852 m_gradientComponents.comps[i].blue = (CGFloat) (col.Blue() / 255.0);
853 m_gradientComponents.comps[i].alpha = (CGFloat) (col.Alpha() / 255.0);
854 }
855
856 return CGFunctionCreate ( &m_gradientComponents, 1,
857 input_value_range,
858 4,
859 output_value_ranges,
860 &callbacks);
861 }
862
863 //
864 // Font
865 //
866
867 #if wxOSX_USE_IPHONE
868
869 extern UIFont* CreateUIFont( const wxFont& font );
870 extern void DrawTextInContext( CGContextRef context, CGPoint where, UIFont *font, NSString* text );
871 extern CGSize MeasureTextInContext( UIFont *font, NSString* text );
872
873 #endif
874
875 class wxMacCoreGraphicsFontData : public wxGraphicsObjectRefData
876 {
877 public:
878 wxMacCoreGraphicsFontData( wxGraphicsRenderer* renderer, const wxFont &font, const wxColour& col );
879 ~wxMacCoreGraphicsFontData();
880
881 #if wxOSX_USE_ATSU_TEXT
882 virtual ATSUStyle GetATSUStyle() { return m_macATSUIStyle; }
883 #endif
884 #if wxOSX_USE_CORE_TEXT
885 CTFontRef OSXGetCTFont() const { return m_ctFont ; }
886 #endif
887 wxColour GetColour() const { return m_colour ; }
888
889 bool GetUnderlined() const { return m_underlined ; }
890 #if wxOSX_USE_IPHONE
891 UIFont* GetUIFont() const { return m_uiFont; }
892 #endif
893 private :
894 wxColour m_colour;
895 bool m_underlined;
896 #if wxOSX_USE_ATSU_TEXT
897 ATSUStyle m_macATSUIStyle;
898 #endif
899 #if wxOSX_USE_CORE_TEXT
900 wxCFRef< CTFontRef > m_ctFont;
901 #endif
902 #if wxOSX_USE_IPHONE
903 UIFont* m_uiFont;
904 #endif
905 };
906
907 wxMacCoreGraphicsFontData::wxMacCoreGraphicsFontData(wxGraphicsRenderer* renderer, const wxFont &font, const wxColour& col) : wxGraphicsObjectRefData( renderer )
908 {
909 m_colour = col;
910 m_underlined = font.GetUnderlined();
911
912 #if wxOSX_USE_CORE_TEXT
913 m_ctFont.reset( wxMacCreateCTFont( font ) );
914 #endif
915 #if wxOSX_USE_IPHONE
916 m_uiFont = CreateUIFont(font);
917 wxMacCocoaRetain( m_uiFont );
918 #endif
919 #if wxOSX_USE_ATSU_TEXT
920 OSStatus status = noErr;
921 m_macATSUIStyle = NULL;
922
923 status = ATSUCreateAndCopyStyle( (ATSUStyle) font.MacGetATSUStyle() , &m_macATSUIStyle );
924
925 wxASSERT_MSG( status == noErr, wxT("couldn't create ATSU style") );
926
927 // we need the scale here ...
928
929 Fixed atsuSize = IntToFixed( int( 1 * font.GetPointSize()) );
930 RGBColor atsuColor ;
931 col.GetRGBColor( &atsuColor );
932 ATSUAttributeTag atsuTags[] =
933 {
934 kATSUSizeTag ,
935 kATSUColorTag ,
936 };
937 ByteCount atsuSizes[WXSIZEOF(atsuTags)] =
938 {
939 sizeof( Fixed ) ,
940 sizeof( RGBColor ) ,
941 };
942 ATSUAttributeValuePtr atsuValues[WXSIZEOF(atsuTags)] =
943 {
944 &atsuSize ,
945 &atsuColor ,
946 };
947
948 status = ::ATSUSetAttributes(
949 m_macATSUIStyle, WXSIZEOF(atsuTags),
950 atsuTags, atsuSizes, atsuValues);
951
952 wxASSERT_MSG( status == noErr , wxT("couldn't modify ATSU style") );
953 #endif
954 }
955
956 wxMacCoreGraphicsFontData::~wxMacCoreGraphicsFontData()
957 {
958 #if wxOSX_USE_CORE_TEXT
959 #endif
960 #if wxOSX_USE_ATSU_TEXT
961 if ( m_macATSUIStyle )
962 {
963 ::ATSUDisposeStyle((ATSUStyle)m_macATSUIStyle);
964 m_macATSUIStyle = NULL;
965 }
966 #endif
967 #if wxOSX_USE_IPHONE
968 wxMacCocoaRelease( m_uiFont );
969 #endif
970 }
971
972 class wxMacCoreGraphicsBitmapData : public wxGraphicsBitmapData
973 {
974 public:
975 wxMacCoreGraphicsBitmapData( wxGraphicsRenderer* renderer, CGImageRef bitmap, bool monochrome );
976 ~wxMacCoreGraphicsBitmapData();
977
978 virtual CGImageRef GetBitmap() { return m_bitmap; }
979 virtual void* GetNativeBitmap() const { return m_bitmap; }
980 bool IsMonochrome() { return m_monochrome; }
981
982 #if wxUSE_IMAGE
983 wxImage ConvertToImage() const
984 {
985 return wxBitmap(m_bitmap).ConvertToImage();
986 }
987 #endif // wxUSE_IMAGE
988
989 private :
990 CGImageRef m_bitmap;
991 bool m_monochrome;
992 };
993
994 wxMacCoreGraphicsBitmapData::wxMacCoreGraphicsBitmapData( wxGraphicsRenderer* renderer, CGImageRef bitmap, bool monochrome ) : wxGraphicsBitmapData( renderer ),
995 m_bitmap(bitmap), m_monochrome(monochrome)
996 {
997 }
998
999 wxMacCoreGraphicsBitmapData::~wxMacCoreGraphicsBitmapData()
1000 {
1001 CGImageRelease( m_bitmap );
1002 }
1003
1004
1005 //
1006 // Graphics Matrix
1007 //
1008
1009 //-----------------------------------------------------------------------------
1010 // wxMacCoreGraphicsMatrix declaration
1011 //-----------------------------------------------------------------------------
1012
1013 class WXDLLIMPEXP_CORE wxMacCoreGraphicsMatrixData : public wxGraphicsMatrixData
1014 {
1015 public :
1016 wxMacCoreGraphicsMatrixData(wxGraphicsRenderer* renderer) ;
1017
1018 virtual ~wxMacCoreGraphicsMatrixData() ;
1019
1020 virtual wxGraphicsObjectRefData *Clone() const ;
1021
1022 // concatenates the matrix
1023 virtual void Concat( const wxGraphicsMatrixData *t );
1024
1025 // sets the matrix to the respective values
1026 virtual void Set(wxDouble a=1.0, wxDouble b=0.0, wxDouble c=0.0, wxDouble d=1.0,
1027 wxDouble tx=0.0, wxDouble ty=0.0);
1028
1029 // gets the component valuess of the matrix
1030 virtual void Get(wxDouble* a=NULL, wxDouble* b=NULL, wxDouble* c=NULL,
1031 wxDouble* d=NULL, wxDouble* tx=NULL, wxDouble* ty=NULL) const;
1032
1033 // makes this the inverse matrix
1034 virtual void Invert();
1035
1036 // returns true if the elements of the transformation matrix are equal ?
1037 virtual bool IsEqual( const wxGraphicsMatrixData* t) const ;
1038
1039 // return true if this is the identity matrix
1040 virtual bool IsIdentity() const;
1041
1042 //
1043 // transformation
1044 //
1045
1046 // add the translation to this matrix
1047 virtual void Translate( wxDouble dx , wxDouble dy );
1048
1049 // add the scale to this matrix
1050 virtual void Scale( wxDouble xScale , wxDouble yScale );
1051
1052 // add the rotation to this matrix (radians)
1053 virtual void Rotate( wxDouble angle );
1054
1055 //
1056 // apply the transforms
1057 //
1058
1059 // applies that matrix to the point
1060 virtual void TransformPoint( wxDouble *x, wxDouble *y ) const;
1061
1062 // applies the matrix except for translations
1063 virtual void TransformDistance( wxDouble *dx, wxDouble *dy ) const;
1064
1065 // returns the native representation
1066 virtual void * GetNativeMatrix() const;
1067
1068 private :
1069 CGAffineTransform m_matrix;
1070 } ;
1071
1072 //-----------------------------------------------------------------------------
1073 // wxMacCoreGraphicsMatrix implementation
1074 //-----------------------------------------------------------------------------
1075
1076 wxMacCoreGraphicsMatrixData::wxMacCoreGraphicsMatrixData(wxGraphicsRenderer* renderer) : wxGraphicsMatrixData(renderer)
1077 {
1078 }
1079
1080 wxMacCoreGraphicsMatrixData::~wxMacCoreGraphicsMatrixData()
1081 {
1082 }
1083
1084 wxGraphicsObjectRefData *wxMacCoreGraphicsMatrixData::Clone() const
1085 {
1086 wxMacCoreGraphicsMatrixData* m = new wxMacCoreGraphicsMatrixData(GetRenderer()) ;
1087 m->m_matrix = m_matrix ;
1088 return m;
1089 }
1090
1091 // concatenates the matrix
1092 void wxMacCoreGraphicsMatrixData::Concat( const wxGraphicsMatrixData *t )
1093 {
1094 m_matrix = CGAffineTransformConcat(*((CGAffineTransform*) t->GetNativeMatrix()), m_matrix );
1095 }
1096
1097 // sets the matrix to the respective values
1098 void wxMacCoreGraphicsMatrixData::Set(wxDouble a, wxDouble b, wxDouble c, wxDouble d,
1099 wxDouble tx, wxDouble ty)
1100 {
1101 m_matrix = CGAffineTransformMake((CGFloat) a,(CGFloat) b,(CGFloat) c,(CGFloat) d,(CGFloat) tx,(CGFloat) ty);
1102 }
1103
1104 // gets the component valuess of the matrix
1105 void wxMacCoreGraphicsMatrixData::Get(wxDouble* a, wxDouble* b, wxDouble* c,
1106 wxDouble* d, wxDouble* tx, wxDouble* ty) const
1107 {
1108 if (a) *a = m_matrix.a;
1109 if (b) *b = m_matrix.b;
1110 if (c) *c = m_matrix.c;
1111 if (d) *d = m_matrix.d;
1112 if (tx) *tx= m_matrix.tx;
1113 if (ty) *ty= m_matrix.ty;
1114 }
1115
1116 // makes this the inverse matrix
1117 void wxMacCoreGraphicsMatrixData::Invert()
1118 {
1119 m_matrix = CGAffineTransformInvert( m_matrix );
1120 }
1121
1122 // returns true if the elements of the transformation matrix are equal ?
1123 bool wxMacCoreGraphicsMatrixData::IsEqual( const wxGraphicsMatrixData* t) const
1124 {
1125 return CGAffineTransformEqualToTransform(m_matrix, *((CGAffineTransform*) t->GetNativeMatrix()));
1126 }
1127
1128 // return true if this is the identity matrix
1129 bool wxMacCoreGraphicsMatrixData::IsIdentity() const
1130 {
1131 return ( m_matrix.a == 1 && m_matrix.d == 1 &&
1132 m_matrix.b == 0 && m_matrix.d == 0 && m_matrix.tx == 0 && m_matrix.ty == 0);
1133 }
1134
1135 //
1136 // transformation
1137 //
1138
1139 // add the translation to this matrix
1140 void wxMacCoreGraphicsMatrixData::Translate( wxDouble dx , wxDouble dy )
1141 {
1142 m_matrix = CGAffineTransformTranslate( m_matrix, (CGFloat) dx, (CGFloat) dy);
1143 }
1144
1145 // add the scale to this matrix
1146 void wxMacCoreGraphicsMatrixData::Scale( wxDouble xScale , wxDouble yScale )
1147 {
1148 m_matrix = CGAffineTransformScale( m_matrix, (CGFloat) xScale, (CGFloat) yScale);
1149 }
1150
1151 // add the rotation to this matrix (radians)
1152 void wxMacCoreGraphicsMatrixData::Rotate( wxDouble angle )
1153 {
1154 m_matrix = CGAffineTransformRotate( m_matrix, (CGFloat) angle);
1155 }
1156
1157 //
1158 // apply the transforms
1159 //
1160
1161 // applies that matrix to the point
1162 void wxMacCoreGraphicsMatrixData::TransformPoint( wxDouble *x, wxDouble *y ) const
1163 {
1164 CGPoint pt = CGPointApplyAffineTransform( CGPointMake((CGFloat) *x,(CGFloat) *y), m_matrix);
1165
1166 *x = pt.x;
1167 *y = pt.y;
1168 }
1169
1170 // applies the matrix except for translations
1171 void wxMacCoreGraphicsMatrixData::TransformDistance( wxDouble *dx, wxDouble *dy ) const
1172 {
1173 CGSize sz = CGSizeApplyAffineTransform( CGSizeMake((CGFloat) *dx,(CGFloat) *dy) , m_matrix );
1174 *dx = sz.width;
1175 *dy = sz.height;
1176 }
1177
1178 // returns the native representation
1179 void * wxMacCoreGraphicsMatrixData::GetNativeMatrix() const
1180 {
1181 return (void*) &m_matrix;
1182 }
1183
1184 //
1185 // Graphics Path
1186 //
1187
1188 //-----------------------------------------------------------------------------
1189 // wxMacCoreGraphicsPath declaration
1190 //-----------------------------------------------------------------------------
1191
1192 class WXDLLEXPORT wxMacCoreGraphicsPathData : public wxGraphicsPathData
1193 {
1194 public :
1195 wxMacCoreGraphicsPathData( wxGraphicsRenderer* renderer, CGMutablePathRef path = NULL);
1196
1197 ~wxMacCoreGraphicsPathData();
1198
1199 virtual wxGraphicsObjectRefData *Clone() const;
1200
1201 // begins a new subpath at (x,y)
1202 virtual void MoveToPoint( wxDouble x, wxDouble y );
1203
1204 // adds a straight line from the current point to (x,y)
1205 virtual void AddLineToPoint( wxDouble x, wxDouble y );
1206
1207 // adds a cubic Bezier curve from the current point, using two control points and an end point
1208 virtual void AddCurveToPoint( wxDouble cx1, wxDouble cy1, wxDouble cx2, wxDouble cy2, wxDouble x, wxDouble y );
1209
1210 // closes the current sub-path
1211 virtual void CloseSubpath();
1212
1213 // gets the last point of the current path, (0,0) if not yet set
1214 virtual void GetCurrentPoint( wxDouble* x, wxDouble* y) const;
1215
1216 // adds an arc of a circle centering at (x,y) with radius (r) from startAngle to endAngle
1217 virtual void AddArc( wxDouble x, wxDouble y, wxDouble r, wxDouble startAngle, wxDouble endAngle, bool clockwise );
1218
1219 //
1220 // These are convenience functions which - if not available natively will be assembled
1221 // using the primitives from above
1222 //
1223
1224 // adds a quadratic Bezier curve from the current point, using a control point and an end point
1225 virtual void AddQuadCurveToPoint( wxDouble cx, wxDouble cy, wxDouble x, wxDouble y );
1226
1227 // appends a rectangle as a new closed subpath
1228 virtual void AddRectangle( wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1229
1230 // appends a circle as a new closed subpath
1231 virtual void AddCircle( wxDouble x, wxDouble y, wxDouble r );
1232
1233 // appends an ellipsis as a new closed subpath fitting the passed rectangle
1234 virtual void AddEllipse( wxDouble x, wxDouble y, wxDouble w, wxDouble h);
1235
1236 // 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)
1237 virtual void AddArcToPoint( wxDouble x1, wxDouble y1 , wxDouble x2, wxDouble y2, wxDouble r );
1238
1239 // adds another path
1240 virtual void AddPath( const wxGraphicsPathData* path );
1241
1242 // returns the native path
1243 virtual void * GetNativePath() const { return m_path; }
1244
1245 // give the native path returned by GetNativePath() back (there might be some deallocations necessary)
1246 virtual void UnGetNativePath(void *WXUNUSED(p)) const {}
1247
1248 // transforms each point of this path by the matrix
1249 virtual void Transform( const wxGraphicsMatrixData* matrix );
1250
1251 // gets the bounding box enclosing all points (possibly including control points)
1252 virtual void GetBox(wxDouble *x, wxDouble *y, wxDouble *w, wxDouble *h) const;
1253
1254 virtual bool Contains( wxDouble x, wxDouble y, wxPolygonFillMode fillStyle = wxODDEVEN_RULE) const;
1255 private :
1256 CGMutablePathRef m_path;
1257 };
1258
1259 //-----------------------------------------------------------------------------
1260 // wxMacCoreGraphicsPath implementation
1261 //-----------------------------------------------------------------------------
1262
1263 wxMacCoreGraphicsPathData::wxMacCoreGraphicsPathData( wxGraphicsRenderer* renderer, CGMutablePathRef path) : wxGraphicsPathData(renderer)
1264 {
1265 if ( path )
1266 m_path = path;
1267 else
1268 m_path = CGPathCreateMutable();
1269 }
1270
1271 wxMacCoreGraphicsPathData::~wxMacCoreGraphicsPathData()
1272 {
1273 CGPathRelease( m_path );
1274 }
1275
1276 wxGraphicsObjectRefData* wxMacCoreGraphicsPathData::Clone() const
1277 {
1278 wxMacCoreGraphicsPathData* clone = new wxMacCoreGraphicsPathData(GetRenderer(),CGPathCreateMutableCopy(m_path));
1279 return clone ;
1280 }
1281
1282
1283 // opens (starts) a new subpath
1284 void wxMacCoreGraphicsPathData::MoveToPoint( wxDouble x1 , wxDouble y1 )
1285 {
1286 CGPathMoveToPoint( m_path , NULL , (CGFloat) x1 , (CGFloat) y1 );
1287 }
1288
1289 void wxMacCoreGraphicsPathData::AddLineToPoint( wxDouble x1 , wxDouble y1 )
1290 {
1291 CGPathAddLineToPoint( m_path , NULL , (CGFloat) x1 , (CGFloat) y1 );
1292 }
1293
1294 void wxMacCoreGraphicsPathData::AddCurveToPoint( wxDouble cx1, wxDouble cy1, wxDouble cx2, wxDouble cy2, wxDouble x, wxDouble y )
1295 {
1296 CGPathAddCurveToPoint( m_path , NULL , (CGFloat) cx1 , (CGFloat) cy1 , (CGFloat) cx2, (CGFloat) cy2, (CGFloat) x , (CGFloat) y );
1297 }
1298
1299 void wxMacCoreGraphicsPathData::AddQuadCurveToPoint( wxDouble cx1, wxDouble cy1, wxDouble x, wxDouble y )
1300 {
1301 CGPathAddQuadCurveToPoint( m_path , NULL , (CGFloat) cx1 , (CGFloat) cy1 , (CGFloat) x , (CGFloat) y );
1302 }
1303
1304 void wxMacCoreGraphicsPathData::AddRectangle( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1305 {
1306 CGRect cgRect = { { (CGFloat) x , (CGFloat) y } , { (CGFloat) w , (CGFloat) h } };
1307 CGPathAddRect( m_path , NULL , cgRect );
1308 }
1309
1310 void wxMacCoreGraphicsPathData::AddCircle( wxDouble x, wxDouble y , wxDouble r )
1311 {
1312 CGPathAddEllipseInRect( m_path, NULL, CGRectMake(x-r,y-r,2*r,2*r));
1313 }
1314
1315 void wxMacCoreGraphicsPathData::AddEllipse( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1316 {
1317 CGPathAddEllipseInRect( m_path, NULL, CGRectMake(x,y,w,h));
1318 }
1319
1320 // adds an arc of a circle centering at (x,y) with radius (r) from startAngle to endAngle
1321 void wxMacCoreGraphicsPathData::AddArc( wxDouble x, wxDouble y, wxDouble r, wxDouble startAngle, wxDouble endAngle, bool clockwise )
1322 {
1323 // inverse direction as we the 'normal' state is a y axis pointing down, ie mirrored to the standard core graphics setup
1324 CGPathAddArc( m_path, NULL , (CGFloat) x, (CGFloat) y, (CGFloat) r, (CGFloat) startAngle, (CGFloat) endAngle, !clockwise);
1325 }
1326
1327 void wxMacCoreGraphicsPathData::AddArcToPoint( wxDouble x1, wxDouble y1 , wxDouble x2, wxDouble y2, wxDouble r )
1328 {
1329 CGPathAddArcToPoint( m_path, NULL , (CGFloat) x1, (CGFloat) y1, (CGFloat) x2, (CGFloat) y2, (CGFloat) r);
1330 }
1331
1332 void wxMacCoreGraphicsPathData::AddPath( const wxGraphicsPathData* path )
1333 {
1334 CGPathAddPath( m_path , NULL, (CGPathRef) path->GetNativePath() );
1335 }
1336
1337 // closes the current subpath
1338 void wxMacCoreGraphicsPathData::CloseSubpath()
1339 {
1340 CGPathCloseSubpath( m_path );
1341 }
1342
1343 // gets the last point of the current path, (0,0) if not yet set
1344 void wxMacCoreGraphicsPathData::GetCurrentPoint( wxDouble* x, wxDouble* y) const
1345 {
1346 CGPoint p = CGPathGetCurrentPoint( m_path );
1347 *x = p.x;
1348 *y = p.y;
1349 }
1350
1351 // transforms each point of this path by the matrix
1352 void wxMacCoreGraphicsPathData::Transform( const wxGraphicsMatrixData* matrix )
1353 {
1354 CGMutablePathRef p = CGPathCreateMutable() ;
1355 CGPathAddPath( p, (CGAffineTransform*) matrix->GetNativeMatrix() , m_path );
1356 CGPathRelease( m_path );
1357 m_path = p;
1358 }
1359
1360 // gets the bounding box enclosing all points (possibly including control points)
1361 void wxMacCoreGraphicsPathData::GetBox(wxDouble *x, wxDouble *y, wxDouble *w, wxDouble *h) const
1362 {
1363 CGRect bounds = CGPathGetBoundingBox( m_path ) ;
1364 *x = bounds.origin.x;
1365 *y = bounds.origin.y;
1366 *w = bounds.size.width;
1367 *h = bounds.size.height;
1368 }
1369
1370 bool wxMacCoreGraphicsPathData::Contains( wxDouble x, wxDouble y, wxPolygonFillMode fillStyle) const
1371 {
1372 return CGPathContainsPoint( m_path, NULL, CGPointMake((CGFloat) x,(CGFloat) y), fillStyle == wxODDEVEN_RULE );
1373 }
1374
1375 //
1376 // Graphics Context
1377 //
1378
1379 //-----------------------------------------------------------------------------
1380 // wxMacCoreGraphicsContext declaration
1381 //-----------------------------------------------------------------------------
1382
1383 class WXDLLEXPORT wxMacCoreGraphicsContext : public wxGraphicsContext
1384 {
1385 public:
1386 wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, CGContextRef cgcontext, wxDouble width = 0, wxDouble height = 0 );
1387
1388 #if wxOSX_USE_CARBON
1389 wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, WindowRef window );
1390 #endif
1391
1392 wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, wxWindow* window );
1393
1394 wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer);
1395
1396 ~wxMacCoreGraphicsContext();
1397
1398 void Init();
1399
1400 virtual void StartPage( wxDouble width, wxDouble height );
1401
1402 virtual void EndPage();
1403
1404 virtual void Flush();
1405
1406 // push the current state of the context, ie the transformation matrix on a stack
1407 virtual void PushState();
1408
1409 // pops a stored state from the stack
1410 virtual void PopState();
1411
1412 // clips drawings to the region
1413 virtual void Clip( const wxRegion &region );
1414
1415 // clips drawings to the rect
1416 virtual void Clip( wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1417
1418 // resets the clipping to original extent
1419 virtual void ResetClip();
1420
1421 virtual void * GetNativeContext();
1422
1423 virtual bool SetAntialiasMode(wxAntialiasMode antialias);
1424
1425 virtual bool SetInterpolationQuality(wxInterpolationQuality interpolation);
1426
1427 virtual bool SetCompositionMode(wxCompositionMode op);
1428
1429 virtual void BeginLayer(wxDouble opacity);
1430
1431 virtual void EndLayer();
1432
1433 //
1434 // transformation
1435 //
1436
1437 // translate
1438 virtual void Translate( wxDouble dx , wxDouble dy );
1439
1440 // scale
1441 virtual void Scale( wxDouble xScale , wxDouble yScale );
1442
1443 // rotate (radians)
1444 virtual void Rotate( wxDouble angle );
1445
1446 // concatenates this transform with the current transform of this context
1447 virtual void ConcatTransform( const wxGraphicsMatrix& matrix );
1448
1449 // sets the transform of this context
1450 virtual void SetTransform( const wxGraphicsMatrix& matrix );
1451
1452 // gets the matrix of this context
1453 virtual wxGraphicsMatrix GetTransform() const;
1454 //
1455 // setting the paint
1456 //
1457
1458 // strokes along a path with the current pen
1459 virtual void StrokePath( const wxGraphicsPath &path );
1460
1461 // fills a path with the current brush
1462 virtual void FillPath( const wxGraphicsPath &path, wxPolygonFillMode fillStyle = wxODDEVEN_RULE );
1463
1464 // draws a path by first filling and then stroking
1465 virtual void DrawPath( const wxGraphicsPath &path, wxPolygonFillMode fillStyle = wxODDEVEN_RULE );
1466
1467 virtual bool ShouldOffset() const
1468 {
1469 if ( !m_enableOffset )
1470 return false;
1471
1472 int penwidth = 0 ;
1473 if ( !m_pen.IsNull() )
1474 {
1475 penwidth = (int)((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->GetWidth();
1476 if ( penwidth == 0 )
1477 penwidth = 1;
1478 }
1479 return ( penwidth % 2 ) == 1;
1480 }
1481 //
1482 // text
1483 //
1484
1485 virtual void GetTextExtent( const wxString &text, wxDouble *width, wxDouble *height,
1486 wxDouble *descent, wxDouble *externalLeading ) const;
1487
1488 virtual void GetPartialTextExtents(const wxString& text, wxArrayDouble& widths) const;
1489
1490 //
1491 // image support
1492 //
1493
1494 virtual void DrawBitmap( const wxBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1495
1496 virtual void DrawBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1497
1498 virtual void DrawIcon( const wxIcon &icon, wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1499
1500 // fast convenience methods
1501
1502
1503 virtual void DrawRectangleX( wxDouble x, wxDouble y, wxDouble w, wxDouble h );
1504
1505 void SetNativeContext( CGContextRef cg );
1506
1507 wxDECLARE_NO_COPY_CLASS(wxMacCoreGraphicsContext);
1508
1509 private:
1510 bool EnsureIsValid();
1511 void CheckInvariants() const;
1512
1513 virtual void DoDrawText( const wxString &str, wxDouble x, wxDouble y );
1514 virtual void DoDrawRotatedText( const wxString &str, wxDouble x, wxDouble y, wxDouble angle );
1515
1516 CGContextRef m_cgContext;
1517 #if wxOSX_USE_CARBON
1518 WindowRef m_windowRef;
1519 #else
1520 WXWidget m_view;
1521 #endif
1522 bool m_contextSynthesized;
1523 CGAffineTransform m_windowTransform;
1524 bool m_invisible;
1525
1526 #if wxOSX_USE_COCOA_OR_CARBON
1527 wxCFRef<HIShapeRef> m_clipRgn;
1528 #endif
1529 };
1530
1531 //-----------------------------------------------------------------------------
1532 // device context implementation
1533 //
1534 // more and more of the dc functionality should be implemented by calling
1535 // the appropricate wxMacCoreGraphicsContext, but we will have to do that step by step
1536 // also coordinate conversions should be moved to native matrix ops
1537 //-----------------------------------------------------------------------------
1538
1539 // we always stock two context states, one at entry, to be able to preserve the
1540 // state we were called with, the other one after changing to HI Graphics orientation
1541 // (this one is used for getting back clippings etc)
1542
1543 //-----------------------------------------------------------------------------
1544 // wxMacCoreGraphicsContext implementation
1545 //-----------------------------------------------------------------------------
1546
1547 class wxQuartzOffsetHelper
1548 {
1549 public :
1550 wxQuartzOffsetHelper( CGContextRef cg , bool offset )
1551 {
1552 m_cg = cg;
1553 m_offset = offset;
1554 if ( m_offset )
1555 {
1556 m_userOffset = CGContextConvertSizeToUserSpace( m_cg, CGSizeMake( 0.5 , 0.5 ) );
1557 CGContextTranslateCTM( m_cg, m_userOffset.width , m_userOffset.height );
1558 }
1559 else
1560 {
1561 m_userOffset = CGSizeMake(0.0, 0.0);
1562 }
1563
1564 }
1565 ~wxQuartzOffsetHelper( )
1566 {
1567 if ( m_offset )
1568 CGContextTranslateCTM( m_cg, -m_userOffset.width , -m_userOffset.height );
1569 }
1570 public :
1571 CGSize m_userOffset;
1572 CGContextRef m_cg;
1573 bool m_offset;
1574 } ;
1575
1576 void wxMacCoreGraphicsContext::Init()
1577 {
1578 m_cgContext = NULL;
1579 m_contextSynthesized = false;
1580 m_width = 0;
1581 m_height = 0;
1582 #if wxOSX_USE_CARBON
1583 m_windowRef = NULL;
1584 #endif
1585 #if wxOSX_USE_COCOA_OR_IPHONE
1586 m_view = NULL;
1587 #endif
1588 m_invisible = false;
1589 m_antialias = wxANTIALIAS_DEFAULT;
1590 m_interpolation = wxINTERPOLATION_DEFAULT;
1591 }
1592
1593 wxMacCoreGraphicsContext::wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, CGContextRef cgcontext, wxDouble width, wxDouble height ) : wxGraphicsContext(renderer)
1594 {
1595 Init();
1596 SetNativeContext(cgcontext);
1597 m_width = width;
1598 m_height = height;
1599 }
1600
1601 #if wxOSX_USE_CARBON
1602 wxMacCoreGraphicsContext::wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, WindowRef window ): wxGraphicsContext(renderer)
1603 {
1604 Init();
1605 m_windowRef = window;
1606 m_enableOffset = true;
1607 }
1608 #endif
1609
1610 wxMacCoreGraphicsContext::wxMacCoreGraphicsContext( wxGraphicsRenderer* renderer, wxWindow* window ): wxGraphicsContext(renderer)
1611 {
1612 Init();
1613
1614 m_enableOffset = true;
1615 wxSize sz = window->GetSize();
1616 m_width = sz.x;
1617 m_height = sz.y;
1618
1619 #if wxOSX_USE_COCOA_OR_IPHONE
1620 m_view = window->GetHandle();
1621
1622 #if wxOSX_USE_COCOA
1623 if ( ! window->GetPeer()->IsFlipped() )
1624 {
1625 m_windowTransform = CGAffineTransformMakeTranslation( 0 , m_height );
1626 m_windowTransform = CGAffineTransformScale( m_windowTransform , 1 , -1 );
1627 }
1628 else
1629 #endif
1630 {
1631 m_windowTransform = CGAffineTransformIdentity;
1632 }
1633 #else
1634 int originX , originY;
1635 originX = originY = 0;
1636 Rect bounds = { 0,0,0,0 };
1637 m_windowRef = (WindowRef) window->MacGetTopLevelWindowRef();
1638 window->MacWindowToRootWindow( &originX , &originY );
1639 GetWindowBounds( m_windowRef, kWindowContentRgn, &bounds );
1640 m_windowTransform = CGAffineTransformMakeTranslation( 0 , bounds.bottom - bounds.top );
1641 m_windowTransform = CGAffineTransformScale( m_windowTransform , 1 , -1 );
1642 m_windowTransform = CGAffineTransformTranslate( m_windowTransform, originX, originY ) ;
1643 #endif
1644 }
1645
1646 wxMacCoreGraphicsContext::wxMacCoreGraphicsContext(wxGraphicsRenderer* renderer) : wxGraphicsContext(renderer)
1647 {
1648 Init();
1649 }
1650
1651 wxMacCoreGraphicsContext::~wxMacCoreGraphicsContext()
1652 {
1653 SetNativeContext(NULL);
1654 }
1655
1656
1657 void wxMacCoreGraphicsContext::CheckInvariants() const
1658 {
1659 // check invariants here for debugging ...
1660 }
1661
1662
1663
1664 void wxMacCoreGraphicsContext::StartPage( wxDouble width, wxDouble height )
1665 {
1666 CGRect r;
1667 if ( width != 0 && height != 0)
1668 r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) width , (CGFloat) height );
1669 else
1670 r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) m_width , (CGFloat) m_height );
1671
1672 CGContextBeginPage(m_cgContext, &r );
1673 // CGContextTranslateCTM( m_cgContext , 0 , height == 0 ? m_height : height );
1674 // CGContextScaleCTM( m_cgContext , 1 , -1 );
1675 }
1676
1677 void wxMacCoreGraphicsContext::EndPage()
1678 {
1679 CGContextEndPage(m_cgContext);
1680 }
1681
1682 void wxMacCoreGraphicsContext::Flush()
1683 {
1684 CGContextFlush(m_cgContext);
1685 }
1686
1687 bool wxMacCoreGraphicsContext::EnsureIsValid()
1688 {
1689 CheckInvariants();
1690
1691 if ( !m_cgContext )
1692 {
1693 if (m_invisible)
1694 return false;
1695
1696 #if wxOSX_USE_COCOA
1697 if ( wxOSXLockFocus(m_view) )
1698 {
1699 m_cgContext = wxOSXGetContextFromCurrentContext();
1700 wxASSERT_MSG( m_cgContext != NULL, wxT("Unable to retrieve drawing context from View"));
1701 }
1702 else
1703 {
1704 m_invisible = true;
1705 }
1706 #endif
1707 #if wxOSX_USE_IPHONE
1708 m_cgContext = wxOSXGetContextFromCurrentContext();
1709 if ( m_cgContext == NULL )
1710 {
1711 m_invisible = true;
1712 }
1713 #endif
1714 #if wxOSX_USE_CARBON
1715 OSStatus status = QDBeginCGContext( GetWindowPort( m_windowRef ) , &m_cgContext );
1716 if ( status != noErr )
1717 {
1718 wxFAIL_MSG("Cannot nest wxDCs on the same window");
1719 }
1720 #endif
1721 if ( m_cgContext )
1722 {
1723 CGContextSaveGState( m_cgContext );
1724 #if wxOSX_USE_COCOA_OR_CARBON
1725 if ( m_clipRgn.get() )
1726 {
1727 wxCFRef<HIMutableShapeRef> hishape( HIShapeCreateMutableCopy( m_clipRgn ) );
1728 // if the shape is empty, HIShapeReplacePathInCGContext doesn't work
1729 if ( HIShapeIsEmpty(hishape))
1730 {
1731 CGRect empty = CGRectMake( 0,0,0,0 );
1732 CGContextClipToRect( m_cgContext, empty );
1733 }
1734 else
1735 {
1736 HIShapeReplacePathInCGContext( hishape, m_cgContext );
1737 CGContextClip( m_cgContext );
1738 }
1739 }
1740 #endif
1741 CGContextConcatCTM( m_cgContext, m_windowTransform );
1742 CGContextSetTextMatrix( m_cgContext, CGAffineTransformIdentity );
1743 m_contextSynthesized = true;
1744 CGContextSaveGState( m_cgContext );
1745
1746 #if 0 // turn on for debugging of clientdc
1747 static float color = 0.5 ;
1748 static int channel = 0 ;
1749 CGRect bounds = CGRectMake(-1000,-1000,2000,2000);
1750 CGContextSetRGBFillColor( m_cgContext, channel == 0 ? color : 0.5 ,
1751 channel == 1 ? color : 0.5 , channel == 2 ? color : 0.5 , 1 );
1752 CGContextFillRect( m_cgContext, bounds );
1753 color += 0.1 ;
1754 if ( color > 0.9 )
1755 {
1756 color = 0.5 ;
1757 channel++ ;
1758 if ( channel == 3 )
1759 channel = 0 ;
1760 }
1761 #endif
1762 }
1763 }
1764 CheckInvariants();
1765
1766 return m_cgContext != NULL;
1767 }
1768
1769 bool wxMacCoreGraphicsContext::SetAntialiasMode(wxAntialiasMode antialias)
1770 {
1771 if (!EnsureIsValid())
1772 return true;
1773
1774 if (m_antialias == antialias)
1775 return true;
1776
1777 m_antialias = antialias;
1778
1779 bool antialiasMode;
1780 switch (antialias)
1781 {
1782 case wxANTIALIAS_DEFAULT:
1783 antialiasMode = true;
1784 break;
1785 case wxANTIALIAS_NONE:
1786 antialiasMode = false;
1787 break;
1788 default:
1789 return false;
1790 }
1791 CGContextSetShouldAntialias(m_cgContext, antialiasMode);
1792 CheckInvariants();
1793 return true;
1794 }
1795
1796 bool wxMacCoreGraphicsContext::SetInterpolationQuality(wxInterpolationQuality interpolation)
1797 {
1798 if (!EnsureIsValid())
1799 return true;
1800
1801 if (m_interpolation == interpolation)
1802 return true;
1803
1804 m_interpolation = interpolation;
1805 CGInterpolationQuality quality;
1806
1807 switch (interpolation)
1808 {
1809 case wxINTERPOLATION_DEFAULT:
1810 quality = kCGInterpolationDefault;
1811 break;
1812 case wxINTERPOLATION_NONE:
1813 quality = kCGInterpolationNone;
1814 break;
1815 case wxINTERPOLATION_FAST:
1816 quality = kCGInterpolationLow;
1817 break;
1818 case wxINTERPOLATION_GOOD:
1819 #if wxOSX_USE_COCOA_OR_CARBON
1820 quality = UMAGetSystemVersion() < 0x1060 ? kCGInterpolationHigh : (CGInterpolationQuality) 4 /*kCGInterpolationMedium only on 10.6*/;
1821 #else
1822 quality = kCGInterpolationMedium;
1823 #endif
1824 break;
1825 case wxINTERPOLATION_BEST:
1826 quality = kCGInterpolationHigh;
1827 break;
1828 default:
1829 return false;
1830 }
1831 CGContextSetInterpolationQuality(m_cgContext, quality);
1832 CheckInvariants();
1833 return true;
1834 }
1835
1836 bool wxMacCoreGraphicsContext::SetCompositionMode(wxCompositionMode op)
1837 {
1838 if (!EnsureIsValid())
1839 return true;
1840
1841 if ( m_composition == op )
1842 return true;
1843
1844 m_composition = op;
1845
1846 if (m_composition == wxCOMPOSITION_DEST)
1847 return true;
1848
1849 #if wxOSX_USE_COCOA_OR_CARBON
1850 if ( UMAGetSystemVersion() < 0x1060 )
1851 {
1852 CGCompositeOperation cop = kCGCompositeOperationSourceOver;
1853 CGBlendMode mode = kCGBlendModeNormal;
1854 switch( op )
1855 {
1856 case wxCOMPOSITION_CLEAR:
1857 cop = kCGCompositeOperationClear;
1858 break;
1859 case wxCOMPOSITION_SOURCE:
1860 cop = kCGCompositeOperationCopy;
1861 break;
1862 case wxCOMPOSITION_OVER:
1863 mode = kCGBlendModeNormal;
1864 break;
1865 case wxCOMPOSITION_IN:
1866 cop = kCGCompositeOperationSourceIn;
1867 break;
1868 case wxCOMPOSITION_OUT:
1869 cop = kCGCompositeOperationSourceOut;
1870 break;
1871 case wxCOMPOSITION_ATOP:
1872 cop = kCGCompositeOperationSourceAtop;
1873 break;
1874 case wxCOMPOSITION_DEST_OVER:
1875 cop = kCGCompositeOperationDestinationOver;
1876 break;
1877 case wxCOMPOSITION_DEST_IN:
1878 cop = kCGCompositeOperationDestinationIn;
1879 break;
1880 case wxCOMPOSITION_DEST_OUT:
1881 cop = kCGCompositeOperationDestinationOut;
1882 break;
1883 case wxCOMPOSITION_DEST_ATOP:
1884 cop = kCGCompositeOperationDestinationAtop;
1885 break;
1886 case wxCOMPOSITION_XOR:
1887 cop = kCGCompositeOperationXOR;
1888 break;
1889 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1890 case wxCOMPOSITION_ADD:
1891 mode = kCGBlendModePlusLighter ;
1892 break;
1893 #endif
1894 default:
1895 return false;
1896 }
1897 if ( cop != kCGCompositeOperationSourceOver )
1898 CGContextSetCompositeOperation(m_cgContext, cop);
1899 else
1900 CGContextSetBlendMode(m_cgContext, mode);
1901 }
1902 #endif
1903 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1904 else
1905 {
1906 CGBlendMode mode = kCGBlendModeNormal;
1907 switch( op )
1908 {
1909 case wxCOMPOSITION_CLEAR:
1910 mode = kCGBlendModeClear;
1911 break;
1912 case wxCOMPOSITION_SOURCE:
1913 mode = kCGBlendModeCopy;
1914 break;
1915 case wxCOMPOSITION_OVER:
1916 mode = kCGBlendModeNormal;
1917 break;
1918 case wxCOMPOSITION_IN:
1919 mode = kCGBlendModeSourceIn;
1920 break;
1921 case wxCOMPOSITION_OUT:
1922 mode = kCGBlendModeSourceOut;
1923 break;
1924 case wxCOMPOSITION_ATOP:
1925 mode = kCGBlendModeSourceAtop;
1926 break;
1927 case wxCOMPOSITION_DEST_OVER:
1928 mode = kCGBlendModeDestinationOver;
1929 break;
1930 case wxCOMPOSITION_DEST_IN:
1931 mode = kCGBlendModeDestinationIn;
1932 break;
1933 case wxCOMPOSITION_DEST_OUT:
1934 mode = kCGBlendModeDestinationOut;
1935 break;
1936 case wxCOMPOSITION_DEST_ATOP:
1937 mode = kCGBlendModeDestinationAtop;
1938 break;
1939 case wxCOMPOSITION_XOR:
1940 mode = kCGBlendModeXOR;
1941 break;
1942
1943 case wxCOMPOSITION_ADD:
1944 mode = kCGBlendModePlusLighter ;
1945 break;
1946 default:
1947 return false;
1948 }
1949 CGContextSetBlendMode(m_cgContext, mode);
1950 }
1951 #endif
1952 CheckInvariants();
1953 return true;
1954 }
1955
1956 void wxMacCoreGraphicsContext::BeginLayer(wxDouble opacity)
1957 {
1958 CheckInvariants();
1959 CGContextSaveGState(m_cgContext);
1960 CGContextSetAlpha(m_cgContext, (CGFloat) opacity);
1961 CGContextBeginTransparencyLayer(m_cgContext, 0);
1962 CheckInvariants();
1963 }
1964
1965 void wxMacCoreGraphicsContext::EndLayer()
1966 {
1967 CheckInvariants();
1968 CGContextEndTransparencyLayer(m_cgContext);
1969 CGContextRestoreGState(m_cgContext);
1970 CheckInvariants();
1971 }
1972
1973 void wxMacCoreGraphicsContext::Clip( const wxRegion &region )
1974 {
1975 CheckInvariants();
1976 #if wxOSX_USE_COCOA_OR_CARBON
1977 if( m_cgContext )
1978 {
1979 wxCFRef<HIShapeRef> shape = wxCFRefFromGet(region.GetWXHRGN());
1980 // if the shape is empty, HIShapeReplacePathInCGContext doesn't work
1981 if ( HIShapeIsEmpty(shape))
1982 {
1983 CGRect empty = CGRectMake( 0,0,0,0 );
1984 CGContextClipToRect( m_cgContext, empty );
1985 }
1986 else
1987 {
1988 HIShapeReplacePathInCGContext( shape, m_cgContext );
1989 CGContextClip( m_cgContext );
1990 }
1991 }
1992 else
1993 {
1994 // this offsetting to device coords is not really correct, but since we cannot apply affine transforms
1995 // to regions we try at least to have correct translations
1996 HIMutableShapeRef mutableShape = HIShapeCreateMutableCopy( region.GetWXHRGN() );
1997
1998 CGPoint transformedOrigin = CGPointApplyAffineTransform( CGPointZero, m_windowTransform );
1999 HIShapeOffset( mutableShape, transformedOrigin.x, transformedOrigin.y );
2000 m_clipRgn.reset(mutableShape);
2001 }
2002 #else
2003 // allow usage as measuring context
2004 // wxASSERT_MSG( m_cgContext != NULL, "Needs a valid context for clipping" );
2005 #endif
2006 CheckInvariants();
2007 }
2008
2009 // clips drawings to the rect
2010 void wxMacCoreGraphicsContext::Clip( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2011 {
2012 CheckInvariants();
2013 CGRect r = CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h );
2014 if ( m_cgContext )
2015 {
2016 CGContextClipToRect( m_cgContext, r );
2017 }
2018 else
2019 {
2020 #if wxOSX_USE_COCOA_OR_CARBON
2021 // the clipping itself must be stored as device coordinates, otherwise
2022 // we cannot apply it back correctly
2023 r.origin= CGPointApplyAffineTransform( r.origin, m_windowTransform );
2024 r.size= CGSizeApplyAffineTransform(r.size, m_windowTransform);
2025 m_clipRgn.reset(HIShapeCreateWithRect(&r));
2026 #else
2027 // allow usage as measuring context
2028 // wxFAIL_MSG( "Needs a valid context for clipping" );
2029 #endif
2030 }
2031 CheckInvariants();
2032 }
2033
2034 // resets the clipping to original extent
2035 void wxMacCoreGraphicsContext::ResetClip()
2036 {
2037 if ( m_cgContext )
2038 {
2039 // there is no way for clearing the clip, we can only revert to the stored
2040 // state, but then we have to make sure everything else is NOT restored
2041 CGAffineTransform transform = CGContextGetCTM( m_cgContext );
2042 CGContextRestoreGState( m_cgContext );
2043 CGContextSaveGState( m_cgContext );
2044 CGAffineTransform transformNew = CGContextGetCTM( m_cgContext );
2045 transformNew = CGAffineTransformInvert( transformNew ) ;
2046 CGContextConcatCTM( m_cgContext, transformNew);
2047 CGContextConcatCTM( m_cgContext, transform);
2048 }
2049 else
2050 {
2051 #if wxOSX_USE_COCOA_OR_CARBON
2052 m_clipRgn.reset();
2053 #else
2054 // allow usage as measuring context
2055 // wxFAIL_MSG( "Needs a valid context for clipping" );
2056 #endif
2057 }
2058 CheckInvariants();
2059 }
2060
2061 void wxMacCoreGraphicsContext::StrokePath( const wxGraphicsPath &path )
2062 {
2063 if ( m_pen.IsNull() )
2064 return ;
2065
2066 if (!EnsureIsValid())
2067 return;
2068
2069 if (m_composition == wxCOMPOSITION_DEST)
2070 return;
2071
2072 wxQuartzOffsetHelper helper( m_cgContext , ShouldOffset() );
2073
2074 ((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->Apply(this);
2075 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
2076 CGContextStrokePath( m_cgContext );
2077
2078 CheckInvariants();
2079 }
2080
2081 void wxMacCoreGraphicsContext::DrawPath( const wxGraphicsPath &path , wxPolygonFillMode fillStyle )
2082 {
2083 if (!EnsureIsValid())
2084 return;
2085
2086 if (m_composition == wxCOMPOSITION_DEST)
2087 return;
2088
2089 if ( !m_brush.IsNull() && ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
2090 {
2091 // when using shading, we cannot draw pen and brush at the same time
2092 // revert to the base implementation of first filling and then stroking
2093 wxGraphicsContext::DrawPath( path, fillStyle );
2094 return;
2095 }
2096
2097 CGPathDrawingMode mode = kCGPathFill ;
2098 if ( m_brush.IsNull() )
2099 {
2100 if ( m_pen.IsNull() )
2101 return;
2102 else
2103 mode = kCGPathStroke;
2104 }
2105 else
2106 {
2107 if ( m_pen.IsNull() )
2108 {
2109 if ( fillStyle == wxODDEVEN_RULE )
2110 mode = kCGPathEOFill;
2111 else
2112 mode = kCGPathFill;
2113 }
2114 else
2115 {
2116 if ( fillStyle == wxODDEVEN_RULE )
2117 mode = kCGPathEOFillStroke;
2118 else
2119 mode = kCGPathFillStroke;
2120 }
2121 }
2122
2123 if ( !m_brush.IsNull() )
2124 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
2125 if ( !m_pen.IsNull() )
2126 ((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->Apply(this);
2127
2128 wxQuartzOffsetHelper helper( m_cgContext , ShouldOffset() );
2129
2130 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
2131 CGContextDrawPath( m_cgContext , mode );
2132
2133 CheckInvariants();
2134 }
2135
2136 void wxMacCoreGraphicsContext::FillPath( const wxGraphicsPath &path , wxPolygonFillMode fillStyle )
2137 {
2138 if ( m_brush.IsNull() )
2139 return;
2140
2141 if (!EnsureIsValid())
2142 return;
2143
2144 if (m_composition == wxCOMPOSITION_DEST)
2145 return;
2146
2147 if ( ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
2148 {
2149 CGContextSaveGState( m_cgContext );
2150 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
2151 CGContextClip( m_cgContext );
2152 CGContextDrawShading( m_cgContext, ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->GetShading() );
2153 CGContextRestoreGState( m_cgContext);
2154 }
2155 else
2156 {
2157 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
2158 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
2159 if ( fillStyle == wxODDEVEN_RULE )
2160 CGContextEOFillPath( m_cgContext );
2161 else
2162 CGContextFillPath( m_cgContext );
2163 }
2164
2165 CheckInvariants();
2166 }
2167
2168 void wxMacCoreGraphicsContext::SetNativeContext( CGContextRef cg )
2169 {
2170 // we allow either setting or clearing but not replacing
2171 wxASSERT( m_cgContext == NULL || cg == NULL );
2172
2173 if ( m_cgContext )
2174 {
2175 CheckInvariants();
2176 CGContextRestoreGState( m_cgContext );
2177 CGContextRestoreGState( m_cgContext );
2178 if ( m_contextSynthesized )
2179 {
2180 #if wxOSX_USE_CARBON
2181 QDEndCGContext( GetWindowPort( m_windowRef ) , &m_cgContext);
2182 #endif
2183 #if wxOSX_USE_COCOA
2184 wxOSXUnlockFocus(m_view);
2185 #endif
2186 }
2187 else
2188 CGContextRelease(m_cgContext);
2189 }
2190
2191 m_cgContext = cg;
2192
2193 // FIXME: This check is needed because currently we need to use a DC/GraphicsContext
2194 // in order to get font properties, like wxFont::GetPixelSize, but since we don't have
2195 // a native window attached to use, I create a wxGraphicsContext with a NULL CGContextRef
2196 // for this one operation.
2197
2198 // When wxFont::GetPixelSize on Mac no longer needs a graphics context, this check
2199 // can be removed.
2200 if (m_cgContext)
2201 {
2202 CGContextRetain(m_cgContext);
2203 CGContextSaveGState( m_cgContext );
2204 CGContextSetTextMatrix( m_cgContext, CGAffineTransformIdentity );
2205 CGContextSaveGState( m_cgContext );
2206 m_contextSynthesized = false;
2207 }
2208 }
2209
2210 void wxMacCoreGraphicsContext::Translate( wxDouble dx , wxDouble dy )
2211 {
2212 if ( m_cgContext )
2213 CGContextTranslateCTM( m_cgContext, (CGFloat) dx, (CGFloat) dy );
2214 else
2215 m_windowTransform = CGAffineTransformTranslate(m_windowTransform, (CGFloat) dx, (CGFloat) dy);
2216 }
2217
2218 void wxMacCoreGraphicsContext::Scale( wxDouble xScale , wxDouble yScale )
2219 {
2220 if ( m_cgContext )
2221 CGContextScaleCTM( m_cgContext , (CGFloat) xScale , (CGFloat) yScale );
2222 else
2223 m_windowTransform = CGAffineTransformScale(m_windowTransform, (CGFloat) xScale, (CGFloat) yScale);
2224 }
2225
2226 void wxMacCoreGraphicsContext::Rotate( wxDouble angle )
2227 {
2228 if ( m_cgContext )
2229 CGContextRotateCTM( m_cgContext , (CGFloat) angle );
2230 else
2231 m_windowTransform = CGAffineTransformRotate(m_windowTransform, (CGFloat) angle);
2232 }
2233
2234 void wxMacCoreGraphicsContext::DrawBitmap( const wxBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2235 {
2236 wxGraphicsBitmap bitmap = GetRenderer()->CreateBitmap(bmp);
2237 DrawBitmap(bitmap, x, y, w, h);
2238 }
2239
2240 void wxMacCoreGraphicsContext::DrawBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2241 {
2242 if (!EnsureIsValid())
2243 return;
2244
2245 if (m_composition == wxCOMPOSITION_DEST)
2246 return;
2247
2248 #ifdef __WXMAC__
2249 wxMacCoreGraphicsBitmapData* refdata = static_cast<wxMacCoreGraphicsBitmapData*>(bmp.GetRefData());
2250 CGImageRef image = refdata->GetBitmap();
2251 CGRect r = CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h );
2252 if ( refdata->IsMonochrome() == 1 )
2253 {
2254 // is a mask, the '1' in the mask tell where to draw the current brush
2255 if ( !m_brush.IsNull() )
2256 {
2257 if ( ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
2258 {
2259 // TODO clip to mask
2260 /*
2261 CGContextSaveGState( m_cgContext );
2262 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
2263 CGContextClip( m_cgContext );
2264 CGContextDrawShading( m_cgContext, ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->GetShading() );
2265 CGContextRestoreGState( m_cgContext);
2266 */
2267 }
2268 else
2269 {
2270 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
2271 wxMacDrawCGImage( m_cgContext , &r , image );
2272 }
2273 }
2274 }
2275 else
2276 {
2277 wxMacDrawCGImage( m_cgContext , &r , image );
2278 }
2279 #endif
2280
2281 CheckInvariants();
2282 }
2283
2284 void wxMacCoreGraphicsContext::DrawIcon( const wxIcon &icon, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2285 {
2286 if (!EnsureIsValid())
2287 return;
2288
2289 if (m_composition == wxCOMPOSITION_DEST)
2290 return;
2291
2292 CGRect r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) w , (CGFloat) h );
2293 CGContextSaveGState( m_cgContext );
2294 CGContextTranslateCTM( m_cgContext,(CGFloat) x ,(CGFloat) (y + h) );
2295 CGContextScaleCTM( m_cgContext, 1, -1 );
2296 #if wxOSX_USE_COCOA_OR_CARBON
2297 PlotIconRefInContext( m_cgContext , &r , kAlignNone , kTransformNone ,
2298 NULL , kPlotIconRefNormalFlags , icon.GetHICON() );
2299 #endif
2300 CGContextRestoreGState( m_cgContext );
2301
2302 CheckInvariants();
2303 }
2304
2305 void wxMacCoreGraphicsContext::PushState()
2306 {
2307 if (!EnsureIsValid())
2308 return;
2309
2310 CGContextSaveGState( m_cgContext );
2311 }
2312
2313 void wxMacCoreGraphicsContext::PopState()
2314 {
2315 if (!EnsureIsValid())
2316 return;
2317
2318 CGContextRestoreGState( m_cgContext );
2319 }
2320
2321 void wxMacCoreGraphicsContext::DoDrawText( const wxString &str, wxDouble x, wxDouble y )
2322 {
2323 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2324
2325 if (!EnsureIsValid())
2326 return;
2327
2328 if (m_composition == wxCOMPOSITION_DEST)
2329 return;
2330
2331 #if wxOSX_USE_CORE_TEXT
2332 if ( UMAGetSystemVersion() >= 0x1050 )
2333 {
2334 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2335 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2336 CTFontRef font = fref->OSXGetCTFont();
2337 CGColorRef col = wxMacCreateCGColor( fref->GetColour() );
2338 #if 0
2339 // right now there's no way to get continuous underlines, only words, so we emulate it
2340 CTUnderlineStyle ustyle = fref->GetUnderlined() ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone ;
2341 wxCFRef<CFNumberRef> underlined( CFNumberCreate(NULL, kCFNumberSInt32Type, &ustyle) );
2342 CFStringRef keys[] = { kCTFontAttributeName , kCTForegroundColorAttributeName, kCTUnderlineStyleAttributeName };
2343 CFTypeRef values[] = { font, col, underlined };
2344 #else
2345 CFStringRef keys[] = { kCTFontAttributeName , kCTForegroundColorAttributeName };
2346 CFTypeRef values[] = { font, col };
2347 #endif
2348 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2349 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2350 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, text, attributes) );
2351 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2352
2353 y += CTFontGetAscent(font);
2354
2355 CGContextSaveGState(m_cgContext);
2356 CGAffineTransform textMatrix = CGContextGetTextMatrix(m_cgContext);
2357
2358 CGContextTranslateCTM(m_cgContext, (CGFloat) x, (CGFloat) y);
2359 CGContextScaleCTM(m_cgContext, 1, -1);
2360 CGContextSetTextMatrix(m_cgContext, CGAffineTransformIdentity);
2361
2362 CTLineDraw( line, m_cgContext );
2363
2364 if ( fref->GetUnderlined() ) {
2365 //AKT: draw horizontal line 1 pixel thick and with 1 pixel gap under baseline
2366 CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
2367
2368 CGPoint points[] = { {0.0, -2.0}, {width, -2.0} };
2369
2370 CGContextSetStrokeColorWithColor(m_cgContext, col);
2371 CGContextSetShouldAntialias(m_cgContext, false);
2372 CGContextSetLineWidth(m_cgContext, 1.0);
2373 CGContextStrokeLineSegments(m_cgContext, points, 2);
2374 }
2375
2376 CGContextRestoreGState(m_cgContext);
2377 CGContextSetTextMatrix(m_cgContext, textMatrix);
2378 CFRelease( col );
2379 CheckInvariants();
2380 return;
2381 }
2382 #endif
2383 #if wxOSX_USE_ATSU_TEXT
2384 {
2385 DrawText(str, x, y, 0.0);
2386 return;
2387 }
2388 #endif
2389 #if wxOSX_USE_IPHONE
2390 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2391
2392 CGContextSaveGState(m_cgContext);
2393
2394 CGColorRef col = wxMacCreateCGColor( fref->GetColour() );
2395 CGContextSetTextDrawingMode (m_cgContext, kCGTextFill);
2396 CGContextSetFillColorWithColor( m_cgContext, col );
2397
2398 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2399 DrawTextInContext( m_cgContext, CGPointMake( x, y ), fref->GetUIFont() , text.AsNSString() );
2400
2401 CGContextRestoreGState(m_cgContext);
2402 CFRelease( col );
2403 #endif
2404
2405 CheckInvariants();
2406 }
2407
2408 void wxMacCoreGraphicsContext::DoDrawRotatedText(const wxString &str,
2409 wxDouble x, wxDouble y,
2410 wxDouble angle)
2411 {
2412 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2413
2414 if (!EnsureIsValid())
2415 return;
2416
2417 if (m_composition == wxCOMPOSITION_DEST)
2418 return;
2419
2420 #if wxOSX_USE_CORE_TEXT
2421 if ( UMAGetSystemVersion() >= 0x1050 )
2422 {
2423 // default implementation takes care of rotation and calls non rotated DrawText afterwards
2424 wxGraphicsContext::DoDrawRotatedText( str, x, y, angle );
2425 return;
2426 }
2427 #endif
2428 #if wxOSX_USE_ATSU_TEXT
2429 {
2430 OSStatus status = noErr;
2431 ATSUTextLayout atsuLayout;
2432 wxMacUniCharBuffer unibuf( str );
2433 UniCharCount chars = unibuf.GetChars();
2434
2435 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2436 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2437 &chars , &style , &atsuLayout );
2438
2439 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the rotated text") );
2440
2441 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2442 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2443
2444 int iAngle = int( angle * RAD2DEG );
2445 if ( abs(iAngle) > 0 )
2446 {
2447 Fixed atsuAngle = IntToFixed( iAngle );
2448 ATSUAttributeTag atsuTags[] =
2449 {
2450 kATSULineRotationTag ,
2451 };
2452 ByteCount atsuSizes[WXSIZEOF(atsuTags)] =
2453 {
2454 sizeof( Fixed ) ,
2455 };
2456 ATSUAttributeValuePtr atsuValues[WXSIZEOF(atsuTags)] =
2457 {
2458 &atsuAngle ,
2459 };
2460 status = ::ATSUSetLayoutControls(atsuLayout , WXSIZEOF(atsuTags),
2461 atsuTags, atsuSizes, atsuValues );
2462 }
2463
2464 {
2465 ATSUAttributeTag atsuTags[] =
2466 {
2467 kATSUCGContextTag ,
2468 };
2469 ByteCount atsuSizes[WXSIZEOF(atsuTags)] =
2470 {
2471 sizeof( CGContextRef ) ,
2472 };
2473 ATSUAttributeValuePtr atsuValues[WXSIZEOF(atsuTags)] =
2474 {
2475 &m_cgContext ,
2476 };
2477 status = ::ATSUSetLayoutControls(atsuLayout , WXSIZEOF(atsuTags),
2478 atsuTags, atsuSizes, atsuValues );
2479 }
2480
2481 ATSUTextMeasurement textBefore, textAfter;
2482 ATSUTextMeasurement ascent, descent;
2483
2484 status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2485 &textBefore , &textAfter, &ascent , &descent );
2486
2487 wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
2488
2489 Rect rect;
2490 x += (int)(sin(angle) * FixedToFloat(ascent));
2491 y += (int)(cos(angle) * FixedToFloat(ascent));
2492
2493 status = ::ATSUMeasureTextImage( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2494 IntToFixed(x) , IntToFixed(y) , &rect );
2495 wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
2496
2497 CGContextSaveGState(m_cgContext);
2498 CGContextTranslateCTM(m_cgContext, (CGFloat) x, (CGFloat) y);
2499 CGContextScaleCTM(m_cgContext, 1, -1);
2500 status = ::ATSUDrawText( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2501 IntToFixed(0) , IntToFixed(0) );
2502
2503 wxASSERT_MSG( status == noErr , wxT("couldn't draw the rotated text") );
2504
2505 CGContextRestoreGState(m_cgContext);
2506
2507 ::ATSUDisposeTextLayout(atsuLayout);
2508 CheckInvariants();
2509
2510 return;
2511 }
2512 #endif
2513 #if wxOSX_USE_IPHONE
2514 // default implementation takes care of rotation and calls non rotated DrawText afterwards
2515 wxGraphicsContext::DoDrawRotatedText( str, x, y, angle );
2516 #endif
2517
2518 CheckInvariants();
2519 }
2520
2521 void wxMacCoreGraphicsContext::GetTextExtent( const wxString &str, wxDouble *width, wxDouble *height,
2522 wxDouble *descent, wxDouble *externalLeading ) const
2523 {
2524 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::GetTextExtent - no valid font set") );
2525
2526 if ( width )
2527 *width = 0;
2528 if ( height )
2529 *height = 0;
2530 if ( descent )
2531 *descent = 0;
2532 if ( externalLeading )
2533 *externalLeading = 0;
2534
2535 if (str.empty())
2536 return;
2537
2538 #if wxOSX_USE_CORE_TEXT
2539 if ( UMAGetSystemVersion() >= 0x1050 )
2540 {
2541 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2542 CTFontRef font = fref->OSXGetCTFont();
2543
2544 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2545 CFStringRef keys[] = { kCTFontAttributeName };
2546 CFTypeRef values[] = { font };
2547 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2548 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2549 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, text, attributes) );
2550 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2551
2552 CGFloat a, d, l, w;
2553 w = CTLineGetTypographicBounds(line, &a, &d, &l);
2554
2555 if ( height )
2556 *height = a+d+l;
2557 if ( descent )
2558 *descent = d;
2559 if ( externalLeading )
2560 *externalLeading = l;
2561 if ( width )
2562 *width = w;
2563 return;
2564 }
2565 #endif
2566 #if wxOSX_USE_ATSU_TEXT
2567 {
2568 OSStatus status = noErr;
2569
2570 ATSUTextLayout atsuLayout;
2571 wxMacUniCharBuffer unibuf( str );
2572 UniCharCount chars = unibuf.GetChars();
2573
2574 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2575 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2576 &chars , &style , &atsuLayout );
2577
2578 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the text") );
2579
2580 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2581 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2582
2583 ATSUTextMeasurement textBefore, textAfter;
2584 ATSUTextMeasurement textAscent, textDescent;
2585
2586 status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2587 &textBefore , &textAfter, &textAscent , &textDescent );
2588
2589 if ( height )
2590 *height = FixedToFloat(textAscent + textDescent);
2591 if ( descent )
2592 *descent = FixedToFloat(textDescent);
2593 if ( externalLeading )
2594 *externalLeading = 0;
2595 if ( width )
2596 *width = FixedToFloat(textAfter - textBefore);
2597
2598 ::ATSUDisposeTextLayout(atsuLayout);
2599
2600 return;
2601 }
2602 #endif
2603 #if wxOSX_USE_IPHONE
2604 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2605
2606 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2607 CGSize sz = MeasureTextInContext( fref->GetUIFont() , text.AsNSString() );
2608
2609 if ( height )
2610 *height = sz.height;
2611 /*
2612 if ( descent )
2613 *descent = FixedToFloat(textDescent);
2614 if ( externalLeading )
2615 *externalLeading = 0;
2616 */
2617 if ( width )
2618 *width = sz.width;
2619 #endif
2620
2621 CheckInvariants();
2622 }
2623
2624 void wxMacCoreGraphicsContext::GetPartialTextExtents(const wxString& text, wxArrayDouble& widths) const
2625 {
2626 widths.Empty();
2627 widths.Add(0, text.length());
2628
2629 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2630
2631 if (text.empty())
2632 return;
2633
2634 #if wxOSX_USE_CORE_TEXT
2635 {
2636 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2637 CTFontRef font = fref->OSXGetCTFont();
2638
2639 wxCFStringRef t(text, wxLocale::GetSystemEncoding() );
2640 CFStringRef keys[] = { kCTFontAttributeName };
2641 CFTypeRef values[] = { font };
2642 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2643 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2644 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, t, attributes) );
2645 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2646
2647 int chars = text.length();
2648 for ( int pos = 0; pos < (int)chars; pos ++ )
2649 {
2650 widths[pos] = CTLineGetOffsetForStringIndex( line, pos+1 , NULL );
2651 }
2652
2653 return;
2654 }
2655 #endif
2656 #if wxOSX_USE_ATSU_TEXT
2657 {
2658 OSStatus status = noErr;
2659 ATSUTextLayout atsuLayout;
2660 wxMacUniCharBuffer unibuf( text );
2661 UniCharCount chars = unibuf.GetChars();
2662
2663 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2664 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2665 &chars , &style , &atsuLayout );
2666
2667 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the text") );
2668
2669 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2670 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2671
2672 // new implementation from JS, keep old one just in case
2673 #if 0
2674 for ( int pos = 0; pos < (int)chars; pos ++ )
2675 {
2676 unsigned long actualNumberOfBounds = 0;
2677 ATSTrapezoid glyphBounds;
2678
2679 // We get a single bound, since the text should only require one. If it requires more, there is an issue
2680 OSStatus result;
2681 result = ATSUGetGlyphBounds( atsuLayout, 0, 0, kATSUFromTextBeginning, pos + 1,
2682 kATSUseDeviceOrigins, 1, &glyphBounds, &actualNumberOfBounds );
2683 if (result != noErr || actualNumberOfBounds != 1 )
2684 return;
2685
2686 widths[pos] = FixedToFloat( glyphBounds.upperRight.x - glyphBounds.upperLeft.x );
2687 //unsigned char uch = s[i];
2688 }
2689 #else
2690 ATSLayoutRecord *layoutRecords = NULL;
2691 ItemCount glyphCount = 0;
2692
2693 // Get the glyph extents
2694 OSStatus err = ::ATSUDirectGetLayoutDataArrayPtrFromTextLayout(atsuLayout,
2695 0,
2696 kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
2697 (void **)
2698 &layoutRecords,
2699 &glyphCount);
2700 wxASSERT(glyphCount == (text.length()+1));
2701
2702 if ( err == noErr && glyphCount == (text.length()+1))
2703 {
2704 for ( int pos = 1; pos < (int)glyphCount ; pos ++ )
2705 {
2706 widths[pos-1] = FixedToFloat( layoutRecords[pos].realPos );
2707 }
2708 }
2709
2710 ::ATSUDirectReleaseLayoutDataArrayPtr(NULL,
2711 kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
2712 (void **) &layoutRecords);
2713 #endif
2714 ::ATSUDisposeTextLayout(atsuLayout);
2715 }
2716 #endif
2717 #if wxOSX_USE_IPHONE
2718 // TODO core graphics text implementation here
2719 #endif
2720
2721 CheckInvariants();
2722 }
2723
2724 void * wxMacCoreGraphicsContext::GetNativeContext()
2725 {
2726 return m_cgContext;
2727 }
2728
2729
2730 void wxMacCoreGraphicsContext::DrawRectangleX( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2731 {
2732 if (m_composition == wxCOMPOSITION_DEST)
2733 return;
2734
2735 CGRect rect = CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h );
2736 if ( !m_brush.IsNull() )
2737 {
2738 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
2739 CGContextFillRect(m_cgContext, rect);
2740 }
2741
2742 wxQuartzOffsetHelper helper( m_cgContext , ShouldOffset() );
2743 if ( !m_pen.IsNull() )
2744 {
2745 ((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->Apply(this);
2746 CGContextStrokeRect(m_cgContext, rect);
2747 }
2748 }
2749
2750 // concatenates this transform with the current transform of this context
2751 void wxMacCoreGraphicsContext::ConcatTransform( const wxGraphicsMatrix& matrix )
2752 {
2753 if ( m_cgContext )
2754 CGContextConcatCTM( m_cgContext, *(CGAffineTransform*) matrix.GetNativeMatrix());
2755 else
2756 m_windowTransform = CGAffineTransformConcat(*(CGAffineTransform*) matrix.GetNativeMatrix(), m_windowTransform);
2757 }
2758
2759 // sets the transform of this context
2760 void wxMacCoreGraphicsContext::SetTransform( const wxGraphicsMatrix& matrix )
2761 {
2762 CheckInvariants();
2763 if ( m_cgContext )
2764 {
2765 CGAffineTransform transform = CGContextGetCTM( m_cgContext );
2766 transform = CGAffineTransformInvert( transform ) ;
2767 CGContextConcatCTM( m_cgContext, transform);
2768 CGContextConcatCTM( m_cgContext, *(CGAffineTransform*) matrix.GetNativeMatrix());
2769 }
2770 else
2771 {
2772 m_windowTransform = *(CGAffineTransform*) matrix.GetNativeMatrix();
2773 }
2774 CheckInvariants();
2775 }
2776
2777 // gets the matrix of this context
2778 wxGraphicsMatrix wxMacCoreGraphicsContext::GetTransform() const
2779 {
2780 wxGraphicsMatrix m = CreateMatrix();
2781 *((CGAffineTransform*) m.GetNativeMatrix()) = ( m_cgContext == NULL ? m_windowTransform :
2782 CGContextGetCTM( m_cgContext ));
2783 return m;
2784 }
2785
2786
2787 #if wxUSE_IMAGE
2788
2789 // ----------------------------------------------------------------------------
2790 // wxMacCoreGraphicsImageContext
2791 // ----------------------------------------------------------------------------
2792
2793 // This is a GC that can be used to draw on wxImage. In this implementation we
2794 // simply draw on a wxBitmap using wxMemoryDC and then convert it to wxImage in
2795 // the end so it's not especially interesting and exists mainly for
2796 // compatibility with the other platforms.
2797 class wxMacCoreGraphicsImageContext : public wxMacCoreGraphicsContext
2798 {
2799 public:
2800 wxMacCoreGraphicsImageContext(wxGraphicsRenderer* renderer,
2801 wxImage& image) :
2802 wxMacCoreGraphicsContext(renderer),
2803 m_image(image),
2804 m_bitmap(image),
2805 m_memDC(m_bitmap)
2806 {
2807 SetNativeContext
2808 (
2809 (CGContextRef)(m_memDC.GetGraphicsContext()->GetNativeContext())
2810 );
2811 m_width = image.GetWidth();
2812 m_height = image.GetHeight();
2813 }
2814
2815 virtual ~wxMacCoreGraphicsImageContext()
2816 {
2817 m_memDC.SelectObject(wxNullBitmap);
2818 m_image = m_bitmap.ConvertToImage();
2819 }
2820
2821 private:
2822 wxImage& m_image;
2823 wxBitmap m_bitmap;
2824 wxMemoryDC m_memDC;
2825 };
2826
2827 #endif // wxUSE_IMAGE
2828
2829 //
2830 // Renderer
2831 //
2832
2833 //-----------------------------------------------------------------------------
2834 // wxMacCoreGraphicsRenderer declaration
2835 //-----------------------------------------------------------------------------
2836
2837 class WXDLLIMPEXP_CORE wxMacCoreGraphicsRenderer : public wxGraphicsRenderer
2838 {
2839 public :
2840 wxMacCoreGraphicsRenderer() {}
2841
2842 virtual ~wxMacCoreGraphicsRenderer() {}
2843
2844 // Context
2845
2846 virtual wxGraphicsContext * CreateContext( const wxWindowDC& dc);
2847 virtual wxGraphicsContext * CreateContext( const wxMemoryDC& dc);
2848 #if wxUSE_PRINTING_ARCHITECTURE
2849 virtual wxGraphicsContext * CreateContext( const wxPrinterDC& dc);
2850 #endif
2851
2852 virtual wxGraphicsContext * CreateContextFromNativeContext( void * context );
2853
2854 virtual wxGraphicsContext * CreateContextFromNativeWindow( void * window );
2855
2856 virtual wxGraphicsContext * CreateContext( wxWindow* window );
2857
2858 #if wxUSE_IMAGE
2859 virtual wxGraphicsContext * CreateContextFromImage(wxImage& image);
2860 #endif // wxUSE_IMAGE
2861
2862 virtual wxGraphicsContext * CreateMeasuringContext();
2863
2864 // Path
2865
2866 virtual wxGraphicsPath CreatePath();
2867
2868 // Matrix
2869
2870 virtual wxGraphicsMatrix CreateMatrix( wxDouble a=1.0, wxDouble b=0.0, wxDouble c=0.0, wxDouble d=1.0,
2871 wxDouble tx=0.0, wxDouble ty=0.0);
2872
2873
2874 virtual wxGraphicsPen CreatePen(const wxPen& pen) ;
2875
2876 virtual wxGraphicsBrush CreateBrush(const wxBrush& brush ) ;
2877
2878 virtual wxGraphicsBrush
2879 CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
2880 wxDouble x2, wxDouble y2,
2881 const wxGraphicsGradientStops& stops);
2882
2883 virtual wxGraphicsBrush
2884 CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
2885 wxDouble xc, wxDouble yc,
2886 wxDouble radius,
2887 const wxGraphicsGradientStops& stops);
2888
2889 // sets the font
2890 virtual wxGraphicsFont CreateFont( const wxFont &font , const wxColour &col = *wxBLACK ) ;
2891 virtual wxGraphicsFont CreateFont(double sizeInPixels,
2892 const wxString& facename,
2893 int flags = wxFONTFLAG_DEFAULT,
2894 const wxColour& col = *wxBLACK);
2895
2896 // create a native bitmap representation
2897 virtual wxGraphicsBitmap CreateBitmap( const wxBitmap &bitmap ) ;
2898
2899 #if wxUSE_IMAGE
2900 virtual wxGraphicsBitmap CreateBitmapFromImage(const wxImage& image);
2901 virtual wxImage CreateImageFromBitmap(const wxGraphicsBitmap& bmp);
2902 #endif // wxUSE_IMAGE
2903
2904 // create a graphics bitmap from a native bitmap
2905 virtual wxGraphicsBitmap CreateBitmapFromNativeBitmap( void* bitmap );
2906
2907 // create a native bitmap representation
2908 virtual wxGraphicsBitmap CreateSubBitmap( const wxGraphicsBitmap &bitmap, wxDouble x, wxDouble y, wxDouble w, wxDouble h ) ;
2909 private :
2910 DECLARE_DYNAMIC_CLASS_NO_COPY(wxMacCoreGraphicsRenderer)
2911 } ;
2912
2913 //-----------------------------------------------------------------------------
2914 // wxMacCoreGraphicsRenderer implementation
2915 //-----------------------------------------------------------------------------
2916
2917 IMPLEMENT_DYNAMIC_CLASS(wxMacCoreGraphicsRenderer,wxGraphicsRenderer)
2918
2919 static wxMacCoreGraphicsRenderer gs_MacCoreGraphicsRenderer;
2920
2921 wxGraphicsRenderer* wxGraphicsRenderer::GetDefaultRenderer()
2922 {
2923 return &gs_MacCoreGraphicsRenderer;
2924 }
2925
2926 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxWindowDC& dc )
2927 {
2928 const wxDCImpl* impl = dc.GetImpl();
2929 wxWindowDCImpl *win_impl = wxDynamicCast( impl, wxWindowDCImpl );
2930 if (win_impl)
2931 {
2932 int w, h;
2933 win_impl->GetSize( &w, &h );
2934 CGContextRef cgctx = 0;
2935
2936 wxASSERT_MSG(win_impl->GetWindow(), "Invalid wxWindow in wxMacCoreGraphicsRenderer::CreateContext");
2937 if (win_impl->GetWindow())
2938 cgctx = (CGContextRef)(win_impl->GetWindow()->MacGetCGContextRef());
2939
2940 // having a cgctx being NULL is fine (will be created on demand)
2941 // this is the case for all wxWindowDCs except wxPaintDC
2942 wxMacCoreGraphicsContext *context =
2943 new wxMacCoreGraphicsContext( this, cgctx, (wxDouble) w, (wxDouble) h );
2944 context->EnableOffset(true);
2945 return context;
2946 }
2947 return NULL;
2948 }
2949
2950 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxMemoryDC& dc )
2951 {
2952 #ifdef __WXMAC__
2953 const wxDCImpl* impl = dc.GetImpl();
2954 wxMemoryDCImpl *mem_impl = wxDynamicCast( impl, wxMemoryDCImpl );
2955 if (mem_impl)
2956 {
2957 int w, h;
2958 mem_impl->GetSize( &w, &h );
2959 wxMacCoreGraphicsContext* context = new wxMacCoreGraphicsContext( this,
2960 (CGContextRef)(mem_impl->GetGraphicsContext()->GetNativeContext()), (wxDouble) w, (wxDouble) h );
2961 context->EnableOffset(true);
2962 return context;
2963 }
2964 #endif
2965 return NULL;
2966 }
2967
2968 #if wxUSE_PRINTING_ARCHITECTURE
2969 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxPrinterDC& dc )
2970 {
2971 #ifdef __WXMAC__
2972 const wxDCImpl* impl = dc.GetImpl();
2973 wxPrinterDCImpl *print_impl = wxDynamicCast( impl, wxPrinterDCImpl );
2974 if (print_impl)
2975 {
2976 int w, h;
2977 print_impl->GetSize( &w, &h );
2978 return new wxMacCoreGraphicsContext( this,
2979 (CGContextRef)(print_impl->GetGraphicsContext()->GetNativeContext()), (wxDouble) w, (wxDouble) h );
2980 }
2981 #endif
2982 return NULL;
2983 }
2984 #endif
2985
2986 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContextFromNativeContext( void * context )
2987 {
2988 return new wxMacCoreGraphicsContext(this,(CGContextRef)context);
2989 }
2990
2991 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContextFromNativeWindow( void * window )
2992 {
2993 #if wxOSX_USE_CARBON
2994 wxMacCoreGraphicsContext* context = new wxMacCoreGraphicsContext(this,(WindowRef)window);
2995 context->EnableOffset(true);
2996 return context;
2997 #else
2998 wxUnusedVar(window);
2999 return NULL;
3000 #endif
3001 }
3002
3003 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( wxWindow* window )
3004 {
3005 return new wxMacCoreGraphicsContext(this, window );
3006 }
3007
3008 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateMeasuringContext()
3009 {
3010 return new wxMacCoreGraphicsContext(this);
3011 }
3012
3013 #if wxUSE_IMAGE
3014
3015 wxGraphicsContext*
3016 wxMacCoreGraphicsRenderer::CreateContextFromImage(wxImage& image)
3017 {
3018 return new wxMacCoreGraphicsImageContext(this, image);
3019 }
3020
3021 #endif // wxUSE_IMAGE
3022
3023 // Path
3024
3025 wxGraphicsPath wxMacCoreGraphicsRenderer::CreatePath()
3026 {
3027 wxGraphicsPath m;
3028 m.SetRefData( new wxMacCoreGraphicsPathData(this));
3029 return m;
3030 }
3031
3032
3033 // Matrix
3034
3035 wxGraphicsMatrix wxMacCoreGraphicsRenderer::CreateMatrix( wxDouble a, wxDouble b, wxDouble c, wxDouble d,
3036 wxDouble tx, wxDouble ty)
3037 {
3038 wxGraphicsMatrix m;
3039 wxMacCoreGraphicsMatrixData* data = new wxMacCoreGraphicsMatrixData( this );
3040 data->Set( a,b,c,d,tx,ty ) ;
3041 m.SetRefData(data);
3042 return m;
3043 }
3044
3045 wxGraphicsPen wxMacCoreGraphicsRenderer::CreatePen(const wxPen& pen)
3046 {
3047 if ( !pen.IsOk() || pen.GetStyle() == wxTRANSPARENT )
3048 return wxNullGraphicsPen;
3049 else
3050 {
3051 wxGraphicsPen p;
3052 p.SetRefData(new wxMacCoreGraphicsPenData( this, pen ));
3053 return p;
3054 }
3055 }
3056
3057 wxGraphicsBrush wxMacCoreGraphicsRenderer::CreateBrush(const wxBrush& brush )
3058 {
3059 if ( !brush.IsOk() || brush.GetStyle() == wxTRANSPARENT )
3060 return wxNullGraphicsBrush;
3061 else
3062 {
3063 wxGraphicsBrush p;
3064 p.SetRefData(new wxMacCoreGraphicsBrushData( this, brush ));
3065 return p;
3066 }
3067 }
3068
3069 wxGraphicsBitmap wxMacCoreGraphicsRenderer::CreateBitmap( const wxBitmap& bmp )
3070 {
3071 if ( bmp.IsOk() )
3072 {
3073 wxGraphicsBitmap p;
3074 p.SetRefData(new wxMacCoreGraphicsBitmapData( this , bmp.CreateCGImage(), bmp.GetDepth() == 1 ) );
3075 return p;
3076 }
3077 else
3078 return wxNullGraphicsBitmap;
3079 }
3080
3081 #if wxUSE_IMAGE
3082
3083 wxGraphicsBitmap
3084 wxMacCoreGraphicsRenderer::CreateBitmapFromImage(const wxImage& image)
3085 {
3086 // We don't have any direct way to convert wxImage to CGImage so pass by
3087 // wxBitmap. This makes this function pretty useless in this implementation
3088 // but it allows to have the same API as with Cairo backend where we can
3089 // convert wxImage to a Cairo surface directly, bypassing wxBitmap.
3090 return CreateBitmap(wxBitmap(image));
3091 }
3092
3093 wxImage wxMacCoreGraphicsRenderer::CreateImageFromBitmap(const wxGraphicsBitmap& bmp)
3094 {
3095 wxMacCoreGraphicsBitmapData* const
3096 data = static_cast<wxMacCoreGraphicsBitmapData*>(bmp.GetRefData());
3097
3098 return data ? data->ConvertToImage() : wxNullImage;
3099 }
3100
3101 #endif // wxUSE_IMAGE
3102
3103 wxGraphicsBitmap wxMacCoreGraphicsRenderer::CreateBitmapFromNativeBitmap( void* bitmap )
3104 {
3105 if ( bitmap != NULL )
3106 {
3107 wxGraphicsBitmap p;
3108 p.SetRefData(new wxMacCoreGraphicsBitmapData( this , (CGImageRef) bitmap, false ));
3109 return p;
3110 }
3111 else
3112 return wxNullGraphicsBitmap;
3113 }
3114
3115 wxGraphicsBitmap wxMacCoreGraphicsRenderer::CreateSubBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
3116 {
3117 wxMacCoreGraphicsBitmapData* refdata =static_cast<wxMacCoreGraphicsBitmapData*>(bmp.GetRefData());
3118 CGImageRef img = refdata->GetBitmap();
3119 if ( img )
3120 {
3121 wxGraphicsBitmap p;
3122 CGImageRef subimg = CGImageCreateWithImageInRect(img,CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h ));
3123 p.SetRefData(new wxMacCoreGraphicsBitmapData( this , subimg, refdata->IsMonochrome() ) );
3124 return p;
3125 }
3126 else
3127 return wxNullGraphicsBitmap;
3128 }
3129
3130 wxGraphicsBrush
3131 wxMacCoreGraphicsRenderer::CreateLinearGradientBrush(wxDouble x1, wxDouble y1,
3132 wxDouble x2, wxDouble y2,
3133 const wxGraphicsGradientStops& stops)
3134 {
3135 wxGraphicsBrush p;
3136 wxMacCoreGraphicsBrushData* d = new wxMacCoreGraphicsBrushData( this );
3137 d->CreateLinearGradientBrush(x1, y1, x2, y2, stops);
3138 p.SetRefData(d);
3139 return p;
3140 }
3141
3142 wxGraphicsBrush
3143 wxMacCoreGraphicsRenderer::CreateRadialGradientBrush(wxDouble xo, wxDouble yo,
3144 wxDouble xc, wxDouble yc,
3145 wxDouble radius,
3146 const wxGraphicsGradientStops& stops)
3147 {
3148 wxGraphicsBrush p;
3149 wxMacCoreGraphicsBrushData* d = new wxMacCoreGraphicsBrushData( this );
3150 d->CreateRadialGradientBrush(xo, yo, xc, yc, radius, stops);
3151 p.SetRefData(d);
3152 return p;
3153 }
3154
3155 wxGraphicsFont wxMacCoreGraphicsRenderer::CreateFont( const wxFont &font , const wxColour &col )
3156 {
3157 if ( font.IsOk() )
3158 {
3159 wxGraphicsFont p;
3160 p.SetRefData(new wxMacCoreGraphicsFontData( this , font, col ));
3161 return p;
3162 }
3163 else
3164 return wxNullGraphicsFont;
3165 }
3166
3167 wxGraphicsFont
3168 wxMacCoreGraphicsRenderer::CreateFont(double sizeInPixels,
3169 const wxString& facename,
3170 int flags,
3171 const wxColour& col)
3172 {
3173 // This implementation is not ideal as we don't support fractional font
3174 // sizes right now, but it's the simplest one.
3175 //
3176 // Notice that under Mac we always use 72 DPI so the font size in pixels is
3177 // the same as the font size in points and we can pass it directly to wxFont
3178 // ctor.
3179 wxFont font(wxRound(sizeInPixels),
3180 wxFONTFAMILY_DEFAULT,
3181 flags & wxFONTFLAG_ITALIC ? wxFONTSTYLE_ITALIC
3182 : wxFONTSTYLE_NORMAL,
3183 flags & wxFONTFLAG_BOLD ? wxFONTWEIGHT_BOLD
3184 : wxFONTWEIGHT_NORMAL,
3185 (flags & wxFONTFLAG_UNDERLINED) != 0,
3186 facename);
3187
3188 wxGraphicsFont f;
3189 f.SetRefData(new wxMacCoreGraphicsFontData(this, font, col));
3190 return f;
3191 }
3192
3193 //
3194 // CoreGraphics Helper Methods
3195 //
3196
3197 // Data Providers and Consumers
3198
3199 size_t UMAPutBytesCFRefCallback( void *info, const void *bytes, size_t count )
3200 {
3201 CFMutableDataRef data = (CFMutableDataRef) info;
3202 if ( data )
3203 {
3204 CFDataAppendBytes( data, (const UInt8*) bytes, count );
3205 }
3206 return count;
3207 }
3208
3209 void wxMacReleaseCFDataProviderCallback(void *info,
3210 const void *WXUNUSED(data),
3211 size_t WXUNUSED(count))
3212 {
3213 if ( info )
3214 CFRelease( (CFDataRef) info );
3215 }
3216
3217 void wxMacReleaseCFDataConsumerCallback( void *info )
3218 {
3219 if ( info )
3220 CFRelease( (CFDataRef) info );
3221 }
3222
3223 CGDataProviderRef wxMacCGDataProviderCreateWithCFData( CFDataRef data )
3224 {
3225 if ( data == NULL )
3226 return NULL;
3227
3228 return CGDataProviderCreateWithCFData( data );
3229 }
3230
3231 CGDataConsumerRef wxMacCGDataConsumerCreateWithCFData( CFMutableDataRef data )
3232 {
3233 if ( data == NULL )
3234 return NULL;
3235
3236 return CGDataConsumerCreateWithCFData( data );
3237 }
3238
3239 void
3240 wxMacReleaseMemoryBufferProviderCallback(void *info,
3241 const void * WXUNUSED_UNLESS_DEBUG(data),
3242 size_t WXUNUSED(size))
3243 {
3244 wxMemoryBuffer* membuf = (wxMemoryBuffer*) info ;
3245
3246 wxASSERT( data == membuf->GetData() ) ;
3247
3248 delete membuf ;
3249 }
3250
3251 CGDataProviderRef wxMacCGDataProviderCreateWithMemoryBuffer( const wxMemoryBuffer& buf )
3252 {
3253 wxMemoryBuffer* b = new wxMemoryBuffer( buf );
3254 if ( b->GetDataLen() == 0 )
3255 return NULL;
3256
3257 return CGDataProviderCreateWithData( b , (const void *) b->GetData() , b->GetDataLen() ,
3258 wxMacReleaseMemoryBufferProviderCallback );
3259 }