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;
151 bool wxDC::CocoaLockFocus()
156 bool wxDC::CocoaUnlockFocus()
161 /*static*/ WX_NSAffineTransform wxDC::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
163 NSAffineTransform *transform = nil;
164 // This transform flips the graphics since wxDC uses top-left origin
167 // The transform is auto released
168 transform = [NSAffineTransform transform];
170 y' = 0x + -1y + window's height
172 NSAffineTransformStruct matrix = {
177 [transform setTransformStruct: matrix];
182 void wxDC::CocoaApplyTransformations()
184 [m_cocoaWxToBoundsTransform concat];
185 // TODO: Apply device/logical/user position/scaling transformations
188 void wxDC::CocoaUnapplyTransformations()
190 // NOTE: You *must* call this with focus held.
191 // Undo all transforms so we're back in true Cocoa coords with
192 // no scaling or flipping.
193 NSAffineTransform *invertTransform;
194 invertTransform = [m_cocoaWxToBoundsTransform copy];
195 [invertTransform invert];
196 [invertTransform concat];
197 [invertTransform release];
200 bool wxDC::CocoaGetBounds(void *rectData)
202 // We don't know what we are so we can't return anything.
206 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
208 wxAutoNSAutoreleasePool pool;
209 if(!CocoaTakeFocus()) return;
210 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
211 CocoaSetPenForNSBezierPath(m_pen,bezpath);
213 [m_brush.GetNSColor() set];
217 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
219 wxAutoNSAutoreleasePool pool;
220 if(!CocoaTakeFocus()) return;
221 NSBezierPath *bezpath = [NSBezierPath bezierPath];
222 [bezpath moveToPoint:NSMakePoint(x1,y1)];
223 [bezpath lineToPoint:NSMakePoint(x2,y2)];
225 CocoaSetPenForNSBezierPath(m_pen,bezpath);
229 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
231 wxAutoNSAutoreleasePool pool;
232 // FIXME: Cache this so it can be used for DoDrawText
233 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
234 NSAttributedString *attributedString = [[NSAttributedString alloc]
235 initWithString:wxNSStringWithWxString(text.c_str())];
236 [sm_cocoaNSTextStorage setAttributedString:attributedString];
237 [attributedString release];
239 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
240 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
242 *x=(int)usedRect.size.width;
244 *y=(int)usedRect.size.height;
251 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
253 wxAutoNSAutoreleasePool pool;
254 if(!CocoaTakeFocus()) return;
255 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
256 NSAttributedString *attributedString = [[NSAttributedString alloc]
257 initWithString:wxNSStringWithWxString(text.c_str())];
258 [sm_cocoaNSTextStorage setAttributedString:attributedString];
259 [attributedString release];
261 // Set the color (and later font) attributes
262 NSColor *fgColor = m_textForegroundColour.GetNSColor();
263 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
265 fgColor = [NSColor clearColor];
267 bgColor = [NSColor clearColor];
268 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
269 fgColor, NSForegroundColorAttributeName,
270 bgColor, NSBackgroundColorAttributeName,
272 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
275 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
276 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
277 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
278 // there is no length or we don't start at zero
279 if(!glyphRange.length)
281 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
283 NSAffineTransform *transform = [NSAffineTransform transform];
284 [transform translateXBy:x yBy:y];
286 NSAffineTransform *flipTransform = [NSAffineTransform transform];
288 y' = 0x + -1y + window's height
290 NSAffineTransformStruct matrix = {
293 , 0, usedRect.size.height
295 [flipTransform setTransformStruct: matrix];
297 NSGraphicsContext *context = [NSGraphicsContext currentContext];
298 [context saveGraphicsState];
300 [flipTransform concat];
302 // Draw+fill a rectangle so we can see where the shit is supposed to be.
303 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
304 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
305 [[NSColor blackColor] set];
307 [[NSColor blueColor] set];
311 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
312 layoutLocation.x = 0.0;
313 layoutLocation.y *= -1.0;
314 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
315 if(m_backgroundMode==wxSOLID)
316 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
317 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
319 [context restoreGraphicsState];
322 // wxDCBase functions
323 int wxDCBase::DeviceToLogicalX(int x) const
328 int wxDCBase::DeviceToLogicalY(int y) const
333 int wxDCBase::DeviceToLogicalXRel(int x) const
338 int wxDCBase::DeviceToLogicalYRel(int y) const
343 int wxDCBase::LogicalToDeviceX(int x) const
348 int wxDCBase::LogicalToDeviceY(int y) const
353 int wxDCBase::LogicalToDeviceXRel(int x) const
358 int wxDCBase::LogicalToDeviceYRel(int y) const
363 ///////////////////////////////////////////////////////////////////////////
364 // cut here, the rest is stubs
365 ///////////////////////////////////////////////////////////////////////////
367 //-----------------------------------------------------------------------------
369 //-----------------------------------------------------------------------------
371 #define mm2inches 0.0393700787402
372 #define inches2mm 25.4
373 #define mm2twips 56.6929133859
374 #define twips2mm 0.0176388888889
375 #define mm2pt 2.83464566929
376 #define pt2mm 0.352777777778
378 //-----------------------------------------------------------------------------
380 //-----------------------------------------------------------------------------
382 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
386 void wxDC::DoDrawPoint( int x, int y )
390 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
394 void wxDC::DoDrawLines( int, wxPoint *, int, int )
398 int wxDC::GetDepth() const
403 wxSize wxDC::GetPPI() const
408 bool wxDC::CanGetTextExtent() const
413 wxCoord wxDC::GetCharHeight() const
418 wxCoord wxDC::GetCharWidth() const
423 bool wxDC::CanDrawBitmap() const
428 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
433 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
437 void wxDC::SetPen(const wxPen& pen)
442 void wxDC::SetBrush(const wxBrush& brush)
447 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
451 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
455 void wxDC::DestroyClippingRegion()
459 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
463 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
467 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
471 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
475 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
477 wxAutoNSAutoreleasePool pool;
478 if(!CocoaTakeFocus()) return;
483 // Draw a rect so we can see where it's supposed to be
484 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
485 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
486 [[NSColor blackColor] set];
488 [[NSColor blueColor] set];
492 NSAffineTransform *transform = [NSAffineTransform transform];
493 [transform translateXBy:x yBy:y];
495 NSAffineTransform *flipTransform = [NSAffineTransform transform];
497 y' = 0x + -1y + window's height
499 NSAffineTransformStruct matrix = {
504 [flipTransform setTransformStruct: matrix];
506 NSGraphicsContext *context = [NSGraphicsContext currentContext];
507 [context saveGraphicsState];
509 [flipTransform concat];
511 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
513 [nsimage drawAtPoint: NSMakePoint(0,0)
514 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
515 operation: NSCompositeSourceOver
519 [context restoreGraphicsState];
522 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
527 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
532 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)
534 if(!CocoaTakeFocus()) return false;
535 if(!source) return false;
536 return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
537 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
540 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
541 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
542 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
547 void wxDC::DoGetSize( int* width, int* height ) const
549 *width = m_maxX-m_minX;
550 *height = m_maxY-m_minY;
553 void wxDC::DoGetSizeMM( int* width, int* height ) const
560 void wxDC::SetTextForeground( const wxColour &col )
563 m_textForegroundColour = col;
566 void wxDC::SetTextBackground( const wxColour &col )
569 m_textBackgroundColour = col;
574 if(!CocoaTakeFocus()) return;
577 if(!CocoaGetBounds(&boundsRect)) return;
579 NSGraphicsContext *context = [NSGraphicsContext currentContext];
580 [context saveGraphicsState];
582 // Undo all transforms so when we draw our bounds rect we
583 // really overwrite our bounds rect.
584 CocoaUnapplyTransformations();
586 [m_backgroundBrush.GetNSColor() set];
587 [NSBezierPath fillRect:boundsRect];
589 [context restoreGraphicsState];
592 void wxDC::SetBackground(const wxBrush& brush)
594 m_backgroundBrush = brush;
597 void wxDC::SetPalette(const wxPalette&)
601 void wxDC::SetLogicalFunction(int)
606 void wxDC::SetMapMode( int mode )
620 SetLogicalScale( 1.0, 1.0 );
623 if (mode != wxMM_TEXT)
628 void wxDC::SetUserScale( double x, double y )
630 // allow negative ? -> no
633 ComputeScaleAndOrigin();
636 void wxDC::SetLogicalScale( double x, double y )
641 ComputeScaleAndOrigin();
644 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
646 m_logicalOriginX = x * m_signX; // is this still correct ?
647 m_logicalOriginY = y * m_signY;
648 ComputeScaleAndOrigin();
651 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
653 ComputeScaleAndOrigin();
656 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
658 m_signX = (xLeftRight ? 1 : -1);
659 m_signY = (yBottomUp ? -1 : 1);
660 ComputeScaleAndOrigin();
663 void wxDC::ComputeScaleAndOrigin(void)
665 // CMB: copy scale to see if it changes
666 double origScaleX = m_scaleX;
667 double origScaleY = m_scaleY;
669 m_scaleX = m_logicalScaleX * m_userScaleX;
670 m_scaleY = m_logicalScaleY * m_userScaleY;
672 // CMB: if scale has changed call SetPen to recalulate the line width
673 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
675 // this is a bit artificial, but we need to force wxDC to think
676 // the pen has changed
677 const wxPen* pen = & GetPen();