1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/dc.mm
4 // Author: David Elliott
8 // Copyright: (c) 2003 David Elliott
9 // Licence: wxWindows 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"
23 #include "wx/cocoa/ObjcRef.h"
25 #import <AppKit/NSBezierPath.h>
26 #import <AppKit/NSTextStorage.h>
27 #import <AppKit/NSLayoutManager.h>
28 #import <AppKit/NSTextContainer.h>
29 #import <AppKit/NSGraphicsContext.h>
30 #import <AppKit/NSAffineTransform.h>
31 #import <AppKit/NSColor.h>
32 #import <AppKit/NSTypesetter.h>
33 #import <AppKit/NSImage.h>
35 #include "wx/listimpl.cpp"
36 WX_DEFINE_LIST(wxCocoaDCStack);
38 IMPLEMENT_ABSTRACT_CLASS(wxCocoaDCImpl, wxDCImpl)
40 WX_NSTextStorage wxCocoaDCImpl::sm_cocoaNSTextStorage = nil;
41 WX_NSLayoutManager wxCocoaDCImpl::sm_cocoaNSLayoutManager = nil;
42 WX_NSTextContainer wxCocoaDCImpl::sm_cocoaNSTextContainer = nil;
43 wxCocoaDCStack wxCocoaDCImpl::sm_cocoaDCStack;
45 inline void CocoaSetPenForNSBezierPath(wxPen &pen, NSBezierPath *bezpath)
47 [pen.GetNSColor() set];
48 const CGFloat *pattern;
49 [bezpath setLineDash:pattern count:pen.GetCocoaLineDash(&pattern) phase:0.0];
50 [bezpath setLineWidth:pen.GetWidth()];
54 [bezpath setLineJoinStyle:NSBevelLineJoinStyle];
57 [bezpath setLineJoinStyle:NSRoundLineJoinStyle];
60 [bezpath setLineJoinStyle:NSMiterLineJoinStyle];
66 [bezpath setLineCapStyle:NSRoundLineCapStyle];
68 case wxCAP_PROJECTING:
69 [bezpath setLineCapStyle:NSSquareLineCapStyle];
72 [bezpath setLineCapStyle:NSButtLineCapStyle];
77 void wxCocoaDCImpl::CocoaInitializeTextSystem()
79 wxAutoNSAutoreleasePool pool;
81 wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized! BAD PROGRAMMER!"));
83 // FIXME: Never released
84 sm_cocoaNSTextStorage = wxGCSafeRetain([[[NSTextStorage alloc] init] autorelease]);
86 // FIXME: Never released
87 sm_cocoaNSLayoutManager = wxGCSafeRetain([[[NSLayoutManager alloc] init] autorelease]);
89 [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
90 // NSTextStorage retains NSLayoutManager, but so do we
91 // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
93 // NOTE: initWithContainerSize is the designated initializer, but the
94 // Apple CircleView sample gets away with just calling init, which
95 // is all we really need for our purposes.
96 // FIXME: Never released
97 sm_cocoaNSTextContainer = wxGCSafeRetain([[[NSTextContainer alloc] init] autorelease]);
98 [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
99 // NSLayoutManager retains NSTextContainer, but so do we
100 // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
103 void wxCocoaDCImpl::CocoaShutdownTextSystem()
105 [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
106 [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
107 [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
110 void wxCocoaDCImpl::CocoaUnwindStackAndLoseFocus()
112 wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
115 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
116 for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
118 wxCocoaDCImpl *dc = node->GetData();
121 if(!dc->CocoaUnlockFocus())
123 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
125 sm_cocoaDCStack.Erase(node);
127 wxASSERT(node==ourNode);
128 wxASSERT(ourNode->GetData() == this);
129 ourNode->GetData()->CocoaUnlockFocus();
130 sm_cocoaDCStack.Erase(ourNode);
134 bool wxCocoaDCImpl::CocoaUnwindStackAndTakeFocus()
136 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
137 for(;node;node = sm_cocoaDCStack.GetFirst())
139 wxCocoaDCImpl *dc = node->GetData();
141 // If we're on the stack, then it's unwound enough and we have focus
144 // If unable to unlockFocus (e.g. wxPaintDC) stop here
145 if(!dc->CocoaUnlockFocus())
147 sm_cocoaDCStack.Erase(node);
149 return CocoaLockFocus();
152 wxCocoaDCImpl::wxCocoaDCImpl(wxDC *owner)
155 m_cocoaWxToBoundsTransform = nil;
156 m_pen = *wxBLACK_PEN;
159 wxCocoaDCImpl::~wxDC(void)
161 [m_cocoaWxToBoundsTransform release];
164 bool wxCocoaDCImpl::CocoaLockFocus()
169 bool wxCocoaDCImpl::CocoaUnlockFocus()
174 /*static*/ WX_NSAffineTransform wxCocoaDCImpl::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
176 NSAffineTransform *transform = nil;
177 // This transform flips the graphics since wxDC uses top-left origin
180 // The transform is auto released
181 transform = [NSAffineTransform transform];
183 y' = 0x + -1y + window's height
185 NSAffineTransformStruct matrix = {
190 [transform setTransformStruct: matrix];
195 void wxCocoaDCImpl::CocoaApplyTransformations()
197 [m_cocoaWxToBoundsTransform concat];
198 // TODO: Apply device/logical/user position/scaling transformations
201 void wxCocoaDCImpl::CocoaUnapplyTransformations()
203 // NOTE: You *must* call this with focus held.
204 // Undo all transforms so we're back in true Cocoa coords with
205 // no scaling or flipping.
206 NSAffineTransform *invertTransform;
207 invertTransform = [m_cocoaWxToBoundsTransform copy];
208 [invertTransform invert];
209 [invertTransform concat];
210 [invertTransform release];
213 bool wxCocoaDCImpl::CocoaGetBounds(void *rectData)
215 // We don't know what we are so we can't return anything.
219 void wxCocoaDCImpl::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
221 wxAutoNSAutoreleasePool pool;
222 if(!CocoaTakeFocus()) return;
223 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
224 CocoaSetPenForNSBezierPath(m_pen,bezpath);
226 [m_brush.GetNSColor() set];
230 void wxCocoaDCImpl::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
232 wxAutoNSAutoreleasePool pool;
233 if(!CocoaTakeFocus()) return;
234 NSBezierPath *bezpath = [NSBezierPath bezierPath];
235 [bezpath moveToPoint:NSMakePoint(x1,y1)];
236 [bezpath lineToPoint:NSMakePoint(x2,y2)];
238 CocoaSetPenForNSBezierPath(m_pen,bezpath);
242 void wxCocoaDCImpl::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, const wxFont *theFont) const
244 wxAutoNSAutoreleasePool pool;
245 // FIXME: Cache this so it can be used for DoDrawText
246 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
247 NSAttributedString *attributedString = [[NSAttributedString alloc]
248 initWithString:wxNSStringWithWxString(text.c_str())];
249 [sm_cocoaNSTextStorage setAttributedString:attributedString];
250 [attributedString release];
252 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
253 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
255 *x=(int)usedRect.size.width;
257 *y=(int)usedRect.size.height;
264 void wxCocoaDCImpl::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
266 wxAutoNSAutoreleasePool pool;
267 if(!CocoaTakeFocus()) return;
268 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
269 NSAttributedString *attributedString = [[NSAttributedString alloc]
270 initWithString:wxNSStringWithWxString(text.c_str())];
271 [sm_cocoaNSTextStorage setAttributedString:attributedString];
272 [attributedString release];
274 // Set the color (and later font) attributes
275 NSColor *fgColor = m_textForegroundColour.GetNSColor();
276 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
278 fgColor = [NSColor clearColor];
280 bgColor = [NSColor clearColor];
281 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
282 fgColor, NSForegroundColorAttributeName,
283 bgColor, NSBackgroundColorAttributeName,
285 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
288 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
289 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
290 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
291 // there is no length or we don't start at zero
292 if(!glyphRange.length)
294 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
296 NSAffineTransform *transform = [NSAffineTransform transform];
297 [transform translateXBy:x yBy:y];
299 NSAffineTransform *flipTransform = [NSAffineTransform transform];
301 y' = 0x + -1y + window's height
303 NSAffineTransformStruct matrix = {
306 , 0, usedRect.size.height
308 [flipTransform setTransformStruct: matrix];
310 NSGraphicsContext *context = [NSGraphicsContext currentContext];
311 [context saveGraphicsState];
313 [flipTransform concat];
315 // Draw+fill a rectangle so we can see where the shit is supposed to be.
316 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
317 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
318 [[NSColor blackColor] set];
320 [[NSColor blueColor] set];
324 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
325 layoutLocation.x = 0.0;
326 layoutLocation.y *= -1.0;
328 // Save the location as is for underlining
329 NSPoint underlineLocation = layoutLocation;
331 // Offset the location by the baseline for drawing the glyphs.
332 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
334 if(m_backgroundMode==wxSOLID)
335 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
336 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
338 int underlineStyle = GetFont().GetUnderlined() ? NSUnderlineStyleSingle : NSUnderlineStyleNone;
339 NSRange lineGlyphRange;
340 NSRect lineRect = [sm_cocoaNSLayoutManager lineFragmentRectForGlyphAtIndex:0 effectiveRange:&lineGlyphRange];
342 [sm_cocoaNSLayoutManager underlineGlyphRange:glyphRange underlineType:underlineStyle
343 lineFragmentRect:lineRect lineFragmentGlyphRange:lineGlyphRange
344 containerOrigin:underlineLocation];
346 [context restoreGraphicsState];
349 ///////////////////////////////////////////////////////////////////////////
350 // cut here, the rest is stubs
351 ///////////////////////////////////////////////////////////////////////////
353 //-----------------------------------------------------------------------------
355 //-----------------------------------------------------------------------------
357 void wxCocoaDCImpl::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
361 void wxCocoaDCImpl::DoDrawPoint( int x, int y )
365 void wxCocoaDCImpl::DoDrawPolygon( int, const wxPoint *, int, int, wxPolygonFillMode)
369 void wxCocoaDCImpl::DoDrawLines( int, const wxPoint *, int, int )
373 int wxCocoaDCImpl::GetDepth() const
378 wxSize wxCocoaDCImpl::GetPPI() const
383 bool wxCocoaDCImpl::CanGetTextExtent() const
388 wxCoord wxCocoaDCImpl::GetCharHeight() const
393 wxCoord wxCocoaDCImpl::GetCharWidth() const
398 bool wxCocoaDCImpl::CanDrawBitmap() const
403 bool wxCocoaDCImpl::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
408 void wxCocoaDCImpl::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
412 void wxCocoaDCImpl::SetFont(const wxFont& font)
417 void wxCocoaDCImpl::SetPen(const wxPen& pen)
422 void wxCocoaDCImpl::SetBrush(const wxBrush& brush)
427 void wxCocoaDCImpl::DoSetClippingRegionAsRegion(const wxRegion& region)
431 void wxCocoaDCImpl::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
435 void wxCocoaDCImpl::DestroyClippingRegion()
439 void wxCocoaDCImpl::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
443 void wxCocoaDCImpl::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
447 void wxCocoaDCImpl::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
451 void wxCocoaDCImpl::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
455 void wxCocoaDCImpl::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
457 wxAutoNSAutoreleasePool pool;
458 if(!CocoaTakeFocus()) return;
463 // Draw a rect so we can see where it's supposed to be
464 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
465 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
466 [[NSColor blackColor] set];
468 [[NSColor blueColor] set];
472 NSAffineTransform *transform = [NSAffineTransform transform];
473 [transform translateXBy:x yBy:y];
475 NSAffineTransform *flipTransform = [NSAffineTransform transform];
477 y' = 0x + -1y + window's height
479 NSAffineTransformStruct matrix = {
484 [flipTransform setTransformStruct: matrix];
486 NSGraphicsContext *context = [NSGraphicsContext currentContext];
487 [context saveGraphicsState];
489 [flipTransform concat];
491 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
493 [nsimage drawAtPoint: NSMakePoint(0,0)
494 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
495 operation: NSCompositeSourceOver
499 [context restoreGraphicsState];
502 bool wxCocoaDCImpl::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, wxFloodFillStyle style)
507 void wxCocoaDCImpl::DoCrossHair(wxCoord x, wxCoord y)
512 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)
514 if(!CocoaTakeFocus()) return false;
515 if(!source) return false;
516 wxCocoaDCImpl *sourceImpl = static_cast<wxCocoaDCImpl*>(source->GetImpl());
517 return sourceImpl->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
518 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
521 bool wxCocoaDCImpl::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
522 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
523 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
528 void wxCocoaDCImpl::DoGetSize( int* width, int* height ) const
530 *width = m_maxX-m_minX;
531 *height = m_maxY-m_minY;
534 void wxCocoaDCImpl::DoGetSizeMM( int* width, int* height ) const
541 void wxCocoaDCImpl::SetTextForeground( const wxColour &col )
543 // if (!IsOk()) return;
544 m_textForegroundColour = col;
547 void wxCocoaDCImpl::SetTextBackground( const wxColour &col )
549 // if (!IsOk()) return;
550 m_textBackgroundColour = col;
553 void wxCocoaDCImpl::Clear()
555 if(!CocoaTakeFocus()) return;
558 if(!CocoaGetBounds(&boundsRect)) return;
560 NSGraphicsContext *context = [NSGraphicsContext currentContext];
561 [context saveGraphicsState];
563 // Undo all transforms so when we draw our bounds rect we
564 // really overwrite our bounds rect.
565 CocoaUnapplyTransformations();
567 [m_backgroundBrush.GetNSColor() set];
568 [NSBezierPath fillRect:boundsRect];
570 [context restoreGraphicsState];
573 void wxCocoaDCImpl::SetBackground(const wxBrush& brush)
575 m_backgroundBrush = brush;
578 void wxCocoaDCImpl::SetPalette(const wxPalette&)
582 void wxCocoaDCImpl::SetLogicalFunction(wxRasterOperationMode)
587 void wxCocoaDCImpl::SetMapMode( wxMappingMode mode )
601 SetLogicalScale( 1.0, 1.0 );
604 if (mode != wxMM_TEXT)
609 void wxCocoaDCImpl::SetUserScale( double x, double y )
611 // allow negative ? -> no
614 ComputeScaleAndOrigin();
617 void wxCocoaDCImpl::SetLogicalScale( double x, double y )
622 ComputeScaleAndOrigin();
625 void wxCocoaDCImpl::SetLogicalOrigin( wxCoord x, wxCoord y )
627 m_logicalOriginX = x * m_signX; // is this still correct ?
628 m_logicalOriginY = y * m_signY;
629 ComputeScaleAndOrigin();
632 void wxCocoaDCImpl::SetDeviceOrigin( wxCoord x, wxCoord y )
634 ComputeScaleAndOrigin();
637 void wxCocoaDCImpl::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
639 m_signX = (xLeftRight ? 1 : -1);
640 m_signY = (yBottomUp ? -1 : 1);
641 ComputeScaleAndOrigin();
644 void wxCocoaDCImpl::ComputeScaleAndOrigin(void)
646 // CMB: copy scale to see if it changes
647 double origScaleX = m_scaleX;
648 double origScaleY = m_scaleY;
650 m_scaleX = m_logicalScaleX * m_userScaleX;
651 m_scaleY = m_logicalScaleY * m_userScaleY;
653 // CMB: if scale has changed call SetPen to recalulate the line width
654 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
657 // this is a bit artificial, but we need to force wxDC to think
658 // the pen has changed
659 const wxPen* pen = & GetPen();