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/math.h" //math constants
32 #include "wx/listimpl.cpp"
33 WX_DEFINE_LIST(wxCocoaDCStack);
35 IMPLEMENT_ABSTRACT_CLASS(wxDC, wxObject)
36 WX_NSTextStorage wxDC::sm_cocoaNSTextStorage = nil;
37 WX_NSLayoutManager wxDC::sm_cocoaNSLayoutManager = nil;
38 WX_NSTextContainer wxDC::sm_cocoaNSTextContainer = nil;
39 wxCocoaDCStack wxDC::sm_cocoaDCStack;
41 inline void CocoaSetPenForNSBezierPath(wxPen &pen, NSBezierPath *bezpath)
43 [pen.GetNSColor() set];
45 [bezpath setLineDash:pattern count:pen.GetCocoaLineDash(&pattern) phase:0.0];
46 [bezpath setLineWidth:pen.GetWidth()];
50 [bezpath setLineJoinStyle:NSBevelLineJoinStyle];
53 [bezpath setLineJoinStyle:NSRoundLineJoinStyle];
56 [bezpath setLineJoinStyle:NSMiterLineJoinStyle];
62 [bezpath setLineCapStyle:NSRoundLineCapStyle];
64 case wxCAP_PROJECTING:
65 [bezpath setLineCapStyle:NSSquareLineCapStyle];
68 [bezpath setLineCapStyle:NSButtLineCapStyle];
73 void wxDC::CocoaInitializeTextSystem()
75 wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,wxT("Text system already initalized! BAD PROGRAMMER!"));
77 sm_cocoaNSTextStorage = [[NSTextStorage alloc] init];
79 sm_cocoaNSLayoutManager = [[NSLayoutManager alloc] init];
80 [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
81 // NSTextStorage retains NSLayoutManager, but so do we
82 // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
84 // NOTE: initWithContainerSize is the designated initializer, but the
85 // Apple CircleView sample gets away with just calling init, which
86 // is all we really need for our purposes.
87 sm_cocoaNSTextContainer = [[NSTextContainer alloc] init];
88 [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
89 // NSLayoutManager retains NSTextContainer, but so do we
90 // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
93 void wxDC::CocoaShutdownTextSystem()
95 [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
96 [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
97 [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
100 void wxDC::CocoaUnwindStackAndLoseFocus()
102 wxCocoaDCStack::compatibility_iterator ourNode=sm_cocoaDCStack.Find(this);
105 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
106 for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
108 wxDC *dc = node->GetData();
111 if(!dc->CocoaUnlockFocus())
113 wxFAIL_MSG(wxT("Unable to unlock focus on higher-level DC!"));
115 sm_cocoaDCStack.Erase(node);
117 wxASSERT(node==ourNode);
118 wxASSERT(ourNode->GetData() == this);
119 ourNode->GetData()->CocoaUnlockFocus();
120 sm_cocoaDCStack.Erase(ourNode);
124 bool wxDC::CocoaUnwindStackAndTakeFocus()
126 wxCocoaDCStack::compatibility_iterator node=sm_cocoaDCStack.GetFirst();
127 for(;node;node = sm_cocoaDCStack.GetFirst())
129 wxDC *dc = node->GetData();
131 // If we're on the stack, then it's unwound enough and we have focus
134 // If unable to unlockFocus (e.g. wxPaintDC) stop here
135 if(!dc->CocoaUnlockFocus())
137 sm_cocoaDCStack.Erase(node);
139 return CocoaLockFocus();
144 m_cocoaWxToBoundsTransform = nil;
145 m_pen = *wxBLACK_PEN;
150 [m_cocoaWxToBoundsTransform release];
153 bool wxDC::CocoaLockFocus()
158 bool wxDC::CocoaUnlockFocus()
163 /*static*/ WX_NSAffineTransform wxDC::CocoaGetWxToBoundsTransform(bool isFlipped, float height)
165 NSAffineTransform *transform = nil;
166 // This transform flips the graphics since wxDC uses top-left origin
169 // The transform is auto released
170 transform = [NSAffineTransform transform];
172 y' = 0x + -1y + window's height
174 NSAffineTransformStruct matrix = {
179 [transform setTransformStruct: matrix];
184 void wxDC::CocoaApplyTransformations()
186 [m_cocoaWxToBoundsTransform concat];
187 // TODO: Apply device/logical/user position/scaling transformations
190 void wxDC::CocoaUnapplyTransformations()
192 // NOTE: You *must* call this with focus held.
193 // Undo all transforms so we're back in true Cocoa coords with
194 // no scaling or flipping.
195 NSAffineTransform *invertTransform;
196 invertTransform = [m_cocoaWxToBoundsTransform copy];
197 [invertTransform invert];
198 [invertTransform concat];
199 [invertTransform release];
202 bool wxDC::CocoaGetBounds(void *rectData)
204 // We don't know what we are so we can't return anything.
208 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
210 wxAutoNSAutoreleasePool pool;
211 if(!CocoaTakeFocus()) return;
212 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
213 CocoaSetPenForNSBezierPath(m_pen,bezpath);
215 [m_brush.GetNSColor() set];
219 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
221 wxAutoNSAutoreleasePool pool;
222 if(!CocoaTakeFocus()) return;
223 NSBezierPath *bezpath = [NSBezierPath bezierPath];
224 [bezpath moveToPoint:NSMakePoint(x1,y1)];
225 [bezpath lineToPoint:NSMakePoint(x2,y2)];
227 CocoaSetPenForNSBezierPath(m_pen,bezpath);
231 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
233 wxAutoNSAutoreleasePool pool;
234 // FIXME: Cache this so it can be used for DoDrawText
235 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
236 NSAttributedString *attributedString = [[NSAttributedString alloc]
237 initWithString:wxNSStringWithWxString(text.c_str())];
238 [sm_cocoaNSTextStorage setAttributedString:attributedString];
239 [attributedString release];
241 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
242 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
244 *x=(int)usedRect.size.width;
246 *y=(int)usedRect.size.height;
253 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
255 wxAutoNSAutoreleasePool pool;
256 if(!CocoaTakeFocus()) return;
257 wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, wxT("Text system has not been initialized. BAD PROGRAMMER!"));
258 NSAttributedString *attributedString = [[NSAttributedString alloc]
259 initWithString:wxNSStringWithWxString(text.c_str())];
260 [sm_cocoaNSTextStorage setAttributedString:attributedString];
261 [attributedString release];
263 // Set the color (and later font) attributes
264 NSColor *fgColor = m_textForegroundColour.GetNSColor();
265 NSColor *bgColor = m_textBackgroundColour.GetNSColor();
267 fgColor = [NSColor clearColor];
269 bgColor = [NSColor clearColor];
270 NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
271 fgColor, NSForegroundColorAttributeName,
272 bgColor, NSBackgroundColorAttributeName,
274 [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
277 NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
278 NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
279 // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
280 // there is no length or we don't start at zero
281 if(!glyphRange.length)
283 wxASSERT_MSG(glyphRange.location==0,wxT("glyphRange must begin at zero"));
285 NSAffineTransform *transform = [NSAffineTransform transform];
286 [transform translateXBy:x yBy:y];
288 NSAffineTransform *flipTransform = [NSAffineTransform transform];
290 y' = 0x + -1y + window's height
292 NSAffineTransformStruct matrix = {
295 , 0, usedRect.size.height
297 [flipTransform setTransformStruct: matrix];
299 NSGraphicsContext *context = [NSGraphicsContext currentContext];
300 [context saveGraphicsState];
302 [flipTransform concat];
304 // Draw+fill a rectangle so we can see where the shit is supposed to be.
305 wxLogTrace(wxTRACE_COCOA,wxT("(%f,%f) (%fx%f)"),usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
306 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
307 [[NSColor blackColor] set];
309 [[NSColor blueColor] set];
313 NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
314 layoutLocation.x = 0.0;
315 layoutLocation.y *= -1.0;
316 layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
317 if(m_backgroundMode==wxSOLID)
318 [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange atPoint:NSZeroPoint];
319 [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange atPoint:layoutLocation];
321 [context restoreGraphicsState];
324 // wxDCBase functions
325 int wxDCBase::DeviceToLogicalX(int x) const
330 int wxDCBase::DeviceToLogicalY(int y) const
335 int wxDCBase::DeviceToLogicalXRel(int x) const
340 int wxDCBase::DeviceToLogicalYRel(int y) const
345 int wxDCBase::LogicalToDeviceX(int x) const
350 int wxDCBase::LogicalToDeviceY(int y) const
355 int wxDCBase::LogicalToDeviceXRel(int x) const
360 int wxDCBase::LogicalToDeviceYRel(int y) const
365 ///////////////////////////////////////////////////////////////////////////
366 // cut here, the rest is stubs
367 ///////////////////////////////////////////////////////////////////////////
369 //-----------------------------------------------------------------------------
371 //-----------------------------------------------------------------------------
373 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
377 void wxDC::DoDrawPoint( int x, int y )
381 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
385 void wxDC::DoDrawLines( int, wxPoint *, int, int )
389 int wxDC::GetDepth() const
394 wxSize wxDC::GetPPI() const
399 bool wxDC::CanGetTextExtent() const
404 wxCoord wxDC::GetCharHeight() const
409 wxCoord wxDC::GetCharWidth() const
414 bool wxDC::CanDrawBitmap() const
419 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
424 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
428 void wxDC::SetPen(const wxPen& pen)
433 void wxDC::SetBrush(const wxBrush& brush)
438 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
442 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
446 void wxDC::DestroyClippingRegion()
450 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
454 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
458 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
462 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
466 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
468 wxAutoNSAutoreleasePool pool;
469 if(!CocoaTakeFocus()) return;
474 // Draw a rect so we can see where it's supposed to be
475 wxLogTrace(wxTRACE_COCOA,wxT("image at (%d,%d) size %dx%d"),x,y,bmp.GetWidth(),bmp.GetHeight());
476 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
477 [[NSColor blackColor] set];
479 [[NSColor blueColor] set];
483 NSAffineTransform *transform = [NSAffineTransform transform];
484 [transform translateXBy:x yBy:y];
486 NSAffineTransform *flipTransform = [NSAffineTransform transform];
488 y' = 0x + -1y + window's height
490 NSAffineTransformStruct matrix = {
495 [flipTransform setTransformStruct: matrix];
497 NSGraphicsContext *context = [NSGraphicsContext currentContext];
498 [context saveGraphicsState];
500 [flipTransform concat];
502 NSImage *nsimage = [bmp.GetNSImage(useMask) retain];
504 [nsimage drawAtPoint: NSMakePoint(0,0)
505 fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
506 operation: NSCompositeSourceOver
510 [context restoreGraphicsState];
513 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
518 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
523 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)
525 if(!CocoaTakeFocus()) return false;
526 if(!source) return false;
527 return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
528 xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
531 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
532 wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
533 int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
538 void wxDC::DoGetSize( int* width, int* height ) const
540 *width = m_maxX-m_minX;
541 *height = m_maxY-m_minY;
544 void wxDC::DoGetSizeMM( int* width, int* height ) const
551 void wxDC::SetTextForeground( const wxColour &col )
554 m_textForegroundColour = col;
557 void wxDC::SetTextBackground( const wxColour &col )
560 m_textBackgroundColour = col;
565 if(!CocoaTakeFocus()) return;
568 if(!CocoaGetBounds(&boundsRect)) return;
570 NSGraphicsContext *context = [NSGraphicsContext currentContext];
571 [context saveGraphicsState];
573 // Undo all transforms so when we draw our bounds rect we
574 // really overwrite our bounds rect.
575 CocoaUnapplyTransformations();
577 [m_backgroundBrush.GetNSColor() set];
578 [NSBezierPath fillRect:boundsRect];
580 [context restoreGraphicsState];
583 void wxDC::SetBackground(const wxBrush& brush)
585 m_backgroundBrush = brush;
588 void wxDC::SetPalette(const wxPalette&)
592 void wxDC::SetLogicalFunction(int)
597 void wxDC::SetMapMode( int mode )
611 SetLogicalScale( 1.0, 1.0 );
614 if (mode != wxMM_TEXT)
619 void wxDC::SetUserScale( double x, double y )
621 // allow negative ? -> no
624 ComputeScaleAndOrigin();
627 void wxDC::SetLogicalScale( double x, double y )
632 ComputeScaleAndOrigin();
635 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
637 m_logicalOriginX = x * m_signX; // is this still correct ?
638 m_logicalOriginY = y * m_signY;
639 ComputeScaleAndOrigin();
642 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
644 ComputeScaleAndOrigin();
647 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
649 m_signX = (xLeftRight ? 1 : -1);
650 m_signY = (yBottomUp ? -1 : 1);
651 ComputeScaleAndOrigin();
654 void wxDC::ComputeScaleAndOrigin(void)
656 // CMB: copy scale to see if it changes
657 double origScaleX = m_scaleX;
658 double origScaleY = m_scaleY;
660 m_scaleX = m_logicalScaleX * m_userScaleX;
661 m_scaleY = m_logicalScaleY * m_userScaleY;
663 // CMB: if scale has changed call SetPen to recalulate the line width
664 if (m_scaleX != origScaleX || m_scaleY != origScaleY)
666 // this is a bit artificial, but we need to force wxDC to think
667 // the pen has changed
668 const wxPen* pen = & GetPen();