1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/dc.mm
4 // Author: David Elliott
8 // Copyright: (c) 2003 David Elliott
9 // Licence: wxWidgets licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
18 #include "wx/cocoa/autorelease.h"
19 #include "wx/cocoa/string.h"
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>
31 #include "wx/listimpl.cpp"
32 WX_DEFINE_LIST(wxCocoaDCStack);
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;
40 inline void CocoaSetPenForNSBezierPath(wxPen &pen, NSBezierPath *bezpath)
42 [pen.GetNSColor() set];
44 [bezpath setLineDash:pattern count:pen.GetCocoaLineDash(&pattern) phase:0.0];
45 [bezpath setLineWidth:pen.GetWidth()];
49 [bezpath setLineJoinStyle:NSBevelLineJoinStyle];
52 [bezpath setLineJoinStyle:NSRoundLineJoinStyle];
55 [bezpath setLineJoinStyle:NSMiterLineJoinStyle];
61 [bezpath setLineCapStyle:NSRoundLineCapStyle];
63 case wxCAP_PROJECTING:
64 [bezpath setLineCapStyle:NSSquareLineCapStyle];
67 [bezpath setLineCapStyle:NSButtLineCapStyle];
72 void wxDC::CocoaInitializeTextSystem()
74 wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized! BAD PROGRAMMER!"));
76 sm_cocoaNSTextStorage = [[NSTextStorage alloc] init];
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];
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];
92 void wxDC::CocoaShutdownTextSystem()
94 [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
95 [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
96 [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
99 void wxDC::CocoaUnwindStackAndLoseFocus()
101 wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
104 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
105 for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
107 wxDC *dc = node->GetData();
110 if(!dc->CocoaUnlockFocus())
112 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
114 sm_cocoaDCStack.Erase(node);
116 wxASSERT(node==ourNode);
117 wxASSERT(ourNode->GetData() == this);
118 ourNode->GetData()->CocoaUnlockFocus();
119 sm_cocoaDCStack.Erase(ourNode);
123 bool wxDC::CocoaUnwindStackAndTakeFocus()
125 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
126 for(;node;node = sm_cocoaDCStack.GetFirst())
128 wxDC *dc = node->GetData();
130 // If we're on the stack, then it's unwound enough and we have focus
133 // If unable to unlockFocus (e.g. wxPaintDC) stop here
134 if(!dc->CocoaUnlockFocus())
136 sm_cocoaDCStack.Erase(node);
138 return CocoaLockFocus();
143 m_cocoaWxToBoundsTransform = nil;
144 m_pen = *wxBLACK_PEN;
149 [m_cocoaWxToBoundsTransform release];
152 bool wxDC::CocoaLockFocus()
157 bool wxDC::CocoaUnlockFocus()
162 /*static*/ WX_NSAffineTransform wxDC::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
164 NSAffineTransform *transform = nil;
165 // This transform flips the graphics since wxDC uses top-left origin
168 // The transform is auto released
169 transform = [NSAffineTransform transform];
171 y' = 0x + -1y + window's height
173 NSAffineTransformStruct matrix = {
178 [transform setTransformStruct: matrix];
183 void wxDC::CocoaApplyTransformations()
185 [m_cocoaWxToBoundsTransform concat];
186 // TODO: Apply device/logical/user position/scaling transformations
189 void wxDC::CocoaUnapplyTransformations()
191 // NOTE: You *must* call this with focus held.
192 // Undo all transforms so we're back in true Cocoa coords with
193 // no scaling or flipping.
194 NSAffineTransform *invertTransform;
195 invertTransform = [m_cocoaWxToBoundsTransform copy];
196 [invertTransform invert];
197 [invertTransform concat];
198 [invertTransform release];
201 bool wxDC::CocoaGetBounds(void *rectData)
203 // We don't know what we are so we can't return anything.
207 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
209 wxAutoNSAutoreleasePool pool;
210 if(!CocoaTakeFocus()) return;
211 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
212 CocoaSetPenForNSBezierPath(m_pen,bezpath);
214 [m_brush.GetNSColor() set];
218 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
220 wxAutoNSAutoreleasePool pool;
221 if(!CocoaTakeFocus()) return;
222 NSBezierPath *bezpath = [NSBezierPath bezierPath];
223 [bezpath moveToPoint:NSMakePoint(x1,y1)];
224 [bezpath lineToPoint:NSMakePoint(x2,y2)];
226 CocoaSetPenForNSBezierPath(m_pen,bezpath);
230 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
232 wxAutoNSAutoreleasePool pool;
233 // FIXME: Cache this so it can be used for DoDrawText
234 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
235 NSAttributedString *attributedString = [[NSAttributedString alloc]
236 initWithString:wxNSStringWithWxString(text.c_str())];
237 [sm_cocoaNSTextStorage setAttributedString:attributedString];
238 [attributedString release];
240 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
241 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
243 *x=(int)usedRect.size.width;
245 *y=(int)usedRect.size.height;
252 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
254 wxAutoNSAutoreleasePool pool;
255 if(!CocoaTakeFocus()) return;
256 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
257 NSAttributedString *attributedString = [[NSAttributedString alloc]
258 initWithString:wxNSStringWithWxString(text.c_str())];
259 [sm_cocoaNSTextStorage setAttributedString:attributedString];
260 [attributedString release];
262 // Set the color (and later font) attributes
263 NSColor *fgColor = m_textForegroundColour.GetNSColor();
264 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
266 fgColor = [NSColor clearColor];
268 bgColor = [NSColor clearColor];
269 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
270 fgColor, NSForegroundColorAttributeName,
271 bgColor, NSBackgroundColorAttributeName,
273 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
276 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
277 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
278 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
279 // there is no length or we don't start at zero
280 if(!glyphRange.length)
282 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
284 NSAffineTransform *transform = [NSAffineTransform transform];
285 [transform translateXBy:x yBy:y];
287 NSAffineTransform *flipTransform = [NSAffineTransform transform];
289 y' = 0x + -1y + window's height
291 NSAffineTransformStruct matrix = {
294 , 0, usedRect.size.height
296 [flipTransform setTransformStruct: matrix];
298 NSGraphicsContext *context = [NSGraphicsContext currentContext];
299 [context saveGraphicsState];
301 [flipTransform concat];
303 // Draw+fill a rectangle so we can see where the shit is supposed to be.
304 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
305 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
306 [[NSColor blackColor] set];
308 [[NSColor blueColor] set];
312 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
313 layoutLocation.x = 0.0;
314 layoutLocation.y *= -1.0;
315 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
316 if(m_backgroundMode==wxSOLID)
317 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
318 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
320 [context restoreGraphicsState];
323 // wxDCBase functions
324 int wxDCBase::DeviceToLogicalX(int x) const
329 int wxDCBase::DeviceToLogicalY(int y) const
334 int wxDCBase::DeviceToLogicalXRel(int x) const
339 int wxDCBase::DeviceToLogicalYRel(int y) const
344 int wxDCBase::LogicalToDeviceX(int x) const
349 int wxDCBase::LogicalToDeviceY(int y) const
354 int wxDCBase::LogicalToDeviceXRel(int x) const
359 int wxDCBase::LogicalToDeviceYRel(int y) const
364 ///////////////////////////////////////////////////////////////////////////
365 // cut here, the rest is stubs
366 ///////////////////////////////////////////////////////////////////////////
368 //-----------------------------------------------------------------------------
370 //-----------------------------------------------------------------------------
372 #define mm2inches 0.0393700787402
373 #define inches2mm 25.4
374 #define mm2twips 56.6929133859
375 #define twips2mm 0.0176388888889
376 #define mm2pt 2.83464566929
377 #define pt2mm 0.352777777778
379 //-----------------------------------------------------------------------------
381 //-----------------------------------------------------------------------------
383 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
387 void wxDC::DoDrawPoint( int x, int y )
391 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
395 void wxDC::DoDrawLines( int, wxPoint *, int, int )
399 int wxDC::GetDepth() const
404 wxSize wxDC::GetPPI() const
409 bool wxDC::CanGetTextExtent() const
414 wxCoord wxDC::GetCharHeight() const
419 wxCoord wxDC::GetCharWidth() const
424 bool wxDC::CanDrawBitmap() const
429 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
434 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
438 void wxDC::SetPen(const wxPen& pen)
443 void wxDC::SetBrush(const wxBrush& brush)
448 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
452 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
456 void wxDC::DestroyClippingRegion()
460 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
464 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
468 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
472 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
476 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
478 wxAutoNSAutoreleasePool pool;
479 if(!CocoaTakeFocus()) return;
484 // Draw a rect so we can see where it's supposed to be
485 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
486 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
487 [[NSColor blackColor] set];
489 [[NSColor blueColor] set];
493 NSAffineTransform *transform = [NSAffineTransform transform];
494 [transform translateXBy:x yBy:y];
496 NSAffineTransform *flipTransform = [NSAffineTransform transform];
498 y' = 0x + -1y + window's height
500 NSAffineTransformStruct matrix = {
505 [flipTransform setTransformStruct: matrix];
507 NSGraphicsContext *context = [NSGraphicsContext currentContext];
508 [context saveGraphicsState];
510 [flipTransform concat];
512 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
514 [nsimage drawAtPoint: NSMakePoint(0,0)
515 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
516 operation: NSCompositeSourceOver
520 [context restoreGraphicsState];
523 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
528 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
533 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)
535 if(!CocoaTakeFocus()) return false;
536 if(!source) return false;
537 return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
538 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
541 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
542 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
543 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
548 void wxDC::DoGetSize( int* width, int* height ) const
550 *width = m_maxX-m_minX;
551 *height = m_maxY-m_minY;
554 void wxDC::DoGetSizeMM( int* width, int* height ) const
561 void wxDC::SetTextForeground( const wxColour &col )
564 m_textForegroundColour = col;
567 void wxDC::SetTextBackground( const wxColour &col )
570 m_textBackgroundColour = col;
575 if(!CocoaTakeFocus()) return;
578 if(!CocoaGetBounds(&boundsRect)) return;
580 NSGraphicsContext *context = [NSGraphicsContext currentContext];
581 [context saveGraphicsState];
583 // Undo all transforms so when we draw our bounds rect we
584 // really overwrite our bounds rect.
585 CocoaUnapplyTransformations();
587 [m_backgroundBrush.GetNSColor() set];
588 [NSBezierPath fillRect:boundsRect];
590 [context restoreGraphicsState];
593 void wxDC::SetBackground(const wxBrush& brush)
595 m_backgroundBrush = brush;
598 void wxDC::SetPalette(const wxPalette&)
602 void wxDC::SetLogicalFunction(int)
607 void wxDC::SetMapMode( int mode )
621 SetLogicalScale( 1.0, 1.0 );
624 if (mode != wxMM_TEXT)
629 void wxDC::SetUserScale( double x, double y )
631 // allow negative ? -> no
634 ComputeScaleAndOrigin();
637 void wxDC::SetLogicalScale( double x, double y )
642 ComputeScaleAndOrigin();
645 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
647 m_logicalOriginX = x * m_signX; // is this still correct ?
648 m_logicalOriginY = y * m_signY;
649 ComputeScaleAndOrigin();
652 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
654 ComputeScaleAndOrigin();
657 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
659 m_signX = (xLeftRight ? 1 : -1);
660 m_signY = (yBottomUp ? -1 : 1);
661 ComputeScaleAndOrigin();
664 void wxDC::ComputeScaleAndOrigin(void)
666 // CMB: copy scale to see if it changes
667 double origScaleX = m_scaleX;
668 double origScaleY = m_scaleY;
670 m_scaleX = m_logicalScaleX * m_userScaleX;
671 m_scaleY = m_logicalScaleY * m_userScaleY;
673 // CMB: if scale has changed call SetPen to recalulate the line width
674 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
676 // this is a bit artificial, but we need to force wxDC to think
677 // the pen has changed
678 const wxPen* pen = & GetPen();