1/////////////////////////////////////////////////////////////////////////////
2// Name:        src/mac/carbon/dccg.cpp
3// Purpose:     wxDC class
4// Author:      Stefan Csomor
5// Modified by:
6// Created:     01/02/97
7// RCS-ID:      $Id: dccg.cpp 55129 2008-08-19 04:50:45Z SC $
8// Copyright:   (c) Stefan Csomor
9// Licence:     wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12#include "wx/wxprec.h"
13
14#include "wx/dc.h"
15
16#if wxMAC_USE_CORE_GRAPHICS
17
18#ifndef WX_PRECOMP
19    #include "wx/log.h"
20    #include "wx/dcmemory.h"
21    #include "wx/region.h"
22#endif
23
24#include "wx/mac/uma.h"
25
26#ifdef __MSL__
27    #if __MSL__ >= 0x6000
28        #include "math.h"
29        // in case our functions were defined outside std, we make it known all the same
30        namespace std { }
31        using namespace std ;
32    #endif
33#endif
34
35#include "wx/mac/private.h"
36
37
38#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
39typedef float CGFloat ;
40#endif
41
42#ifndef wxMAC_USE_CORE_GRAPHICS_BLEND_MODES
43#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
44    #define wxMAC_USE_CORE_GRAPHICS_BLEND_MODES 1
45#else
46    #define wxMAC_USE_CORE_GRAPHICS_BLEND_MODES 0
47#endif
48#endif
49
50//-----------------------------------------------------------------------------
51// constants
52//-----------------------------------------------------------------------------
53
54#if !defined( __DARWIN__ ) || defined(__MWERKS__)
55#ifndef M_PI
56const double M_PI = 3.14159265358979 ;
57#endif
58#endif
59
60static const double RAD2DEG = 180.0 / M_PI;
61
62#ifndef __LP64__
63
64// TODO: update
65// The textctrl implementation still needs that (needs what?) for the non-HIView implementation
66//
67wxMacWindowClipper::wxMacWindowClipper( const wxWindow* win ) :
68    wxMacPortSaver( (GrafPtr) GetWindowPort( (WindowRef) win->MacGetTopLevelWindowRef() ) )
69{
70    m_newPort = (GrafPtr) GetWindowPort( (WindowRef) win->MacGetTopLevelWindowRef() ) ;
71    m_formerClip = NewRgn() ;
72    m_newClip = NewRgn() ;
73    GetClip( m_formerClip ) ;
74
75    if ( win )
76    {
77        // guard against half constructed objects, this just leads to a empty clip
78        if ( win->GetPeer() )
79        {
80            int x = 0 , y = 0;
81            win->MacWindowToRootWindow( &x, &y ) ;
82
83            // get area including focus rect
84            CopyRgn( (RgnHandle) ((wxWindow*)win)->MacGetVisibleRegion(true).GetWXHRGN() , m_newClip ) ;
85            if ( !EmptyRgn( m_newClip ) )
86                OffsetRgn( m_newClip , x , y ) ;
87        }
88
89        SetClip( m_newClip ) ;
90    }
91}
92
93wxMacWindowClipper::~wxMacWindowClipper()
94{
95    SetPort( m_newPort ) ;
96    SetClip( m_formerClip ) ;
97    DisposeRgn( m_newClip ) ;
98    DisposeRgn( m_formerClip ) ;
99}
100
101wxMacWindowStateSaver::wxMacWindowStateSaver( const wxWindow* win ) :
102    wxMacWindowClipper( win )
103{
104    // the port is already set at this point
105    m_newPort = (GrafPtr) GetWindowPort( (WindowRef) win->MacGetTopLevelWindowRef() ) ;
106    GetThemeDrawingState( &m_themeDrawingState ) ;
107}
108
109wxMacWindowStateSaver::~wxMacWindowStateSaver()
110{
111    SetPort( m_newPort ) ;
112    SetThemeDrawingState( m_themeDrawingState , true ) ;
113}
114
115// minimal implementation only used for appearance drawing < 10.3
116
117#ifndef wxMAC_USE_CORE_GRAPHICS
118wxMacPortSetter::wxMacPortSetter( const wxDC* dc ) :
119    m_ph( (GrafPtr) dc->m_macPort )
120{
121    wxASSERT( dc->Ok() ) ;
122    m_dc = dc ;
123
124//    dc->MacSetupPort(&m_ph) ;
125}
126
127wxMacPortSetter::~wxMacPortSetter()
128{
129//    m_dc->MacCleanupPort(&m_ph) ;
130}
131
132#endif
133
134#endif
135
136//-----------------------------------------------------------------------------
137// Local functions
138//-----------------------------------------------------------------------------
139
140static inline double DegToRad(double deg) { return (deg * M_PI) / 180.0; }
141
142//-----------------------------------------------------------------------------
143// device context implementation
144//
145// more and more of the dc functionality should be implemented by calling
146// the appropricate wxMacCGContext, but we will have to do that step by step
147// also coordinate conversions should be moved to native matrix ops
148//-----------------------------------------------------------------------------
149
150// we always stock two context states, one at entry, to be able to preserve the
151// state we were called with, the other one after changing to HI Graphics orientation
152// (this one is used for getting back clippings etc)
153
154//-----------------------------------------------------------------------------
155// wxGraphicPath implementation
156//-----------------------------------------------------------------------------
157
158#if !wxUSE_GRAPHICS_CONTEXT
159
160IMPLEMENT_ABSTRACT_CLASS(wxDC, wxObject)
161
162wxMacCGPath::wxMacCGPath()
163{
164    m_path = CGPathCreateMutable() ;
165}
166
167wxMacCGPath::~wxMacCGPath()
168{
169    CGPathRelease( m_path ) ;
170}
171
172// opens (starts) a new subpath
173void wxMacCGPath::MoveToPoint( wxCoord x1 , wxCoord y1 )
174{
175    CGPathMoveToPoint( m_path , NULL , x1 , y1 ) ;
176}
177
178void wxMacCGPath::AddLineToPoint( wxCoord x1 , wxCoord y1 )
179{
180    CGPathAddLineToPoint( m_path , NULL , x1 , y1 ) ;
181}
182
183void wxMacCGPath::AddQuadCurveToPoint( wxCoord cx1, wxCoord cy1, wxCoord x1, wxCoord y1 )
184{
185    CGPathAddQuadCurveToPoint( m_path , NULL , cx1 , cy1 , x1 , y1 );
186}
187
188void wxMacCGPath::AddRectangle( wxCoord x, wxCoord y, wxCoord w, wxCoord h )
189{
190    CGRect cgRect = { { x , y } , { w , h } } ;
191    CGPathAddRect( m_path , NULL , cgRect ) ;
192}
193
194void wxMacCGPath::AddCircle( wxCoord x, wxCoord y , wxCoord r )
195{
196    CGPathAddArc( m_path , NULL , x , y , r , 0.0 , 2 * M_PI , true ) ;
197}
198
199// closes the current subpath
200void wxMacCGPath::CloseSubpath()
201{
202    CGPathCloseSubpath( m_path ) ;
203}
204
205CGPathRef wxMacCGPath::GetPath() const
206{
207    return m_path ;
208}
209
210void wxMacCGPath::AddArcToPoint( wxCoord x1, wxCoord y1 , wxCoord x2, wxCoord y2, wxCoord r )
211{
212    CGPathAddArcToPoint( m_path, NULL , x1, y1, x2, y2, r);
213}
214
215void wxMacCGPath::AddArc( wxCoord x, wxCoord y, wxCoord r, double startAngle, double endAngle, bool clockwise )
216{
217    CGPathAddArc( m_path, NULL , x, y, r, startAngle, endAngle, clockwise);
218}
219
220//-----------------------------------------------------------------------------
221// wxGraphicContext implementation
222//-----------------------------------------------------------------------------
223
224wxMacCGContext::wxMacCGContext( CGrafPtr port )
225{
226    m_qdPort = port ;
227    m_cgContext = NULL ;
228    m_mode = kCGPathFill;
229    m_macATSUIStyle = NULL ;
230}
231
232wxMacCGContext::wxMacCGContext( CGContextRef cgcontext )
233{
234    m_qdPort = NULL ;
235    m_cgContext = cgcontext ;
236    m_mode = kCGPathFill;
237    m_macATSUIStyle = NULL ;
238    CGContextSaveGState( m_cgContext ) ;
239    CGContextSaveGState( m_cgContext ) ;
240}
241
242wxMacCGContext::wxMacCGContext()
243{
244    m_qdPort = NULL ;
245    m_cgContext = NULL ;
246    m_mode = kCGPathFill;
247    m_macATSUIStyle = NULL ;
248}
249
250wxMacCGContext::~wxMacCGContext()
251{
252    if ( m_cgContext )
253    {
254        CGContextSynchronize( m_cgContext ) ;
255        CGContextRestoreGState( m_cgContext ) ;
256        CGContextRestoreGState( m_cgContext ) ;
257    }
258#ifndef __LP64__
259    if ( m_qdPort )
260        QDEndCGContext( m_qdPort, &m_cgContext ) ;
261#endif
262}
263
264
265void wxMacCGContext::Clip( const wxRegion &region )
266{
267//    ClipCGContextToRegion ( m_cgContext, &bounds , (RgnHandle) dc->m_macCurrentClipRgn ) ;
268}
269
270void wxMacCGContext::StrokePath( const wxGraphicPath *p )
271{
272    const wxMacCGPath* path = dynamic_cast< const wxMacCGPath*>( p ) ;
273
274    int width = m_pen.GetWidth();
275    if ( width == 0 )
276        width = 1 ;
277    if ( m_pen.GetStyle() == wxTRANSPARENT )
278        width = 0 ;
279
280    bool offset = ( width % 2 ) == 1 ;
281
282    if ( offset )
283        CGContextTranslateCTM( m_cgContext, 0.5, 0.5 );
284
285    CGContextAddPath( m_cgContext , path->GetPath() ) ;
286    CGContextStrokePath( m_cgContext ) ;
287
288    if ( offset )
289        CGContextTranslateCTM( m_cgContext, -0.5, -0.5 );
290}
291
292void wxMacCGContext::DrawPath( const wxGraphicPath *p , int fillStyle )
293{
294    const wxMacCGPath* path = dynamic_cast< const wxMacCGPath*>( p ) ;
295    CGPathDrawingMode mode = m_mode ;
296
297    if ( fillStyle == wxODDEVEN_RULE )
298    {
299        if ( mode == kCGPathFill )
300            mode = kCGPathEOFill ;
301        else if ( mode == kCGPathFillStroke )
302            mode = kCGPathEOFillStroke ;
303    }
304
305    int width = m_pen.GetWidth();
306    if ( width == 0 )
307        width = 1 ;
308    if ( m_pen.GetStyle() == wxTRANSPARENT )
309        width = 0 ;
310
311    bool offset = ( width % 2 ) == 1 ;
312
313    if ( offset )
314        CGContextTranslateCTM( m_cgContext, 0.5, 0.5 );
315
316    CGContextAddPath( m_cgContext , path->GetPath() ) ;
317    CGContextDrawPath( m_cgContext , mode ) ;
318
319    if ( offset )
320        CGContextTranslateCTM( m_cgContext, -0.5, -0.5 );
321}
322
323void wxMacCGContext::FillPath( const wxGraphicPath *p , const wxColor &fillColor , int fillStyle )
324{
325    const wxMacCGPath* path = dynamic_cast< const wxMacCGPath*>( p ) ;
326    CGContextSaveGState( m_cgContext ) ;
327
328    RGBColor col = MAC_WXCOLORREF( fillColor.GetPixel() ) ;
329    CGContextSetRGBFillColor( m_cgContext , col.red / 65536.0 , col.green / 65536.0 , col.blue / 65536.0 , 1.0 ) ;
330    CGPathDrawingMode mode = kCGPathFill ;
331
332    if ( fillStyle == wxODDEVEN_RULE )
333        mode = kCGPathEOFill ;
334
335    CGContextBeginPath( m_cgContext ) ;
336    CGContextAddPath( m_cgContext , path->GetPath() ) ;
337    CGContextClosePath( m_cgContext ) ;
338    CGContextDrawPath( m_cgContext , mode ) ;
339
340    CGContextRestoreGState( m_cgContext ) ;
341}
342
343wxGraphicPath* wxMacCGContext::CreatePath()
344{
345    // make sure that we now have a real cgref, before doing
346    // anything with paths
347    CGContextRef cg = GetNativeContext() ;
348    cg = NULL ;
349
350    return new wxMacCGPath() ;
351}
352
353// in case we only got a QDPort only create a cgref now
354
355CGContextRef wxMacCGContext::GetNativeContext()
356{
357    if ( m_cgContext == NULL )
358    {
359        Rect bounds ;
360        OSStatus status = noErr;
361#ifndef __LP64__
362        GetPortBounds( (CGrafPtr) m_qdPort , &bounds ) ;
363        status = QDBeginCGContext((CGrafPtr) m_qdPort , &m_cgContext) ;
364#endif
365        CGContextSaveGState( m_cgContext ) ;
366
367        wxASSERT_MSG( status == noErr , wxT("Cannot nest wxDCs on the same window") ) ;
368
369        CGContextTranslateCTM( m_cgContext , 0 , bounds.bottom - bounds.top ) ;
370        CGContextScaleCTM( m_cgContext , 1 , -1 ) ;
371
372        CGContextSaveGState( m_cgContext ) ;
373        SetPen( m_pen ) ;
374        SetBrush( m_brush ) ;
375    }
376
377    return m_cgContext ;
378}
379
380void wxMacCGContext::SetNativeContext( CGContextRef cg )
381{
382    // we allow either setting or clearing but not replacing
383    wxASSERT( m_cgContext == NULL || cg == NULL ) ;
384
385    if ( cg )
386        CGContextSaveGState( cg ) ;
387    m_cgContext = cg ;
388}
389
390void wxMacCGContext::Translate( wxCoord dx , wxCoord dy )
391{
392    CGContextTranslateCTM( m_cgContext, dx, dy );
393}
394
395void wxMacCGContext::Scale( wxCoord xScale , wxCoord yScale )
396{
397    CGContextScaleCTM( m_cgContext , xScale , yScale ) ;
398}
399
400void wxMacCGContext::DrawBitmap( const wxBitmap &bmp, wxCoord x, wxCoord y, wxCoord w, wxCoord h )
401{
402    CGImageRef image = (CGImageRef)( bmp.CGImageCreate() ) ;
403    HIRect r = CGRectMake( 0 , 0 , w , h );
404
405    CGContextSaveGState( m_cgContext );
406    CGContextTranslateCTM( m_cgContext, x , y + h );
407    CGContextScaleCTM( m_cgContext, 1, -1 );
408
409    // in case image is a mask, set the foreground color
410    CGContextSetRGBFillColor( m_cgContext , m_textForegroundColor.Red() / 255.0 , m_textForegroundColor.Green() / 255.0 ,
411        m_textForegroundColor.Blue() / 255.0 , m_textForegroundColor.Alpha() / 255.0 ) ;
412    CGContextDrawImage( m_cgContext, r, image );
413    CGContextRestoreGState( m_cgContext );
414
415    CGImageRelease( image ) ;
416}
417
418void wxMacCGContext::DrawIcon( const wxIcon &icon, wxCoord x, wxCoord y, wxCoord w, wxCoord h )
419{
420    CGRect r = CGRectMake( 0 , 0 , w , h ) ;
421    CGContextSaveGState( m_cgContext );
422    CGContextTranslateCTM( m_cgContext, x , y + h );
423    CGContextScaleCTM( m_cgContext, 1, -1 );
424    PlotIconRefInContext( m_cgContext , &r , kAlignNone , kTransformNone ,
425        NULL , kPlotIconRefNormalFlags , MAC_WXHICON( icon.GetHICON() ) ) ;
426    CGContextRestoreGState( m_cgContext ) ;
427}
428
429void wxMacCGContext::PushState()
430{
431    CGContextSaveGState( m_cgContext );
432}
433
434void wxMacCGContext::PopState()
435{
436    CGContextRestoreGState( m_cgContext );
437}
438
439void wxMacCGContext::SetTextColor( const wxColour &col )
440{
441    m_textForegroundColor = col ;
442}
443
444#pragma mark -
445#pragma mark wxMacCGPattern, ImagePattern, HatchPattern classes
446
447// CGPattern wrapper class: always allocate on heap, never call destructor
448
449class wxMacCGPattern
450{
451public :
452    wxMacCGPattern() {}
453
454    // is guaranteed to be called only with a non-Null CGContextRef
455    virtual void Render( CGContextRef ctxRef ) = 0 ;
456
457    operator CGPatternRef() const { return m_patternRef ; }
458
459protected :
460    virtual ~wxMacCGPattern()
461    {
462        // as this is called only when the m_patternRef is been released;
463        // don't release it again
464    }
465
466    static void _Render( void *info, CGContextRef ctxRef )
467    {
468        wxMacCGPattern* self = (wxMacCGPattern*) info ;
469        if ( self && ctxRef )
470            self->Render( ctxRef ) ;
471    }
472
473    static void _Dispose( void *info )
474    {
475        wxMacCGPattern* self = (wxMacCGPattern*) info ;
476        delete self ;
477    }
478
479    CGPatternRef m_patternRef ;
480
481    static const CGPatternCallbacks ms_Callbacks ;
482} ;
483
484const CGPatternCallbacks wxMacCGPattern::ms_Callbacks = { 0, &wxMacCGPattern::_Render, &wxMacCGPattern::_Dispose };
485
486class ImagePattern : public wxMacCGPattern
487{
488public :
489    ImagePattern( const wxBitmap* bmp , const CGAffineTransform& transform )
490    {
491        wxASSERT( bmp && bmp->Ok() ) ;
492
493        Init( (CGImageRef) bmp->CGImageCreate() , transform ) ;
494    }
495
496    // ImagePattern takes ownership of CGImageRef passed in
497    ImagePattern( CGImageRef image , const CGAffineTransform& transform )
498    {
499        if ( image )
500            CFRetain( image ) ;
501
502        Init( image , transform ) ;
503    }
504
505    virtual void Render( CGContextRef ctxRef )
506    {
507        if (m_image != NULL)
508            HIViewDrawCGImage( ctxRef, &m_imageBounds, m_image );
509    }
510
511protected :
512    void Init( CGImageRef image, const CGAffineTransform& transform )
513    {
514        m_image = image ;
515        if ( m_image )
516        {
517            m_imageBounds = CGRectMake( 0.0, 0.0, (CGFloat)CGImageGetWidth( m_image ), (CGFloat)CGImageGetHeight( m_image ) ) ;
518            m_patternRef = CGPatternCreate(
519                this , m_imageBounds, transform ,
520                m_imageBounds.size.width, m_imageBounds.size.height,
521                kCGPatternTilingNoDistortion, true , &wxMacCGPattern::ms_Callbacks ) ;
522        }
523    }
524
525    virtual ~ImagePattern()
526    {
527        if ( m_image )
528            CGImageRelease( m_image ) ;
529    }
530
531    CGImageRef m_image ;
532    CGRect m_imageBounds ;
533} ;
534
535class HatchPattern : public wxMacCGPattern
536{
537public :
538    HatchPattern( int hatchstyle, const CGAffineTransform& transform )
539    {
540        m_hatch = hatchstyle ;
541        m_imageBounds = CGRectMake( 0.0, 0.0, 8.0 , 8.0 ) ;
542        m_patternRef = CGPatternCreate(
543            this , m_imageBounds, transform ,
544            m_imageBounds.size.width, m_imageBounds.size.height,
545            kCGPatternTilingNoDistortion, false , &wxMacCGPattern::ms_Callbacks ) ;
546    }
547
548    void StrokeLineSegments( CGContextRef ctxRef , const CGPoint pts[] , size_t count )
549    {
550#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
551        if ( UMAGetSystemVersion() >= 0x1040 )
552        {
553            CGContextStrokeLineSegments( ctxRef , pts , count ) ;
554        }
555        else
556#endif
557        {
558            CGContextBeginPath( ctxRef );
559            for (size_t i = 0; i < count; i += 2)
560            {
561                CGContextMoveToPoint(ctxRef, pts[i].x, pts[i].y);
562                CGContextAddLineToPoint(ctxRef, pts[i+1].x, pts[i+1].y);
563            }
564            CGContextStrokePath(ctxRef);
565        }
566    }
567
568    virtual void Render( CGContextRef ctxRef )
569    {
570        switch ( m_hatch )
571        {
572            case wxBDIAGONAL_HATCH :
573                {
574                    CGPoint pts[] =
575                    {
576                    { 8.0 , 0.0 } , { 0.0 , 8.0 }
577                    };
578                    StrokeLineSegments( ctxRef , pts , 2 ) ;
579                }
580                break ;
581
582            case wxCROSSDIAG_HATCH :
583                {
584                    CGPoint pts[] =
585                    {
586                        { 0.0 , 0.0 } , { 8.0 , 8.0 } ,
587                        { 8.0 , 0.0 } , { 0.0 , 8.0 }
588                    };
589                    StrokeLineSegments( ctxRef , pts , 4 ) ;
590                }
591                break ;
592
593            case wxFDIAGONAL_HATCH :
594                {
595                    CGPoint pts[] =
596                    {
597                    { 0.0 , 0.0 } , { 8.0 , 8.0 }
598                    };
599                    StrokeLineSegments( ctxRef , pts , 2 ) ;
600                }
601                break ;
602
603            case wxCROSS_HATCH :
604                {
605                    CGPoint pts[] =
606                    {
607                    { 0.0 , 4.0 } , { 8.0 , 4.0 } ,
608                    { 4.0 , 0.0 } , { 4.0 , 8.0 } ,
609                    };
610                    StrokeLineSegments( ctxRef , pts , 4 ) ;
611                }
612                break ;
613
614            case wxHORIZONTAL_HATCH :
615                {
616                    CGPoint pts[] =
617                    {
618                    { 0.0 , 4.0 } , { 8.0 , 4.0 } ,
619                    };
620                    StrokeLineSegments( ctxRef , pts , 2 ) ;
621                }
622                break ;
623
624            case wxVERTICAL_HATCH :
625                {
626                    CGPoint pts[] =
627                    {
628                    { 4.0 , 0.0 } , { 4.0 , 8.0 } ,
629                    };
630                    StrokeLineSegments( ctxRef , pts , 2 ) ;
631                }
632                break ;
633
634            default:
635                break;
636        }
637    }
638
639protected :
640    virtual ~HatchPattern() {}
641
642    CGRect      m_imageBounds ;
643    int         m_hatch ;
644};
645
646#pragma mark -
647
648void wxMacCGContext::SetPen( const wxPen &pen )
649{
650    m_pen = pen ;
651    if ( m_cgContext == NULL )
652        return ;
653
654    bool fill = m_brush.GetStyle() != wxTRANSPARENT ;
655    bool stroke = pen.GetStyle() != wxTRANSPARENT ;
656
657#if 0
658    // we can benchmark performance; should go into a setting eventually
659    CGContextSetShouldAntialias( m_cgContext , false ) ;
660#endif
661
662    if ( fill || stroke )
663    {
664        // set up brushes
665        m_mode = kCGPathFill ; // just a default
666
667        if ( stroke )
668        {
669            CGContextSetRGBStrokeColor( m_cgContext , pen.GetColour().Red() / 255.0 , pen.GetColour().Green() / 255.0 ,
670                    pen.GetColour().Blue() / 255.0 , pen.GetColour().Alpha() / 255.0 ) ;
671
672            // TODO: * m_dc->m_scaleX
673            CGFloat penWidth = pen.GetWidth();
674            if (penWidth <= 0.0)
675                penWidth = 0.1;
676            CGContextSetLineWidth( m_cgContext , penWidth ) ;
677
678            CGLineCap cap ;
679            switch ( pen.GetCap() )
680            {
681                case wxCAP_ROUND :
682                    cap = kCGLineCapRound ;
683                    break ;
684
685                case wxCAP_PROJECTING :
686                    cap = kCGLineCapSquare ;
687                    break ;
688
689                case wxCAP_BUTT :
690                    cap = kCGLineCapButt ;
691                    break ;
692
693                default :
694                    cap = kCGLineCapButt ;
695                    break ;
696            }
697
698            CGLineJoin join ;
699            switch ( pen.GetJoin() )
700            {
701                case wxJOIN_BEVEL :
702                    join = kCGLineJoinBevel ;
703                    break ;
704
705                case wxJOIN_MITER :
706                    join = kCGLineJoinMiter ;
707                    break ;
708
709                case wxJOIN_ROUND :
710                    join = kCGLineJoinRound ;
711                    break ;
712
713                default :
714                    join = kCGLineJoinMiter ;
715                    break;
716            }
717
718            m_mode = kCGPathStroke ;
719            int count = 0 ;
720
721            const CGFloat *lengths = NULL ;
722            CGFloat *userLengths = NULL ;
723
724            const CGFloat dashUnit = penWidth < 1.0 ? 1.0 : penWidth;
725
726            const CGFloat dotted[] = { dashUnit , dashUnit + 2.0 };
727            const CGFloat short_dashed[] = { 9.0 , 6.0 };
728            const CGFloat dashed[] = { 19.0 , 9.0 };
729            const CGFloat dotted_dashed[] = { 9.0 , 6.0 , 3.0 , 3.0 };
730
731            switch ( pen.GetStyle() )
732            {
733                case wxSOLID :
734                    break ;
735
736                case wxDOT :
737                    lengths = dotted ;
738                    count = WXSIZEOF(dotted);
739                    break ;
740
741                case wxLONG_DASH :
742                    lengths = dashed ;
743                    count = WXSIZEOF(dashed) ;
744                    break ;
745
746                case wxSHORT_DASH :
747                    lengths = short_dashed ;
748                    count = WXSIZEOF(short_dashed) ;
749                    break ;
750
751                case wxDOT_DASH :
752                    lengths = dotted_dashed ;
753                    count = WXSIZEOF(dotted_dashed);
754                    break ;
755
756                case wxUSER_DASH :
757                    wxDash *dashes ;
758                    count = pen.GetDashes( &dashes ) ;
759                    if ((dashes != NULL) && (count > 0))
760                    {
761                        userLengths = new CGFloat[count] ;
762                        for ( int i = 0 ; i < count ; ++i )
763                        {
764                            userLengths[i] = dashes[i] * dashUnit ;
765
766                            if ( i % 2 == 1 && userLengths[i] < dashUnit + 2.0 )
767                                userLengths[i] = dashUnit + 2.0 ;
768                            else if ( i % 2 == 0 && userLengths[i] < dashUnit )
769                                userLengths[i] = dashUnit ;
770                        }
771                    }
772                    lengths = userLengths ;
773                    break ;
774
775                case wxSTIPPLE :
776                    {
777                        CGFloat  alphaArray[1] = { 1.0 } ;
778                        wxBitmap* bmp = pen.GetStipple() ;
779                        if ( bmp && bmp->Ok() )
780                        {
781                            wxMacCFRefHolder<CGColorSpaceRef> patternSpace( CGColorSpaceCreatePattern( NULL ) ) ;
782                            CGContextSetStrokeColorSpace( m_cgContext , patternSpace ) ;
783                            wxMacCFRefHolder<CGPatternRef> pattern( *( new ImagePattern( bmp , CGContextGetCTM( m_cgContext ) ) ) );
784                            CGContextSetStrokePattern( m_cgContext, pattern , alphaArray ) ;
785                        }
786                    }
787                    break ;
788
789                default :
790                    {
791                        wxMacCFRefHolder<CGColorSpaceRef> patternSpace( CGColorSpaceCreatePattern( wxMacGetGenericRGBColorSpace() ) ) ;
792                        CGContextSetStrokeColorSpace( m_cgContext , patternSpace ) ;
793                        wxMacCFRefHolder<CGPatternRef> pattern( *( new HatchPattern( pen.GetStyle() , CGContextGetCTM( m_cgContext ) ) ) );
794
795                        CGFloat  colorArray[4] = { pen.GetColour().Red() / 255.0 , pen.GetColour().Green() / 255.0 ,
796                            pen.GetColour().Blue() / 255.0 , pen.GetColour().Alpha() / 255.0 } ;
797
798                        CGContextSetStrokePattern( m_cgContext, pattern , colorArray ) ;
799                    }
800                    break ;
801            }
802
803            if ((lengths != NULL) && (count > 0))
804            {
805                CGContextSetLineDash( m_cgContext , 0 , lengths , count ) ;
806                // force the line cap, otherwise we get artifacts (overlaps) and just solid lines
807                cap = kCGLineCapButt ;
808            }
809            else
810            {
811               CGContextSetLineDash( m_cgContext , 0 , NULL , 0 ) ;
812            }
813
814            CGContextSetLineCap( m_cgContext , cap ) ;
815            CGContextSetLineJoin( m_cgContext , join ) ;
816
817            delete[] userLengths ;
818        }
819
820        if ( fill && stroke )
821            m_mode = kCGPathFillStroke ;
822    }
823}
824
825void wxMacCGContext::SetBrush( const wxBrush &brush )
826{
827    m_brush = brush ;
828    if ( m_cgContext == NULL )
829        return ;
830
831    bool fill = brush.GetStyle() != wxTRANSPARENT ;
832    bool stroke = m_pen.GetStyle() != wxTRANSPARENT ;
833
834#if 0
835    // we can benchmark performance, should go into a setting later
836    CGContextSetShouldAntialias( m_cgContext , false ) ;
837#endif
838
839    if ( fill || stroke )
840    {
841        // setup brushes
842        m_mode = kCGPathFill ; // just a default
843
844        if ( fill )
845        {
846            if ( brush.GetStyle() == wxSOLID )
847            {
848                CGContextSetRGBFillColor( m_cgContext , brush.GetColour().Red() / 255.0 , brush.GetColour().Green() / 255.0 ,
849                    brush.GetColour().Blue() / 255.0 , brush.GetColour().Alpha() / 255.0 ) ;
850            }
851            else if ( brush.IsHatch() )
852            {
853                wxMacCFRefHolder<CGColorSpaceRef> patternSpace( CGColorSpaceCreatePattern( wxMacGetGenericRGBColorSpace() ) ) ;
854                CGContextSetFillColorSpace( m_cgContext , patternSpace ) ;
855                wxMacCFRefHolder<CGPatternRef> pattern( *( new HatchPattern( brush.GetStyle() , CGContextGetCTM( m_cgContext ) ) ) );
856
857                CGFloat  colorArray[4] = { brush.GetColour().Red() / 255.0 , brush.GetColour().Green() / 255.0 ,
858                    brush.GetColour().Blue() / 255.0 , brush.GetColour().Alpha() / 255.0 } ;
859
860                CGContextSetFillPattern( m_cgContext, pattern , colorArray ) ;
861            }
862            else
863            {
864                // now brush is a bitmap
865                CGFloat  alphaArray[1] = { 1.0 } ;
866                wxBitmap* bmp = brush.GetStipple() ;
867                if ( bmp && bmp->Ok() )
868                {
869                    wxMacCFRefHolder<CGColorSpaceRef> patternSpace( CGColorSpaceCreatePattern( NULL ) ) ;
870                    CGContextSetFillColorSpace( m_cgContext , patternSpace ) ;
871                    wxMacCFRefHolder<CGPatternRef> pattern( *( new ImagePattern( bmp , CGContextGetCTM( m_cgContext ) ) ) );
872                    CGContextSetFillPattern( m_cgContext, pattern , alphaArray ) ;
873                }
874            }
875
876            m_mode = kCGPathFill ;
877        }
878
879        if ( fill && stroke )
880            m_mode = kCGPathFillStroke ;
881        else if ( stroke )
882            m_mode = kCGPathStroke ;
883    }
884}
885
886void wxMacCGContext::DrawText( const wxString &str, wxCoord x, wxCoord y, double angle )
887{
888    OSStatus status = noErr ;
889    ATSUTextLayout atsuLayout ;
890    UniCharCount chars = str.length() ;
891    UniChar* ubuf = NULL ;
892
893#if SIZEOF_WCHAR_T == 4
894    wxMBConvUTF16 converter ;
895#if wxUSE_UNICODE
896    size_t unicharlen = converter.WC2MB( NULL , str.wc_str() , 0 ) ;
897    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
898    converter.WC2MB( (char*) ubuf , str.wc_str(), unicharlen + 2 ) ;
899#else
900    const wxWCharBuffer wchar = str.wc_str( wxConvLocal ) ;
901    size_t unicharlen = converter.WC2MB( NULL , wchar.data() , 0 ) ;
902    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
903    converter.WC2MB( (char*) ubuf , wchar.data() , unicharlen + 2 ) ;
904#endif
905    chars = unicharlen / 2 ;
906#else
907#if wxUSE_UNICODE
908    ubuf = (UniChar*) str.wc_str() ;
909#else
910    wxWCharBuffer wchar = str.wc_str( wxConvLocal ) ;
911    chars = wxWcslen( wchar.data() ) ;
912    ubuf = (UniChar*) wchar.data() ;
913#endif
914#endif
915
916    status = ::ATSUCreateTextLayoutWithTextPtr( (UniCharArrayPtr) ubuf , 0 , chars , chars , 1 ,
917        &chars , (ATSUStyle*) &m_macATSUIStyle , &atsuLayout ) ;
918
919    wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the rotated text") );
920
921    status = ::ATSUSetTransientFontMatching( atsuLayout , true ) ;
922    wxASSERT_MSG( status == noErr , wxT("couldn't setup transient font matching") );
923
924    int iAngle = int( angle );
925    if ( abs(iAngle) > 0 )
926    {
927        Fixed atsuAngle = IntToFixed( iAngle ) ;
928        ATSUAttributeTag atsuTags[] =
929        {
930            kATSULineRotationTag ,
931        } ;
932        ByteCount atsuSizes[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
933        {
934            sizeof( Fixed ) ,
935        } ;
936        ATSUAttributeValuePtr    atsuValues[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
937        {
938            &atsuAngle ,
939        } ;
940        status = ::ATSUSetLayoutControls(atsuLayout , sizeof(atsuTags) / sizeof(ATSUAttributeTag),
941            atsuTags, atsuSizes, atsuValues ) ;
942    }
943
944    {
945        ATSUAttributeTag atsuTags[] =
946        {
947            kATSUCGContextTag ,
948        } ;
949        ByteCount atsuSizes[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
950        {
951            sizeof( CGContextRef ) ,
952        } ;
953        ATSUAttributeValuePtr    atsuValues[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
954        {
955            &m_cgContext ,
956        } ;
957        status = ::ATSUSetLayoutControls(atsuLayout , sizeof(atsuTags) / sizeof(ATSUAttributeTag),
958            atsuTags, atsuSizes, atsuValues ) ;
959    }
960
961    ATSUTextMeasurement textBefore, textAfter ;
962    ATSUTextMeasurement ascent, descent ;
963
964    status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
965        &textBefore , &textAfter, &ascent , &descent );
966
967    wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
968
969    Rect rect ;
970/*
971    // TODO
972    if ( m_backgroundMode == wxSOLID )
973    {
974        wxGraphicPath* path = m_graphicContext->CreatePath() ;
975        path->MoveToPoint( drawX , drawY ) ;
976        path->AddLineToPoint(
977            (int) (drawX + sin(angle / RAD2DEG) * FixedToInt(ascent + descent)) ,
978            (int) (drawY + cos(angle / RAD2DEG) * FixedToInt(ascent + descent)) ) ;
979        path->AddLineToPoint(
980            (int) (drawX + sin(angle / RAD2DEG) * FixedToInt(ascent + descent ) + cos(angle / RAD2DEG) * FixedToInt(textAfter)) ,
981            (int) (drawY + cos(angle / RAD2DEG) * FixedToInt(ascent + descent) - sin(angle / RAD2DEG) * FixedToInt(textAfter)) ) ;
982        path->AddLineToPoint(
983            (int) (drawX + cos(angle / RAD2DEG) * FixedToInt(textAfter)) ,
984            (int) (drawY - sin(angle / RAD2DEG) * FixedToInt(textAfter)) ) ;
985
986        m_graphicContext->FillPath( path , m_textBackgroundColour ) ;
987        delete path ;
988    }
989*/
990    x += (int)(sin(angle / RAD2DEG) * FixedToInt(ascent));
991    y += (int)(cos(angle / RAD2DEG) * FixedToInt(ascent));
992
993    status = ::ATSUMeasureTextImage( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
994        IntToFixed(x) , IntToFixed(y) , &rect );
995    wxASSERT_MSG( status == noErr , wxT("couldn't measure the rotated text") );
996
997    CGContextSaveGState(m_cgContext);
998    CGContextTranslateCTM(m_cgContext, x, y);
999    CGContextScaleCTM(m_cgContext, 1, -1);
1000    status = ::ATSUDrawText( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
1001        IntToFixed(0) , IntToFixed(0) );
1002
1003    wxASSERT_MSG( status == noErr , wxT("couldn't draw the rotated text") );
1004
1005    CGContextRestoreGState(m_cgContext) ;
1006
1007    ::ATSUDisposeTextLayout(atsuLayout);
1008
1009#if SIZEOF_WCHAR_T == 4
1010    free( ubuf ) ;
1011#endif
1012}
1013
1014void wxMacCGContext::GetTextExtent( const wxString &str, wxCoord *width, wxCoord *height,
1015                            wxCoord *descent, wxCoord *externalLeading ) const
1016{
1017    wxCHECK_RET( m_macATSUIStyle != NULL, wxT("wxDC(cg)::DoGetTextExtent - no valid font set") ) ;
1018
1019    OSStatus status = noErr ;
1020
1021    ATSUTextLayout atsuLayout ;
1022    UniCharCount chars = str.length() ;
1023    UniChar* ubuf = NULL ;
1024
1025#if SIZEOF_WCHAR_T == 4
1026    wxMBConvUTF16 converter ;
1027#if wxUSE_UNICODE
1028    size_t unicharlen = converter.WC2MB( NULL , str.wc_str() , 0 ) ;
1029    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
1030    converter.WC2MB( (char*) ubuf , str.wc_str(), unicharlen + 2 ) ;
1031#else
1032    const wxWCharBuffer wchar = str.wc_str( wxConvLocal ) ;
1033    size_t unicharlen = converter.WC2MB( NULL , wchar.data() , 0 ) ;
1034    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
1035    converter.WC2MB( (char*) ubuf , wchar.data() , unicharlen + 2 ) ;
1036#endif
1037    chars = unicharlen / 2 ;
1038#else
1039#if wxUSE_UNICODE
1040    ubuf = (UniChar*) str.wc_str() ;
1041#else
1042    wxWCharBuffer wchar = str.wc_str( wxConvLocal ) ;
1043    chars = wxWcslen( wchar.data() ) ;
1044    ubuf = (UniChar*) wchar.data() ;
1045#endif
1046#endif
1047
1048    status = ::ATSUCreateTextLayoutWithTextPtr( (UniCharArrayPtr) ubuf , 0 , chars , chars , 1 ,
1049        &chars , (ATSUStyle*) &m_macATSUIStyle , &atsuLayout ) ;
1050
1051    wxASSERT_MSG( status == noErr , wxT("couldn't create the layout of the text") );
1052
1053    ATSUTextMeasurement textBefore, textAfter ;
1054    ATSUTextMeasurement textAscent, textDescent ;
1055
1056    status = ::ATSUGetUnjustifiedBounds( atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd,
1057        &textBefore , &textAfter, &textAscent , &textDescent );
1058
1059    if ( height )
1060        *height = FixedToInt(textAscent + textDescent) ;
1061    if ( descent )
1062        *descent = FixedToInt(textDescent) ;
1063    if ( externalLeading )
1064        *externalLeading = 0 ;
1065    if ( width )
1066        *width = FixedToInt(textAfter - textBefore) ;
1067
1068    ::ATSUDisposeTextLayout(atsuLayout);
1069#if SIZEOF_WCHAR_T == 4
1070    free( ubuf ) ;
1071#endif
1072}
1073
1074void wxMacCGContext::GetPartialTextExtents(const wxString& text, wxArrayInt& widths) const
1075{
1076    widths.Empty();
1077    widths.Add(0, text.length());
1078
1079    if (text.empty())
1080        return ;
1081
1082    ATSUTextLayout atsuLayout ;
1083    UniCharCount chars = text.length() ;
1084    UniChar* ubuf = NULL ;
1085
1086#if SIZEOF_WCHAR_T == 4
1087    wxMBConvUTF16 converter ;
1088#if wxUSE_UNICODE
1089    size_t unicharlen = converter.WC2MB( NULL , text.wc_str() , 0 ) ;
1090    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
1091    converter.WC2MB( (char*) ubuf , text.wc_str(), unicharlen + 2 ) ;
1092#else
1093    const wxWCharBuffer wchar = text.wc_str( wxConvLocal ) ;
1094    size_t unicharlen = converter.WC2MB( NULL , wchar.data() , 0 ) ;
1095    ubuf = (UniChar*) malloc( unicharlen + 2 ) ;
1096    converter.WC2MB( (char*) ubuf , wchar.data() , unicharlen + 2 ) ;
1097#endif
1098    chars = unicharlen / 2 ;
1099#else
1100#if wxUSE_UNICODE
1101    ubuf = (UniChar*) text.wc_str() ;
1102#else
1103    wxWCharBuffer wchar = text.wc_str( wxConvLocal ) ;
1104    chars = wxWcslen( wchar.data() ) ;
1105    ubuf = (UniChar*) wchar.data() ;
1106#endif
1107#endif
1108
1109    ::ATSUCreateTextLayoutWithTextPtr( (UniCharArrayPtr) ubuf , 0 , chars , chars , 1 ,
1110        &chars , (ATSUStyle*) &m_macATSUIStyle , &atsuLayout ) ;
1111
1112    for ( int pos = 0; pos < (int)chars; pos ++ )
1113    {
1114        unsigned long actualNumberOfBounds = 0;
1115        ATSTrapezoid glyphBounds;
1116
1117        // We get a single bound, since the text should only require one. If it requires more, there is an issue
1118        OSStatus result;
1119        result = ATSUGetGlyphBounds( atsuLayout, 0, 0, kATSUFromTextBeginning, pos + 1,
1120            kATSUseDeviceOrigins, 1, &glyphBounds, &actualNumberOfBounds );
1121        if (result != noErr || actualNumberOfBounds != 1 )
1122            return ;
1123
1124        widths[pos] = FixedToInt( glyphBounds.upperRight.x - glyphBounds.upperLeft.x );
1125        //unsigned char uch = s[i];
1126    }
1127
1128    ::ATSUDisposeTextLayout(atsuLayout);
1129#if SIZEOF_WCHAR_T == 4
1130    free( ubuf ) ;
1131#endif
1132}
1133
1134void wxMacCGContext::SetFont( const wxFont &font )
1135{
1136    if ( m_macATSUIStyle )
1137    {
1138        ::ATSUDisposeStyle((ATSUStyle)m_macATSUIStyle);
1139        m_macATSUIStyle = NULL ;
1140    }
1141
1142    if ( font.Ok() )
1143    {
1144        OSStatus status ;
1145
1146        status = ATSUCreateAndCopyStyle( (ATSUStyle) font.MacGetATSUStyle() , (ATSUStyle*) &m_macATSUIStyle ) ;
1147
1148        wxASSERT_MSG( status == noErr, wxT("couldn't create ATSU style") ) ;
1149
1150        // we need the scale here ...
1151
1152        Fixed atsuSize = IntToFixed( int( /*m_scaleY*/ 1 * font.MacGetFontSize()) ) ;
1153        RGBColor atsuColor = MAC_WXCOLORREF( m_textForegroundColor.GetPixel() ) ;
1154        ATSUAttributeTag atsuTags[] =
1155        {
1156                kATSUSizeTag ,
1157                kATSUColorTag ,
1158        } ;
1159        ByteCount atsuSizes[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
1160        {
1161                sizeof( Fixed ) ,
1162                sizeof( RGBColor ) ,
1163        } ;
1164        ATSUAttributeValuePtr atsuValues[sizeof(atsuTags) / sizeof(ATSUAttributeTag)] =
1165        {
1166                &atsuSize ,
1167                &atsuColor ,
1168        } ;
1169
1170        status = ::ATSUSetAttributes(
1171            (ATSUStyle)m_macATSUIStyle, sizeof(atsuTags) / sizeof(ATSUAttributeTag) ,
1172            atsuTags, atsuSizes, atsuValues);
1173
1174        wxASSERT_MSG( status == noErr , wxT("couldn't modify ATSU style") ) ;
1175    }
1176}
1177
1178
1179#pragma mark -
1180
1181wxDC::wxDC()
1182{
1183    m_ok = false ;
1184    m_colour = true;
1185    m_mm_to_pix_x = mm2pt;
1186    m_mm_to_pix_y = mm2pt;
1187
1188    m_externalDeviceOriginX = 0;
1189    m_externalDeviceOriginY = 0;
1190    m_logicalScaleX = 1.0;
1191    m_logicalScaleY = 1.0;
1192    m_userScaleX = 1.0;
1193    m_userScaleY = 1.0;
1194    m_scaleX = 1.0;
1195    m_scaleY = 1.0;
1196    m_needComputeScaleX =
1197    m_needComputeScaleY = false;
1198
1199    m_macPort = 0 ;
1200    m_macLocalOrigin.x =
1201    m_macLocalOrigin.y = 0 ;
1202
1203    m_pen = *wxBLACK_PEN;
1204    m_font = *wxNORMAL_FONT;
1205    m_brush = *wxWHITE_BRUSH;
1206
1207    m_macATSUIStyle = NULL ;
1208    m_graphicContext = NULL ;
1209}
1210
1211wxDC::~wxDC()
1212{
1213    if ( m_macATSUIStyle )
1214    {
1215        ::ATSUDisposeStyle((ATSUStyle)m_macATSUIStyle);
1216        m_macATSUIStyle = NULL ;
1217    }
1218
1219    delete m_graphicContext ;
1220}
1221
1222void wxDC::DoDrawBitmap( const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask )
1223{
1224    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawBitmap - invalid DC") );
1225    wxCHECK_RET( bmp.Ok(), wxT("wxDC(cg)::DoDrawBitmap - invalid bitmap") );
1226
1227    wxCoord xx = XLOG2DEVMAC(x);
1228    wxCoord yy = YLOG2DEVMAC(y);
1229    wxCoord w = bmp.GetWidth();
1230    wxCoord h = bmp.GetHeight();
1231    wxCoord ww = XLOG2DEVREL(w);
1232    wxCoord hh = YLOG2DEVREL(h);
1233
1234    if ( bmp.GetDepth()==1 )
1235    {
1236        wxGraphicPath* path = m_graphicContext->CreatePath() ;
1237        path->AddRectangle( xx , yy , ww , hh ) ;
1238        m_graphicContext->FillPath( path , m_textBackgroundColour, wxODDEVEN_RULE) ;
1239        delete path;
1240        m_graphicContext->DrawBitmap( bmp, xx , yy , ww , hh ) ;
1241    }
1242    else
1243    {
1244        m_graphicContext->DrawBitmap( bmp, xx , yy , ww , hh ) ;
1245    }
1246}
1247
1248void wxDC::DoDrawIcon( const wxIcon &icon, wxCoord x, wxCoord y )
1249{
1250    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawIcon - invalid DC") );
1251    wxCHECK_RET( icon.Ok(), wxT("wxDC(cg)::DoDrawIcon - invalid icon") );
1252
1253    wxCoord xx = XLOG2DEVMAC(x);
1254    wxCoord yy = YLOG2DEVMAC(y);
1255    wxCoord w = icon.GetWidth();
1256    wxCoord h = icon.GetHeight();
1257    wxCoord ww = XLOG2DEVREL(w);
1258    wxCoord hh = YLOG2DEVREL(h);
1259
1260    m_graphicContext->DrawIcon( icon , xx, yy, ww, hh ) ;
1261}
1262
1263void wxDC::DoSetClippingRegion( wxCoord x, wxCoord y, wxCoord width, wxCoord height )
1264{
1265    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoSetClippingRegion - invalid DC") );
1266
1267    wxCoord xx, yy, ww, hh;
1268    xx = XLOG2DEVMAC(x);
1269    yy = YLOG2DEVMAC(y);
1270    ww = XLOG2DEVREL(width);
1271    hh = YLOG2DEVREL(height);
1272
1273    CGContextRef cgContext = ((wxMacCGContext*)(m_graphicContext))->GetNativeContext() ;
1274    CGRect clipRect = CGRectMake( xx , yy , ww, hh ) ;
1275    CGContextClipToRect( cgContext , clipRect ) ;
1276
1277//    SetRectRgn( (RgnHandle) m_macCurrentClipRgn , xx , yy , xx + ww , yy + hh ) ;
1278//    SectRgn( (RgnHandle) m_macCurrentClipRgn , (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
1279
1280    if ( m_clipping )
1281    {
1282        m_clipX1 = wxMax( m_clipX1, xx );
1283        m_clipY1 = wxMax( m_clipY1, yy );
1284        m_clipX2 = wxMin( m_clipX2, (xx + ww) );
1285        m_clipY2 = wxMin( m_clipY2, (yy + hh) );
1286    }
1287    else
1288    {
1289        m_clipping = true;
1290
1291        m_clipX1 = xx;
1292        m_clipY1 = yy;
1293        m_clipX2 = xx + ww;
1294        m_clipY2 = yy + hh;
1295    }
1296
1297    // TODO: as soon as we don't reset the context for each operation anymore
1298    // we have to update the context as well
1299}
1300
1301void wxDC::DoSetClippingRegionAsRegion( const wxRegion &region )
1302{
1303    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoSetClippingRegionAsRegion - invalid DC") );
1304
1305    if (region.Empty())
1306    {
1307        DestroyClippingRegion();
1308        return;
1309    }
1310
1311    wxCoord x, y, w, h;
1312    region.GetBox( x, y, w, h );
1313    wxCoord xx, yy, ww, hh;
1314    xx = XLOG2DEVMAC(x);
1315    yy = YLOG2DEVMAC(y);
1316    ww = XLOG2DEVREL(w);
1317    hh = YLOG2DEVREL(h);
1318
1319    // if we have a scaling that we cannot map onto native regions
1320    // we must use the box
1321    if ( ww != w || hh != h )
1322    {
1323        wxDC::DoSetClippingRegion( x, y, w, h );
1324    }
1325    else
1326    {
1327        if ( m_clipping )
1328        {
1329            m_clipX1 = wxMax( m_clipX1, xx );
1330            m_clipY1 = wxMax( m_clipY1, yy );
1331            m_clipX2 = wxMin( m_clipX2, (xx + ww) );
1332            m_clipY2 = wxMin( m_clipY2, (yy + hh) );
1333        }
1334        else
1335        {
1336            m_clipping = true;
1337
1338            m_clipX1 = xx;
1339            m_clipY1 = yy;
1340            m_clipX2 = xx + ww;
1341            m_clipY2 = yy + hh;
1342        }
1343    }
1344}
1345
1346void wxDC::DestroyClippingRegion()
1347{
1348    CGContextRef cgContext = ((wxMacCGContext*)(m_graphicContext))->GetNativeContext() ;
1349    CGContextRestoreGState( cgContext );
1350    CGContextSaveGState( cgContext );
1351
1352    m_graphicContext->SetPen( m_pen ) ;
1353    m_graphicContext->SetBrush( m_brush ) ;
1354
1355    m_clipping = false;
1356}
1357
1358void wxDC::DoGetSizeMM( int* width, int* height ) const
1359{
1360    int w = 0, h = 0;
1361
1362    GetSize( &w, &h );
1363    if (width)
1364        *width = long( double(w) / (m_scaleX * m_mm_to_pix_x) );
1365    if (height)
1366        *height = long( double(h) / (m_scaleY * m_mm_to_pix_y) );
1367}
1368
1369void wxDC::SetTextForeground( const wxColour &col )
1370{
1371    wxCHECK_RET( Ok(), wxT("wxDC(cg)::SetTextForeground - invalid DC") );
1372
1373    if ( col != m_textForegroundColour )
1374    {
1375        m_textForegroundColour = col;
1376        m_graphicContext->SetTextColor( col );
1377        // in the current implementation the font contains the text color
1378        m_graphicContext->SetFont(m_font);
1379    }
1380}
1381
1382void wxDC::SetTextBackground( const wxColour &col )
1383{
1384    wxCHECK_RET( Ok(), wxT("wxDC(cg)::SetTextBackground - invalid DC") );
1385
1386    m_textBackgroundColour = col;
1387}
1388
1389void wxDC::SetMapMode( int mode )
1390{
1391    switch (mode)
1392    {
1393    case wxMM_TWIPS:
1394        SetLogicalScale( twips2mm * m_mm_to_pix_x, twips2mm * m_mm_to_pix_y );
1395        break;
1396
1397    case wxMM_POINTS:
1398        SetLogicalScale( pt2mm * m_mm_to_pix_x, pt2mm * m_mm_to_pix_y );
1399        break;
1400
1401    case wxMM_METRIC:
1402        SetLogicalScale( m_mm_to_pix_x, m_mm_to_pix_y );
1403        break;
1404
1405    case wxMM_LOMETRIC:
1406        SetLogicalScale( m_mm_to_pix_x / 10.0, m_mm_to_pix_y / 10.0 );
1407        break;
1408
1409    case wxMM_TEXT:
1410    default:
1411        SetLogicalScale( 1.0, 1.0 );
1412        break;
1413    }
1414
1415    if (mode != wxMM_TEXT)
1416    {
1417        m_needComputeScaleX =
1418        m_needComputeScaleY = true;
1419    }
1420}
1421
1422void wxDC::SetUserScale( double x, double y )
1423{
1424    // allow negative ? -> no
1425    m_userScaleX = x;
1426    m_userScaleY = y;
1427    ComputeScaleAndOrigin();
1428}
1429
1430void wxDC::SetLogicalScale( double x, double y )
1431{
1432    // allow negative ?
1433    m_logicalScaleX = x;
1434    m_logicalScaleY = y;
1435    ComputeScaleAndOrigin();
1436}
1437
1438void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
1439{
1440    m_logicalOriginX = x * m_signX;   // is this still correct ?
1441    m_logicalOriginY = y * m_signY;
1442    ComputeScaleAndOrigin();
1443}
1444
1445void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
1446{
1447    m_externalDeviceOriginX = x;
1448    m_externalDeviceOriginY = y;
1449    ComputeScaleAndOrigin();
1450}
1451
1452void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
1453{
1454    m_signX = (xLeftRight ?  1 : -1);
1455    m_signY = (yBottomUp ? -1 :  1);
1456    ComputeScaleAndOrigin();
1457}
1458
1459wxSize wxDC::GetPPI() const
1460{
1461    return wxSize(72, 72);
1462}
1463
1464int wxDC::GetDepth() const
1465{
1466    return 32;
1467}
1468
1469void wxDC::ComputeScaleAndOrigin()
1470{
1471    // CMB: copy scale to see if it changes
1472    double origScaleX = m_scaleX;
1473    double origScaleY = m_scaleY;
1474    m_scaleX = m_logicalScaleX * m_userScaleX;
1475    m_scaleY = m_logicalScaleY * m_userScaleY;
1476    m_deviceOriginX = m_externalDeviceOriginX;
1477    m_deviceOriginY = m_externalDeviceOriginY;
1478
1479    // CMB: if scale has changed call SetPen to recalulate the line width
1480    if (m_scaleX != origScaleX || m_scaleY != origScaleY)
1481    {
1482        // this is a bit artificial, but we need to force wxDC to think
1483        // the pen has changed
1484        wxPen pen( GetPen() );
1485
1486        m_pen = wxNullPen;
1487        SetPen( pen );
1488    }
1489}
1490
1491void wxDC::SetPalette( const wxPalette& palette )
1492{
1493}
1494
1495void wxDC::SetBackgroundMode( int mode )
1496{
1497    m_backgroundMode = mode ;
1498}
1499
1500void wxDC::SetFont( const wxFont &font )
1501{
1502    m_font = font;
1503    if ( m_graphicContext )
1504        m_graphicContext->SetFont( font ) ;
1505}
1506
1507void wxDC::SetPen( const wxPen &pen )
1508{
1509    if ( m_pen == pen )
1510        return ;
1511
1512    m_pen = pen;
1513    if ( m_graphicContext )
1514    {
1515        if ( m_pen.GetStyle() == wxSOLID || m_pen.GetStyle() == wxTRANSPARENT )
1516        {
1517            m_graphicContext->SetPen( m_pen ) ;
1518        }
1519        else
1520        {
1521            // we have to compensate for moved device origins etc. otherwise patterned pens are standing still
1522            // eg when using a wxScrollWindow and scrolling around
1523            int origX = XLOG2DEVMAC( 0 ) ;
1524            int origY = YLOG2DEVMAC( 0 ) ;
1525            m_graphicContext->Translate( origX , origY ) ;
1526            m_graphicContext->SetPen( m_pen ) ;
1527            m_graphicContext->Translate( -origX , -origY ) ;
1528        }
1529    }
1530}
1531
1532void wxDC::SetBrush( const wxBrush &brush )
1533{
1534    if (m_brush == brush)
1535        return;
1536
1537    m_brush = brush;
1538    if ( m_graphicContext )
1539    {
1540        if ( brush.GetStyle() == wxSOLID || brush.GetStyle() == wxTRANSPARENT )
1541        {
1542            m_graphicContext->SetBrush( m_brush ) ;
1543        }
1544        else
1545        {
1546            // we have to compensate for moved device origins etc. otherwise patterned brushes are standing still
1547            // eg when using a wxScrollWindow and scrolling around
1548            int origX = XLOG2DEVMAC(0) ;
1549            int origY = YLOG2DEVMAC(0) ;
1550            m_graphicContext->Translate( origX , origY ) ;
1551            m_graphicContext->SetBrush( m_brush ) ;
1552            m_graphicContext->Translate( -origX , -origY ) ;
1553        }
1554    }
1555}
1556
1557void wxDC::SetBackground( const wxBrush &brush )
1558{
1559    if (m_backgroundBrush == brush)
1560        return;
1561
1562    m_backgroundBrush = brush;
1563    if (!m_backgroundBrush.Ok())
1564        return;
1565}
1566
1567void wxDC::SetLogicalFunction( int function )
1568{
1569    if (m_logicalFunction == function)
1570        return;
1571
1572    m_logicalFunction = function ;
1573#if wxMAC_USE_CORE_GRAPHICS_BLEND_MODES
1574    if ( CGContextSetBlendMode != 0 )
1575    {
1576        CGContextRef cgContext = ((wxMacCGContext*)(m_graphicContext))->GetNativeContext() ;
1577        if ( m_logicalFunction == wxCOPY )
1578            CGContextSetBlendMode( cgContext, kCGBlendModeNormal ) ;
1579        else if ( m_logicalFunction == wxINVERT || m_logicalFunction == wxXOR )
1580            CGContextSetBlendMode( cgContext, kCGBlendModeExclusion ) ;
1581        else
1582            CGContextSetBlendMode( cgContext, kCGBlendModeNormal ) ;
1583    }
1584#endif
1585}
1586
1587extern bool wxDoFloodFill(wxDC *dc, wxCoord x, wxCoord y,
1588                          const wxColour & col, int style);
1589
1590bool wxDC::DoFloodFill(wxCoord x, wxCoord y,
1591                       const wxColour& col, int style)
1592{
1593    return wxDoFloodFill(this, x, y, col, style);
1594}
1595
1596bool wxDC::DoGetPixel( wxCoord x, wxCoord y, wxColour *col ) const
1597{
1598    wxCHECK_MSG( Ok(), false, wxT("wxDC(cg)::DoGetPixel - invalid DC") );
1599
1600    RGBColor colour;
1601#ifndef __LP64__
1602    wxMacPortSaver helper((CGrafPtr)m_macPort) ;
1603    // NB: GetCPixel is a deprecated QD call, and a slow one at that
1604    GetCPixel(
1605        XLOG2DEVMAC(x) + m_macLocalOriginInPort.x - m_macLocalOrigin.x,
1606        YLOG2DEVMAC(y) + m_macLocalOriginInPort.y - m_macLocalOrigin.y, &colour );
1607#endif
1608    // convert from Mac colour to wx
1609    col->Set( colour.red >> 8, colour.green >> 8, colour.blue >> 8 );
1610
1611    return true ;
1612}
1613
1614void wxDC::DoDrawLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2 )
1615{
1616    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawLine - invalid DC") );
1617
1618#if !wxMAC_USE_CORE_GRAPHICS_BLEND_MODES
1619    if ( m_logicalFunction != wxCOPY )
1620        return ;
1621#endif
1622
1623    wxCoord xx1 = XLOG2DEVMAC(x1) ;
1624    wxCoord yy1 = YLOG2DEVMAC(y1) ;
1625    wxCoord xx2 = XLOG2DEVMAC(x2) ;
1626    wxCoord yy2 = YLOG2DEVMAC(y2) ;
1627
1628    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1629    path->MoveToPoint( xx1, yy1 ) ;
1630    path->AddLineToPoint( xx2 , yy2 ) ;
1631    path->CloseSubpath() ;
1632    m_graphicContext->StrokePath( path ) ;
1633    delete path ;
1634
1635    CalcBoundingBox(x1, y1);
1636    CalcBoundingBox(x2, y2);
1637}
1638
1639void wxDC::DoCrossHair( wxCoord x, wxCoord y )
1640{
1641    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoCrossHair - invalid DC") );
1642
1643    if ( m_logicalFunction != wxCOPY )
1644        return ;
1645
1646    int w = 0, h = 0;
1647
1648    GetSize( &w, &h );
1649    wxCoord xx = XLOG2DEVMAC(x);
1650    wxCoord yy = YLOG2DEVMAC(y);
1651
1652    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1653    path->MoveToPoint( XLOG2DEVMAC(0), yy ) ;
1654    path->AddLineToPoint( XLOG2DEVMAC(w), yy ) ;
1655    path->CloseSubpath() ;
1656    path->MoveToPoint( xx, YLOG2DEVMAC(0) ) ;
1657    path->AddLineToPoint( xx, YLOG2DEVMAC(h) ) ;
1658    path->CloseSubpath() ;
1659    m_graphicContext->StrokePath( path ) ;
1660    delete path ;
1661
1662    CalcBoundingBox(x, y);
1663    CalcBoundingBox(x + w, y + h);
1664}
1665
1666void wxDC::DoDrawArc( wxCoord x1, wxCoord y1,
1667                      wxCoord x2, wxCoord y2,
1668                      wxCoord xc, wxCoord yc )
1669{
1670    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawArc - invalid DC") );
1671
1672    if ( m_logicalFunction != wxCOPY )
1673        return ;
1674
1675    wxCoord xx1 = XLOG2DEVMAC(x1);
1676    wxCoord yy1 = YLOG2DEVMAC(y1);
1677    wxCoord xx2 = XLOG2DEVMAC(x2);
1678    wxCoord yy2 = YLOG2DEVMAC(y2);
1679    wxCoord xxc = XLOG2DEVMAC(xc);
1680    wxCoord yyc = YLOG2DEVMAC(yc);
1681
1682    double dx = xx1 - xxc;
1683    double dy = yy1 - yyc;
1684    double radius = sqrt((double)(dx * dx + dy * dy));
1685    wxCoord rad = (wxCoord)radius;
1686    double sa, ea;
1687    if (xx1 == xx2 && yy1 == yy2)
1688    {
1689        sa = 0.0;
1690        ea = 360.0;
1691    }
1692    else if (radius == 0.0)
1693    {
1694        sa = ea = 0.0;
1695    }
1696    else
1697    {
1698        sa = (xx1 - xxc == 0) ?
1699            (yy1 - yyc < 0) ? 90.0 : -90.0 :
1700        -atan2(double(yy1 - yyc), double(xx1 - xxc)) * RAD2DEG;
1701        ea = (xx2 - xxc == 0) ?
1702            (yy2 - yyc < 0) ? 90.0 : -90.0 :
1703        -atan2(double(yy2 - yyc), double(xx2 - xxc)) * RAD2DEG;
1704    }
1705
1706    bool fill = m_brush.GetStyle() != wxTRANSPARENT ;
1707
1708    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1709    m_graphicContext->PushState() ;
1710    m_graphicContext->Translate( xxc, yyc ) ;
1711    m_graphicContext->Scale( 1, -1 ) ;
1712    if ( fill )
1713        path->MoveToPoint( 0, 0 ) ;
1714    path->AddArc( 0, 0, rad , DegToRad(sa) , DegToRad(ea), false ) ;
1715    if ( fill )
1716        path->AddLineToPoint( 0, 0 ) ;
1717    m_graphicContext->DrawPath( path ) ;
1718    m_graphicContext->PopState() ;
1719    delete path ;
1720}
1721
1722void wxDC::DoDrawEllipticArc( wxCoord x, wxCoord y, wxCoord w, wxCoord h,
1723                              double sa, double ea )
1724{
1725    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawEllipticArc - invalid DC") );
1726
1727    if ( m_logicalFunction != wxCOPY )
1728        return ;
1729
1730    wxCoord xx = XLOG2DEVMAC(x);
1731    wxCoord yy = YLOG2DEVMAC(y);
1732    wxCoord ww = m_signX * XLOG2DEVREL(w);
1733    wxCoord hh = m_signY * YLOG2DEVREL(h);
1734
1735    // handle -ve width and/or height
1736    if (ww < 0)
1737    {
1738        ww = -ww;
1739        xx = xx - ww;
1740    }
1741    if (hh < 0)
1742    {
1743        hh = -hh;
1744        yy = yy - hh;
1745    }
1746
1747    bool fill = m_brush.GetStyle() != wxTRANSPARENT ;
1748
1749    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1750    m_graphicContext->PushState() ;
1751    m_graphicContext->Translate( xx + ww / 2, yy + hh / 2 ) ;
1752    m_graphicContext->Scale( 1 * ww / 2 , -1 * hh / 2 ) ;
1753    if ( fill )
1754        path->MoveToPoint( 0, 0 ) ;
1755    path->AddArc( 0, 0, 1 , DegToRad(sa) , DegToRad(ea), false ) ;
1756    if ( fill )
1757        path->AddLineToPoint( 0, 0 ) ;
1758    m_graphicContext->DrawPath( path ) ;
1759    m_graphicContext->PopState() ;
1760    delete path ;
1761}
1762
1763void wxDC::DoDrawPoint( wxCoord x, wxCoord y )
1764{
1765    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawPoint - invalid DC") );
1766
1767    DoDrawLine( x , y , x + 1 , y + 1 ) ;
1768}
1769
1770void wxDC::DoDrawLines(int n, wxPoint points[],
1771                        wxCoord xoffset, wxCoord yoffset)
1772{
1773    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawLines - invalid DC") );
1774
1775#if !wxMAC_USE_CORE_GRAPHICS_BLEND_MODES
1776    if ( m_logicalFunction != wxCOPY )
1777        return ;
1778#endif
1779
1780    wxCoord x1, x2 , y1 , y2 ;
1781    x1 = XLOG2DEVMAC(points[0].x + xoffset);
1782    y1 = YLOG2DEVMAC(points[0].y + yoffset);
1783    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1784    path->MoveToPoint( x1 , y1 ) ;
1785    for (int i = 1; i < n; i++)
1786    {
1787        x2 = XLOG2DEVMAC(points[i].x + xoffset);
1788        y2 = YLOG2DEVMAC(points[i].y + yoffset);
1789
1790        path->AddLineToPoint( x2 , y2 ) ;
1791    }
1792
1793    m_graphicContext->StrokePath( path ) ;
1794    delete path ;
1795}
1796
1797#if wxUSE_SPLINES
1798void wxDC::DoDrawSpline(wxList *points)
1799{
1800    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawSpline - invalid DC") );
1801
1802    if ( m_logicalFunction != wxCOPY )
1803        return ;
1804
1805    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1806
1807    wxList::compatibility_iterator node = points->GetFirst();
1808    if (node == wxList::compatibility_iterator())
1809        // empty list
1810        return;
1811
1812    wxPoint *p = (wxPoint *)node->GetData();
1813
1814    wxCoord x1 = p->x;
1815    wxCoord y1 = p->y;
1816
1817    node = node->GetNext();
1818    p = (wxPoint *)node->GetData();
1819
1820    wxCoord x2 = p->x;
1821    wxCoord y2 = p->y;
1822    wxCoord cx1 = ( x1 + x2 ) / 2;
1823    wxCoord cy1 = ( y1 + y2 ) / 2;
1824
1825    path->MoveToPoint( XLOG2DEVMAC( x1 ) , YLOG2DEVMAC( y1 ) ) ;
1826    path->AddLineToPoint( XLOG2DEVMAC( cx1 ) , YLOG2DEVMAC( cy1 ) ) ;
1827
1828#if !wxUSE_STL
1829    while ((node = node->GetNext()) != NULL)
1830#else
1831    while ((node = node->GetNext()))
1832#endif // !wxUSE_STL
1833    {
1834        p = (wxPoint *)node->GetData();
1835        x1 = x2;
1836        y1 = y2;
1837        x2 = p->x;
1838        y2 = p->y;
1839        wxCoord cx4 = (x1 + x2) / 2;
1840        wxCoord cy4 = (y1 + y2) / 2;
1841
1842        path->AddQuadCurveToPoint(
1843            XLOG2DEVMAC( x1 ) , YLOG2DEVMAC( y1 ) ,
1844            XLOG2DEVMAC( cx4 ) , YLOG2DEVMAC( cy4 ) ) ;
1845
1846        cx1 = cx4;
1847        cy1 = cy4;
1848    }
1849
1850    path->AddLineToPoint( XLOG2DEVMAC( x2 ) , YLOG2DEVMAC( y2 ) ) ;
1851
1852    m_graphicContext->StrokePath( path ) ;
1853    delete path ;
1854}
1855#endif
1856
1857void wxDC::DoDrawPolygon( int n, wxPoint points[],
1858                          wxCoord xoffset, wxCoord yoffset,
1859                          int fillStyle )
1860{
1861    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawPolygon - invalid DC") );
1862
1863    if ( n <= 0 || (m_brush.GetStyle() == wxTRANSPARENT && m_pen.GetStyle() == wxTRANSPARENT ) )
1864        return ;
1865    if ( m_logicalFunction != wxCOPY )
1866        return ;
1867
1868    wxCoord x1, x2 , y1 , y2 ;
1869    x2 = x1 = XLOG2DEVMAC(points[0].x + xoffset);
1870    y2 = y1 = YLOG2DEVMAC(points[0].y + yoffset);
1871
1872    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1873    path->MoveToPoint( x1 , y1 ) ;
1874    for (int i = 1; i < n; i++)
1875    {
1876        x2 = XLOG2DEVMAC(points[i].x + xoffset);
1877        y2 = YLOG2DEVMAC(points[i].y + yoffset);
1878
1879        path->AddLineToPoint( x2 , y2 ) ;
1880    }
1881
1882    if ( x1 != x2 || y1 != y2 )
1883        path->AddLineToPoint( x1, y1 ) ;
1884
1885    path->CloseSubpath() ;
1886    m_graphicContext->DrawPath( path , fillStyle ) ;
1887
1888    delete path ;
1889}
1890
1891void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
1892{
1893    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawRectangle - invalid DC") );
1894
1895    if ( m_logicalFunction != wxCOPY )
1896        return ;
1897
1898    wxCoord xx = XLOG2DEVMAC(x);
1899    wxCoord yy = YLOG2DEVMAC(y);
1900    wxCoord ww = m_signX * XLOG2DEVREL(width);
1901    wxCoord hh = m_signY * YLOG2DEVREL(height);
1902
1903    // CMB: draw nothing if transformed w or h is 0
1904    if (ww == 0 || hh == 0)
1905        return;
1906
1907    // CMB: handle -ve width and/or height
1908    if (ww < 0)
1909    {
1910        ww = -ww;
1911        xx = xx - ww;
1912    }
1913    if (hh < 0)
1914    {
1915        hh = -hh;
1916        yy = yy - hh;
1917    }
1918
1919    int penwidth = m_pen.GetWidth();
1920    if ( penwidth == 0 )
1921        penwidth = 1 ;
1922    if ( m_pen.GetStyle() == wxTRANSPARENT )
1923        penwidth = 0 ;
1924
1925    bool offset = ( penwidth % 2 ) == 1 ;
1926
1927    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1928    // if we are offsetting the entire rectangle is moved 0.5, so the border line gets off by 1
1929    if ( offset )
1930        path->AddRectangle( xx , yy , ww-1 , hh-1 ) ;
1931    else
1932        path->AddRectangle( xx , yy , ww , hh ) ;
1933
1934    m_graphicContext->DrawPath( path ) ;
1935    delete path ;
1936}
1937
1938void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y,
1939                                   wxCoord width, wxCoord height,
1940                                   double radius)
1941{
1942    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawRoundedRectangle - invalid DC") );
1943
1944    if ( m_logicalFunction != wxCOPY )
1945        return ;
1946
1947    if (radius < 0.0)
1948        radius = - radius * ((width < height) ? width : height);
1949    wxCoord xx = XLOG2DEVMAC(x);
1950    wxCoord yy = YLOG2DEVMAC(y);
1951    wxCoord ww = m_signX * XLOG2DEVREL(width);
1952    wxCoord hh = m_signY * YLOG2DEVREL(height);
1953
1954    // CMB: draw nothing if transformed w or h is 0
1955    if (ww == 0 || hh == 0)
1956        return;
1957
1958    // CMB: handle -ve width and/or height
1959    if (ww < 0)
1960    {
1961        ww = -ww;
1962        xx = xx - ww;
1963    }
1964    if (hh < 0)
1965    {
1966        hh = -hh;
1967        yy = yy - hh;
1968    }
1969
1970    wxGraphicPath* path = m_graphicContext->CreatePath() ;
1971    if ( radius == 0)
1972    {
1973        path->AddRectangle( xx , yy , ww , hh ) ;
1974        m_graphicContext->DrawPath( path ) ;
1975    }
1976    else
1977    {
1978        path->MoveToPoint( xx + ww, yy + hh / 2);
1979        path->AddArcToPoint(xx + ww, yy + hh, xx + ww / 2,yy +  hh, radius);
1980        path->AddArcToPoint(xx , yy + hh, xx , yy + hh / 2, radius);
1981        path->AddArcToPoint(xx , yy , xx + ww / 2, yy , radius);
1982        path->AddArcToPoint(xx + ww, yy , xx + ww, yy + hh / 2, radius);
1983        path->CloseSubpath();
1984        m_graphicContext->DrawPath( path ) ;
1985    }
1986    delete path ;
1987}
1988
1989void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
1990{
1991    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawEllipse - invalid DC") );
1992
1993    if ( m_logicalFunction != wxCOPY )
1994        return ;
1995
1996    wxCoord xx = XLOG2DEVMAC(x);
1997    wxCoord yy = YLOG2DEVMAC(y);
1998    wxCoord ww = m_signX * XLOG2DEVREL(width);
1999    wxCoord hh = m_signY * YLOG2DEVREL(height);
2000
2001    // CMB: draw nothing if transformed w or h is 0
2002    if (ww == 0 || hh == 0)
2003        return;
2004
2005    // CMB: handle -ve width and/or height
2006    if (ww < 0)
2007    {
2008        ww = -ww;
2009        xx = xx - ww;
2010    }
2011    if (hh < 0)
2012    {
2013        hh = -hh;
2014        yy = yy - hh;
2015    }
2016
2017    wxGraphicPath* path = m_graphicContext->CreatePath() ;
2018    m_graphicContext->PushState() ;
2019    m_graphicContext->Translate(xx + ww / 2, yy + hh / 2);
2020    m_graphicContext->Scale(ww / 2 , hh / 2);
2021    path->AddArc( 0, 0, 1, 0 , 2 * M_PI , false ) ;
2022    m_graphicContext->DrawPath( path ) ;
2023    m_graphicContext->PopState() ;
2024    delete path ;
2025}
2026
2027bool wxDC::CanDrawBitmap() const
2028{
2029    return true ;
2030}
2031
2032bool wxDC::DoBlit(
2033    wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height,
2034    wxDC *source, wxCoord xsrc, wxCoord ysrc, int logical_func , bool useMask,
2035    wxCoord xsrcMask, wxCoord ysrcMask )
2036{
2037    wxCHECK_MSG( Ok(), false, wxT("wxDC(cg)::DoBlit - invalid DC") );
2038    wxCHECK_MSG( source->Ok(), false, wxT("wxDC(cg)::DoBlit - invalid source DC") );
2039
2040    if ( logical_func == wxNO_OP )
2041        return true ;
2042
2043    if (xsrcMask == -1 && ysrcMask == -1)
2044    {
2045        xsrcMask = xsrc;
2046        ysrcMask = ysrc;
2047    }
2048
2049    wxCoord yysrc = source->YLOG2DEVMAC(ysrc) ;
2050    wxCoord xxsrc = source->XLOG2DEVMAC(xsrc) ;
2051    wxCoord wwsrc = source->XLOG2DEVREL(width) ;
2052    wxCoord hhsrc = source->YLOG2DEVREL(height) ;
2053
2054    wxCoord yydest = YLOG2DEVMAC(ydest) ;
2055    wxCoord xxdest = XLOG2DEVMAC(xdest) ;
2056    wxCoord wwdest = XLOG2DEVREL(width) ;
2057    wxCoord hhdest = YLOG2DEVREL(height) ;
2058
2059    wxMemoryDC* memdc = dynamic_cast<wxMemoryDC*>(source) ;
2060    if ( memdc && logical_func == wxCOPY )
2061    {
2062        wxBitmap blit = memdc->GetSelectedObject() ;
2063
2064        wxASSERT_MSG( blit.Ok() , wxT("Invalid bitmap for blitting") ) ;
2065
2066        wxCoord bmpwidth = blit.GetWidth();
2067        wxCoord bmpheight = blit.GetHeight();
2068
2069        if ( xxsrc != 0 || yysrc != 0 || bmpwidth != wwsrc || bmpheight != hhsrc )
2070        {
2071            wwsrc = wxMin( wwsrc , bmpwidth - xxsrc ) ;
2072            hhsrc = wxMin( hhsrc , bmpheight - yysrc ) ;
2073            if ( wwsrc > 0 && hhsrc > 0 )
2074            {
2075                if ( xxsrc >= 0 && yysrc >= 0 )
2076                {
2077                    wxRect subrect( xxsrc, yysrc, wwsrc , hhsrc ) ;
2078                    // TODO we perhaps could add a DrawSubBitmap call to dc for performance reasons
2079                    blit = blit.GetSubBitmap( subrect ) ;
2080                }
2081                else
2082                {
2083                    // in this case we'd probably have to adjust the different coordinates, but
2084                    // we have to find out proper contract first
2085                    blit = wxNullBitmap ;
2086                }
2087            }
2088            else
2089            {
2090                blit = wxNullBitmap ;
2091            }
2092        }
2093
2094        if ( blit.Ok() )
2095        {
2096            m_graphicContext->DrawBitmap( blit, xxdest , yydest , wwdest , hhdest ) ;
2097        }
2098    }
2099    else
2100    {
2101        wxFAIL_MSG( wxT("Blitting is only supported from bitmap contexts, and only with wxCOPY logical operation.") ) ;
2102        return false ;
2103    }
2104
2105    return true;
2106}
2107
2108void wxDC::DoDrawRotatedText(const wxString& str, wxCoord x, wxCoord y,
2109                              double angle)
2110{
2111    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawRotatedText - invalid DC") );
2112//    wxCHECK_RET( m_macATSUIStyle != NULL, wxT("wxDC(cg)::DoDrawRotatedText - no valid font set") );
2113
2114    if ( str.length() == 0 )
2115        return ;
2116    if ( m_logicalFunction != wxCOPY )
2117        return ;
2118
2119    int drawX = XLOG2DEVMAC(x) ;
2120    int drawY = YLOG2DEVMAC(y) ;
2121
2122    m_graphicContext->DrawText( str, drawX ,drawY , angle ) ;
2123}
2124
2125void wxDC::DoDrawText(const wxString& strtext, wxCoord x, wxCoord y)
2126{
2127    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoDrawText - invalid DC") );
2128
2129    DoDrawRotatedText( strtext , x , y , 0.0 ) ;
2130}
2131
2132bool wxDC::CanGetTextExtent() const
2133{
2134    wxCHECK_MSG( Ok(), false, wxT("wxDC(cg)::CanGetTextExtent - invalid DC") );
2135
2136    return true ;
2137}
2138
2139void wxDC::DoGetTextExtent( const wxString &str, wxCoord *width, wxCoord *height,
2140                            wxCoord *descent, wxCoord *externalLeading ,
2141                            wxFont *theFont ) const
2142{
2143    wxCHECK_RET( Ok(), wxT("wxDC(cg)::DoGetTextExtent - invalid DC") );
2144
2145    if ( theFont )
2146    {
2147        m_graphicContext->SetFont( *theFont ) ;
2148    }
2149
2150    wxCoord h , d , e , w ;
2151
2152    m_graphicContext->GetTextExtent( str, &w, &h, &d, &e ) ;
2153
2154    if ( height )
2155        *height = YDEV2LOGREL( h ) ;
2156    if ( descent )
2157        *descent =YDEV2LOGREL( d);
2158    if ( externalLeading )
2159        *externalLeading = YDEV2LOGREL( e);
2160    if ( width )
2161        *width = XDEV2LOGREL( w ) ;
2162
2163    if ( theFont )
2164    {
2165        m_graphicContext->SetFont( m_font ) ;
2166    }
2167}
2168
2169bool wxDC::DoGetPartialTextExtents(const wxString& text, wxArrayInt& widths) const
2170{
2171    wxCHECK_MSG( Ok(), false, wxT("wxDC(cg)::DoGetPartialTextExtents - invalid DC") );
2172
2173    m_graphicContext->GetPartialTextExtents( text, widths ) ;
2174    for ( size_t i = 0 ; i < widths.GetCount() ; ++i )
2175        widths[i] = XDEV2LOGREL( widths[i] );
2176
2177    return true;
2178}
2179
2180wxCoord wxDC::GetCharWidth(void) const
2181{
2182    wxCoord width ;
2183    DoGetTextExtent( wxT("g") , &width , NULL , NULL , NULL , NULL ) ;
2184
2185    return width ;
2186}
2187
2188wxCoord wxDC::GetCharHeight(void) const
2189{
2190    wxCoord height ;
2191    DoGetTextExtent( wxT("g") , NULL , &height , NULL , NULL , NULL ) ;
2192
2193    return height ;
2194}
2195
2196void wxDC::Clear(void)
2197{
2198    wxCHECK_RET( Ok(), wxT("wxDC(cg)::Clear - invalid DC") );
2199
2200    if (m_backgroundBrush.Ok() && m_backgroundBrush.GetStyle() != wxTRANSPARENT)
2201    {
2202        HIRect rect = CGRectMake( -10000 , -10000 , 20000 , 20000 ) ;
2203        CGContextRef cg = ((wxMacCGContext*)(m_graphicContext))->GetNativeContext() ;
2204        switch ( m_backgroundBrush.MacGetBrushKind() )
2205        {
2206            case kwxMacBrushTheme :
2207                {
2208#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
2209                    if ( HIThemeSetFill != 0 )
2210                    {
2211                        HIThemeSetFill( m_backgroundBrush.MacGetTheme(), NULL, cg, kHIThemeOrientationNormal );
2212                        CGContextFillRect(cg, rect);
2213
2214                    }
2215                    else
2216#endif
2217                    {
2218                        RGBColor color;
2219                        GetThemeBrushAsColor( m_backgroundBrush.MacGetTheme(), 32, true, &color );
2220                        CGContextSetRGBFillColor( cg, (CGFloat) color.red / 65536,
2221                            (CGFloat) color.green / 65536, (CGFloat) color.blue / 65536, 1 );
2222                            CGContextFillRect( cg, rect );
2223                    }
2224
2225                    // reset to normal value
2226                    RGBColor col = MAC_WXCOLORREF( GetBrush().GetColour().GetPixel() ) ;
2227                    CGContextSetRGBFillColor( cg, col.red / 65536.0, col.green / 65536.0, col.blue / 65536.0, 1.0 );
2228                }
2229                break ;
2230
2231            case kwxMacBrushThemeBackground :
2232                {
2233                    wxFAIL_MSG( wxT("There shouldn't be theme backgrounds under Quartz") ) ;
2234
2235#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
2236                    if ( UMAGetSystemVersion() >= 0x1030 )
2237                    {
2238                        HIThemeBackgroundDrawInfo drawInfo ;
2239                        drawInfo.version = 0 ;
2240                        drawInfo.state = kThemeStateActive ;
2241                        drawInfo.kind = m_backgroundBrush.MacGetThemeBackground( NULL ) ;
2242                        if ( drawInfo.kind == kThemeBackgroundMetal )
2243                        {
2244                            HIThemeDrawBackground( &rect, &drawInfo, cg, kHIThemeOrientationNormal ) ;
2245                            HIThemeApplyBackground( &rect, &drawInfo, cg, kHIThemeOrientationNormal ) ;
2246                        }
2247                    }
2248#endif
2249                }
2250                break ;
2251
2252            case kwxMacBrushColour :
2253                {
2254                    // FIXME: doesn't correctly render stippled brushes !!
2255                    // FIXME: should this be replaced by ::SetBrush() ??
2256
2257                    RGBColor col = MAC_WXCOLORREF( m_backgroundBrush.GetColour().GetPixel()) ;
2258                    CGContextSetRGBFillColor( cg , col.red / 65536.0 , col.green / 65536.0 , col.blue / 65536.0 , 1.0 ) ;
2259                    CGContextFillRect(cg, rect);
2260
2261                    // reset to normal value
2262                    col = MAC_WXCOLORREF( GetBrush().GetColour().GetPixel() ) ;
2263                    CGContextSetRGBFillColor( cg , col.red / 65536.0 , col.green / 65536.0 , col.blue / 65536.0 , 1.0 ) ;
2264                }
2265                break ;
2266
2267            default :
2268                wxFAIL_MSG( wxT("unknown brush kind") ) ;
2269                break ;
2270        }
2271    }
2272}
2273
2274#endif
2275
2276#pragma mark -
2277
2278// ---------------------------------------------------------------------------
2279// coordinates transformations
2280// ---------------------------------------------------------------------------
2281/*
2282    wxCoord XLOG2DEVMAC(wxCoord x) const
2283    {
2284        long new_x = x - m_logicalOriginX;
2285        if (new_x > 0)
2286            return (wxCoord)((double)new_x * m_scaleX + 0.5) * m_signX + m_deviceOriginX + m_macLocalOrigin.x;
2287        else
2288            return (wxCoord)((double)new_x * m_scaleX - 0.5) * m_signX + m_deviceOriginX + m_macLocalOrigin.x;
2289    }
2290
2291    wxCoord YLOG2DEVMAC(wxCoord y) const
2292    {
2293        long new_y = y - m_logicalOriginY;
2294        if (new_y > 0)
2295            return (wxCoord)((double)new_y * m_scaleY + 0.5) * m_signY + m_deviceOriginY + m_macLocalOrigin.y;
2296        else
2297            return (wxCoord)((double)new_y * m_scaleY - 0.5) * m_signY + m_deviceOriginY + m_macLocalOrigin.y;
2298    }
2299*/ // TODO
2300wxCoord wxDCBase::DeviceToLogicalX(wxCoord x) const
2301{
2302    return wxRound((double)(x - m_deviceOriginX) / m_scaleX) * m_signX + m_logicalOriginX;
2303}
2304
2305wxCoord wxDCBase::DeviceToLogicalY(wxCoord y) const
2306{
2307    return wxRound((double)(y - m_deviceOriginY) / m_scaleY) * m_signY + m_logicalOriginY;
2308}
2309
2310wxCoord wxDCBase::DeviceToLogicalXRel(wxCoord x) const
2311{
2312    return wxRound((double)(x) / m_scaleX);
2313}
2314
2315wxCoord wxDCBase::DeviceToLogicalYRel(wxCoord y) const
2316{
2317    return wxRound((double)(y) / m_scaleY);
2318}
2319
2320wxCoord wxDCBase::LogicalToDeviceX(wxCoord x) const
2321{
2322    return wxRound((double)(x - m_logicalOriginX) * m_scaleX) * m_signX + m_deviceOriginX;
2323}
2324
2325wxCoord wxDCBase::LogicalToDeviceY(wxCoord y) const
2326{
2327    return wxRound((double)(y - m_logicalOriginY) * m_scaleY) * m_signY + m_deviceOriginY;
2328}
2329
2330wxCoord wxDCBase::LogicalToDeviceXRel(wxCoord x) const
2331{
2332    return wxRound((double)(x) * m_scaleX);
2333}
2334
2335wxCoord wxDCBase::LogicalToDeviceYRel(wxCoord y) const
2336{
2337    return wxRound((double)(y) * m_scaleY);
2338}
2339
2340#endif // wxMAC_USE_CORE_GRAPHICS
2341