1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/dc.mm
4 // Author: David Elliott
7 // Copyright: (c) 2003 David Elliott
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 #include "wx/wxprec.h"
13 #include "wx/cocoa/dc.h"
17 #include "wx/math.h" //math constants
20 #include "wx/cocoa/autorelease.h"
21 #include "wx/cocoa/string.h"
22 #include "wx/cocoa/ObjcRef.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 wxAutoNSAutoreleasePool pool;
80 wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized! BAD PROGRAMMER!"));
82 // FIXME: Never released
83 sm_cocoaNSTextStorage = wxGCSafeRetain([[[NSTextStorage alloc] init] autorelease]);
85 // FIXME: Never released
86 sm_cocoaNSLayoutManager = wxGCSafeRetain([[[NSLayoutManager alloc] init] autorelease]);
88 [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
89 // NSTextStorage retains NSLayoutManager, but so do we
90 // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
92 // NOTE: initWithContainerSize is the designated initializer, but the
93 // Apple CircleView sample gets away with just calling init, which
94 // is all we really need for our purposes.
95 // FIXME: Never released
96 sm_cocoaNSTextContainer = wxGCSafeRetain([[[NSTextContainer alloc] init] autorelease]);
97 [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
98 // NSLayoutManager retains NSTextContainer, but so do we
99 // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
102 void wxCocoaDCImpl::CocoaShutdownTextSystem()
104 [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
105 [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
106 [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
109 void wxCocoaDCImpl::CocoaUnwindStackAndLoseFocus()
111 wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
114 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
115 for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
117 wxCocoaDCImpl *dc = node->GetData();
120 if(!dc->CocoaUnlockFocus())
122 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
124 sm_cocoaDCStack.Erase(node);
126 wxASSERT(node==ourNode);
127 wxASSERT(ourNode->GetData() == this);
128 ourNode->GetData()->CocoaUnlockFocus();
129 sm_cocoaDCStack.Erase(ourNode);
133 bool wxCocoaDCImpl::CocoaUnwindStackAndTakeFocus()
135 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
136 for(;node;node = sm_cocoaDCStack.GetFirst())
138 wxCocoaDCImpl *dc = node->GetData();
140 // If we're on the stack, then it's unwound enough and we have focus
143 // If unable to unlockFocus (e.g. wxPaintDC) stop here
144 if(!dc->CocoaUnlockFocus())
146 sm_cocoaDCStack.Erase(node);
148 return CocoaLockFocus();
151 wxCocoaDCImpl::wxCocoaDCImpl(wxDC *owner)
154 m_cocoaWxToBoundsTransform = nil;
155 m_pen = *wxBLACK_PEN;
158 wxCocoaDCImpl::~wxDC(void)
160 [m_cocoaWxToBoundsTransform release];
163 bool wxCocoaDCImpl::CocoaLockFocus()
168 bool wxCocoaDCImpl::CocoaUnlockFocus()
173 /*static*/ WX_NSAffineTransform wxCocoaDCImpl::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
175 NSAffineTransform *transform = nil;
176 // This transform flips the graphics since wxDC uses top-left origin
179 // The transform is auto released
180 transform = [NSAffineTransform transform];
182 y' = 0x + -1y + window's height
184 NSAffineTransformStruct matrix = {
189 [transform setTransformStruct: matrix];
194 void wxCocoaDCImpl::CocoaApplyTransformations()
196 [m_cocoaWxToBoundsTransform concat];
197 // TODO: Apply device/logical/user position/scaling transformations
200 void wxCocoaDCImpl::CocoaUnapplyTransformations()
202 // NOTE: You *must* call this with focus held.
203 // Undo all transforms so we're back in true Cocoa coords with
204 // no scaling or flipping.
205 NSAffineTransform *invertTransform;
206 invertTransform = [m_cocoaWxToBoundsTransform copy];
207 [invertTransform invert];
208 [invertTransform concat];
209 [invertTransform release];
212 bool wxCocoaDCImpl::CocoaGetBounds(void *rectData)
214 // We don't know what we are so we can't return anything.
218 void wxCocoaDCImpl::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
220 wxAutoNSAutoreleasePool pool;
221 if(!CocoaTakeFocus()) return;
222 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
223 CocoaSetPenForNSBezierPath(m_pen,bezpath);
225 [m_brush.GetNSColor() set];
229 void wxCocoaDCImpl::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
231 wxAutoNSAutoreleasePool pool;
232 if(!CocoaTakeFocus()) return;
233 NSBezierPath *bezpath = [NSBezierPath bezierPath];
234 [bezpath moveToPoint:NSMakePoint(x1,y1)];
235 [bezpath lineToPoint:NSMakePoint(x2,y2)];
237 CocoaSetPenForNSBezierPath(m_pen,bezpath);
241 void wxCocoaDCImpl::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, const wxFont *theFont) const
243 wxAutoNSAutoreleasePool pool;
244 // FIXME: Cache this so it can be used for DoDrawText
245 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
246 NSAttributedString *attributedString = [[NSAttributedString alloc]
247 initWithString:wxNSStringWithWxString(text.c_str())];
248 [sm_cocoaNSTextStorage setAttributedString:attributedString];
249 [attributedString release];
251 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
252 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
254 *x=(int)usedRect.size.width;
256 *y=(int)usedRect.size.height;
263 void wxCocoaDCImpl::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
265 wxAutoNSAutoreleasePool pool;
266 if(!CocoaTakeFocus()) return;
267 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
268 NSAttributedString *attributedString = [[NSAttributedString alloc]
269 initWithString:wxNSStringWithWxString(text.c_str())];
270 [sm_cocoaNSTextStorage setAttributedString:attributedString];
271 [attributedString release];
273 // Set the color (and later font) attributes
274 NSColor *fgColor = m_textForegroundColour.GetNSColor();
275 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
277 fgColor = [NSColor clearColor];
279 bgColor = [NSColor clearColor];
280 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
281 fgColor, NSForegroundColorAttributeName,
282 bgColor, NSBackgroundColorAttributeName,
284 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
287 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
288 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
289 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
290 // there is no length or we don't start at zero
291 if(!glyphRange.length)
293 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
295 NSAffineTransform *transform = [NSAffineTransform transform];
296 [transform translateXBy:x yBy:y];
298 NSAffineTransform *flipTransform = [NSAffineTransform transform];
300 y' = 0x + -1y + window's height
302 NSAffineTransformStruct matrix = {
305 , 0, usedRect.size.height
307 [flipTransform setTransformStruct: matrix];
309 NSGraphicsContext *context = [NSGraphicsContext currentContext];
310 [context saveGraphicsState];
312 [flipTransform concat];
314 // Draw+fill a rectangle so we can see where the shit is supposed to be.
315 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
316 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
317 [[NSColor blackColor] set];
319 [[NSColor blueColor] set];
323 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
324 layoutLocation.x = 0.0;
325 layoutLocation.y *= -1.0;
327 // Save the location as is for underlining
328 NSPoint underlineLocation = layoutLocation;
330 // Offset the location by the baseline for drawing the glyphs.
331 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
333 if(m_backgroundMode==wxSOLID)
334 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
335 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
337 int underlineStyle = GetFont().GetUnderlined() ? NSUnderlineStyleSingle : NSUnderlineStyleNone;
338 NSRange lineGlyphRange;
339 NSRect lineRect = [sm_cocoaNSLayoutManager lineFragmentRectForGlyphAtIndex:0 effectiveRange:&lineGlyphRange];
341 [sm_cocoaNSLayoutManager underlineGlyphRange:glyphRange underlineType:underlineStyle
342 lineFragmentRect:lineRect lineFragmentGlyphRange:lineGlyphRange
343 containerOrigin:underlineLocation];
345 [context restoreGraphicsState];
348 ///////////////////////////////////////////////////////////////////////////
349 // cut here, the rest is stubs
350 ///////////////////////////////////////////////////////////////////////////
352 //-----------------------------------------------------------------------------
354 //-----------------------------------------------------------------------------
356 void wxCocoaDCImpl::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
360 void wxCocoaDCImpl::DoDrawPoint( int x, int y )
364 void wxCocoaDCImpl::DoDrawPolygon( int, const wxPoint *, int, int, wxPolygonFillMode)
368 void wxCocoaDCImpl::DoDrawLines( int, const wxPoint *, int, int )
372 int wxCocoaDCImpl::GetDepth() const
377 wxSize wxCocoaDCImpl::GetPPI() const
382 bool wxCocoaDCImpl::CanGetTextExtent() const
387 wxCoord wxCocoaDCImpl::GetCharHeight() const
392 wxCoord wxCocoaDCImpl::GetCharWidth() const
397 bool wxCocoaDCImpl::CanDrawBitmap() const
402 bool wxCocoaDCImpl::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
407 void wxCocoaDCImpl::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
411 void wxCocoaDCImpl::SetFont(const wxFont& font)
416 void wxCocoaDCImpl::SetPen(const wxPen& pen)
421 void wxCocoaDCImpl::SetBrush(const wxBrush& brush)
426 void wxCocoaDCImpl::DoSetClippingRegionAsRegion(const wxRegion& region)
430 void wxCocoaDCImpl::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
434 void wxCocoaDCImpl::DestroyClippingRegion()
438 void wxCocoaDCImpl::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
442 void wxCocoaDCImpl::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
446 void wxCocoaDCImpl::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
450 void wxCocoaDCImpl::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
454 void wxCocoaDCImpl::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
456 wxAutoNSAutoreleasePool pool;
457 if(!CocoaTakeFocus()) return;
462 // Draw a rect so we can see where it's supposed to be
463 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
464 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
465 [[NSColor blackColor] set];
467 [[NSColor blueColor] set];
471 NSAffineTransform *transform = [NSAffineTransform transform];
472 [transform translateXBy:x yBy:y];
474 NSAffineTransform *flipTransform = [NSAffineTransform transform];
476 y' = 0x + -1y + window's height
478 NSAffineTransformStruct matrix = {
483 [flipTransform setTransformStruct: matrix];
485 NSGraphicsContext *context = [NSGraphicsContext currentContext];
486 [context saveGraphicsState];
488 [flipTransform concat];
490 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
492 [nsimage drawAtPoint: NSMakePoint(0,0)
493 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
494 operation: NSCompositeSourceOver
498 [context restoreGraphicsState];
501 bool wxCocoaDCImpl::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, wxFloodFillStyle style)
506 void wxCocoaDCImpl::DoCrossHair(wxCoord x, wxCoord y)
511 bool wxCocoaDCImpl::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height, wxDC *source, wxCoord xsrc, wxCoord ysrc, wxRasterOperationMode rop, bool useMask , wxCoord xsrcMask, wxCoord ysrcMask)
513 if(!CocoaTakeFocus()) return false;
514 if(!source) return false;
515 wxCocoaDCImpl *sourceImpl = static_cast<wxCocoaDCImpl*>(source->GetImpl());
516 return sourceImpl->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
517 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
520 bool wxCocoaDCImpl::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
521 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
522 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
527 void wxCocoaDCImpl::DoGetSize( int* width, int* height ) const
529 *width = m_maxX-m_minX;
530 *height = m_maxY-m_minY;
533 void wxCocoaDCImpl::DoGetSizeMM( int* width, int* height ) const
540 void wxCocoaDCImpl::SetTextForeground( const wxColour &col )
542 // if (!IsOk()) return;
543 m_textForegroundColour = col;
546 void wxCocoaDCImpl::SetTextBackground( const wxColour &col )
548 // if (!IsOk()) return;
549 m_textBackgroundColour = col;
552 void wxCocoaDCImpl::Clear()
554 if(!CocoaTakeFocus()) return;
557 if(!CocoaGetBounds(&boundsRect)) return;
559 NSGraphicsContext *context = [NSGraphicsContext currentContext];
560 [context saveGraphicsState];
562 // Undo all transforms so when we draw our bounds rect we
563 // really overwrite our bounds rect.
564 CocoaUnapplyTransformations();
566 [m_backgroundBrush.GetNSColor() set];
567 [NSBezierPath fillRect:boundsRect];
569 [context restoreGraphicsState];
572 void wxCocoaDCImpl::SetBackground(const wxBrush& brush)
574 m_backgroundBrush = brush;
577 void wxCocoaDCImpl::SetPalette(const wxPalette&)
581 void wxCocoaDCImpl::SetLogicalFunction(wxRasterOperationMode)
586 void wxCocoaDCImpl::SetMapMode( wxMappingMode mode )
600 SetLogicalScale( 1.0, 1.0 );
603 if (mode != wxMM_TEXT)
608 void wxCocoaDCImpl::SetUserScale( double x, double y )
610 // allow negative ? -> no
613 ComputeScaleAndOrigin();
616 void wxCocoaDCImpl::SetLogicalScale( double x, double y )
621 ComputeScaleAndOrigin();
624 void wxCocoaDCImpl::SetLogicalOrigin( wxCoord x, wxCoord y )
626 m_logicalOriginX = x * m_signX; // is this still correct ?
627 m_logicalOriginY = y * m_signY;
628 ComputeScaleAndOrigin();
631 void wxCocoaDCImpl::SetDeviceOrigin( wxCoord x, wxCoord y )
633 ComputeScaleAndOrigin();
636 void wxCocoaDCImpl::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
638 m_signX = (xLeftRight ? 1 : -1);
639 m_signY = (yBottomUp ? -1 : 1);
640 ComputeScaleAndOrigin();
643 void wxCocoaDCImpl::ComputeScaleAndOrigin(void)
645 // CMB: copy scale to see if it changes
646 double origScaleX = m_scaleX;
647 double origScaleY = m_scaleY;
649 m_scaleX = m_logicalScaleX * m_userScaleX;
650 m_scaleY = m_logicalScaleY * m_userScaleY;
652 // CMB: if scale has changed call SetPen to recalulate the line width
653 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
656 // this is a bit artificial, but we need to force wxDC to think
657 // the pen has changed
658 const wxPen* pen = & GetPen();