Make wxCocoa work with wxUSE_STL==1:
[wxWidgets.git] / src / cocoa / dc.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/cocoa/dc.mm
3 // Purpose:     wxDC
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2003/04/01
7 // RCS-ID:      $Id$
8 // Copyright:   (c) 2003 David Elliott
9 // Licence:     wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13 #ifndef WX_PRECOMP
14     #include "wx/log.h"
15     #include "wx/dc.h"
16 #endif //WX_PRECOMP
17
18 #include "wx/cocoa/autorelease.h"
19 #include "wx/cocoa/string.h"
20
21 #import <AppKit/NSBezierPath.h>
22 #import <AppKit/NSTextStorage.h>
23 #import <AppKit/NSLayoutManager.h>
24 #import <AppKit/NSTextContainer.h>
25 #import <AppKit/NSGraphicsContext.h>
26 #import <AppKit/NSAffineTransform.h>
27 #import <AppKit/NSColor.h>
28 #import <AppKit/NSTypesetter.h>
29 #import <AppKit/NSImage.h>
30
31 #include <wx/listimpl.cpp>
32 WX_DEFINE_LIST(wxCocoaDCStack);
33
34 IMPLEMENT_ABSTRACT_CLASS(wxDC, wxObject)
35 WX_NSTextStorage wxDC::sm_cocoaNSTextStorage = nil;
36 WX_NSLayoutManager wxDC::sm_cocoaNSLayoutManager = nil;
37 WX_NSTextContainer wxDC::sm_cocoaNSTextContainer = nil;
38 wxCocoaDCStack wxDC::sm_cocoaDCStack;
39
40 inline void CocoaSetPenForNSBezierPath(wxPen &pen, NSBezierPath *bezpath)
41 {
42     [pen.GetNSColor() set];
43     const float *pattern;
44     [bezpath setLineDash:pattern count:pen.GetCocoaLineDash(&pattern) phase:0.0];
45     [bezpath setLineWidth:pen.GetWidth()];
46     switch(pen.GetJoin())
47     {
48     case wxJOIN_BEVEL:
49         [bezpath setLineJoinStyle:NSBevelLineJoinStyle];
50         break;
51     case wxJOIN_ROUND:
52         [bezpath setLineJoinStyle:NSRoundLineJoinStyle];
53         break;
54     case wxJOIN_MITER:
55         [bezpath setLineJoinStyle:NSMiterLineJoinStyle];
56         break;
57     }
58     switch(pen.GetCap())
59     {
60     case wxCAP_ROUND:
61         [bezpath setLineCapStyle:NSRoundLineCapStyle];
62         break;
63     case wxCAP_PROJECTING:
64         [bezpath setLineCapStyle:NSSquareLineCapStyle];
65         break;
66     case wxCAP_BUTT:
67         [bezpath setLineCapStyle:NSButtLineCapStyle];
68         break;
69     }
70 }
71
72 void wxDC::CocoaInitializeTextSystem()
73 {
74     wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized!  BAD PROGRAMMER!"));
75
76     sm_cocoaNSTextStorage = [[NSTextStorage alloc] init];
77
78     sm_cocoaNSLayoutManager = [[NSLayoutManager alloc] init];
79     [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
80     // NSTextStorage retains NSLayoutManager, but so do we
81     // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
82
83     // NOTE:  initWithContainerSize is the designated initializer, but the
84     // Apple CircleView sample gets away with just calling init, which
85     // is all we really need for our purposes.
86     sm_cocoaNSTextContainer = [[NSTextContainer alloc] init];
87     [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
88     // NSLayoutManager retains NSTextContainer, but so do we
89     // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
90 }
91
92 void wxDC::CocoaShutdownTextSystem()
93 {
94     [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
95     [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
96     [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
97 }
98
99 void wxDC::CocoaUnwindStackAndLoseFocus()
100 {
101     wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
102     if(ourNode)
103     {
104         wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
105         for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
106         {
107             wxDC *dc = node->GetData();
108             wxASSERT(dc);
109             wxASSERT(dc!=this);
110             if(!dc->CocoaUnlockFocus())
111             {
112                 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
113             }
114             sm_cocoaDCStack.Erase(node);
115         }
116         wxASSERT(node==ourNode);
117         wxASSERT(ourNode->GetData() == this);
118         ourNode->GetData()->CocoaUnlockFocus();
119         sm_cocoaDCStack.Erase(ourNode);
120     }
121 }
122
123 bool wxDC::CocoaUnwindStackAndTakeFocus()
124 {
125     wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
126     for(;node;node = sm_cocoaDCStack.GetFirst())
127     {
128         wxDC *dc = node->GetData();
129         wxASSERT(dc);
130         // If we're on the stack, then it's unwound enough and we have focus
131         if(dc==this)
132             return true;
133         // If unable to unlockFocus (e.g. wxPaintDC) stop here
134         if(!dc->CocoaUnlockFocus())
135             break;
136         sm_cocoaDCStack.Erase(node);
137     }
138     return CocoaLockFocus();
139 }
140
141 wxDC::wxDC(void)
142 {
143     m_cocoaFlipped = false;
144     m_cocoaHeight = 0.0;
145     m_pen = *wxBLACK_PEN;
146 }
147
148 wxDC::~wxDC(void)
149 {
150 }
151
152 bool wxDC::CocoaLockFocus()
153 {
154     return false;
155 }
156
157 bool wxDC::CocoaUnlockFocus()
158 {
159     return false;
160 }
161
162 void wxDC::CocoaApplyTransformations()
163 {
164     // This transform flips the graphics since wxDC uses top-left origin
165     if(!m_cocoaFlipped)
166     {
167         // The transform is auto released
168         NSAffineTransform *transform = [NSAffineTransform transform];
169         /*  x' = 1x + 0y + 0
170             y' = 0x + -1y + window's height
171         */
172         NSAffineTransformStruct matrix = {
173             1,  0
174         ,   0, -1
175         ,   0, m_cocoaHeight
176         };
177         [transform setTransformStruct: matrix];
178         // Apply the transform 
179         [transform concat];
180     }
181     // TODO: Apply scaling transformation
182 }
183
184 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
185 {
186     if(!CocoaTakeFocus()) return;
187     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
188     CocoaSetPenForNSBezierPath(m_pen,bezpath);
189     [bezpath stroke];
190     [m_brush.GetNSColor() set];
191     [bezpath fill];
192 }
193
194 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
195 {
196     if(!CocoaTakeFocus()) return;
197     NSBezierPath *bezpath = [NSBezierPath bezierPath];
198     [bezpath moveToPoint:NSMakePoint(x1,y1)];
199     [bezpath lineToPoint:NSMakePoint(x2,y2)];
200
201     CocoaSetPenForNSBezierPath(m_pen,bezpath);
202     [bezpath stroke];
203 }
204
205 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
206 {
207     wxAutoNSAutoreleasePool pool;
208 // FIXME: Cache this so it can be used for DoDrawText
209     wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized.  BAD PROGRAMMER!"));
210     NSAttributedString *attributedString = [[NSAttributedString alloc]
211             initWithString:wxNSStringWithWxString(text.c_str())];
212     [sm_cocoaNSTextStorage setAttributedString:attributedString];
213     [attributedString release];
214
215     NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
216     NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
217     if(x)
218         *x=(int)usedRect.size.width;
219     if(y)
220         *y=(int)usedRect.size.height;
221     if(descent)
222         *descent=0;
223     if(externalLeading)
224         *externalLeading=0;
225 }
226
227 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
228 {
229     if(!CocoaTakeFocus()) return;
230     wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized.  BAD PROGRAMMER!"));
231     NSAttributedString *attributedString = [[NSAttributedString alloc]
232             initWithString:wxNSStringWithWxString(text.c_str())];
233     [sm_cocoaNSTextStorage setAttributedString:attributedString];
234     [attributedString release];
235
236     // Set the color (and later font) attributes
237     NSColor *fgColor = m_textForegroundColour.GetNSColor();
238     NSColor *bgColor = m_textBackgroundColour.GetNSColor();
239     if(!fgColor)
240         fgColor = [NSColor clearColor];
241     if(!bgColor)
242         bgColor = [NSColor clearColor];
243     NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
244             fgColor, NSForegroundColorAttributeName,
245             bgColor, NSBackgroundColorAttributeName,
246             nil];
247     [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
248     [attrDict release];
249
250     NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
251     NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
252     // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
253     // there is no length or we don't start at zero
254     if(!glyphRange.length)
255         return;
256     wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
257
258     NSAffineTransform *transform = [NSAffineTransform transform];
259     [transform translateXBy:x yBy:y];
260
261     NSAffineTransform *flipTransform = [NSAffineTransform transform];
262     /*  x' = 1x + 0y + 0
263         y' = 0x + -1y + window's height
264     */
265     NSAffineTransformStruct matrix = {
266         1,  0
267     ,   0, -1
268     ,   0, usedRect.size.height
269     };
270     [flipTransform setTransformStruct: matrix];
271
272     NSGraphicsContext *context = [NSGraphicsContext currentContext];
273     [context saveGraphicsState];
274     [transform concat];
275     [flipTransform concat];
276     #if 0
277     // Draw+fill a rectangle so we can see where the shit is supposed to be.
278     wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
279     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
280     [[NSColor blackColor] set];
281     [bezpath stroke];
282     [[NSColor blueColor] set];
283     [bezpath fill];
284     #endif
285
286     NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
287     layoutLocation.x = 0.0;
288     layoutLocation.y *= -1.0;
289     layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
290     if(m_backgroundMode==wxSOLID)
291         [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange  atPoint:NSZeroPoint];
292     [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange  atPoint:layoutLocation];
293
294     [context restoreGraphicsState];
295 }
296
297 // wxDCBase functions
298 int wxDCBase::DeviceToLogicalX(int x) const
299 {
300     return x;
301 }
302
303 int wxDCBase::DeviceToLogicalY(int y) const
304 {
305     return y;
306 }
307
308 int wxDCBase::DeviceToLogicalXRel(int x) const
309 {
310     return x;
311 }
312
313 int wxDCBase::DeviceToLogicalYRel(int y) const
314 {
315     return y;
316 }
317
318 int wxDCBase::LogicalToDeviceX(int x) const
319 {
320     return x;
321 }
322
323 int wxDCBase::LogicalToDeviceY(int y) const
324 {
325     return y;
326 }
327
328 int wxDCBase::LogicalToDeviceXRel(int x) const
329 {
330     return x;
331 }
332
333 int wxDCBase::LogicalToDeviceYRel(int y) const
334 {
335     return y;
336 }
337
338 ///////////////////////////////////////////////////////////////////////////
339 // cut here, the rest is stubs
340 ///////////////////////////////////////////////////////////////////////////
341
342 //-----------------------------------------------------------------------------
343 // constants
344 //-----------------------------------------------------------------------------
345
346 #define mm2inches               0.0393700787402
347 #define inches2mm               25.4
348 #define mm2twips                56.6929133859
349 #define twips2mm                0.0176388888889
350 #define mm2pt                   2.83464566929
351 #define pt2mm                   0.352777777778
352
353 //-----------------------------------------------------------------------------
354 // wxDC
355 //-----------------------------------------------------------------------------
356
357 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
358 {
359 };
360
361 void wxDC::DoDrawPoint( int x, int y ) 
362
363 };
364
365 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
366 {
367 };
368
369 void wxDC::DoDrawLines( int, wxPoint *, int, int )
370 {
371 }
372
373 int wxDC::GetDepth() const
374 {
375     return 0;
376 }
377
378 wxSize wxDC::GetPPI() const
379 {
380     return wxSize(0,0);
381 }
382
383 bool wxDC::CanGetTextExtent() const
384 {
385     return false;
386 }
387
388 wxCoord wxDC::GetCharHeight() const
389 {
390     return 0;
391 }
392
393 wxCoord wxDC::GetCharWidth() const
394 {
395     return 0;
396 }
397
398 bool wxDC::CanDrawBitmap() const
399 {
400     return true;
401 }
402
403 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
404 {
405     return false;
406 }
407
408 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
409 {
410 }
411     
412 void wxDC::SetPen(const wxPen& pen)
413 {
414     m_pen = pen;
415 }
416
417 void wxDC::SetBrush(const wxBrush& brush)
418 {
419     m_brush = brush;
420 }
421
422 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
423 {
424 }
425
426 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
427 {
428 }
429
430 void wxDC::DestroyClippingRegion()
431 {
432 }
433
434 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
435 {
436 }
437
438 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
439 {
440 }
441
442 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
443 {
444 }
445
446 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
447 {
448 }
449
450 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
451 {
452     if(!CocoaTakeFocus()) return;
453     if(!bmp.Ok())
454         return;
455
456 #if 0
457     // Draw a rect so we can see where it's supposed to be
458     wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
459     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
460     [[NSColor blackColor] set];
461     [bezpath stroke];
462     [[NSColor blueColor] set];
463     [bezpath fill];
464 #endif // 0
465
466     NSAffineTransform *transform = [NSAffineTransform transform];
467     [transform translateXBy:x yBy:y];
468
469     NSAffineTransform *flipTransform = [NSAffineTransform transform];
470     /*  x' = 1x + 0y + 0
471         y' = 0x + -1y + window's height
472     */
473     NSAffineTransformStruct matrix = {
474         1,  0
475     ,   0, -1
476     ,   0, bmp.GetHeight()
477     };
478     [flipTransform setTransformStruct: matrix];
479
480     NSGraphicsContext *context = [NSGraphicsContext currentContext];
481     [context saveGraphicsState];
482     [transform concat];
483     [flipTransform concat];
484
485     NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
486
487     [nsimage drawAtPoint: NSMakePoint(0,0)
488         fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
489         operation: NSCompositeSourceOver
490         fraction: 1.0];
491         
492     [nsimage release];
493     [context restoreGraphicsState];
494 }
495
496 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
497 {
498     return false;
499 }
500
501 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
502 {
503 }
504
505
506 bool wxDC::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height, wxDC *source, wxCoord xsrc, wxCoord ysrc, int rop, bool useMask , wxCoord xsrcMask, wxCoord ysrcMask)
507 {
508     if(!CocoaTakeFocus()) return false;
509     if(!source) return false;
510     return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
511         xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
512 }
513
514 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
515     wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
516     int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
517 {
518     return false;
519 }
520
521 void wxDC::DoGetSize( int* width, int* height ) const
522 {
523   *width = m_maxX-m_minX;
524   *height = m_maxY-m_minY;
525 };
526
527 void wxDC::DoGetSizeMM( int* width, int* height ) const
528 {
529   int w = 0;
530   int h = 0;
531   GetSize( &w, &h );
532 };
533
534 void wxDC::SetTextForeground( const wxColour &col )
535 {
536   if (!Ok()) return;
537   m_textForegroundColour = col;
538 };
539
540 void wxDC::SetTextBackground( const wxColour &col )
541 {
542   if (!Ok()) return;
543   m_textBackgroundColour = col;
544 };
545
546 void wxDC::Clear()
547 {
548 }
549
550 void wxDC::SetBackground(const wxBrush& brush)
551 {
552     m_backgroundBrush = brush;
553 }
554
555 void wxDC::SetPalette(const wxPalette&)
556 {
557 }
558
559 void wxDC::SetLogicalFunction(int)
560 {
561 }
562
563
564 void wxDC::SetMapMode( int mode )
565 {
566   switch (mode) 
567   {
568     case wxMM_TWIPS:
569       break;
570     case wxMM_POINTS:
571       break;
572     case wxMM_METRIC:
573       break;
574     case wxMM_LOMETRIC:
575       break;
576     default:
577     case wxMM_TEXT:
578       SetLogicalScale( 1.0, 1.0 );
579       break;
580   };
581   if (mode != wxMM_TEXT)
582   {
583   };
584 };
585
586 void wxDC::SetUserScale( double x, double y )
587 {
588   // allow negative ? -> no
589   m_userScaleX = x;
590   m_userScaleY = y;
591   ComputeScaleAndOrigin();
592 };
593
594 void wxDC::SetLogicalScale( double x, double y )
595 {
596   // allow negative ?
597   m_logicalScaleX = x;
598   m_logicalScaleY = y;
599   ComputeScaleAndOrigin();
600 };
601
602 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
603 {
604   m_logicalOriginX = x * m_signX;   // is this still correct ?
605   m_logicalOriginY = y * m_signY;
606   ComputeScaleAndOrigin();
607 };
608
609 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
610 {
611   ComputeScaleAndOrigin();
612 };
613
614 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
615 {
616   m_signX = (xLeftRight ?  1 : -1);
617   m_signY = (yBottomUp  ? -1 :  1);
618   ComputeScaleAndOrigin();
619 };
620
621 void wxDC::ComputeScaleAndOrigin(void)
622 {
623   // CMB: copy scale to see if it changes
624   double origScaleX = m_scaleX;
625   double origScaleY = m_scaleY;
626
627   m_scaleX = m_logicalScaleX * m_userScaleX;
628   m_scaleY = m_logicalScaleY * m_userScaleY;
629
630   // CMB: if scale has changed call SetPen to recalulate the line width 
631   if (m_scaleX != origScaleX || m_scaleY != origScaleY)
632   {
633     // this is a bit artificial, but we need to force wxDC to think
634     // the pen has changed
635     wxPen* pen = & GetPen();
636     wxPen tempPen;
637     m_pen = tempPen;
638     SetPen(* pen);
639   }
640 };
641