fixing leak, fixes #11782
[wxWidgets.git] / src / osx / carbon / utilscocoa.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/carbon/utils.mm
3 // Purpose:     various cocoa mixin utility functions
4 // Author:      Stefan Csomor
5 // Modified by:
6 // Created:     1998-01-01
7 // RCS-ID:      $Id: utilscocoa.mm 48805 2007-09-19 14:52:25Z SC $
8 // Copyright:   (c) Stefan Csomor
9 // Licence:     wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #if wxOSX_USE_COCOA_OR_CARBON
15 #include <Cocoa/Cocoa.h>
16 #else
17 #import <UIKit/UIKit.h>
18 #endif
19
20 #ifdef __WXMAC__
21 #include "wx/osx/private.h"
22 #endif
23
24 #include "wx/fontutil.h"
25
26 #ifdef __WXMAC__
27
28 #if wxOSX_USE_CARBON
29 bool wxMacInitCocoa()
30 {
31     bool cocoaLoaded = NSApplicationLoad();
32     wxASSERT_MSG(cocoaLoaded,wxT("Couldn't load Cocoa in Carbon Environment")) ;
33     return cocoaLoaded;
34 }
35 #endif
36
37 wxMacAutoreleasePool::wxMacAutoreleasePool()
38 {
39     m_pool = [[NSAutoreleasePool alloc] init];
40 }
41
42 wxMacAutoreleasePool::~wxMacAutoreleasePool()
43 {
44     [(NSAutoreleasePool*)m_pool release];
45 }
46
47 #endif
48
49 #if wxOSX_USE_COCOA
50
51 CGContextRef wxOSXGetContextFromCurrentContext()
52 {
53     CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]
54                                           graphicsPort];
55     return context;
56 }
57
58 bool wxOSXLockFocus( WXWidget view)
59 {
60     return [view lockFocusIfCanDraw];
61 }
62
63 void wxOSXUnlockFocus( WXWidget view)
64 {
65     [view unlockFocus];
66 }
67
68 #endif
69
70 #if wxOSX_USE_IPHONE
71
72 CGContextRef wxOSXGetContextFromCurrentContext()
73 {
74     CGContextRef context = UIGraphicsGetCurrentContext();
75     return context;
76 }
77
78 #endif
79
80 // ----------------------------------------------------------------------------
81 // NSObject Utils
82 // ----------------------------------------------------------------------------
83
84 void wxMacCocoaRelease( void* obj )
85 {
86     [(NSObject*)obj release];
87 }
88
89 void wxMacCocoaAutorelease( void* obj )
90 {
91     [(NSObject*)obj autorelease];
92 }
93
94 void* wxMacCocoaRetain( void* obj )
95 {
96     [(NSObject*)obj retain];
97     return obj;
98 }
99
100 // ----------------------------------------------------------------------------
101 // NSFont Utils
102 // ----------------------------------------------------------------------------
103
104 #if wxOSX_USE_COCOA
105 wxFont::wxFont(WX_NSFont nsfont)
106 {
107     [nsfont retain];
108     wxNativeFontInfo info;
109     SetNativeInfoFromNSFont(nsfont, &info);
110     Create(info);
111 }
112
113 void wxFont::SetNativeInfoFromNSFont(WX_NSFont nsfont, wxNativeFontInfo* info)
114 {   
115     NSFontDescriptor*desc = [[nsfont fontDescriptor] retain];
116     if ( info->m_faceName.empty())
117     {
118         wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
119         wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
120         bool underlined = false;
121
122         int size = (int) ([desc pointSize]+0.5);
123         NSFontSymbolicTraits traits = [desc symbolicTraits];
124
125         if ( traits & NSFontBoldTrait )
126             fontweight = wxFONTWEIGHT_BOLD ;
127         else
128             fontweight = wxFONTWEIGHT_NORMAL ;
129         if ( traits & NSFontItalicTrait )
130             fontstyle = wxFONTSTYLE_ITALIC ;
131
132         wxCFStringRef fontname( [desc postscriptName] );
133         info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
134             fontname.AsString(), wxFONTENCODING_DEFAULT);
135
136     }
137     info->m_nsFontDescriptor = desc;
138 }
139
140 WX_NSFont wxFont::OSXCreateNSFont(wxOSXSystemFont font, wxNativeFontInfo* info)
141 {
142     NSFont* nsfont = nil;
143     switch( font )
144     {
145         case wxOSX_SYSTEM_FONT_NORMAL:
146             nsfont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
147             break;
148         case wxOSX_SYSTEM_FONT_BOLD:
149             nsfont = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
150             break;
151         case wxOSX_SYSTEM_FONT_SMALL:
152             nsfont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
153             break;
154         case wxOSX_SYSTEM_FONT_SMALL_BOLD:
155             nsfont = [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]];
156             break;
157         case wxOSX_SYSTEM_FONT_MINI:
158             nsfont = [NSFont systemFontOfSize:
159                 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
160             break;
161        case wxOSX_SYSTEM_FONT_MINI_BOLD:
162             nsfont = [NSFont boldSystemFontOfSize:
163                 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
164             break;
165         case wxOSX_SYSTEM_FONT_LABELS:
166             nsfont = [NSFont labelFontOfSize:[NSFont labelFontSize]];
167             break;
168        case wxOSX_SYSTEM_FONT_VIEWS:
169             nsfont = [NSFont controlContentFontOfSize:0];
170             break;
171         default:
172             break;
173     }
174     [nsfont retain];
175     SetNativeInfoFromNSFont(nsfont, info);
176     return nsfont;
177 }
178
179 void wxNativeFontInfo::OSXValidateNSFontDescriptor()
180 {
181     NSFontDescriptor* desc  = nil;
182     NSFontSymbolicTraits traits = 0;
183     float weight = 0;
184
185     if (m_weight == wxFONTWEIGHT_BOLD)
186     {
187         traits |= NSFontBoldTrait;
188         weight = 1.0;
189     }
190     else if (m_weight == wxFONTWEIGHT_LIGHT)
191         weight = -1;
192
193     if (m_style == wxFONTSTYLE_ITALIC || m_style == wxFONTSTYLE_SLANT)
194         traits |= NSFontItalicTrait;
195
196     desc = [NSFontDescriptor fontDescriptorWithFontAttributes:
197         [NSDictionary dictionaryWithObjectsAndKeys:
198             wxCFStringRef(m_faceName).AsNSString(), NSFontFamilyAttribute,
199             [NSNumber numberWithFloat:m_pointSize], NSFontSizeAttribute,
200             [NSNumber numberWithUnsignedInt:traits], NSFontSymbolicTrait,
201             [NSNumber numberWithFloat:weight],NSFontWeightTrait,
202             nil]];
203
204     wxMacCocoaRetain(desc);
205     m_nsFontDescriptor = desc;
206 }
207
208 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
209 {
210     NSFont* nsFont;
211     nsFont = [NSFont fontWithDescriptor:info->m_nsFontDescriptor size:info->m_pointSize];
212     wxMacCocoaRetain(nsFont);
213     return nsFont;
214 }
215
216 #endif
217
218 #if wxOSX_USE_IPHONE
219
220 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
221 {
222     UIFont* uifont;
223     switch( font )
224     {
225         case wxOSX_SYSTEM_FONT_NORMAL:
226             uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
227             break;
228         case wxOSX_SYSTEM_FONT_BOLD:
229             uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
230             break;
231         case wxOSX_SYSTEM_FONT_MINI:
232         case wxOSX_SYSTEM_FONT_SMALL:
233             uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
234             break;
235         case wxOSX_SYSTEM_FONT_MINI_BOLD:
236         case wxOSX_SYSTEM_FONT_SMALL_BOLD:
237             uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
238             break;
239         case wxOSX_SYSTEM_FONT_VIEWS:
240         case wxOSX_SYSTEM_FONT_LABELS:
241             uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
242             break;
243         default:
244             break;
245     }
246     [uifont retain];
247     if ( info->m_faceName.empty())
248     {
249         wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
250         wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
251         bool underlined = false;
252
253         int size = (int) ([uifont pointSize]+0.5);
254         /*
255         NSFontSymbolicTraits traits = [desc symbolicTraits];
256
257         if ( traits & NSFontBoldTrait )
258             fontweight = wxFONTWEIGHT_BOLD ;
259         else
260             fontweight = wxFONTWEIGHT_NORMAL ;
261         if ( traits & NSFontItalicTrait )
262             fontstyle = wxFONTSTYLE_ITALIC ;
263         */
264         wxCFStringRef fontname( wxCFRetain([uifont familyName]) );
265         info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
266             fontname.AsString(), wxFONTENCODING_DEFAULT);
267
268     }
269     return uifont;
270 }
271
272 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
273 {
274     UIFont* uiFont;
275     uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
276     wxMacCocoaRetain(uiFont);
277     return uiFont;
278 }
279
280 #endif
281 // ----------------------------------------------------------------------------
282 // NSImage Utils
283 // ----------------------------------------------------------------------------
284
285 #if wxOSX_USE_IPHONE
286
287 WX_UIImage  wxOSXCreateUIImageFromCGImage( CGImageRef image )
288 {
289     UIImage  *newImage = [UIImage imageWithCGImage:image];
290     [newImage autorelease];
291     return( newImage );
292 }
293
294 #endif
295
296 #if wxOSX_USE_COCOA
297
298 //  From "Cocoa Drawing Guide:Working with Images"
299 WX_NSImage  wxOSXCreateNSImageFromCGImage( CGImageRef image )
300 {
301     NSRect      imageRect    = NSMakeRect(0.0, 0.0, 0.0, 0.0);
302
303     // Get the image dimensions.
304     imageRect.size.height = CGImageGetHeight(image);
305     imageRect.size.width = CGImageGetWidth(image);
306
307     // Create a new image to receive the Quartz image data.
308     NSImage  *newImage = [[NSImage alloc] initWithSize:imageRect.size];
309     [newImage lockFocus];
310
311     // Get the Quartz context and draw.
312     CGContextRef  imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
313     CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
314     [newImage unlockFocus];
315
316     /*
317         // Create a bitmap rep from the image...
318         NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
319         // Create an NSImage and add the bitmap rep to it...
320         NSImage *image = [[NSImage alloc] init];
321         [image addRepresentation:bitmapRep];
322         [bitmapRep release];
323     */
324     [newImage autorelease];
325     return( newImage );
326 }
327
328 CGImageRef wxOSXCreateCGImageFromNSImage( WX_NSImage nsimage )
329 {
330     // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
331     
332     NSSize imageSize = [nsimage size];
333     CGColorSpaceRef genericRGB = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); 
334     CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, 0, genericRGB, kCGImageAlphaPremultipliedFirst); 
335     NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
336     [NSGraphicsContext saveGraphicsState];
337     [NSGraphicsContext setCurrentContext:nsGraphicsContext];
338     [[NSColor whiteColor] setFill];
339     NSRectFill(NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height));
340     [nsimage drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
341     [NSGraphicsContext setCurrentContext:nsGraphicsContext];
342     CGImageRef image = CGBitmapContextCreateImage(context);
343     CFRelease(context);
344     return image;
345  }
346
347 // ----------------------------------------------------------------------------
348 // NSCursor Utils
349 // ----------------------------------------------------------------------------
350
351 // copied from cursor.mm
352
353 static NSCursor* wxGetStockCursor( short sIndex )
354 {
355     ClassicCursor* pCursor = &gMacCursors[sIndex];
356
357     //Classic mac cursors are 1bps 16x16 black and white with a
358     //identical mask that is 1 for on and 0 for off
359     NSImage *theImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
360
361     //NSCursor takes an NSImage takes a number of Representations - here
362     //we need only one for the raw data
363     NSBitmapImageRep *theRep = [[NSBitmapImageRep alloc]
364         initWithBitmapDataPlanes: NULL  // Tell Cocoa to allocate the planes for us.
365         pixelsWide: 16      // All classic cursors are 16x16
366         pixelsHigh: 16
367         bitsPerSample: 1    // All classic cursors are bitmaps with bitmasks
368         samplesPerPixel: 2  // Sample 0:image 1:mask
369         hasAlpha: YES       // Identify last sample as a mask
370         isPlanar: YES       // Use a separate array for each sample
371         colorSpaceName: NSCalibratedWhiteColorSpace // 0.0=black 1.0=white
372         bytesPerRow: 2      // Rows in each plane are on 2-byte boundaries (no pad)
373         bitsPerPixel: 1];   // same as bitsPerSample since data is planar
374
375     // Ensure that Cocoa allocated 2 and only 2 of the 5 possible planes
376     unsigned char *planes[5];
377     [theRep getBitmapDataPlanes:planes];
378     wxASSERT(planes[0] != NULL);
379     wxASSERT(planes[1] != NULL);
380     wxASSERT(planes[2] == NULL);
381     wxASSERT(planes[3] == NULL);
382     wxASSERT(planes[4] == NULL);
383
384     // NOTE1: The Cursor's bits field is white=0 black=1.. thus the bitwise-not
385     // Why not use NSCalibratedBlackColorSpace?  Because that reverses the
386     // sense of the alpha (mask) plane.
387     // NOTE2: The mask data is 0=off 1=on
388     // NOTE3: Cocoa asks for "premultiplied" color planes.  Since we have a
389     // 1-bit color plane and a 1-bit alpha plane we can just do a bitwise-and
390     // on the two.  The original cursor bitmaps have 0 (white actually) for
391     // any masked-off pixels.  Therefore every masked-off pixel would be wrong
392     // since we bit-flip all of the picture bits.  In practice, Cocoa doesn't
393     // seem to care, but we are following the documentation.
394
395     // Fill in the color (black/white) plane
396     for(int i=0; i<16; ++i)
397     {
398         planes[0][2*i  ] = (~pCursor->bits[i] & pCursor->mask[i]) >> 8 & 0xff;
399         planes[0][2*i+1] = (~pCursor->bits[i] & pCursor->mask[i]) & 0xff;
400     }
401     // Fill in the alpha (i.e. mask) plane
402     for(int i=0; i<16; ++i)
403     {
404         planes[1][2*i  ] = pCursor->mask[i] >> 8 & 0xff;
405         planes[1][2*i+1] = pCursor->mask[i] & 0xff;
406     }
407
408     //add the representation (data) to the image
409     [theImage addRepresentation:theRep];
410
411     //create the new cursor
412     NSCursor* theCursor =  [[NSCursor alloc]  initWithImage:theImage
413                                     hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
414                             ];
415
416     //do the usual cleanups
417     [theRep release];
418     [theImage release];
419
420     //return the new cursor
421     return theCursor;
422 }
423
424 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
425 {
426     WX_NSCursor cursor = nil;
427     switch (cursor_type)
428     {
429     case wxCURSOR_COPY_ARROW:
430         cursor = [[NSCursor arrowCursor] retain];
431         break;
432
433     case wxCURSOR_WATCH:
434     case wxCURSOR_WAIT:
435         // should be displayed by the system when things are running
436         cursor = [[NSCursor arrowCursor] retain];
437         break;
438
439     case wxCURSOR_IBEAM:
440         cursor = [[NSCursor IBeamCursor] retain];
441         break;
442
443     case wxCURSOR_CROSS:
444         cursor = [[NSCursor crosshairCursor] retain];
445         break;
446
447     case wxCURSOR_SIZENWSE:
448         cursor = wxGetStockCursor(kwxCursorSizeNWSE);
449         break;
450
451     case wxCURSOR_SIZENESW:
452         cursor = wxGetStockCursor(kwxCursorSizeNESW);
453         break;
454
455     case wxCURSOR_SIZEWE:
456         cursor = [[NSCursor resizeLeftRightCursor] retain];
457         break;
458
459     case wxCURSOR_SIZENS:
460         cursor = [[NSCursor resizeUpDownCursor] retain];
461         break;
462
463     case wxCURSOR_SIZING:
464         cursor = wxGetStockCursor(kwxCursorSize);
465         break;
466
467     case wxCURSOR_HAND:
468         cursor = [[NSCursor pointingHandCursor] retain];
469         break;
470
471     case wxCURSOR_BULLSEYE:
472         cursor = wxGetStockCursor(kwxCursorBullseye);
473         break;
474
475     case wxCURSOR_PENCIL:
476         cursor = wxGetStockCursor(kwxCursorPencil);
477         break;
478
479     case wxCURSOR_MAGNIFIER:
480         cursor = wxGetStockCursor(kwxCursorMagnifier);
481         break;
482
483     case wxCURSOR_NO_ENTRY:
484         cursor = wxGetStockCursor(kwxCursorNoEntry);
485         break;
486
487     case wxCURSOR_PAINT_BRUSH:
488         cursor = wxGetStockCursor(kwxCursorPaintBrush);
489         break;
490
491     case wxCURSOR_POINT_LEFT:
492         cursor = wxGetStockCursor(kwxCursorPointLeft);
493         break;
494
495     case wxCURSOR_POINT_RIGHT:
496         cursor = wxGetStockCursor(kwxCursorPointRight);
497         break;
498
499     case wxCURSOR_QUESTION_ARROW:
500         cursor = wxGetStockCursor(kwxCursorQuestionArrow);
501         break;
502
503     case wxCURSOR_BLANK:
504         cursor = wxGetStockCursor(kwxCursorBlank);
505         break;
506
507     case wxCURSOR_RIGHT_ARROW:
508         cursor = wxGetStockCursor(kwxCursorRightArrow);
509         break;
510
511     case wxCURSOR_SPRAYCAN:
512         cursor = wxGetStockCursor(kwxCursorRoller);
513         break;
514
515     case wxCURSOR_OPEN_HAND:
516         cursor = [[NSCursor openHandCursor] retain];
517         break;
518
519     case wxCURSOR_CLOSED_HAND:
520         cursor = [[NSCursor closedHandCursor] retain];
521         break;
522
523     case wxCURSOR_CHAR:
524     case wxCURSOR_ARROW:
525     case wxCURSOR_LEFT_BUTTON:
526     case wxCURSOR_RIGHT_BUTTON:
527     case wxCURSOR_MIDDLE_BUTTON:
528     default:
529         cursor = [[NSCursor arrowCursor] retain];
530         break;
531     }
532     return cursor;
533 }
534
535 //  C-based style wrapper routines around NSCursor
536 WX_NSCursor  wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
537 {
538     static BOOL    firstTime  = YES;
539
540     if ( firstTime )
541     {
542         //  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
543         [[[NSWindow alloc] init] release];
544         firstTime = NO;
545     }
546
547     NSImage    *nsImage  = wxOSXCreateNSImageFromCGImage( cgImageRef );
548     NSCursor  *cursor    = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
549
550     [nsImage release];
551
552     return cursor;
553 }
554
555 void  wxMacCocoaSetCursor( WX_NSCursor cursor )
556 {
557     [cursor set];
558 }
559
560 void  wxMacCocoaHideCursor()
561 {
562     [NSCursor hide];
563 }
564
565 void  wxMacCocoaShowCursor()
566 {
567     [NSCursor unhide];
568 }
569
570 #endif
571