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