1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/carbon/utils.mm
3 // Purpose: various cocoa mixin utility functions
4 // Author: Stefan Csomor
7 // RCS-ID: $Id: utilscocoa.mm 48805 2007-09-19 14:52:25Z SC $
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
14 #if wxOSX_USE_COCOA_OR_CARBON
15 #include <Cocoa/Cocoa.h>
17 #import <UIKit/UIKit.h>
21 #include "wx/osx/private.h"
24 #include "wx/fontutil.h"
31 bool cocoaLoaded = NSApplicationLoad();
32 wxASSERT_MSG(cocoaLoaded,wxT("Couldn't load Cocoa in Carbon Environment")) ;
37 wxMacAutoreleasePool::wxMacAutoreleasePool()
39 m_pool = [[NSAutoreleasePool alloc] init];
42 wxMacAutoreleasePool::~wxMacAutoreleasePool()
44 [(NSAutoreleasePool*)m_pool release];
51 CGContextRef wxOSXGetContextFromCurrentContext()
53 CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]
58 bool wxOSXLockFocus( WXWidget view)
60 return [view lockFocusIfCanDraw];
63 void wxOSXUnlockFocus( WXWidget view)
72 CGContextRef wxOSXGetContextFromCurrentContext()
74 CGContextRef context = UIGraphicsGetCurrentContext();
80 // ----------------------------------------------------------------------------
82 // ----------------------------------------------------------------------------
84 void wxMacCocoaRelease( void* obj )
86 [(NSObject*)obj release];
89 void wxMacCocoaAutorelease( void* obj )
91 [(NSObject*)obj autorelease];
94 void* wxMacCocoaRetain( void* obj )
96 [(NSObject*)obj retain];
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
105 wxFont::wxFont(WX_NSFont nsfont)
108 wxNativeFontInfo info;
109 SetNativeInfoFromNSFont(nsfont, &info);
113 void wxFont::SetNativeInfoFromNSFont(WX_NSFont nsfont, wxNativeFontInfo* info)
115 NSFontDescriptor*desc = [[nsfont fontDescriptor] retain];
116 if ( info->m_faceName.empty())
118 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
119 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
120 bool underlined = false;
122 int size = (int) ([desc pointSize]+0.5);
123 NSFontSymbolicTraits traits = [desc symbolicTraits];
125 if ( traits & NSFontBoldTrait )
126 fontweight = wxFONTWEIGHT_BOLD ;
128 fontweight = wxFONTWEIGHT_NORMAL ;
129 if ( traits & NSFontItalicTrait )
130 fontstyle = wxFONTSTYLE_ITALIC ;
132 wxCFStringRef fontname( [desc postscriptName] );
133 info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
134 fontname.AsString(), wxFONTENCODING_DEFAULT);
137 info->m_nsFontDescriptor = desc;
140 WX_NSFont wxFont::OSXCreateNSFont(wxOSXSystemFont font, wxNativeFontInfo* info)
142 NSFont* nsfont = nil;
145 case wxOSX_SYSTEM_FONT_NORMAL:
146 nsfont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
148 case wxOSX_SYSTEM_FONT_BOLD:
149 nsfont = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
151 case wxOSX_SYSTEM_FONT_SMALL:
152 nsfont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
154 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
155 nsfont = [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]];
157 case wxOSX_SYSTEM_FONT_MINI:
158 nsfont = [NSFont systemFontOfSize:
159 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
161 case wxOSX_SYSTEM_FONT_MINI_BOLD:
162 nsfont = [NSFont boldSystemFontOfSize:
163 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
165 case wxOSX_SYSTEM_FONT_LABELS:
166 nsfont = [NSFont labelFontOfSize:[NSFont labelFontSize]];
168 case wxOSX_SYSTEM_FONT_VIEWS:
169 nsfont = [NSFont controlContentFontOfSize:0];
175 SetNativeInfoFromNSFont(nsfont, info);
179 void wxNativeFontInfo::OSXValidateNSFontDescriptor()
181 NSFontDescriptor* desc = nil;
182 NSFontSymbolicTraits traits = 0;
185 if (m_weight == wxFONTWEIGHT_BOLD)
187 traits |= NSFontBoldTrait;
190 else if (m_weight == wxFONTWEIGHT_LIGHT)
193 if (m_style == wxFONTSTYLE_ITALIC || m_style == wxFONTSTYLE_SLANT)
194 traits |= NSFontItalicTrait;
196 NSDictionary* traitsdict = [NSDictionary dictionaryWithObjectsAndKeys:
197 [NSNumber numberWithUnsignedInt:traits], NSFontSymbolicTrait,
200 desc = [NSFontDescriptor fontDescriptorWithFontAttributes:
201 [NSDictionary dictionaryWithObjectsAndKeys:
202 wxCFStringRef(m_faceName).AsNSString(), NSFontFamilyAttribute,
203 [NSNumber numberWithFloat:m_pointSize], NSFontSizeAttribute,
204 traitsdict, NSFontTraitsAttribute,
205 [NSNumber numberWithFloat:weight],NSFontWeightTrait,
208 wxMacCocoaRetain(desc);
209 m_nsFontDescriptor = desc;
212 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
215 nsFont = [NSFont fontWithDescriptor:info->m_nsFontDescriptor size:info->m_pointSize];
216 wxMacCocoaRetain(nsFont);
224 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
229 case wxOSX_SYSTEM_FONT_NORMAL:
230 uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
232 case wxOSX_SYSTEM_FONT_BOLD:
233 uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
235 case wxOSX_SYSTEM_FONT_MINI:
236 case wxOSX_SYSTEM_FONT_SMALL:
237 uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
239 case wxOSX_SYSTEM_FONT_MINI_BOLD:
240 case wxOSX_SYSTEM_FONT_SMALL_BOLD:
241 uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
243 case wxOSX_SYSTEM_FONT_VIEWS:
244 case wxOSX_SYSTEM_FONT_LABELS:
245 uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
251 if ( info->m_faceName.empty())
253 wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
254 wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
255 bool underlined = false;
257 int size = (int) ([uifont pointSize]+0.5);
259 NSFontSymbolicTraits traits = [desc symbolicTraits];
261 if ( traits & NSFontBoldTrait )
262 fontweight = wxFONTWEIGHT_BOLD ;
264 fontweight = wxFONTWEIGHT_NORMAL ;
265 if ( traits & NSFontItalicTrait )
266 fontstyle = wxFONTSTYLE_ITALIC ;
268 wxCFStringRef fontname( wxCFRetain([uifont familyName]) );
269 info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
270 fontname.AsString(), wxFONTENCODING_DEFAULT);
276 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
279 uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
280 wxMacCocoaRetain(uiFont);
285 // ----------------------------------------------------------------------------
287 // ----------------------------------------------------------------------------
291 WX_UIImage wxOSXCreateUIImageFromCGImage( CGImageRef image )
293 UIImage *newImage = [UIImage imageWithCGImage:image];
294 [newImage autorelease];
302 // From "Cocoa Drawing Guide:Working with Images"
303 WX_NSImage wxOSXCreateNSImageFromCGImage( CGImageRef image )
305 NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
307 // Get the image dimensions.
308 imageRect.size.height = CGImageGetHeight(image);
309 imageRect.size.width = CGImageGetWidth(image);
311 // Create a new image to receive the Quartz image data.
312 NSImage *newImage = [[NSImage alloc] initWithSize:imageRect.size];
313 [newImage lockFocus];
315 // Get the Quartz context and draw.
316 CGContextRef imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
317 CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
318 [newImage unlockFocus];
321 // Create a bitmap rep from the image...
322 NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
323 // Create an NSImage and add the bitmap rep to it...
324 NSImage *image = [[NSImage alloc] init];
325 [image addRepresentation:bitmapRep];
328 [newImage autorelease];
332 CGImageRef wxOSXCreateCGImageFromNSImage( WX_NSImage nsimage )
334 // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
336 NSSize imageSize = [nsimage size];
337 CGColorSpaceRef genericRGB = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
338 CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, 0, genericRGB, kCGImageAlphaPremultipliedFirst);
339 NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
340 [NSGraphicsContext saveGraphicsState];
341 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
342 [[NSColor whiteColor] setFill];
343 NSRectFill(NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height));
344 [nsimage drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
345 [NSGraphicsContext setCurrentContext:nsGraphicsContext];
346 CGImageRef image = CGBitmapContextCreateImage(context);
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
355 // copied from cursor.mm
357 static NSCursor* wxGetStockCursor( short sIndex )
359 ClassicCursor* pCursor = &gMacCursors[sIndex];
361 //Classic mac cursors are 1bps 16x16 black and white with a
362 //identical mask that is 1 for on and 0 for off
363 NSImage *theImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
365 //NSCursor takes an NSImage takes a number of Representations - here
366 //we need only one for the raw data
367 NSBitmapImageRep *theRep = [[NSBitmapImageRep alloc]
368 initWithBitmapDataPlanes: NULL // Tell Cocoa to allocate the planes for us.
369 pixelsWide: 16 // All classic cursors are 16x16
371 bitsPerSample: 1 // All classic cursors are bitmaps with bitmasks
372 samplesPerPixel: 2 // Sample 0:image 1:mask
373 hasAlpha: YES // Identify last sample as a mask
374 isPlanar: YES // Use a separate array for each sample
375 colorSpaceName: NSCalibratedWhiteColorSpace // 0.0=black 1.0=white
376 bytesPerRow: 2 // Rows in each plane are on 2-byte boundaries (no pad)
377 bitsPerPixel: 1]; // same as bitsPerSample since data is planar
379 // Ensure that Cocoa allocated 2 and only 2 of the 5 possible planes
380 unsigned char *planes[5];
381 [theRep getBitmapDataPlanes:planes];
382 wxASSERT(planes[0] != NULL);
383 wxASSERT(planes[1] != NULL);
384 wxASSERT(planes[2] == NULL);
385 wxASSERT(planes[3] == NULL);
386 wxASSERT(planes[4] == NULL);
388 // NOTE1: The Cursor's bits field is white=0 black=1.. thus the bitwise-not
389 // Why not use NSCalibratedBlackColorSpace? Because that reverses the
390 // sense of the alpha (mask) plane.
391 // NOTE2: The mask data is 0=off 1=on
392 // NOTE3: Cocoa asks for "premultiplied" color planes. Since we have a
393 // 1-bit color plane and a 1-bit alpha plane we can just do a bitwise-and
394 // on the two. The original cursor bitmaps have 0 (white actually) for
395 // any masked-off pixels. Therefore every masked-off pixel would be wrong
396 // since we bit-flip all of the picture bits. In practice, Cocoa doesn't
397 // seem to care, but we are following the documentation.
399 // Fill in the color (black/white) plane
400 for(int i=0; i<16; ++i)
402 planes[0][2*i ] = (~pCursor->bits[i] & pCursor->mask[i]) >> 8 & 0xff;
403 planes[0][2*i+1] = (~pCursor->bits[i] & pCursor->mask[i]) & 0xff;
405 // Fill in the alpha (i.e. mask) plane
406 for(int i=0; i<16; ++i)
408 planes[1][2*i ] = pCursor->mask[i] >> 8 & 0xff;
409 planes[1][2*i+1] = pCursor->mask[i] & 0xff;
412 //add the representation (data) to the image
413 [theImage addRepresentation:theRep];
415 //create the new cursor
416 NSCursor* theCursor = [[NSCursor alloc] initWithImage:theImage
417 hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
420 //do the usual cleanups
424 //return the new cursor
428 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
430 WX_NSCursor cursor = nil;
433 case wxCURSOR_COPY_ARROW:
434 cursor = [[NSCursor arrowCursor] retain];
439 // should be displayed by the system when things are running
440 cursor = [[NSCursor arrowCursor] retain];
444 cursor = [[NSCursor IBeamCursor] retain];
448 cursor = [[NSCursor crosshairCursor] retain];
451 case wxCURSOR_SIZENWSE:
452 cursor = wxGetStockCursor(kwxCursorSizeNWSE);
455 case wxCURSOR_SIZENESW:
456 cursor = wxGetStockCursor(kwxCursorSizeNESW);
459 case wxCURSOR_SIZEWE:
460 cursor = [[NSCursor resizeLeftRightCursor] retain];
463 case wxCURSOR_SIZENS:
464 cursor = [[NSCursor resizeUpDownCursor] retain];
467 case wxCURSOR_SIZING:
468 cursor = wxGetStockCursor(kwxCursorSize);
472 cursor = [[NSCursor pointingHandCursor] retain];
475 case wxCURSOR_BULLSEYE:
476 cursor = wxGetStockCursor(kwxCursorBullseye);
479 case wxCURSOR_PENCIL:
480 cursor = wxGetStockCursor(kwxCursorPencil);
483 case wxCURSOR_MAGNIFIER:
484 cursor = wxGetStockCursor(kwxCursorMagnifier);
487 case wxCURSOR_NO_ENTRY:
488 cursor = wxGetStockCursor(kwxCursorNoEntry);
491 case wxCURSOR_PAINT_BRUSH:
492 cursor = wxGetStockCursor(kwxCursorPaintBrush);
495 case wxCURSOR_POINT_LEFT:
496 cursor = wxGetStockCursor(kwxCursorPointLeft);
499 case wxCURSOR_POINT_RIGHT:
500 cursor = wxGetStockCursor(kwxCursorPointRight);
503 case wxCURSOR_QUESTION_ARROW:
504 cursor = wxGetStockCursor(kwxCursorQuestionArrow);
508 cursor = wxGetStockCursor(kwxCursorBlank);
511 case wxCURSOR_RIGHT_ARROW:
512 cursor = wxGetStockCursor(kwxCursorRightArrow);
515 case wxCURSOR_SPRAYCAN:
516 cursor = wxGetStockCursor(kwxCursorRoller);
519 case wxCURSOR_OPEN_HAND:
520 cursor = [[NSCursor openHandCursor] retain];
523 case wxCURSOR_CLOSED_HAND:
524 cursor = [[NSCursor closedHandCursor] retain];
529 case wxCURSOR_LEFT_BUTTON:
530 case wxCURSOR_RIGHT_BUTTON:
531 case wxCURSOR_MIDDLE_BUTTON:
533 cursor = [[NSCursor arrowCursor] retain];
539 // C-based style wrapper routines around NSCursor
540 WX_NSCursor wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
542 static BOOL firstTime = YES;
546 // 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
547 [[[NSWindow alloc] init] release];
551 NSImage *nsImage = wxOSXCreateNSImageFromCGImage( cgImageRef );
552 NSCursor *cursor = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
559 void wxMacCocoaSetCursor( WX_NSCursor cursor )
564 void wxMacCocoaHideCursor()
569 void wxMacCocoaShowCursor()