]> git.saurik.com Git - wxWidgets.git/blob - src/osx/carbon/graphics.cpp
74720dc37aed07f46cd7f24c9e95b96d0c0f6c9b
[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 #if wxOSX_USE_COCOA_OR_IPHONE
1528 if ( m_view )
1529 {
1530 CGContextFlush(m_cgContext);
1531 }
1532 #endif
1533 }
1534
1535 void wxMacCoreGraphicsContext::GetSize( wxDouble* width, wxDouble* height)
1536 {
1537 *width = m_width;
1538 *height = m_height;
1539 }
1540
1541
1542 void wxMacCoreGraphicsContext::StartPage( wxDouble width, wxDouble height )
1543 {
1544 CGRect r;
1545 if ( width != 0 && height != 0)
1546 r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) width , (CGFloat) height );
1547 else
1548 r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) m_width , (CGFloat) m_height );
1549
1550 CGContextBeginPage(m_cgContext, &r );
1551 // CGContextTranslateCTM( m_cgContext , 0 , height == 0 ? m_height : height );
1552 // CGContextScaleCTM( m_cgContext , 1 , -1 );
1553 }
1554
1555 void wxMacCoreGraphicsContext::EndPage()
1556 {
1557 CGContextEndPage(m_cgContext);
1558 }
1559
1560 void wxMacCoreGraphicsContext::Flush()
1561 {
1562 CGContextFlush(m_cgContext);
1563 }
1564
1565 bool wxMacCoreGraphicsContext::EnsureIsValid()
1566 {
1567 if ( !m_cgContext )
1568 {
1569 if (m_invisible)
1570 return false;
1571
1572 #if wxOSX_USE_COCOA_OR_IPHONE
1573 if ( wxOSXLockFocus(m_view) )
1574 {
1575 m_cgContext = wxOSXGetContextFromCurrentNSContext();
1576 wxASSERT_MSG( m_cgContext != NULL, _T("Unable to retrieve drawing context from View"));
1577 }
1578 else
1579 {
1580 m_invisible = true;
1581 }
1582 #endif
1583 #if wxOSX_USE_CARBON
1584 OSStatus status = QDBeginCGContext( GetWindowPort( m_windowRef ) , &m_cgContext );
1585 if ( status != noErr )
1586 {
1587 wxFAIL_MSG("Cannot nest wxDCs on the same window");
1588 }
1589 #endif
1590 if ( m_cgContext )
1591 {
1592 CGContextConcatCTM( m_cgContext, m_windowTransform );
1593 CGContextSaveGState( m_cgContext );
1594 m_contextSynthesized = true;
1595 if ( m_clipRgn.get() )
1596 {
1597 // the clip region is in device coordinates, so we convert this again to user coordinates
1598 wxCFRef<HIMutableShapeRef> hishape( HIShapeCreateMutableCopy( m_clipRgn ) );
1599 CGPoint transformedOrigin = CGPointApplyAffineTransform( CGPointZero,m_windowTransform);
1600 HIShapeOffset( hishape, -transformedOrigin.x, -transformedOrigin.y );
1601 // if the shape is empty, HIShapeReplacePathInCGContext doesn't work
1602 if ( HIShapeIsEmpty(hishape))
1603 {
1604 CGRect empty = CGRectMake( 0,0,0,0 );
1605 CGContextClipToRect( m_cgContext, empty );
1606 }
1607 else
1608 {
1609 HIShapeReplacePathInCGContext( hishape, m_cgContext );
1610 CGContextClip( m_cgContext );
1611 }
1612 }
1613 CGContextSaveGState( m_cgContext );
1614
1615 #if 0 // turn on for debugging of clientdc
1616 static float color = 0.5 ;
1617 static int channel = 0 ;
1618 CGRect bounds = CGRectMake(-1000,-1000,2000,2000);
1619 CGContextSetRGBFillColor( m_cgContext, channel == 0 ? color : 0.5 ,
1620 channel == 1 ? color : 0.5 , channel == 2 ? color : 0.5 , 1 );
1621 CGContextFillRect( m_cgContext, bounds );
1622 color += 0.1 ;
1623 if ( color > 0.9 )
1624 {
1625 color = 0.5 ;
1626 channel++ ;
1627 if ( channel == 3 )
1628 channel = 0 ;
1629 }
1630 #endif
1631 }
1632 }
1633 return m_cgContext != NULL;
1634 }
1635
1636 // TODO test whether the private CGContextSetCompositeOperation works under 10.3 (using NSCompositingModes)
1637
1638 bool wxMacCoreGraphicsContext::SetLogicalFunction( wxRasterOperationMode function )
1639 {
1640 if (m_logicalFunction == function)
1641 return true;
1642
1643 if (EnsureIsValid()==false)
1644 return true;
1645
1646 bool retval = false;
1647 bool shouldAntiAlias = true;
1648 CGBlendMode mode = kCGBlendModeNormal;
1649
1650 #if defined(__WXMAC__) && ( wxOSX_USE_IPHONE || ( MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 ) )
1651 #if wxOSX_USE_IPHONE
1652 if ( 1 )
1653 #else
1654 if ( UMAGetSystemVersion() >= 0x1050 )
1655 #endif
1656 {
1657 retval = true;
1658 switch ( function )
1659 {
1660 // TODO find best corresponding porter duff modes
1661 case wxCOPY :
1662 mode = kCGBlendModeCopy;
1663 break;
1664 case wxCLEAR :
1665 mode = kCGBlendModeClear;
1666 break;
1667 case wxXOR :
1668 mode = kCGBlendModeXOR;
1669 shouldAntiAlias = false;
1670 break;
1671 default :
1672 retval = false;
1673 break;
1674 }
1675 }
1676 else
1677 #endif
1678 {
1679 if ( function == wxCOPY )
1680 {
1681 retval = true;
1682 }
1683 else if ( function == wxINVERT || function == wxXOR )
1684 {
1685 // change color to white
1686 mode = kCGBlendModeExclusion;
1687 shouldAntiAlias = false;
1688 retval = true;
1689 }
1690 }
1691
1692 if (retval)
1693 {
1694 m_logicalFunction = function;
1695 CGContextSetBlendMode( m_cgContext, mode );
1696 CGContextSetShouldAntialias(m_cgContext, shouldAntiAlias);
1697 }
1698 return retval ;
1699 }
1700
1701 void wxMacCoreGraphicsContext::Clip( const wxRegion &region )
1702 {
1703 #if wxOSX_USE_COCOA_OR_CARBON
1704 if( m_cgContext )
1705 {
1706 wxCFRef<HIShapeRef> shape = wxCFRefFromGet(region.GetWXHRGN());
1707 // if the shape is empty, HIShapeReplacePathInCGContext doesn't work
1708 if ( HIShapeIsEmpty(shape))
1709 {
1710 CGRect empty = CGRectMake( 0,0,0,0 );
1711 CGContextClipToRect( m_cgContext, empty );
1712 }
1713 else
1714 {
1715 HIShapeReplacePathInCGContext( shape, m_cgContext );
1716 CGContextClip( m_cgContext );
1717 }
1718 }
1719 else
1720 {
1721 // this offsetting to device coords is not really correct, but since we cannot apply affine transforms
1722 // to regions we try at least to have correct translations
1723 HIMutableShapeRef mutableShape = HIShapeCreateMutableCopy( region.GetWXHRGN() );
1724
1725 CGPoint transformedOrigin = CGPointApplyAffineTransform( CGPointZero, m_windowTransform );
1726 HIShapeOffset( mutableShape, transformedOrigin.x, transformedOrigin.y );
1727 m_clipRgn.reset(mutableShape);
1728 }
1729 #else
1730 // allow usage as measuring context
1731 // wxASSERT_MSG( m_cgContext != NULL, "Needs a valid context for clipping" );
1732 #endif
1733 }
1734
1735 // clips drawings to the rect
1736 void wxMacCoreGraphicsContext::Clip( wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1737 {
1738 CGRect r = CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h );
1739 if ( m_cgContext )
1740 {
1741 CGContextClipToRect( m_cgContext, r );
1742 }
1743 else
1744 {
1745 #if wxOSX_USE_COCOA_OR_CARBON
1746 // the clipping itself must be stored as device coordinates, otherwise
1747 // we cannot apply it back correctly
1748 r.origin= CGPointApplyAffineTransform( r.origin, m_windowTransform );
1749 m_clipRgn.reset(HIShapeCreateWithRect(&r));
1750 #else
1751 // allow usage as measuring context
1752 // wxFAIL_MSG( "Needs a valid context for clipping" );
1753 #endif
1754 }
1755 }
1756
1757 // resets the clipping to original extent
1758 void wxMacCoreGraphicsContext::ResetClip()
1759 {
1760 if ( m_cgContext )
1761 {
1762 // there is no way for clearing the clip, we can only revert to the stored
1763 // state, but then we have to make sure everything else is NOT restored
1764 CGAffineTransform transform = CGContextGetCTM( m_cgContext );
1765 CGContextRestoreGState( m_cgContext );
1766 CGContextSaveGState( m_cgContext );
1767 CGAffineTransform transformNew = CGContextGetCTM( m_cgContext );
1768 transformNew = CGAffineTransformInvert( transformNew ) ;
1769 CGContextConcatCTM( m_cgContext, transformNew);
1770 CGContextConcatCTM( m_cgContext, transform);
1771 }
1772 else
1773 {
1774 #if wxOSX_USE_COCOA_OR_CARBON
1775 m_clipRgn.reset();
1776 #else
1777 // allow usage as measuring context
1778 // wxFAIL_MSG( "Needs a valid context for clipping" );
1779 #endif
1780 }
1781 }
1782
1783 void wxMacCoreGraphicsContext::StrokePath( const wxGraphicsPath &path )
1784 {
1785 if ( m_pen.IsNull() )
1786 return ;
1787
1788 if (EnsureIsValid()==false)
1789 return;
1790
1791 wxQuartzOffsetHelper helper( m_cgContext , ShouldOffset() );
1792
1793 ((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->Apply(this);
1794 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
1795 CGContextStrokePath( m_cgContext );
1796 }
1797
1798 void wxMacCoreGraphicsContext::DrawPath( const wxGraphicsPath &path , wxPolygonFillMode fillStyle )
1799 {
1800 if (EnsureIsValid()==false)
1801 return;
1802
1803 if ( !m_brush.IsNull() && ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
1804 {
1805 // when using shading, we cannot draw pen and brush at the same time
1806 // revert to the base implementation of first filling and then stroking
1807 wxGraphicsContext::DrawPath( path, fillStyle );
1808 return;
1809 }
1810
1811 CGPathDrawingMode mode = kCGPathFill ;
1812 if ( m_brush.IsNull() )
1813 {
1814 if ( m_pen.IsNull() )
1815 return;
1816 else
1817 mode = kCGPathStroke;
1818 }
1819 else
1820 {
1821 if ( m_pen.IsNull() )
1822 {
1823 if ( fillStyle == wxODDEVEN_RULE )
1824 mode = kCGPathEOFill;
1825 else
1826 mode = kCGPathFill;
1827 }
1828 else
1829 {
1830 if ( fillStyle == wxODDEVEN_RULE )
1831 mode = kCGPathEOFillStroke;
1832 else
1833 mode = kCGPathFillStroke;
1834 }
1835 }
1836
1837 if ( !m_brush.IsNull() )
1838 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
1839 if ( !m_pen.IsNull() )
1840 ((wxMacCoreGraphicsPenData*)m_pen.GetRefData())->Apply(this);
1841
1842 wxQuartzOffsetHelper helper( m_cgContext , ShouldOffset() );
1843
1844 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
1845 CGContextDrawPath( m_cgContext , mode );
1846 }
1847
1848 void wxMacCoreGraphicsContext::FillPath( const wxGraphicsPath &path , wxPolygonFillMode fillStyle )
1849 {
1850 if ( m_brush.IsNull() )
1851 return;
1852
1853 if (EnsureIsValid()==false)
1854 return;
1855
1856 if ( ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
1857 {
1858 CGContextSaveGState( m_cgContext );
1859 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
1860 CGContextClip( m_cgContext );
1861 CGContextDrawShading( m_cgContext, ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->GetShading() );
1862 CGContextRestoreGState( m_cgContext);
1863 }
1864 else
1865 {
1866 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
1867 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
1868 if ( fillStyle == wxODDEVEN_RULE )
1869 CGContextEOFillPath( m_cgContext );
1870 else
1871 CGContextFillPath( m_cgContext );
1872 }
1873 }
1874
1875 void wxMacCoreGraphicsContext::SetNativeContext( CGContextRef cg )
1876 {
1877 // we allow either setting or clearing but not replacing
1878 wxASSERT( m_cgContext == NULL || cg == NULL );
1879
1880 if ( m_cgContext )
1881 {
1882 CGContextRestoreGState( m_cgContext );
1883 CGContextRestoreGState( m_cgContext );
1884 if ( m_contextSynthesized )
1885 {
1886 // TODO: in case of performance problems, try issuing this not too
1887 // frequently (half of refresh rate)
1888 CGContextFlush(m_cgContext);
1889 #if wxOSX_USE_CARBON
1890 QDEndCGContext( GetWindowPort( m_windowRef ) , &m_cgContext);
1891 #endif
1892 #if wxOSX_USE_COCOA_OR_IPHONE
1893 wxOSXUnlockFocus(m_view);
1894 #endif
1895 }
1896 else
1897 CGContextRelease(m_cgContext);
1898 }
1899
1900 m_cgContext = cg;
1901
1902 // FIXME: This check is needed because currently we need to use a DC/GraphicsContext
1903 // in order to get font properties, like wxFont::GetPixelSize, but since we don't have
1904 // a native window attached to use, I create a wxGraphicsContext with a NULL CGContextRef
1905 // for this one operation.
1906
1907 // When wxFont::GetPixelSize on Mac no longer needs a graphics context, this check
1908 // can be removed.
1909 if (m_cgContext)
1910 {
1911 CGContextRetain(m_cgContext);
1912 CGContextSaveGState( m_cgContext );
1913 CGContextSetTextMatrix( m_cgContext, CGAffineTransformIdentity );
1914 CGContextSaveGState( m_cgContext );
1915 m_contextSynthesized = false;
1916 }
1917 }
1918
1919 void wxMacCoreGraphicsContext::Translate( wxDouble dx , wxDouble dy )
1920 {
1921 if ( m_cgContext )
1922 CGContextTranslateCTM( m_cgContext, (CGFloat) dx, (CGFloat) dy );
1923 else
1924 m_windowTransform = CGAffineTransformTranslate(m_windowTransform, (CGFloat) dx, (CGFloat) dy);
1925 }
1926
1927 void wxMacCoreGraphicsContext::Scale( wxDouble xScale , wxDouble yScale )
1928 {
1929 if ( m_cgContext )
1930 CGContextScaleCTM( m_cgContext , (CGFloat) xScale , (CGFloat) yScale );
1931 else
1932 m_windowTransform = CGAffineTransformScale(m_windowTransform, (CGFloat) xScale, (CGFloat) yScale);
1933 }
1934
1935 void wxMacCoreGraphicsContext::Rotate( wxDouble angle )
1936 {
1937 if ( m_cgContext )
1938 CGContextRotateCTM( m_cgContext , (CGFloat) angle );
1939 else
1940 m_windowTransform = CGAffineTransformRotate(m_windowTransform, (CGFloat) angle);
1941 }
1942
1943 void wxMacCoreGraphicsContext::DrawBitmap( const wxBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1944 {
1945 wxGraphicsBitmap bitmap = GetRenderer()->CreateBitmap(bmp);
1946 DrawBitmap(bitmap, x, y, w, h);
1947 }
1948
1949 void wxMacCoreGraphicsContext::DrawBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1950 {
1951 if (EnsureIsValid()==false)
1952 return;
1953
1954 #ifdef __WXMAC__
1955 wxMacCoreGraphicsBitmapData* refdata =static_cast<wxMacCoreGraphicsBitmapData*>(bmp.GetRefData());
1956 CGImageRef image = refdata->GetBitmap();
1957 CGRect r = CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h );
1958 if ( refdata->IsMonochrome() == 1 )
1959 {
1960 // is is a mask, the '1' in the mask tell where to draw the current brush
1961 if ( !m_brush.IsNull() )
1962 {
1963 if ( ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->IsShading() )
1964 {
1965 // TODO clip to mask
1966 /*
1967 CGContextSaveGState( m_cgContext );
1968 CGContextAddPath( m_cgContext , (CGPathRef) path.GetNativePath() );
1969 CGContextClip( m_cgContext );
1970 CGContextDrawShading( m_cgContext, ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->GetShading() );
1971 CGContextRestoreGState( m_cgContext);
1972 */
1973 }
1974 else
1975 {
1976 ((wxMacCoreGraphicsBrushData*)m_brush.GetRefData())->Apply(this);
1977 wxMacDrawCGImage( m_cgContext , &r , image );
1978 }
1979 }
1980 }
1981 else
1982 {
1983 wxMacDrawCGImage( m_cgContext , &r , image );
1984 }
1985 #endif
1986 }
1987
1988 void wxMacCoreGraphicsContext::DrawIcon( const wxIcon &icon, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
1989 {
1990 if (EnsureIsValid()==false)
1991 return;
1992
1993 CGRect r = CGRectMake( (CGFloat) 0.0 , (CGFloat) 0.0 , (CGFloat) w , (CGFloat) h );
1994 CGContextSaveGState( m_cgContext );
1995 CGContextTranslateCTM( m_cgContext,(CGFloat) x ,(CGFloat) (y + h) );
1996 CGContextScaleCTM( m_cgContext, 1, -1 );
1997 #if wxOSX_USE_COCOA_OR_CARBON
1998 PlotIconRefInContext( m_cgContext , &r , kAlignNone , kTransformNone ,
1999 NULL , kPlotIconRefNormalFlags , icon.GetHICON() );
2000 #endif
2001 CGContextRestoreGState( m_cgContext );
2002 }
2003
2004 void wxMacCoreGraphicsContext::PushState()
2005 {
2006 if (EnsureIsValid()==false)
2007 return;
2008
2009 CGContextSaveGState( m_cgContext );
2010 }
2011
2012 void wxMacCoreGraphicsContext::PopState()
2013 {
2014 if (EnsureIsValid()==false)
2015 return;
2016
2017 CGContextRestoreGState( m_cgContext );
2018 }
2019
2020 void wxMacCoreGraphicsContext::DoDrawText( const wxString &str, wxDouble x, wxDouble y )
2021 {
2022 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2023
2024 if (EnsureIsValid()==false)
2025 return;
2026
2027 #if wxOSX_USE_CORE_TEXT
2028 if ( UMAGetSystemVersion() >= 0x1050 )
2029 {
2030 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2031 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2032 CTFontRef font = fref->GetCTFont();
2033 CGColorRef col = wxMacCreateCGColor( fref->GetColour() );
2034 CTUnderlineStyle ustyle = fref->GetUnderlined() ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone ;
2035 wxCFRef<CFNumberRef> underlined( CFNumberCreate(NULL, kCFNumberSInt32Type, &ustyle) );
2036 CFStringRef keys[] = { kCTFontAttributeName , kCTForegroundColorAttributeName, kCTUnderlineStyleAttributeName };
2037 CFTypeRef values[] = { font, col, underlined };
2038 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2039 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2040 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, text, attributes) );
2041 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2042
2043 y += CTFontGetAscent(font);
2044
2045 CGContextSaveGState(m_cgContext);
2046 CGContextTranslateCTM(m_cgContext, x, y);
2047 CGContextScaleCTM(m_cgContext, 1, -1);
2048 CGContextSetTextPosition(m_cgContext, 0, 0);
2049 CTLineDraw( line, m_cgContext );
2050 CGContextRestoreGState(m_cgContext);
2051 CFRelease( col );
2052 return;
2053 }
2054 #endif
2055 #if wxOSX_USE_ATSU_TEXT
2056 {
2057 DrawText(str, x, y, 0.0);
2058 return;
2059 }
2060 #endif
2061 #if wxOSX_USE_IPHONE
2062 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2063
2064 CGContextSaveGState(m_cgContext);
2065
2066 CGColorRef col = wxMacCreateCGColor( fref->GetColour() );
2067 CGContextSetTextDrawingMode (m_cgContext, kCGTextFill);
2068 CGContextSetFillColorWithColor( m_cgContext, col );
2069
2070 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2071 DrawTextInContext( m_cgContext, CGPointMake( x, y ), fref->GetUIFont() , text.AsNSString() );
2072
2073 CGContextRestoreGState(m_cgContext);
2074 CFRelease( col );
2075 #endif
2076 }
2077
2078 void wxMacCoreGraphicsContext::DoDrawRotatedText(const wxString &str,
2079 wxDouble x, wxDouble y,
2080 wxDouble angle)
2081 {
2082 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2083
2084 if (EnsureIsValid()==false)
2085 return;
2086
2087 #if wxOSX_USE_CORE_TEXT
2088 if ( UMAGetSystemVersion() >= 0x1050 )
2089 {
2090 // default implementation takes care of rotation and calls non rotated DrawText afterwards
2091 wxGraphicsContext::DoDrawRotatedText( str, x, y, angle );
2092 return;
2093 }
2094 #endif
2095 #if wxOSX_USE_ATSU_TEXT
2096 {
2097 OSStatus status = noErr;
2098 ATSUTextLayout atsuLayout;
2099 wxMacUniCharBuffer unibuf( str );
2100 UniCharCount chars = unibuf.GetChars();
2101
2102 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2103 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2104 &chars , &style , &atsuLayout );
2105
2106 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the rotated text") );
2107
2108 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2109 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2110
2111 int iAngle = int( angle * RAD2DEG );
2112 if ( abs(iAngle) > 0 )
2113 {
2114 Fixed atsuAngle = IntToFixed( iAngle );
2115 ATSUAttributeTag atsuTags[] =
2116 {
2117 kATSULineRotationTag ,
2118 };
2119 ByteCount atsuSizes[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
2120 {
2121 sizeof( Fixed ) ,
2122 };
2123 ATSUAttributeValuePtr atsuValues[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
2124 {
2125 &atsuAngle ,
2126 };
2127 status = ::ATSUSetLayoutControls(atsuLayout , sizeof(atsuTags) / sizeof(ATSUAttributeTag),
2128 atsuTags, atsuSizes, atsuValues );
2129 }
2130
2131 {
2132 ATSUAttributeTag atsuTags[] =
2133 {
2134 kATSUCGContextTag ,
2135 };
2136 ByteCount atsuSizes[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
2137 {
2138 sizeof( CGContextRef ) ,
2139 };
2140 ATSUAttributeValuePtr atsuValues[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
2141 {
2142 &m_cgContext ,
2143 };
2144 status = ::ATSUSetLayoutControls(atsuLayout , sizeof(atsuTags) / sizeof(ATSUAttributeTag),
2145 atsuTags, atsuSizes, atsuValues );
2146 }
2147
2148 ATSUTextMeasurement textBefore, textAfter;
2149 ATSUTextMeasurement ascent, descent;
2150
2151 status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2152 &textBefore , &textAfter, &ascent , &descent );
2153
2154 wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
2155
2156 Rect rect;
2157 x += (int)(sin(angle) * FixedToInt(ascent));
2158 y += (int)(cos(angle) * FixedToInt(ascent));
2159
2160 status = ::ATSUMeasureTextImage( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2161 IntToFixed(x) , IntToFixed(y) , &rect );
2162 wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
2163
2164 CGContextSaveGState(m_cgContext);
2165 CGContextTranslateCTM(m_cgContext, (CGFloat) x, (CGFloat) y);
2166 CGContextScaleCTM(m_cgContext, 1, -1);
2167 status = ::ATSUDrawText( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2168 IntToFixed(0) , IntToFixed(0) );
2169
2170 wxASSERT_MSG( status == noErr , wxT("couldn't draw the rotated text") );
2171
2172 CGContextRestoreGState(m_cgContext);
2173
2174 ::ATSUDisposeTextLayout(atsuLayout);
2175
2176 return;
2177 }
2178 #endif
2179 #if wxOSX_USE_IPHONE
2180 // default implementation takes care of rotation and calls non rotated DrawText afterwards
2181 wxGraphicsContext::DoDrawRotatedText( str, x, y, angle );
2182 #endif
2183 }
2184
2185 void wxMacCoreGraphicsContext::GetTextExtent( const wxString &str, wxDouble *width, wxDouble *height,
2186 wxDouble *descent, wxDouble *externalLeading ) const
2187 {
2188 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::GetTextExtent - no valid font set") );
2189
2190 if ( width )
2191 *width = 0;
2192 if ( height )
2193 *height = 0;
2194 if ( descent )
2195 *descent = 0;
2196 if ( externalLeading )
2197 *externalLeading = 0;
2198
2199 if (str.empty())
2200 return;
2201
2202 #if wxOSX_USE_CORE_TEXT
2203 if ( UMAGetSystemVersion() >= 0x1050 )
2204 {
2205 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2206 CTFontRef font = fref->GetCTFont();
2207
2208 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2209 CFStringRef keys[] = { kCTFontAttributeName };
2210 CFTypeRef values[] = { font };
2211 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2212 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2213 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, text, attributes) );
2214 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2215
2216 CGFloat w, a, d, l;
2217
2218 w = CTLineGetTypographicBounds(line, &a, &d, &l) ;
2219
2220 if ( height )
2221 *height = a+d+l;
2222 if ( descent )
2223 *descent = d;
2224 if ( externalLeading )
2225 *externalLeading = l;
2226 if ( width )
2227 *width = w;
2228 return;
2229 }
2230 #endif
2231 #if wxOSX_USE_ATSU_TEXT
2232 {
2233 OSStatus status = noErr;
2234
2235 ATSUTextLayout atsuLayout;
2236 wxMacUniCharBuffer unibuf( str );
2237 UniCharCount chars = unibuf.GetChars();
2238
2239 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2240 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2241 &chars , &style , &atsuLayout );
2242
2243 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the text") );
2244
2245 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2246 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2247
2248 ATSUTextMeasurement textBefore, textAfter;
2249 ATSUTextMeasurement textAscent, textDescent;
2250
2251 status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
2252 &textBefore , &textAfter, &textAscent , &textDescent );
2253
2254 if ( height )
2255 *height = FixedToInt(textAscent + textDescent);
2256 if ( descent )
2257 *descent = FixedToInt(textDescent);
2258 if ( externalLeading )
2259 *externalLeading = 0;
2260 if ( width )
2261 *width = FixedToInt(textAfter - textBefore);
2262
2263 ::ATSUDisposeTextLayout(atsuLayout);
2264
2265 return;
2266 }
2267 #endif
2268 #if wxOSX_USE_IPHONE
2269 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2270
2271 wxCFStringRef text(str, wxLocale::GetSystemEncoding() );
2272 CGSize sz = MeasureTextInContext( fref->GetUIFont() , text.AsNSString() );
2273
2274 if ( height )
2275 *height = sz.height;
2276 /*
2277 if ( descent )
2278 *descent = FixedToInt(textDescent);
2279 if ( externalLeading )
2280 *externalLeading = 0;
2281 */
2282 if ( width )
2283 *width = sz.width;
2284 #endif
2285 }
2286
2287 void wxMacCoreGraphicsContext::GetPartialTextExtents(const wxString& text, wxArrayDouble& widths) const
2288 {
2289 widths.Empty();
2290 widths.Add(0, text.length());
2291
2292 wxCHECK_RET( !m_font.IsNull(), wxT("wxMacCoreGraphicsContext::DrawText - no valid font set") );
2293
2294 if (text.empty())
2295 return;
2296
2297 #if wxOSX_USE_CORE_TEXT
2298 {
2299 wxMacCoreGraphicsFontData* fref = (wxMacCoreGraphicsFontData*)m_font.GetRefData();
2300 CTFontRef font = fref->GetCTFont();
2301
2302 wxCFStringRef t(text, wxLocale::GetSystemEncoding() );
2303 CFStringRef keys[] = { kCTFontAttributeName };
2304 CFTypeRef values[] = { font };
2305 wxCFRef<CFDictionaryRef> attributes( CFDictionaryCreate(kCFAllocatorDefault, (const void**) &keys, (const void**) &values,
2306 WXSIZEOF( keys ), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) );
2307 wxCFRef<CFAttributedStringRef> attrtext( CFAttributedStringCreate(kCFAllocatorDefault, t, attributes) );
2308 wxCFRef<CTLineRef> line( CTLineCreateWithAttributedString(attrtext) );
2309
2310 int chars = text.length();
2311 for ( int pos = 0; pos < (int)chars; pos ++ )
2312 {
2313 widths[pos] = CTLineGetOffsetForStringIndex( line, pos+1 , NULL )+0.5;
2314 }
2315
2316 return;
2317 }
2318 #endif
2319 #if wxOSX_USE_ATSU_TEXT
2320 {
2321 OSStatus status = noErr;
2322 ATSUTextLayout atsuLayout;
2323 wxMacUniCharBuffer unibuf( text );
2324 UniCharCount chars = unibuf.GetChars();
2325
2326 ATSUStyle style = (((wxMacCoreGraphicsFontData*)m_font.GetRefData())->GetATSUStyle());
2327 status = ::ATSUCreateTextLayoutWithTextPtr( unibuf.GetBuffer() , 0 , chars , chars , 1 ,
2328 &chars , &style , &atsuLayout );
2329
2330 wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the text") );
2331
2332 status = ::ATSUSetTransientFontMatching( atsuLayout , true );
2333 wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
2334
2335 // new implementation from JS, keep old one just in case
2336 #if 0
2337 for ( int pos = 0; pos < (int)chars; pos ++ )
2338 {
2339 unsigned long actualNumberOfBounds = 0;
2340 ATSTrapezoid glyphBounds;
2341
2342 // We get a single bound, since the text should only require one. If it requires more, there is an issue
2343 OSStatus result;
2344 result = ATSUGetGlyphBounds( atsuLayout, 0, 0, kATSUFromTextBeginning, pos + 1,
2345 kATSUseDeviceOrigins, 1, &glyphBounds, &actualNumberOfBounds );
2346 if (result != noErr || actualNumberOfBounds != 1 )
2347 return;
2348
2349 widths[pos] = FixedToInt( glyphBounds.upperRight.x - glyphBounds.upperLeft.x );
2350 //unsigned char uch = s[i];
2351 }
2352 #else
2353 ATSLayoutRecord *layoutRecords = NULL;
2354 ItemCount glyphCount = 0;
2355
2356 // Get the glyph extents
2357 OSStatus err = ::ATSUDirectGetLayoutDataArrayPtrFromTextLayout(atsuLayout,
2358 0,
2359 kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
2360 (void **)
2361 &layoutRecords,
2362 &glyphCount);
2363 wxASSERT(glyphCount == (text.length()+1));
2364
2365 if ( err == noErr && glyphCount == (text.length()+1))
2366 {
2367 for ( int pos = 1; pos < (int)glyphCount ; pos ++ )
2368 {
2369 widths[pos-1] = FixedToInt( layoutRecords[pos].realPos );
2370 }
2371 }
2372
2373 ::ATSUDirectReleaseLayoutDataArrayPtr(NULL,
2374 kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
2375 (void **) &layoutRecords);
2376 #endif
2377 ::ATSUDisposeTextLayout(atsuLayout);
2378 }
2379 #endif
2380 #if wxOSX_USE_IPHONE
2381 // TODO core graphics text implementation here
2382 #endif
2383 }
2384
2385 void * wxMacCoreGraphicsContext::GetNativeContext()
2386 {
2387 return m_cgContext;
2388 }
2389
2390 // concatenates this transform with the current transform of this context
2391 void wxMacCoreGraphicsContext::ConcatTransform( const wxGraphicsMatrix& matrix )
2392 {
2393 if ( m_cgContext )
2394 CGContextConcatCTM( m_cgContext, *(CGAffineTransform*) matrix.GetNativeMatrix());
2395 else
2396 m_windowTransform = CGAffineTransformConcat(m_windowTransform, *(CGAffineTransform*) matrix.GetNativeMatrix());
2397 }
2398
2399 // sets the transform of this context
2400 void wxMacCoreGraphicsContext::SetTransform( const wxGraphicsMatrix& matrix )
2401 {
2402 if ( m_cgContext )
2403 {
2404 CGAffineTransform transform = CGContextGetCTM( m_cgContext );
2405 transform = CGAffineTransformInvert( transform ) ;
2406 CGContextConcatCTM( m_cgContext, transform);
2407 CGContextConcatCTM( m_cgContext, *(CGAffineTransform*) matrix.GetNativeMatrix());
2408 }
2409 else
2410 {
2411 m_windowTransform = *(CGAffineTransform*) matrix.GetNativeMatrix();
2412 }
2413 }
2414
2415 // gets the matrix of this context
2416 wxGraphicsMatrix wxMacCoreGraphicsContext::GetTransform() const
2417 {
2418 wxGraphicsMatrix m = CreateMatrix();
2419 *((CGAffineTransform*) m.GetNativeMatrix()) = ( m_cgContext == NULL ? m_windowTransform :
2420 CGContextGetCTM( m_cgContext ));
2421 return m;
2422 }
2423
2424 //
2425 // Renderer
2426 //
2427
2428 //-----------------------------------------------------------------------------
2429 // wxMacCoreGraphicsRenderer declaration
2430 //-----------------------------------------------------------------------------
2431
2432 class WXDLLIMPEXP_CORE wxMacCoreGraphicsRenderer : public wxGraphicsRenderer
2433 {
2434 public :
2435 wxMacCoreGraphicsRenderer() {}
2436
2437 virtual ~wxMacCoreGraphicsRenderer() {}
2438
2439 // Context
2440
2441 virtual wxGraphicsContext * CreateContext( const wxWindowDC& dc);
2442 virtual wxGraphicsContext * CreateContext( const wxMemoryDC& dc);
2443 #if wxUSE_PRINTING_ARCHITECTURE
2444 virtual wxGraphicsContext * CreateContext( const wxPrinterDC& dc);
2445 #endif
2446
2447 virtual wxGraphicsContext * CreateContextFromNativeContext( void * context );
2448
2449 virtual wxGraphicsContext * CreateContextFromNativeWindow( void * window );
2450
2451 virtual wxGraphicsContext * CreateContext( wxWindow* window );
2452
2453 virtual wxGraphicsContext * CreateMeasuringContext();
2454
2455 // Path
2456
2457 virtual wxGraphicsPath CreatePath();
2458
2459 // Matrix
2460
2461 virtual wxGraphicsMatrix CreateMatrix( wxDouble a=1.0, wxDouble b=0.0, wxDouble c=0.0, wxDouble d=1.0,
2462 wxDouble tx=0.0, wxDouble ty=0.0);
2463
2464
2465 virtual wxGraphicsPen CreatePen(const wxPen& pen) ;
2466
2467 virtual wxGraphicsBrush CreateBrush(const wxBrush& brush ) ;
2468
2469 // sets the brush to a linear gradient, starting at (x1,y1) with color c1 to (x2,y2) with color c2
2470 virtual wxGraphicsBrush CreateLinearGradientBrush( wxDouble x1, wxDouble y1, wxDouble x2, wxDouble y2,
2471 const wxColour&c1, const wxColour&c2) ;
2472
2473 // sets the brush to a radial gradient originating at (xo,yc) with color oColor and ends on a circle around (xc,yc)
2474 // with radius r and color cColor
2475 virtual wxGraphicsBrush CreateRadialGradientBrush( wxDouble xo, wxDouble yo, wxDouble xc, wxDouble yc, wxDouble radius,
2476 const wxColour &oColor, const wxColour &cColor) ;
2477
2478 // sets the font
2479 virtual wxGraphicsFont CreateFont( const wxFont &font , const wxColour &col = *wxBLACK ) ;
2480
2481 // create a native bitmap representation
2482 virtual wxGraphicsBitmap CreateBitmap( const wxBitmap &bitmap ) ;
2483
2484 // create a native bitmap representation
2485 virtual wxGraphicsBitmap CreateSubBitmap( const wxGraphicsBitmap &bitmap, wxDouble x, wxDouble y, wxDouble w, wxDouble h ) ;
2486 private :
2487 DECLARE_DYNAMIC_CLASS_NO_COPY(wxMacCoreGraphicsRenderer)
2488 } ;
2489
2490 //-----------------------------------------------------------------------------
2491 // wxMacCoreGraphicsRenderer implementation
2492 //-----------------------------------------------------------------------------
2493
2494 IMPLEMENT_DYNAMIC_CLASS(wxMacCoreGraphicsRenderer,wxGraphicsRenderer)
2495
2496 static wxMacCoreGraphicsRenderer gs_MacCoreGraphicsRenderer;
2497
2498 wxGraphicsRenderer* wxGraphicsRenderer::GetDefaultRenderer()
2499 {
2500 return &gs_MacCoreGraphicsRenderer;
2501 }
2502
2503 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxWindowDC& dc )
2504 {
2505 const wxDCImpl* impl = dc.GetImpl();
2506 wxWindowDCImpl *win_impl = wxDynamicCast( impl, wxWindowDCImpl );
2507 if (win_impl)
2508 {
2509 int w, h;
2510 win_impl->GetSize( &w, &h );
2511 CGContextRef cgctx = 0;
2512
2513 wxASSERT_MSG(win_impl->GetWindow(), "Invalid wxWindow in wxMacCoreGraphicsRenderer::CreateContext");
2514 if (win_impl->GetWindow())
2515 cgctx = (CGContextRef)(win_impl->GetWindow()->MacGetCGContextRef());
2516
2517 if (cgctx != 0)
2518 return new wxMacCoreGraphicsContext( this, cgctx, (wxDouble) w, (wxDouble) h );
2519 }
2520 return NULL;
2521 }
2522
2523 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxMemoryDC& dc )
2524 {
2525 #ifdef __WXMAC__
2526 const wxDCImpl* impl = dc.GetImpl();
2527 wxMemoryDCImpl *mem_impl = wxDynamicCast( impl, wxMemoryDCImpl );
2528 if (mem_impl)
2529 {
2530 int w, h;
2531 mem_impl->GetSize( &w, &h );
2532 return new wxMacCoreGraphicsContext( this,
2533 (CGContextRef)(mem_impl->GetGraphicsContext()->GetNativeContext()), (wxDouble) w, (wxDouble) h );
2534 }
2535 #endif
2536 return NULL;
2537 }
2538
2539 #if wxUSE_PRINTING_ARCHITECTURE
2540 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( const wxPrinterDC& dc )
2541 {
2542 #ifdef __WXMAC__
2543 const wxDCImpl* impl = dc.GetImpl();
2544 wxPrinterDCImpl *print_impl = wxDynamicCast( impl, wxPrinterDCImpl );
2545 if (print_impl)
2546 {
2547 int w, h;
2548 print_impl->GetSize( &w, &h );
2549 return new wxMacCoreGraphicsContext( this,
2550 (CGContextRef)(print_impl->GetGraphicsContext()->GetNativeContext()), (wxDouble) w, (wxDouble) h );
2551 }
2552 #endif
2553 return NULL;
2554 }
2555 #endif
2556
2557 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContextFromNativeContext( void * context )
2558 {
2559 return new wxMacCoreGraphicsContext(this,(CGContextRef)context);
2560 }
2561
2562 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContextFromNativeWindow( void * window )
2563 {
2564 #if wxOSX_USE_CARBON
2565 return new wxMacCoreGraphicsContext(this,(WindowRef)window);
2566 #else
2567 return NULL;
2568 #endif
2569 }
2570
2571 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateContext( wxWindow* window )
2572 {
2573 return new wxMacCoreGraphicsContext(this, window );
2574 }
2575
2576 wxGraphicsContext * wxMacCoreGraphicsRenderer::CreateMeasuringContext()
2577 {
2578 return new wxMacCoreGraphicsContext(this);
2579 }
2580
2581 // Path
2582
2583 wxGraphicsPath wxMacCoreGraphicsRenderer::CreatePath()
2584 {
2585 wxGraphicsPath m;
2586 m.SetRefData( new wxMacCoreGraphicsPathData(this));
2587 return m;
2588 }
2589
2590
2591 // Matrix
2592
2593 wxGraphicsMatrix wxMacCoreGraphicsRenderer::CreateMatrix( wxDouble a, wxDouble b, wxDouble c, wxDouble d,
2594 wxDouble tx, wxDouble ty)
2595 {
2596 wxGraphicsMatrix m;
2597 wxMacCoreGraphicsMatrixData* data = new wxMacCoreGraphicsMatrixData( this );
2598 data->Set( a,b,c,d,tx,ty ) ;
2599 m.SetRefData(data);
2600 return m;
2601 }
2602
2603 wxGraphicsPen wxMacCoreGraphicsRenderer::CreatePen(const wxPen& pen)
2604 {
2605 if ( !pen.Ok() || pen.GetStyle() == wxTRANSPARENT )
2606 return wxNullGraphicsPen;
2607 else
2608 {
2609 wxGraphicsPen p;
2610 p.SetRefData(new wxMacCoreGraphicsPenData( this, pen ));
2611 return p;
2612 }
2613 }
2614
2615 wxGraphicsBrush wxMacCoreGraphicsRenderer::CreateBrush(const wxBrush& brush )
2616 {
2617 if ( !brush.Ok() || brush.GetStyle() == wxTRANSPARENT )
2618 return wxNullGraphicsBrush;
2619 else
2620 {
2621 wxGraphicsBrush p;
2622 p.SetRefData(new wxMacCoreGraphicsBrushData( this, brush ));
2623 return p;
2624 }
2625 }
2626
2627 wxGraphicsBitmap wxMacCoreGraphicsRenderer::CreateBitmap( const wxBitmap& bmp )
2628 {
2629 if ( bmp.Ok() )
2630 {
2631 wxGraphicsBitmap p;
2632 #ifdef __WXMAC__
2633 p.SetRefData(new wxMacCoreGraphicsBitmapData( this , bmp.CreateCGImage(), bmp.GetDepth() == 1 ) );
2634 #endif
2635 return p;
2636 }
2637 else
2638 return wxNullGraphicsBitmap;
2639 }
2640
2641 wxGraphicsBitmap wxMacCoreGraphicsRenderer::CreateSubBitmap( const wxGraphicsBitmap &bmp, wxDouble x, wxDouble y, wxDouble w, wxDouble h )
2642 {
2643 wxMacCoreGraphicsBitmapData* refdata =static_cast<wxMacCoreGraphicsBitmapData*>(bmp.GetRefData());
2644 CGImageRef img = refdata->GetBitmap();
2645 if ( img )
2646 {
2647 wxGraphicsBitmap p;
2648 CGImageRef subimg = CGImageCreateWithImageInRect(img,CGRectMake( (CGFloat) x , (CGFloat) y , (CGFloat) w , (CGFloat) h ));
2649 p.SetRefData(new wxMacCoreGraphicsBitmapData( this , subimg, refdata->IsMonochrome() ) );
2650 return p;
2651 }
2652 else
2653 return wxNullGraphicsBitmap;
2654 }
2655
2656 // sets the brush to a linear gradient, starting at (x1,y1) with color c1 to (x2,y2) with color c2
2657 wxGraphicsBrush wxMacCoreGraphicsRenderer::CreateLinearGradientBrush( wxDouble x1, wxDouble y1, wxDouble x2, wxDouble y2,
2658 const wxColour&c1, const wxColour&c2)
2659 {
2660 wxGraphicsBrush p;
2661 wxMacCoreGraphicsBrushData* d = new wxMacCoreGraphicsBrushData( this );
2662 d->CreateLinearGradientBrush(x1, y1, x2, y2, c1, c2);
2663 p.SetRefData(d);
2664 return p;
2665 }
2666
2667 // sets the brush to a radial gradient originating at (xo,yc) with color oColor and ends on a circle around (xc,yc)
2668 // with radius r and color cColor
2669 wxGraphicsBrush wxMacCoreGraphicsRenderer::CreateRadialGradientBrush( wxDouble xo, wxDouble yo, wxDouble xc, wxDouble yc, wxDouble radius,
2670 const wxColour &oColor, const wxColour &cColor)
2671 {
2672 wxGraphicsBrush p;
2673 wxMacCoreGraphicsBrushData* d = new wxMacCoreGraphicsBrushData( this );
2674 d->CreateRadialGradientBrush(xo,yo,xc,yc,radius,oColor,cColor);
2675 p.SetRefData(d);
2676 return p;
2677 }
2678
2679 // sets the font
2680 wxGraphicsFont wxMacCoreGraphicsRenderer::CreateFont( const wxFont &font , const wxColour &col )
2681 {
2682 if ( font.Ok() )
2683 {
2684 wxGraphicsFont p;
2685 p.SetRefData(new wxMacCoreGraphicsFontData( this , font, col ));
2686 return p;
2687 }
2688 else
2689 return wxNullGraphicsFont;
2690 }
2691
2692 //
2693 // CoreGraphics Helper Methods
2694 //
2695
2696 // Data Providers and Consumers
2697
2698 size_t UMAPutBytesCFRefCallback( void *info, const void *bytes, size_t count )
2699 {
2700 CFMutableDataRef data = (CFMutableDataRef) info;
2701 if ( data )
2702 {
2703 CFDataAppendBytes( data, (const UInt8*) bytes, count );
2704 }
2705 return count;
2706 }
2707
2708 void wxMacReleaseCFDataProviderCallback(void *info,
2709 const void *WXUNUSED(data),
2710 size_t WXUNUSED(count))
2711 {
2712 if ( info )
2713 CFRelease( (CFDataRef) info );
2714 }
2715
2716 void wxMacReleaseCFDataConsumerCallback( void *info )
2717 {
2718 if ( info )
2719 CFRelease( (CFDataRef) info );
2720 }
2721
2722 CGDataProviderRef wxMacCGDataProviderCreateWithCFData( CFDataRef data )
2723 {
2724 if ( data == NULL )
2725 return NULL;
2726
2727 return CGDataProviderCreateWithCFData( data );
2728 }
2729
2730 CGDataConsumerRef wxMacCGDataConsumerCreateWithCFData( CFMutableDataRef data )
2731 {
2732 if ( data == NULL )
2733 return NULL;
2734
2735 return CGDataConsumerCreateWithCFData( data );
2736 }
2737
2738 void
2739 wxMacReleaseMemoryBufferProviderCallback(void *info,
2740 const void * WXUNUSED_UNLESS_DEBUG(data),
2741 size_t WXUNUSED(size))
2742 {
2743 wxMemoryBuffer* membuf = (wxMemoryBuffer*) info ;
2744
2745 wxASSERT( data == membuf->GetData() ) ;
2746
2747 delete membuf ;
2748 }
2749
2750 CGDataProviderRef wxMacCGDataProviderCreateWithMemoryBuffer( const wxMemoryBuffer& buf )
2751 {
2752 wxMemoryBuffer* b = new wxMemoryBuffer( buf );
2753 if ( b->GetDataLen() == 0 )
2754 return NULL;
2755
2756 return CGDataProviderCreateWithData( b , (const void *) b->GetData() , b->GetDataLen() ,
2757 wxMacReleaseMemoryBufferProviderCallback );
2758 }