1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/carbon/utilscocoa.mm
3 // Purpose: various cocoa mixin utility functions
4 // Author: Stefan Csomor
7 // Copyright: (c) Stefan Csomor
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 #include "wx/wxprec.h"
14 #include "wx/object.h"
17 #if wxOSX_USE_COCOA_OR_CARBON
18 #include <Cocoa/Cocoa.h>
20 #import <UIKit/UIKit.h>
24 #include "wx/osx/private.h"
27 #include "wx/fontutil.h"
30 #include "wx/cocoa/string.h"
38 bool cocoaLoaded = NSApplicationLoad();
39 wxASSERT_MSG(cocoaLoaded,wxT("Couldn't load Cocoa in Carbon Environment")) ;
44 wxMacAutoreleasePool::wxMacAutoreleasePool()
46 m_pool = [[NSAutoreleasePool alloc] init];
49 wxMacAutoreleasePool::~wxMacAutoreleasePool()
51 [(NSAutoreleasePool*)m_pool release];
58 CGContextRef wxOSXGetContextFromCurrentContext()
60 CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]
65 bool wxOSXLockFocus( WXWidget view)
67 return [view lockFocusIfCanDraw];
70 void wxOSXUnlockFocus( WXWidget view)
79 CGContextRef wxOSXGetContextFromCurrentContext()
81 CGContextRef context = UIGraphicsGetCurrentContext();
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 void wxMacCocoaRelease( void* obj )
93 [(NSObject*)obj release];
96 void wxMacCocoaAutorelease( void* obj )
98 [(NSObject*)obj autorelease];
101 void* wxMacCocoaRetain( void* obj )
103 [(NSObject*)obj retain];
107 // ----------------------------------------------------------------------------
109 // ----------------------------------------------------------------------------
112 wxFont::wxFont(WX_NSFont nsfont)
115 wxNativeFontInfo info;
116 SetNativeInfoFromNSFont(nsfont, &info);
120 void wxFont::SetNativeInfoFromNSFont(WX_NSFont theFont, wxNativeFontInfo* info)
122 if ( info->m_faceName.empty())
124 //Get more information about the user's chosen font
125 NSFontTraitMask theTraits = [[NSFontManager sharedFontManager] traitsOfFont:theFont];
126 int theFontWeight = [[NSFontManager sharedFontManager] weightOfFont:theFont];
128 wxFontFamily fontFamily = wxFONTFAMILY_DEFAULT;
129 //Set the wx font to the appropriate data
130 if(theTraits & NSFixedPitchFontMask)
131 fontFamily = wxFONTFAMILY_TELETYPE;
133 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
134 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
135 bool underlined = false;
137 int size = (int) ([theFont pointSize]+0.5);
139 if ( theFontWeight >= 9 )
140 fontweight = wxFONTWEIGHT_BOLD ;
141 else if ( theFontWeight < 5 )
142 fontweight = wxFONTWEIGHT_LIGHT;
144 fontweight = wxFONTWEIGHT_NORMAL ;
146 if ( theTraits & NSItalicFontMask )
147 fontstyle = wxFONTSTYLE_ITALIC ;
149 info->Init(size,fontFamily,fontstyle,fontweight,underlined,
150 wxStringWithNSString([theFont familyName]), wxFONTENCODING_DEFAULT);
155 WX_NSFont wxFont::OSXCreateNSFont(wxOSXSystemFont font, wxNativeFontInfo* info)
157 NSFont* nsfont = nil;
160 case wxOSX_SYSTEM_FONT_NORMAL:
161 nsfont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
163 case wxOSX_SYSTEM_FONT_BOLD:
164 nsfont = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
166 case wxOSX_SYSTEM_FONT_SMALL:
167 nsfont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
169 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
170 nsfont = [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]];
172 case wxOSX_SYSTEM_FONT_MINI:
173 nsfont = [NSFont systemFontOfSize:
174 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
176 case wxOSX_SYSTEM_FONT_MINI_BOLD:
177 nsfont = [NSFont boldSystemFontOfSize:
178 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
180 case wxOSX_SYSTEM_FONT_LABELS:
181 nsfont = [NSFont labelFontOfSize:[NSFont labelFontSize]];
183 case wxOSX_SYSTEM_FONT_VIEWS:
184 nsfont = [NSFont controlContentFontOfSize:0];
190 SetNativeInfoFromNSFont(nsfont, info);
194 static inline double DegToRad(double deg) { return (deg * M_PI) / 180.0; }
195 static const NSAffineTransformStruct kSlantNSTransformStruct = { 1, 0, static_cast<CGFloat>(tan(DegToRad(11))), 1, 0, 0 };
197 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
201 NSFontTraitMask traits = 0;
202 if (info->m_weight == wxFONTWEIGHT_BOLD)
204 traits |= NSBoldFontMask;
207 else if (info->m_weight == wxFONTWEIGHT_LIGHT)
210 if (info->m_style == wxFONTSTYLE_ITALIC || info->m_style == wxFONTSTYLE_SLANT)
211 traits |= NSItalicFontMask;
213 nsFont = [[NSFontManager sharedFontManager] fontWithFamily:wxCFStringRef(info->m_faceName).AsNSString()
214 traits:traits weight:weight size:info->m_pointSize];
218 NSFontTraitMask remainingTraits = traits;
219 nsFont = [[NSFontManager sharedFontManager] fontWithFamily:wxCFStringRef(info->m_faceName).AsNSString()
220 traits:0 weight:5 size:info->m_pointSize];
223 if ( info->m_weight == wxFONTWEIGHT_BOLD )
225 nsFont = [NSFont boldSystemFontOfSize:info->m_pointSize];
226 remainingTraits &= ~NSBoldFontMask;
229 nsFont = [NSFont systemFontOfSize:info->m_pointSize];
232 // fallback - if in doubt, let go of the bold attribute
233 if ( nsFont && (remainingTraits & NSItalicFontMask) )
235 NSFont* nsFontWithTraits = nil;
236 if ( remainingTraits & NSBoldFontMask)
238 nsFontWithTraits = [[NSFontManager sharedFontManager] convertFont:nsFont toHaveTrait:NSBoldFontMask];
239 if ( nsFontWithTraits == nil )
241 nsFontWithTraits = [[NSFontManager sharedFontManager] convertFont:nsFont toHaveTrait:NSItalicFontMask];
242 if ( nsFontWithTraits != nil )
243 remainingTraits &= ~NSItalicFontMask;
247 remainingTraits &= ~NSBoldFontMask;
250 // the code below causes crashes, because fontDescriptorWithMatrix is not returning a valid font descriptor
251 // it adds a NSCTFontMatrixAttribute as well which cannot be disposed of correctly by the autorelease pool
252 // so at the moment we have to disable this and cannot synthesize italic fonts if they are not available on the system
254 if ( remainingTraits & NSItalicFontMask )
256 if ( nsFontWithTraits == nil )
257 nsFontWithTraits = nsFont;
259 NSAffineTransform* transform = [NSAffineTransform transform];
260 [transform setTransformStruct:kSlantNSTransformStruct];
261 [transform scaleBy:info->m_pointSize];
262 NSFontDescriptor* italicDesc = [[nsFontWithTraits fontDescriptor] fontDescriptorWithMatrix:transform];
263 if ( italicDesc != nil )
265 NSFont* f = [NSFont fontWithDescriptor:italicDesc size:(CGFloat)(info->m_pointSize)];
267 nsFontWithTraits = f;
271 if ( nsFontWithTraits != nil )
272 nsFont = nsFontWithTraits;
276 wxASSERT_MSG(nsFont != nil,wxT("Couldn't create nsFont")) ;
277 wxMacCocoaRetain(nsFont);
285 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
290 case wxOSX_SYSTEM_FONT_NORMAL:
291 uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
293 case wxOSX_SYSTEM_FONT_BOLD:
294 uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
296 case wxOSX_SYSTEM_FONT_MINI:
297 case wxOSX_SYSTEM_FONT_SMALL:
298 uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
300 case wxOSX_SYSTEM_FONT_MINI_BOLD:
301 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
302 uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
304 case wxOSX_SYSTEM_FONT_VIEWS:
305 case wxOSX_SYSTEM_FONT_LABELS:
306 uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
312 if ( info->m_faceName.empty())
314 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
315 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
316 bool underlined = false;
318 int size = (int) ([uifont pointSize]+0.5);
320 NSFontSymbolicTraits traits = [desc symbolicTraits];
322 if ( traits & NSFontBoldTrait )
323 fontweight = wxFONTWEIGHT_BOLD ;
325 fontweight = wxFONTWEIGHT_NORMAL ;
326 if ( traits & NSFontItalicTrait )
327 fontstyle = wxFONTSTYLE_ITALIC ;
329 wxCFStringRef fontname( wxCFRetain([uifont familyName]) );
330 info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
331 fontname.AsString(), wxFONTENCODING_DEFAULT);
337 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
340 uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
341 wxMacCocoaRetain(uiFont);
347 // ----------------------------------------------------------------------------
349 // ----------------------------------------------------------------------------
353 WXWindow wxOSXGetMainWindow()
355 return [NSApp mainWindow];
359 // ----------------------------------------------------------------------------
361 // ----------------------------------------------------------------------------
365 WX_UIImage wxOSXGetUIImageFromCGImage( CGImageRef image )
367 UIImage *newImage = [UIImage imageWithCGImage:image];
368 [newImage autorelease];
372 wxBitmap wxOSXCreateSystemBitmap(const wxString& name, const wxString &client, const wxSize& size)
375 // unfortunately this only accesses images in the app bundle, not the system wide globals
376 wxCFStringRef cfname(name);
377 return wxBitmap( [[UIImage imageNamed:cfname.AsNSString()] CGImage] );
383 double wxOSXGetMainScreenContentScaleFactor()
387 #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
388 if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
390 scale=[[UIScreen mainScreen] scale];
405 double wxOSXGetMainScreenContentScaleFactor()
414 wxBitmap wxOSXCreateSystemBitmap(const wxString& name, const wxString &WXUNUSED(client), const wxSize& WXUNUSED(size))
416 wxCFStringRef cfname(name);
417 return wxBitmap( [NSImage imageNamed:cfname.AsNSString()] );
420 // From "Cocoa Drawing Guide:Working with Images"
421 WX_NSImage wxOSXGetNSImageFromCGImage( CGImageRef image, double scaleFactor )
423 NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
425 // Get the image dimensions.
426 imageRect.size.height = CGImageGetHeight(image)/scaleFactor;
427 imageRect.size.width = CGImageGetWidth(image)/scaleFactor;
429 // Create a new image to receive the Quartz image data.
430 NSImage *newImage = [[NSImage alloc] initWithSize:imageRect.size];
431 [newImage lockFocus];
433 // Get the Quartz context and draw.
434 CGContextRef imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
435 CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
436 [newImage unlockFocus];
439 // Create a bitmap rep from the image...
440 NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
441 // Create an NSImage and add the bitmap rep to it...
442 NSImage *image = [[NSImage alloc] init];
443 [image addRepresentation:bitmapRep];
446 [newImage autorelease];
450 CGContextRef WXDLLIMPEXP_CORE wxOSXCreateBitmapContextFromNSImage( WX_NSImage nsimage)
452 // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
454 CGContextRef hbitmap = NULL;
457 double scale = wxOSXGetMainScreenContentScaleFactor();
459 NSSize imageSize = [nsimage size];
461 hbitmap = CGBitmapContextCreate(NULL, imageSize.width*scale, imageSize.height*scale, 8, 0, wxMacGetGenericRGBColorSpace(), kCGImageAlphaPremultipliedFirst);
462 CGContextScaleCTM( hbitmap, scale, scale );
464 NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:hbitmap flipped:NO];
465 [NSGraphicsContext saveGraphicsState];
466 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
467 [[NSColor whiteColor] setFill];
468 NSRectFill(NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height));
469 [nsimage drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
470 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
475 double wxOSXGetMainScreenContentScaleFactor()
477 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
478 if ( [ [NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)] )
479 return [[NSScreen mainScreen] backingScaleFactor];
485 CGImageRef wxOSXCreateCGImageFromNSImage( WX_NSImage nsimage, double *scaleptr )
487 // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
489 CGImageRef image = NULL;
492 CGContextRef context = wxOSXCreateBitmapContextFromNSImage(nsimage);
495 // determine content scale
496 CGRect userrect = CGRectMake(0, 0, 10, 10);
498 devicerect = CGContextConvertRectToDeviceSpace(context, userrect);
499 *scaleptr = devicerect.size.height / userrect.size.height;
501 image = CGBitmapContextCreateImage(context);
507 // ----------------------------------------------------------------------------
509 // ----------------------------------------------------------------------------
511 // copied from cursor.mm
513 static NSCursor* wxGetStockCursor( short sIndex )
515 ClassicCursor* pCursor = &gMacCursors[sIndex];
517 //Classic mac cursors are 1bps 16x16 black and white with a
518 //identical mask that is 1 for on and 0 for off
519 NSImage *theImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
521 //NSCursor takes an NSImage takes a number of Representations - here
522 //we need only one for the raw data
523 NSBitmapImageRep *theRep = [[NSBitmapImageRep alloc]
524 initWithBitmapDataPlanes: NULL // Tell Cocoa to allocate the planes for us.
525 pixelsWide: 16 // All classic cursors are 16x16
527 bitsPerSample: 1 // All classic cursors are bitmaps with bitmasks
528 samplesPerPixel: 2 // Sample 0:image 1:mask
529 hasAlpha: YES // Identify last sample as a mask
530 isPlanar: YES // Use a separate array for each sample
531 colorSpaceName: NSCalibratedWhiteColorSpace // 0.0=black 1.0=white
532 bytesPerRow: 2 // Rows in each plane are on 2-byte boundaries (no pad)
533 bitsPerPixel: 1]; // same as bitsPerSample since data is planar
535 // Ensure that Cocoa allocated 2 and only 2 of the 5 possible planes
536 unsigned char *planes[5];
537 [theRep getBitmapDataPlanes:planes];
538 wxASSERT(planes[0] != NULL);
539 wxASSERT(planes[1] != NULL);
540 wxASSERT(planes[2] == NULL);
541 wxASSERT(planes[3] == NULL);
542 wxASSERT(planes[4] == NULL);
544 // NOTE1: The Cursor's bits field is white=0 black=1.. thus the bitwise-not
545 // Why not use NSCalibratedBlackColorSpace? Because that reverses the
546 // sense of the alpha (mask) plane.
547 // NOTE2: The mask data is 0=off 1=on
548 // NOTE3: Cocoa asks for "premultiplied" color planes. Since we have a
549 // 1-bit color plane and a 1-bit alpha plane we can just do a bitwise-and
550 // on the two. The original cursor bitmaps have 0 (white actually) for
551 // any masked-off pixels. Therefore every masked-off pixel would be wrong
552 // since we bit-flip all of the picture bits. In practice, Cocoa doesn't
553 // seem to care, but we are following the documentation.
555 // Fill in the color (black/white) plane
556 for(int i=0; i<16; ++i)
558 planes[0][2*i ] = (~pCursor->bits[i] & pCursor->mask[i]) >> 8 & 0xff;
559 planes[0][2*i+1] = (~pCursor->bits[i] & pCursor->mask[i]) & 0xff;
561 // Fill in the alpha (i.e. mask) plane
562 for(int i=0; i<16; ++i)
564 planes[1][2*i ] = pCursor->mask[i] >> 8 & 0xff;
565 planes[1][2*i+1] = pCursor->mask[i] & 0xff;
568 //add the representation (data) to the image
569 [theImage addRepresentation:theRep];
571 //create the new cursor
572 NSCursor* theCursor = [[NSCursor alloc] initWithImage:theImage
573 hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
576 //do the usual cleanups
580 //return the new cursor
584 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
586 WX_NSCursor cursor = nil;
589 case wxCURSOR_COPY_ARROW:
590 cursor = [[NSCursor arrowCursor] retain];
595 // an arrow should be displayed by the system when things are running
596 // according to the HIG
597 // cursor = [[NSCursor arrowCursor] retain];
598 // but for crossplatform compatibility we display a watch cursor
599 cursor = wxGetStockCursor(kwxCursorWatch);
603 cursor = [[NSCursor IBeamCursor] retain];
607 cursor = [[NSCursor crosshairCursor] retain];
610 case wxCURSOR_SIZENWSE:
611 cursor = wxGetStockCursor(kwxCursorSizeNWSE);
614 case wxCURSOR_SIZENESW:
615 cursor = wxGetStockCursor(kwxCursorSizeNESW);
618 case wxCURSOR_SIZEWE:
619 cursor = [[NSCursor resizeLeftRightCursor] retain];
622 case wxCURSOR_SIZENS:
623 cursor = [[NSCursor resizeUpDownCursor] retain];
626 case wxCURSOR_SIZING:
627 cursor = wxGetStockCursor(kwxCursorSize);
631 cursor = [[NSCursor pointingHandCursor] retain];
634 case wxCURSOR_BULLSEYE:
635 cursor = wxGetStockCursor(kwxCursorBullseye);
638 case wxCURSOR_PENCIL:
639 cursor = wxGetStockCursor(kwxCursorPencil);
642 case wxCURSOR_MAGNIFIER:
643 cursor = wxGetStockCursor(kwxCursorMagnifier);
646 case wxCURSOR_NO_ENTRY:
647 cursor = wxGetStockCursor(kwxCursorNoEntry);
650 case wxCURSOR_PAINT_BRUSH:
651 cursor = wxGetStockCursor(kwxCursorPaintBrush);
654 case wxCURSOR_POINT_LEFT:
655 cursor = wxGetStockCursor(kwxCursorPointLeft);
658 case wxCURSOR_POINT_RIGHT:
659 cursor = wxGetStockCursor(kwxCursorPointRight);
662 case wxCURSOR_QUESTION_ARROW:
663 cursor = wxGetStockCursor(kwxCursorQuestionArrow);
667 cursor = wxGetStockCursor(kwxCursorBlank);
670 case wxCURSOR_RIGHT_ARROW:
671 cursor = wxGetStockCursor(kwxCursorRightArrow);
674 case wxCURSOR_SPRAYCAN:
675 cursor = wxGetStockCursor(kwxCursorRoller);
678 case wxCURSOR_OPEN_HAND:
679 cursor = [[NSCursor openHandCursor] retain];
682 case wxCURSOR_CLOSED_HAND:
683 cursor = [[NSCursor closedHandCursor] retain];
688 case wxCURSOR_LEFT_BUTTON:
689 case wxCURSOR_RIGHT_BUTTON:
690 case wxCURSOR_MIDDLE_BUTTON:
692 cursor = [[NSCursor arrowCursor] retain];
698 // C-based style wrapper routines around NSCursor
699 WX_NSCursor wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
701 static BOOL firstTime = YES;
705 // 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
706 [[[NSWindow alloc] init] release];
710 NSImage *nsImage = wxOSXGetNSImageFromCGImage( cgImageRef );
711 NSCursor *cursor = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
716 void wxMacCocoaSetCursor( WX_NSCursor cursor )
721 void wxMacCocoaHideCursor()
726 void wxMacCocoaShowCursor()