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"
14 #include "wx/cocoa/dc.h"
18 #include "wx/math.h" //math constants
21 #include "wx/cocoa/autorelease.h"
22 #include "wx/cocoa/string.h"
24 #import <AppKit/NSBezierPath.h>
25 #import <AppKit/NSTextStorage.h>
26 #import <AppKit/NSLayoutManager.h>
27 #import <AppKit/NSTextContainer.h>
28 #import <AppKit/NSGraphicsContext.h>
29 #import <AppKit/NSAffineTransform.h>
30 #import <AppKit/NSColor.h>
31 #import <AppKit/NSTypesetter.h>
32 #import <AppKit/NSImage.h>
34 #include "wx/listimpl.cpp"
35 WX_DEFINE_LIST(wxCocoaDCStack);
37 IMPLEMENT_ABSTRACT_CLASS(wxCocoaDCImpl, wxDCImpl)
39 WX_NSTextStorage wxCocoaDCImpl::sm_cocoaNSTextStorage = nil;
40 WX_NSLayoutManager wxCocoaDCImpl::sm_cocoaNSLayoutManager = nil;
41 WX_NSTextContainer wxCocoaDCImpl::sm_cocoaNSTextContainer = nil;
42 wxCocoaDCStack wxCocoaDCImpl::sm_cocoaDCStack;
44 inline void CocoaSetPenForNSBezierPath(wxPen &pen, NSBezierPath *bezpath)
46 [pen.GetNSColor() set];
47 const CGFloat *pattern;
48 [bezpath setLineDash:pattern count:pen.GetCocoaLineDash(&pattern) phase:0.0];
49 [bezpath setLineWidth:pen.GetWidth()];
53 [bezpath setLineJoinStyle:NSBevelLineJoinStyle];
56 [bezpath setLineJoinStyle:NSRoundLineJoinStyle];
59 [bezpath setLineJoinStyle:NSMiterLineJoinStyle];
65 [bezpath setLineCapStyle:NSRoundLineCapStyle];
67 case wxCAP_PROJECTING:
68 [bezpath setLineCapStyle:NSSquareLineCapStyle];
71 [bezpath setLineCapStyle:NSButtLineCapStyle];
76 void wxCocoaDCImpl::CocoaInitializeTextSystem()
78 wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized! BAD PROGRAMMER!"));
80 sm_cocoaNSTextStorage = [[NSTextStorage alloc] init];
82 sm_cocoaNSLayoutManager = [[NSLayoutManager alloc] init];
83 [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
84 // NSTextStorage retains NSLayoutManager, but so do we
85 // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
87 // NOTE: initWithContainerSize is the designated initializer, but the
88 // Apple CircleView sample gets away with just calling init, which
89 // is all we really need for our purposes.
90 sm_cocoaNSTextContainer = [[NSTextContainer alloc] init];
91 [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
92 // NSLayoutManager retains NSTextContainer, but so do we
93 // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
96 void wxCocoaDCImpl::CocoaShutdownTextSystem()
98 [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
99 [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
100 [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
103 void wxCocoaDCImpl::CocoaUnwindStackAndLoseFocus()
105 wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
108 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
109 for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
111 wxCocoaDCImpl *dc = node->GetData();
114 if(!dc->CocoaUnlockFocus())
116 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
118 sm_cocoaDCStack.Erase(node);
120 wxASSERT(node==ourNode);
121 wxASSERT(ourNode->GetData() == this);
122 ourNode->GetData()->CocoaUnlockFocus();
123 sm_cocoaDCStack.Erase(ourNode);
127 bool wxCocoaDCImpl::CocoaUnwindStackAndTakeFocus()
129 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
130 for(;node;node = sm_cocoaDCStack.GetFirst())
132 wxCocoaDCImpl *dc = node->GetData();
134 // If we're on the stack, then it's unwound enough and we have focus
137 // If unable to unlockFocus (e.g. wxPaintDC) stop here
138 if(!dc->CocoaUnlockFocus())
140 sm_cocoaDCStack.Erase(node);
142 return CocoaLockFocus();
145 wxCocoaDCImpl::wxCocoaDCImpl(wxDC *owner)
148 m_cocoaWxToBoundsTransform = nil;
149 m_pen = *wxBLACK_PEN;
152 wxCocoaDCImpl::~wxDC(void)
154 [m_cocoaWxToBoundsTransform release];
157 bool wxCocoaDCImpl::CocoaLockFocus()
162 bool wxCocoaDCImpl::CocoaUnlockFocus()
167 /*static*/ WX_NSAffineTransform wxCocoaDCImpl::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
169 NSAffineTransform *transform = nil;
170 // This transform flips the graphics since wxDC uses top-left origin
173 // The transform is auto released
174 transform = [NSAffineTransform transform];
176 y' = 0x + -1y + window's height
178 NSAffineTransformStruct matrix = {
183 [transform setTransformStruct: matrix];
188 void wxCocoaDCImpl::CocoaApplyTransformations()
190 [m_cocoaWxToBoundsTransform concat];
191 // TODO: Apply device/logical/user position/scaling transformations
194 void wxCocoaDCImpl::CocoaUnapplyTransformations()
196 // NOTE: You *must* call this with focus held.
197 // Undo all transforms so we're back in true Cocoa coords with
198 // no scaling or flipping.
199 NSAffineTransform *invertTransform;
200 invertTransform = [m_cocoaWxToBoundsTransform copy];
201 [invertTransform invert];
202 [invertTransform concat];
203 [invertTransform release];
206 bool wxCocoaDCImpl::CocoaGetBounds(void *rectData)
208 // We don't know what we are so we can't return anything.
212 void wxCocoaDCImpl::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
214 wxAutoNSAutoreleasePool pool;
215 if(!CocoaTakeFocus()) return;
216 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
217 CocoaSetPenForNSBezierPath(m_pen,bezpath);
219 [m_brush.GetNSColor() set];
223 void wxCocoaDCImpl::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
225 wxAutoNSAutoreleasePool pool;
226 if(!CocoaTakeFocus()) return;
227 NSBezierPath *bezpath = [NSBezierPath bezierPath];
228 [bezpath moveToPoint:NSMakePoint(x1,y1)];
229 [bezpath lineToPoint:NSMakePoint(x2,y2)];
231 CocoaSetPenForNSBezierPath(m_pen,bezpath);
235 void wxCocoaDCImpl::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, const wxFont *theFont) const
237 wxAutoNSAutoreleasePool pool;
238 // FIXME: Cache this so it can be used for DoDrawText
239 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
240 NSAttributedString *attributedString = [[NSAttributedString alloc]
241 initWithString:wxNSStringWithWxString(text.c_str())];
242 [sm_cocoaNSTextStorage setAttributedString:attributedString];
243 [attributedString release];
245 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
246 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
248 *x=(int)usedRect.size.width;
250 *y=(int)usedRect.size.height;
257 void wxCocoaDCImpl::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
259 wxAutoNSAutoreleasePool pool;
260 if(!CocoaTakeFocus()) return;
261 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
262 NSAttributedString *attributedString = [[NSAttributedString alloc]
263 initWithString:wxNSStringWithWxString(text.c_str())];
264 [sm_cocoaNSTextStorage setAttributedString:attributedString];
265 [attributedString release];
267 // Set the color (and later font) attributes
268 NSColor *fgColor = m_textForegroundColour.GetNSColor();
269 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
271 fgColor = [NSColor clearColor];
273 bgColor = [NSColor clearColor];
274 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
275 fgColor, NSForegroundColorAttributeName,
276 bgColor, NSBackgroundColorAttributeName,
278 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
281 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
282 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
283 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
284 // there is no length or we don't start at zero
285 if(!glyphRange.length)
287 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
289 NSAffineTransform *transform = [NSAffineTransform transform];
290 [transform translateXBy:x yBy:y];
292 NSAffineTransform *flipTransform = [NSAffineTransform transform];
294 y' = 0x + -1y + window's height
296 NSAffineTransformStruct matrix = {
299 , 0, usedRect.size.height
301 [flipTransform setTransformStruct: matrix];
303 NSGraphicsContext *context = [NSGraphicsContext currentContext];
304 [context saveGraphicsState];
306 [flipTransform concat];
308 // Draw+fill a rectangle so we can see where the shit is supposed to be.
309 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
310 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
311 [[NSColor blackColor] set];
313 [[NSColor blueColor] set];
317 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
318 layoutLocation.x = 0.0;
319 layoutLocation.y *= -1.0;
321 // Save the location as is for underlining
322 NSPoint underlineLocation = layoutLocation;
324 // Offset the location by the baseline for drawing the glyphs.
325 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
327 if(m_backgroundMode==wxSOLID)
328 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
329 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
331 int underlineStyle = GetFont().GetUnderlined() ? NSUnderlineStyleSingle : NSUnderlineStyleNone;
332 NSRange lineGlyphRange;
333 NSRect lineRect = [sm_cocoaNSLayoutManager lineFragmentRectForGlyphAtIndex:0 effectiveRange:&lineGlyphRange];
335 [sm_cocoaNSLayoutManager underlineGlyphRange:glyphRange underlineType:underlineStyle
336 lineFragmentRect:lineRect lineFragmentGlyphRange:lineGlyphRange
337 containerOrigin:underlineLocation];
339 [context restoreGraphicsState];
342 ///////////////////////////////////////////////////////////////////////////
343 // cut here, the rest is stubs
344 ///////////////////////////////////////////////////////////////////////////
346 //-----------------------------------------------------------------------------
348 //-----------------------------------------------------------------------------
350 void wxCocoaDCImpl::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
354 void wxCocoaDCImpl::DoDrawPoint( int x, int y )
358 void wxCocoaDCImpl::DoDrawPolygon( int, wxPoint *, int, int, int)
362 void wxCocoaDCImpl::DoDrawLines( int, wxPoint *, int, int )
366 int wxCocoaDCImpl::GetDepth() const
371 wxSize wxCocoaDCImpl::GetPPI() const
376 bool wxCocoaDCImpl::CanGetTextExtent() const
381 wxCoord wxCocoaDCImpl::GetCharHeight() const
386 wxCoord wxCocoaDCImpl::GetCharWidth() const
391 bool wxCocoaDCImpl::CanDrawBitmap() const
396 bool wxCocoaDCImpl::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
401 void wxCocoaDCImpl::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
405 void wxCocoaDCImpl::SetFont(const wxFont& font)
410 void wxCocoaDCImpl::SetPen(const wxPen& pen)
415 void wxCocoaDCImpl::SetBrush(const wxBrush& brush)
420 void wxCocoaDCImpl::DoSetClippingRegionAsRegion(const wxRegion& region)
424 void wxCocoaDCImpl::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
428 void wxCocoaDCImpl::DestroyClippingRegion()
432 void wxCocoaDCImpl::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
436 void wxCocoaDCImpl::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
440 void wxCocoaDCImpl::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
444 void wxCocoaDCImpl::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
448 void wxCocoaDCImpl::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
450 wxAutoNSAutoreleasePool pool;
451 if(!CocoaTakeFocus()) return;
456 // Draw a rect so we can see where it's supposed to be
457 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
458 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
459 [[NSColor blackColor] set];
461 [[NSColor blueColor] set];
465 NSAffineTransform *transform = [NSAffineTransform transform];
466 [transform translateXBy:x yBy:y];
468 NSAffineTransform *flipTransform = [NSAffineTransform transform];
470 y' = 0x + -1y + window's height
472 NSAffineTransformStruct matrix = {
477 [flipTransform setTransformStruct: matrix];
479 NSGraphicsContext *context = [NSGraphicsContext currentContext];
480 [context saveGraphicsState];
482 [flipTransform concat];
484 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
486 [nsimage drawAtPoint: NSMakePoint(0,0)
487 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
488 operation: NSCompositeSourceOver
492 [context restoreGraphicsState];
495 bool wxCocoaDCImpl::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
500 void wxCocoaDCImpl::DoCrossHair(wxCoord x, wxCoord y)
505 bool wxCocoaDCImpl::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height, wxDC *source, wxCoord xsrc, wxCoord ysrc, int rop, bool useMask , wxCoord xsrcMask, wxCoord ysrcMask)
507 if(!CocoaTakeFocus()) return false;
508 if(!source) return false;
509 wxCocoaDCImpl *sourceImpl = static_cast<wxCocoaDCImpl*>(source->GetImpl());
510 return sourceImpl->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
511 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
514 bool wxCocoaDCImpl::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
515 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
516 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
521 void wxCocoaDCImpl::DoGetSize( int* width, int* height ) const
523 *width = m_maxX-m_minX;
524 *height = m_maxY-m_minY;
527 void wxCocoaDCImpl::DoGetSizeMM( int* width, int* height ) const
534 void wxCocoaDCImpl::SetTextForeground( const wxColour &col )
536 // if (!Ok()) return;
537 m_textForegroundColour = col;
540 void wxCocoaDCImpl::SetTextBackground( const wxColour &col )
542 // if (!Ok()) return;
543 m_textBackgroundColour = col;
546 void wxCocoaDCImpl::Clear()
548 if(!CocoaTakeFocus()) return;
551 if(!CocoaGetBounds(&boundsRect)) return;
553 NSGraphicsContext *context = [NSGraphicsContext currentContext];
554 [context saveGraphicsState];
556 // Undo all transforms so when we draw our bounds rect we
557 // really overwrite our bounds rect.
558 CocoaUnapplyTransformations();
560 [m_backgroundBrush.GetNSColor() set];
561 [NSBezierPath fillRect:boundsRect];
563 [context restoreGraphicsState];
566 void wxCocoaDCImpl::SetBackground(const wxBrush& brush)
568 m_backgroundBrush = brush;
571 void wxCocoaDCImpl::SetPalette(const wxPalette&)
575 void wxCocoaDCImpl::SetLogicalFunction(int)
580 void wxCocoaDCImpl::SetMapMode( int mode )
594 SetLogicalScale( 1.0, 1.0 );
597 if (mode != wxMM_TEXT)
602 void wxCocoaDCImpl::SetUserScale( double x, double y )
604 // allow negative ? -> no
607 ComputeScaleAndOrigin();
610 void wxCocoaDCImpl::SetLogicalScale( double x, double y )
615 ComputeScaleAndOrigin();
618 void wxCocoaDCImpl::SetLogicalOrigin( wxCoord x, wxCoord y )
620 m_logicalOriginX = x * m_signX; // is this still correct ?
621 m_logicalOriginY = y * m_signY;
622 ComputeScaleAndOrigin();
625 void wxCocoaDCImpl::SetDeviceOrigin( wxCoord x, wxCoord y )
627 ComputeScaleAndOrigin();
630 void wxCocoaDCImpl::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
632 m_signX = (xLeftRight ? 1 : -1);
633 m_signY = (yBottomUp ? -1 : 1);
634 ComputeScaleAndOrigin();
637 void wxCocoaDCImpl::ComputeScaleAndOrigin(void)
639 // CMB: copy scale to see if it changes
640 double origScaleX = m_scaleX;
641 double origScaleY = m_scaleY;
643 m_scaleX = m_logicalScaleX * m_userScaleX;
644 m_scaleY = m_logicalScaleY * m_userScaleY;
646 // CMB: if scale has changed call SetPen to recalulate the line width
647 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
650 // this is a bit artificial, but we need to force wxDC to think
651 // the pen has changed
652 const wxPen* pen = & GetPen();