1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/carbon/utilscocoa.mm
3 // Purpose: various cocoa mixin utility functions
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/object.h"
18 #if wxOSX_USE_COCOA_OR_CARBON
19 #include <Cocoa/Cocoa.h>
21 #import <UIKit/UIKit.h>
25 #include "wx/osx/private.h"
28 #include "wx/fontutil.h"
31 #include "wx/cocoa/string.h"
39 bool cocoaLoaded = NSApplicationLoad();
40 wxASSERT_MSG(cocoaLoaded,wxT("Couldn't load Cocoa in Carbon Environment")) ;
45 wxMacAutoreleasePool::wxMacAutoreleasePool()
47 m_pool = [[NSAutoreleasePool alloc] init];
50 wxMacAutoreleasePool::~wxMacAutoreleasePool()
52 [(NSAutoreleasePool*)m_pool release];
59 CGContextRef wxOSXGetContextFromCurrentContext()
61 CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]
66 bool wxOSXLockFocus( WXWidget view)
68 return [view lockFocusIfCanDraw];
71 void wxOSXUnlockFocus( WXWidget view)
80 CGContextRef wxOSXGetContextFromCurrentContext()
82 CGContextRef context = UIGraphicsGetCurrentContext();
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 void wxMacCocoaRelease( void* obj )
94 [(NSObject*)obj release];
97 void wxMacCocoaAutorelease( void* obj )
99 [(NSObject*)obj autorelease];
102 void* wxMacCocoaRetain( void* obj )
104 [(NSObject*)obj retain];
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
113 wxFont::wxFont(WX_NSFont nsfont)
116 wxNativeFontInfo info;
117 SetNativeInfoFromNSFont(nsfont, &info);
121 void wxFont::SetNativeInfoFromNSFont(WX_NSFont theFont, wxNativeFontInfo* info)
123 if ( info->m_faceName.empty())
125 //Get more information about the user's chosen font
126 NSFontTraitMask theTraits = [[NSFontManager sharedFontManager] traitsOfFont:theFont];
127 int theFontWeight = [[NSFontManager sharedFontManager] weightOfFont:theFont];
129 wxFontFamily fontFamily = wxFONTFAMILY_DEFAULT;
130 //Set the wx font to the appropriate data
131 if(theTraits & NSFixedPitchFontMask)
132 fontFamily = wxFONTFAMILY_TELETYPE;
134 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
135 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
136 bool underlined = false;
138 int size = (int) ([theFont pointSize]+0.5);
140 if ( theFontWeight >= 9 )
141 fontweight = wxFONTWEIGHT_BOLD ;
142 else if ( theFontWeight < 5 )
143 fontweight = wxFONTWEIGHT_LIGHT;
145 fontweight = wxFONTWEIGHT_NORMAL ;
147 if ( theTraits & NSItalicFontMask )
148 fontstyle = wxFONTSTYLE_ITALIC ;
150 info->Init(size,fontFamily,fontstyle,fontweight,underlined,
151 wxStringWithNSString([theFont familyName]), wxFONTENCODING_DEFAULT);
156 WX_NSFont wxFont::OSXCreateNSFont(wxOSXSystemFont font, wxNativeFontInfo* info)
158 NSFont* nsfont = nil;
161 case wxOSX_SYSTEM_FONT_NORMAL:
162 nsfont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
164 case wxOSX_SYSTEM_FONT_BOLD:
165 nsfont = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
167 case wxOSX_SYSTEM_FONT_SMALL:
168 nsfont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
170 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
171 nsfont = [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]];
173 case wxOSX_SYSTEM_FONT_MINI:
174 nsfont = [NSFont systemFontOfSize:
175 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
177 case wxOSX_SYSTEM_FONT_MINI_BOLD:
178 nsfont = [NSFont boldSystemFontOfSize:
179 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
181 case wxOSX_SYSTEM_FONT_LABELS:
182 nsfont = [NSFont labelFontOfSize:[NSFont labelFontSize]];
184 case wxOSX_SYSTEM_FONT_VIEWS:
185 nsfont = [NSFont controlContentFontOfSize:0];
191 SetNativeInfoFromNSFont(nsfont, info);
195 static inline double DegToRad(double deg) { return (deg * M_PI) / 180.0; }
196 static const NSAffineTransformStruct kSlantNSTransformStruct = { 1, 0, static_cast<CGFloat>(tan(DegToRad(11))), 1, 0, 0 };
198 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
202 NSFontTraitMask traits = 0;
203 if (info->m_weight == wxFONTWEIGHT_BOLD)
205 traits |= NSBoldFontMask;
208 else if (info->m_weight == wxFONTWEIGHT_LIGHT)
211 if (info->m_style == wxFONTSTYLE_ITALIC || info->m_style == wxFONTSTYLE_SLANT)
212 traits |= NSItalicFontMask;
214 nsFont = [[NSFontManager sharedFontManager] fontWithFamily:wxCFStringRef(info->m_faceName).AsNSString()
215 traits:traits weight:weight size:info->m_pointSize];
219 NSFontTraitMask remainingTraits = traits;
220 nsFont = [[NSFontManager sharedFontManager] fontWithFamily:wxCFStringRef(info->m_faceName).AsNSString()
221 traits:0 weight:5 size:info->m_pointSize];
224 if ( info->m_weight == wxFONTWEIGHT_BOLD )
226 nsFont = [NSFont boldSystemFontOfSize:info->m_pointSize];
227 remainingTraits &= ~NSBoldFontMask;
230 nsFont = [NSFont systemFontOfSize:info->m_pointSize];
233 // fallback - if in doubt, let go of the bold attribute
234 if ( nsFont && (remainingTraits & NSItalicFontMask) )
236 NSFont* nsFontWithTraits = nil;
237 if ( remainingTraits & NSBoldFontMask)
239 nsFontWithTraits = [[NSFontManager sharedFontManager] convertFont:nsFont toHaveTrait:NSBoldFontMask];
240 if ( nsFontWithTraits == nil )
242 nsFontWithTraits = [[NSFontManager sharedFontManager] convertFont:nsFont toHaveTrait:NSItalicFontMask];
243 if ( nsFontWithTraits != nil )
244 remainingTraits &= ~NSItalicFontMask;
248 remainingTraits &= ~NSBoldFontMask;
251 // the code below causes crashes, because fontDescriptorWithMatrix is not returning a valid font descriptor
252 // it adds a NSCTFontMatrixAttribute as well which cannot be disposed of correctly by the autorelease pool
253 // so at the moment we have to disable this and cannot synthesize italic fonts if they are not available on the system
255 if ( remainingTraits & NSItalicFontMask )
257 if ( nsFontWithTraits == nil )
258 nsFontWithTraits = nsFont;
260 NSAffineTransform* transform = [NSAffineTransform transform];
261 [transform setTransformStruct:kSlantNSTransformStruct];
262 [transform scaleBy:info->m_pointSize];
263 NSFontDescriptor* italicDesc = [[nsFontWithTraits fontDescriptor] fontDescriptorWithMatrix:transform];
264 if ( italicDesc != nil )
266 NSFont* f = [NSFont fontWithDescriptor:italicDesc size:(CGFloat)(info->m_pointSize)];
268 nsFontWithTraits = f;
272 if ( nsFontWithTraits != nil )
273 nsFont = nsFontWithTraits;
277 wxASSERT_MSG(nsFont != nil,wxT("Couldn't create nsFont")) ;
278 wxMacCocoaRetain(nsFont);
286 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
291 case wxOSX_SYSTEM_FONT_NORMAL:
292 uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
294 case wxOSX_SYSTEM_FONT_BOLD:
295 uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
297 case wxOSX_SYSTEM_FONT_MINI:
298 case wxOSX_SYSTEM_FONT_SMALL:
299 uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
301 case wxOSX_SYSTEM_FONT_MINI_BOLD:
302 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
303 uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
305 case wxOSX_SYSTEM_FONT_VIEWS:
306 case wxOSX_SYSTEM_FONT_LABELS:
307 uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
313 if ( info->m_faceName.empty())
315 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
316 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
317 bool underlined = false;
319 int size = (int) ([uifont pointSize]+0.5);
321 NSFontSymbolicTraits traits = [desc symbolicTraits];
323 if ( traits & NSFontBoldTrait )
324 fontweight = wxFONTWEIGHT_BOLD ;
326 fontweight = wxFONTWEIGHT_NORMAL ;
327 if ( traits & NSFontItalicTrait )
328 fontstyle = wxFONTSTYLE_ITALIC ;
330 wxCFStringRef fontname( wxCFRetain([uifont familyName]) );
331 info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
332 fontname.AsString(), wxFONTENCODING_DEFAULT);
338 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
341 uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
342 wxMacCocoaRetain(uiFont);
348 // ----------------------------------------------------------------------------
350 // ----------------------------------------------------------------------------
354 WXWindow wxOSXGetMainWindow()
356 return [NSApp mainWindow];
360 // ----------------------------------------------------------------------------
362 // ----------------------------------------------------------------------------
366 WX_UIImage wxOSXGetUIImageFromCGImage( CGImageRef image )
368 UIImage *newImage = [UIImage imageWithCGImage:image];
369 [newImage autorelease];
373 wxBitmap wxOSXCreateSystemBitmap(const wxString& name, const wxString &client, const wxSize& size)
376 // unfortunately this only accesses images in the app bundle, not the system wide globals
377 wxCFStringRef cfname(name);
378 return wxBitmap( [[UIImage imageNamed:cfname.AsNSString()] CGImage] );
388 wxBitmap wxOSXCreateSystemBitmap(const wxString& name, const wxString &WXUNUSED(client), const wxSize& WXUNUSED(size))
390 wxCFStringRef cfname(name);
391 return wxBitmap( [NSImage imageNamed:cfname.AsNSString()] );
394 // From "Cocoa Drawing Guide:Working with Images"
395 WX_NSImage wxOSXGetNSImageFromCGImage( CGImageRef image, double scaleFactor )
397 NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
399 // Get the image dimensions.
400 imageRect.size.height = CGImageGetHeight(image)/scaleFactor;
401 imageRect.size.width = CGImageGetWidth(image)/scaleFactor;
403 // Create a new image to receive the Quartz image data.
404 NSImage *newImage = [[NSImage alloc] initWithSize:imageRect.size];
405 [newImage lockFocus];
407 // Get the Quartz context and draw.
408 CGContextRef imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
409 CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
410 [newImage unlockFocus];
413 // Create a bitmap rep from the image...
414 NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
415 // Create an NSImage and add the bitmap rep to it...
416 NSImage *image = [[NSImage alloc] init];
417 [image addRepresentation:bitmapRep];
420 [newImage autorelease];
424 CGContextRef WXDLLIMPEXP_CORE wxOSXCreateBitmapContextFromNSImage( WX_NSImage nsimage)
426 // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
428 CGContextRef hbitmap = NULL;
431 double scale = wxOSXGetMainScreenContentScaleFactor();
433 NSSize imageSize = [nsimage size];
435 hbitmap = CGBitmapContextCreate(NULL, imageSize.width*scale, imageSize.height*scale, 8, 0, wxMacGetGenericRGBColorSpace(), kCGImageAlphaPremultipliedFirst);
436 CGContextScaleCTM( hbitmap, scale, scale );
438 NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:hbitmap flipped:NO];
439 [NSGraphicsContext saveGraphicsState];
440 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
441 [[NSColor whiteColor] setFill];
442 NSRectFill(NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height));
443 [nsimage drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
444 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
449 double WXDLLIMPEXP_CORE wxOSXGetMainScreenContentScaleFactor()
451 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
452 if ( [ [NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)] )
453 return [[NSScreen mainScreen] backingScaleFactor];
459 CGImageRef wxOSXCreateCGImageFromNSImage( WX_NSImage nsimage, double *scaleptr )
461 // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
463 CGImageRef image = NULL;
466 CGContextRef context = wxOSXCreateBitmapContextFromNSImage(nsimage);
469 // determine content scale
470 CGRect userrect = CGRectMake(0, 0, 10, 10);
472 devicerect = CGContextConvertRectToDeviceSpace(context, userrect);
473 *scaleptr = devicerect.size.height / userrect.size.height;
475 image = CGBitmapContextCreateImage(context);
481 // ----------------------------------------------------------------------------
483 // ----------------------------------------------------------------------------
485 // copied from cursor.mm
487 static NSCursor* wxGetStockCursor( short sIndex )
489 ClassicCursor* pCursor = &gMacCursors[sIndex];
491 //Classic mac cursors are 1bps 16x16 black and white with a
492 //identical mask that is 1 for on and 0 for off
493 NSImage *theImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
495 //NSCursor takes an NSImage takes a number of Representations - here
496 //we need only one for the raw data
497 NSBitmapImageRep *theRep = [[NSBitmapImageRep alloc]
498 initWithBitmapDataPlanes: NULL // Tell Cocoa to allocate the planes for us.
499 pixelsWide: 16 // All classic cursors are 16x16
501 bitsPerSample: 1 // All classic cursors are bitmaps with bitmasks
502 samplesPerPixel: 2 // Sample 0:image 1:mask
503 hasAlpha: YES // Identify last sample as a mask
504 isPlanar: YES // Use a separate array for each sample
505 colorSpaceName: NSCalibratedWhiteColorSpace // 0.0=black 1.0=white
506 bytesPerRow: 2 // Rows in each plane are on 2-byte boundaries (no pad)
507 bitsPerPixel: 1]; // same as bitsPerSample since data is planar
509 // Ensure that Cocoa allocated 2 and only 2 of the 5 possible planes
510 unsigned char *planes[5];
511 [theRep getBitmapDataPlanes:planes];
512 wxASSERT(planes[0] != NULL);
513 wxASSERT(planes[1] != NULL);
514 wxASSERT(planes[2] == NULL);
515 wxASSERT(planes[3] == NULL);
516 wxASSERT(planes[4] == NULL);
518 // NOTE1: The Cursor's bits field is white=0 black=1.. thus the bitwise-not
519 // Why not use NSCalibratedBlackColorSpace? Because that reverses the
520 // sense of the alpha (mask) plane.
521 // NOTE2: The mask data is 0=off 1=on
522 // NOTE3: Cocoa asks for "premultiplied" color planes. Since we have a
523 // 1-bit color plane and a 1-bit alpha plane we can just do a bitwise-and
524 // on the two. The original cursor bitmaps have 0 (white actually) for
525 // any masked-off pixels. Therefore every masked-off pixel would be wrong
526 // since we bit-flip all of the picture bits. In practice, Cocoa doesn't
527 // seem to care, but we are following the documentation.
529 // Fill in the color (black/white) plane
530 for(int i=0; i<16; ++i)
532 planes[0][2*i ] = (~pCursor->bits[i] & pCursor->mask[i]) >> 8 & 0xff;
533 planes[0][2*i+1] = (~pCursor->bits[i] & pCursor->mask[i]) & 0xff;
535 // Fill in the alpha (i.e. mask) plane
536 for(int i=0; i<16; ++i)
538 planes[1][2*i ] = pCursor->mask[i] >> 8 & 0xff;
539 planes[1][2*i+1] = pCursor->mask[i] & 0xff;
542 //add the representation (data) to the image
543 [theImage addRepresentation:theRep];
545 //create the new cursor
546 NSCursor* theCursor = [[NSCursor alloc] initWithImage:theImage
547 hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
550 //do the usual cleanups
554 //return the new cursor
558 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
560 WX_NSCursor cursor = nil;
563 case wxCURSOR_COPY_ARROW:
564 cursor = [[NSCursor arrowCursor] retain];
569 // an arrow should be displayed by the system when things are running
570 // according to the HIG
571 // cursor = [[NSCursor arrowCursor] retain];
572 // but for crossplatform compatibility we display a watch cursor
573 cursor = wxGetStockCursor(kwxCursorWatch);
577 cursor = [[NSCursor IBeamCursor] retain];
581 cursor = [[NSCursor crosshairCursor] retain];
584 case wxCURSOR_SIZENWSE:
585 cursor = wxGetStockCursor(kwxCursorSizeNWSE);
588 case wxCURSOR_SIZENESW:
589 cursor = wxGetStockCursor(kwxCursorSizeNESW);
592 case wxCURSOR_SIZEWE:
593 cursor = [[NSCursor resizeLeftRightCursor] retain];
596 case wxCURSOR_SIZENS:
597 cursor = [[NSCursor resizeUpDownCursor] retain];
600 case wxCURSOR_SIZING:
601 cursor = wxGetStockCursor(kwxCursorSize);
605 cursor = [[NSCursor pointingHandCursor] retain];
608 case wxCURSOR_BULLSEYE:
609 cursor = wxGetStockCursor(kwxCursorBullseye);
612 case wxCURSOR_PENCIL:
613 cursor = wxGetStockCursor(kwxCursorPencil);
616 case wxCURSOR_MAGNIFIER:
617 cursor = wxGetStockCursor(kwxCursorMagnifier);
620 case wxCURSOR_NO_ENTRY:
621 cursor = wxGetStockCursor(kwxCursorNoEntry);
624 case wxCURSOR_PAINT_BRUSH:
625 cursor = wxGetStockCursor(kwxCursorPaintBrush);
628 case wxCURSOR_POINT_LEFT:
629 cursor = wxGetStockCursor(kwxCursorPointLeft);
632 case wxCURSOR_POINT_RIGHT:
633 cursor = wxGetStockCursor(kwxCursorPointRight);
636 case wxCURSOR_QUESTION_ARROW:
637 cursor = wxGetStockCursor(kwxCursorQuestionArrow);
641 cursor = wxGetStockCursor(kwxCursorBlank);
644 case wxCURSOR_RIGHT_ARROW:
645 cursor = wxGetStockCursor(kwxCursorRightArrow);
648 case wxCURSOR_SPRAYCAN:
649 cursor = wxGetStockCursor(kwxCursorRoller);
652 case wxCURSOR_OPEN_HAND:
653 cursor = [[NSCursor openHandCursor] retain];
656 case wxCURSOR_CLOSED_HAND:
657 cursor = [[NSCursor closedHandCursor] retain];
662 case wxCURSOR_LEFT_BUTTON:
663 case wxCURSOR_RIGHT_BUTTON:
664 case wxCURSOR_MIDDLE_BUTTON:
666 cursor = [[NSCursor arrowCursor] retain];
672 // C-based style wrapper routines around NSCursor
673 WX_NSCursor wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
675 static BOOL firstTime = YES;
679 // Must first call [[[NSWindow alloc] init] release] to get the NSWindow machinery set up so that NSCursor can use a window to cache the cursor image
680 [[[NSWindow alloc] init] release];
684 NSImage *nsImage = wxOSXGetNSImageFromCGImage( cgImageRef );
685 NSCursor *cursor = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
690 void wxMacCocoaSetCursor( WX_NSCursor cursor )
695 void wxMacCocoaHideCursor()
700 void wxMacCocoaShowCursor()