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];
199 bool wxDC::CocoaGetBounds(void *rectData)
201 // We don't know what we are so we can't return anything.
205 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
207 wxAutoNSAutoreleasePool pool;
208 if(!CocoaTakeFocus()) return;
209 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
210 CocoaSetPenForNSBezierPath(m_pen,bezpath);
212 [m_brush.GetNSColor() set];
216 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
218 wxAutoNSAutoreleasePool pool;
219 if(!CocoaTakeFocus()) return;
220 NSBezierPath *bezpath = [NSBezierPath bezierPath];
221 [bezpath moveToPoint:NSMakePoint(x1,y1)];
222 [bezpath lineToPoint:NSMakePoint(x2,y2)];
224 CocoaSetPenForNSBezierPath(m_pen,bezpath);
228 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
230 wxAutoNSAutoreleasePool pool;
231 // FIXME: Cache this so it can be used for DoDrawText
232 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
233 NSAttributedString *attributedString = [[NSAttributedString alloc]
234 initWithString:wxNSStringWithWxString(text.c_str())];
235 [sm_cocoaNSTextStorage setAttributedString:attributedString];
236 [attributedString release];
238 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
239 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
241 *x=(int)usedRect.size.width;
243 *y=(int)usedRect.size.height;
250 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
252 wxAutoNSAutoreleasePool pool;
253 if(!CocoaTakeFocus()) return;
254 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
255 NSAttributedString *attributedString = [[NSAttributedString alloc]
256 initWithString:wxNSStringWithWxString(text.c_str())];
257 [sm_cocoaNSTextStorage setAttributedString:attributedString];
258 [attributedString release];
260 // Set the color (and later font) attributes
261 NSColor *fgColor = m_textForegroundColour.GetNSColor();
262 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
264 fgColor = [NSColor clearColor];
266 bgColor = [NSColor clearColor];
267 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
268 fgColor, NSForegroundColorAttributeName,
269 bgColor, NSBackgroundColorAttributeName,
271 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
274 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
275 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
276 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
277 // there is no length or we don't start at zero
278 if(!glyphRange.length)
280 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
282 NSAffineTransform *transform = [NSAffineTransform transform];
283 [transform translateXBy:x yBy:y];
285 NSAffineTransform *flipTransform = [NSAffineTransform transform];
287 y' = 0x + -1y + window's height
289 NSAffineTransformStruct matrix = {
292 , 0, usedRect.size.height
294 [flipTransform setTransformStruct: matrix];
296 NSGraphicsContext *context = [NSGraphicsContext currentContext];
297 [context saveGraphicsState];
299 [flipTransform concat];
301 // Draw+fill a rectangle so we can see where the shit is supposed to be.
302 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
303 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
304 [[NSColor blackColor] set];
306 [[NSColor blueColor] set];
310 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
311 layoutLocation.x = 0.0;
312 layoutLocation.y *= -1.0;
313 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
314 if(m_backgroundMode==wxSOLID)
315 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
316 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
318 [context restoreGraphicsState];
321 // wxDCBase functions
322 int wxDCBase::DeviceToLogicalX(int x) const
327 int wxDCBase::DeviceToLogicalY(int y) const
332 int wxDCBase::DeviceToLogicalXRel(int x) const
337 int wxDCBase::DeviceToLogicalYRel(int y) const
342 int wxDCBase::LogicalToDeviceX(int x) const
347 int wxDCBase::LogicalToDeviceY(int y) const
352 int wxDCBase::LogicalToDeviceXRel(int x) const
357 int wxDCBase::LogicalToDeviceYRel(int y) const
362 ///////////////////////////////////////////////////////////////////////////
363 // cut here, the rest is stubs
364 ///////////////////////////////////////////////////////////////////////////
366 //-----------------------------------------------------------------------------
368 //-----------------------------------------------------------------------------
370 #define mm2inches 0.0393700787402
371 #define inches2mm 25.4
372 #define mm2twips 56.6929133859
373 #define twips2mm 0.0176388888889
374 #define mm2pt 2.83464566929
375 #define pt2mm 0.352777777778
377 //-----------------------------------------------------------------------------
379 //-----------------------------------------------------------------------------
381 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
385 void wxDC::DoDrawPoint( int x, int y )
389 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
393 void wxDC::DoDrawLines( int, wxPoint *, int, int )
397 int wxDC::GetDepth() const
402 wxSize wxDC::GetPPI() const
407 bool wxDC::CanGetTextExtent() const
412 wxCoord wxDC::GetCharHeight() const
417 wxCoord wxDC::GetCharWidth() const
422 bool wxDC::CanDrawBitmap() const
427 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
432 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
436 void wxDC::SetPen(const wxPen& pen)
441 void wxDC::SetBrush(const wxBrush& brush)
446 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
450 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
454 void wxDC::DestroyClippingRegion()
458 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
462 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
466 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
470 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
474 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
476 wxAutoNSAutoreleasePool pool;
477 if(!CocoaTakeFocus()) return;
482 // Draw a rect so we can see where it's supposed to be
483 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
484 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
485 [[NSColor blackColor] set];
487 [[NSColor blueColor] set];
491 NSAffineTransform *transform = [NSAffineTransform transform];
492 [transform translateXBy:x yBy:y];
494 NSAffineTransform *flipTransform = [NSAffineTransform transform];
496 y' = 0x + -1y + window's height
498 NSAffineTransformStruct matrix = {
503 [flipTransform setTransformStruct: matrix];
505 NSGraphicsContext *context = [NSGraphicsContext currentContext];
506 [context saveGraphicsState];
508 [flipTransform concat];
510 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
512 [nsimage drawAtPoint: NSMakePoint(0,0)
513 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
514 operation: NSCompositeSourceOver
518 [context restoreGraphicsState];
521 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
526 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
531 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)
533 if(!CocoaTakeFocus()) return false;
534 if(!source) return false;
535 return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
536 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
539 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
540 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
541 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
546 void wxDC::DoGetSize( int* width, int* height ) const
548 *width = m_maxX-m_minX;
549 *height = m_maxY-m_minY;
552 void wxDC::DoGetSizeMM( int* width, int* height ) const
559 void wxDC::SetTextForeground( const wxColour &col )
562 m_textForegroundColour = col;
565 void wxDC::SetTextBackground( const wxColour &col )
568 m_textBackgroundColour = col;
573 if(!CocoaTakeFocus()) return;
576 if(!CocoaGetBounds(&boundsRect)) return;
578 NSGraphicsContext *context = [NSGraphicsContext currentContext];
579 [context saveGraphicsState];
581 // Undo all transforms so when we draw our bounds rect we
582 // really overwrite our bounds rect.
583 CocoaUnapplyTransformations();
585 [m_backgroundBrush.GetNSColor() set];
586 [NSBezierPath fillRect:boundsRect];
588 [context restoreGraphicsState];
591 void wxDC::SetBackground(const wxBrush& brush)
593 m_backgroundBrush = brush;
596 void wxDC::SetPalette(const wxPalette&)
600 void wxDC::SetLogicalFunction(int)
605 void wxDC::SetMapMode( int mode )
619 SetLogicalScale( 1.0, 1.0 );
622 if (mode != wxMM_TEXT)
627 void wxDC::SetUserScale( double x, double y )
629 // allow negative ? -> no
632 ComputeScaleAndOrigin();
635 void wxDC::SetLogicalScale( double x, double y )
640 ComputeScaleAndOrigin();
643 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
645 m_logicalOriginX = x * m_signX; // is this still correct ?
646 m_logicalOriginY = y * m_signY;
647 ComputeScaleAndOrigin();
650 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
652 ComputeScaleAndOrigin();
655 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
657 m_signX = (xLeftRight ? 1 : -1);
658 m_signY = (yBottomUp ? -1 : 1);
659 ComputeScaleAndOrigin();
662 void wxDC::ComputeScaleAndOrigin(void)
664 // CMB: copy scale to see if it changes
665 double origScaleX = m_scaleX;
666 double origScaleY = m_scaleY;
668 m_scaleX = m_logicalScaleX * m_userScaleX;
669 m_scaleY = m_logicalScaleY * m_userScaleY;
671 // CMB: if scale has changed call SetPen to recalulate the line width
672 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
674 // this is a bit artificial, but we need to force wxDC to think
675 // the pen has changed
676 const wxPen* pen = & GetPen();