better font round-trip fidelity (native->wx->native), fixing fontdialog for osx_cocoa...
[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
106 WX_NSFont wxFont::OSXCreateNSFont(wxOSXSystemFont font, wxNativeFontInfo* info)
107 {
108     NSFont* nsfont = nil;
109     switch( font )
110     {
111         case wxOSX_SYSTEM_FONT_NORMAL:
112             nsfont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
113             break;
114         case wxOSX_SYSTEM_FONT_BOLD:
115             nsfont = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
116             break;
117         case wxOSX_SYSTEM_FONT_SMALL:
118             nsfont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
119             break;
120         case wxOSX_SYSTEM_FONT_SMALL_BOLD:
121             nsfont = [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]];
122             break;
123         case wxOSX_SYSTEM_FONT_MINI:
124             nsfont = [NSFont systemFontOfSize:
125                 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
126             break;
127        case wxOSX_SYSTEM_FONT_MINI_BOLD:
128             nsfont = [NSFont boldSystemFontOfSize:
129                 [NSFont systemFontSizeForControlSize:NSMiniControlSize]];
130             break;
131         case wxOSX_SYSTEM_FONT_LABELS:
132             nsfont = [NSFont labelFontOfSize:[NSFont labelFontSize]];
133             break;
134        case wxOSX_SYSTEM_FONT_VIEWS:
135             nsfont = [NSFont controlContentFontOfSize:0];
136             break;
137         default:
138             break;
139     }
140     [nsfont retain];
141     NSFontDescriptor*desc = [[nsfont fontDescriptor] retain];
142     if ( info->m_faceName.empty())
143     {
144         wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
145         wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
146         bool underlined = false;
147         
148         int size = (int) ([desc pointSize]+0.5);
149         NSFontSymbolicTraits traits = [desc symbolicTraits];
150             
151         if ( traits & NSFontBoldTrait )
152             fontweight = wxFONTWEIGHT_BOLD ;
153         else
154             fontweight = wxFONTWEIGHT_NORMAL ;
155         if ( traits & NSFontItalicTrait )
156             fontstyle = wxFONTSTYLE_ITALIC ;
157              
158         wxCFStringRef fontname( [desc postscriptName] );
159         info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
160             fontname.AsString(), wxFONTENCODING_DEFAULT);
161         
162     }
163     info->m_nsFontDescriptor = desc;
164     return nsfont;
165 }
166
167 void wxNativeFontInfo::OSXValidateNSFontDescriptor()
168 {
169     NSFontDescriptor* desc  = nil;
170     NSFontSymbolicTraits traits = 0;
171     float weight = 0; 
172
173     if (m_weight == wxFONTWEIGHT_BOLD)
174     {
175         traits |= NSFontBoldTrait;
176         weight = 1.0;
177     }
178     else if (m_weight == wxFONTWEIGHT_LIGHT)
179         weight = -1;
180     
181     if (m_style == wxFONTSTYLE_ITALIC || m_style == wxFONTSTYLE_SLANT)
182         traits |= NSFontItalicTrait;
183
184     desc = [NSFontDescriptor fontDescriptorWithFontAttributes:
185         [[NSDictionary alloc] initWithObjectsAndKeys:
186             wxCFStringRef(m_faceName).AsNSString(), NSFontFamilyAttribute, 
187             [NSNumber numberWithFloat:m_pointSize], NSFontSizeAttribute, 
188             [NSNumber numberWithUnsignedInt:traits], NSFontSymbolicTrait, 
189             [NSNumber numberWithFloat:weight],NSFontWeightTrait,
190             nil]];
191
192     wxMacCocoaRetain(desc);
193     m_nsFontDescriptor = desc;
194 }
195
196 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
197 {
198     NSFont* nsFont;
199     nsFont = [NSFont fontWithDescriptor:info->m_nsFontDescriptor size:info->m_pointSize];
200     wxMacCocoaRetain(nsFont);
201     return nsFont;
202 }
203
204 #endif
205
206 #if wxOSX_USE_IPHONE
207
208 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
209 {
210     UIFont* uifont;
211     switch( font )
212     {
213         case wxOSX_SYSTEM_FONT_NORMAL:
214             uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
215             break;
216         case wxOSX_SYSTEM_FONT_BOLD:
217             uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
218             break;
219         case wxOSX_SYSTEM_FONT_MINI:
220         case wxOSX_SYSTEM_FONT_SMALL:
221             uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
222             break;
223         case wxOSX_SYSTEM_FONT_MINI_BOLD:
224         case wxOSX_SYSTEM_FONT_SMALL_BOLD:
225             uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
226             break;
227         case wxOSX_SYSTEM_FONT_VIEWS:
228         case wxOSX_SYSTEM_FONT_LABELS:
229             uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
230             break;
231         default:
232             break;
233     }
234     [uifont retain];
235     if ( info->m_faceName.empty())
236     {
237         wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
238         wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
239         bool underlined = false;
240         
241         int size = (int) ([uifont pointSize]+0.5);
242         /*
243         NSFontSymbolicTraits traits = [desc symbolicTraits];
244             
245         if ( traits & NSFontBoldTrait )
246             fontweight = wxFONTWEIGHT_BOLD ;
247         else
248             fontweight = wxFONTWEIGHT_NORMAL ;
249         if ( traits & NSFontItalicTrait )
250             fontstyle = wxFONTSTYLE_ITALIC ;
251         */
252         wxCFStringRef fontname( [uifont familyName] );
253         info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
254             fontname.AsString(), wxFONTENCODING_DEFAULT);
255         
256     }
257     return uifont;
258 }
259
260 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
261 {
262     UIFont* uiFont;
263     uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
264     wxMacCocoaRetain(uiFont);
265     return uiFont;
266 }
267
268 #endif
269 // ----------------------------------------------------------------------------
270 // NSImage Utils
271 // ----------------------------------------------------------------------------
272
273 #if wxOSX_USE_COCOA
274
275 //  From "Cocoa Drawing Guide:Working with Images"
276 WX_NSImage  wxOSXCreateNSImageFromCGImage( CGImageRef image )
277 {
278     NSRect      imageRect    = NSMakeRect(0.0, 0.0, 0.0, 0.0);
279     
280     // Get the image dimensions.
281     imageRect.size.height = CGImageGetHeight(image);
282     imageRect.size.width = CGImageGetWidth(image);
283     
284     // Create a new image to receive the Quartz image data.
285     NSImage  *newImage = [[NSImage alloc] initWithSize:imageRect.size]; 
286     [newImage lockFocus];
287     
288     // Get the Quartz context and draw.
289     CGContextRef  imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
290     CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
291     [newImage unlockFocus];
292     
293     /*
294         // Create a bitmap rep from the image...
295         NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
296         // Create an NSImage and add the bitmap rep to it...
297         NSImage *image = [[NSImage alloc] init];
298         [image addRepresentation:bitmapRep];
299         [bitmapRep release];
300     */
301     [newImage autorelease];
302     return( newImage );
303 }
304
305 // ----------------------------------------------------------------------------
306 // NSCursor Utils
307 // ----------------------------------------------------------------------------
308
309 // copied from cursor.mm
310
311 static NSCursor* wxGetStockCursor( short sIndex )
312 {
313     ClassicCursor* pCursor = &gMacCursors[sIndex];
314
315     //Classic mac cursors are 1bps 16x16 black and white with a
316     //identical mask that is 1 for on and 0 for off
317     NSImage *theImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
318
319     //NSCursor takes an NSImage takes a number of Representations - here
320     //we need only one for the raw data
321     NSBitmapImageRep *theRep = [[NSBitmapImageRep alloc]
322         initWithBitmapDataPlanes: NULL  // Tell Cocoa to allocate the planes for us.
323         pixelsWide: 16      // All classic cursors are 16x16
324         pixelsHigh: 16
325         bitsPerSample: 1    // All classic cursors are bitmaps with bitmasks
326         samplesPerPixel: 2  // Sample 0:image 1:mask
327         hasAlpha: YES       // Identify last sample as a mask
328         isPlanar: YES       // Use a separate array for each sample
329         colorSpaceName: NSCalibratedWhiteColorSpace // 0.0=black 1.0=white
330         bytesPerRow: 2      // Rows in each plane are on 2-byte boundaries (no pad)
331         bitsPerPixel: 1];   // same as bitsPerSample since data is planar
332
333     // Ensure that Cocoa allocated 2 and only 2 of the 5 possible planes
334     unsigned char *planes[5];
335     [theRep getBitmapDataPlanes:planes];
336     wxASSERT(planes[0] != NULL);
337     wxASSERT(planes[1] != NULL);
338     wxASSERT(planes[2] == NULL);
339     wxASSERT(planes[3] == NULL);
340     wxASSERT(planes[4] == NULL);
341
342     // NOTE1: The Cursor's bits field is white=0 black=1.. thus the bitwise-not
343     // Why not use NSCalibratedBlackColorSpace?  Because that reverses the
344     // sense of the alpha (mask) plane.
345     // NOTE2: The mask data is 0=off 1=on
346     // NOTE3: Cocoa asks for "premultiplied" color planes.  Since we have a
347     // 1-bit color plane and a 1-bit alpha plane we can just do a bitwise-and
348     // on the two.  The original cursor bitmaps have 0 (white actually) for
349     // any masked-off pixels.  Therefore every masked-off pixel would be wrong
350     // since we bit-flip all of the picture bits.  In practice, Cocoa doesn't
351     // seem to care, but we are following the documentation.
352
353     // Fill in the color (black/white) plane
354     for(int i=0; i<16; ++i)
355     {
356         planes[0][2*i  ] = (~pCursor->bits[i] & pCursor->mask[i]) >> 8 & 0xff;
357         planes[0][2*i+1] = (~pCursor->bits[i] & pCursor->mask[i]) & 0xff;
358     }
359     // Fill in the alpha (i.e. mask) plane
360     for(int i=0; i<16; ++i)
361     {
362         planes[1][2*i  ] = pCursor->mask[i] >> 8 & 0xff;
363         planes[1][2*i+1] = pCursor->mask[i] & 0xff;
364     }
365
366     //add the representation (data) to the image
367     [theImage addRepresentation:theRep];
368
369     //create the new cursor
370     NSCursor* theCursor =  [[NSCursor alloc]  initWithImage:theImage
371                                     hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
372                             ];
373
374     //do the usual cleanups
375     [theRep release];
376     [theImage release];
377
378     //return the new cursor
379     return theCursor;
380 }
381
382 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
383 {
384     WX_NSCursor cursor = nil;
385     switch (cursor_type)
386     {
387     case wxCURSOR_COPY_ARROW:
388         cursor = [[NSCursor arrowCursor] retain];
389         break;
390
391     case wxCURSOR_WATCH:
392     case wxCURSOR_WAIT:
393         // should be displayed by the system when things are running
394         cursor = [[NSCursor arrowCursor] retain];
395         break;
396
397     case wxCURSOR_IBEAM:
398         cursor = [[NSCursor IBeamCursor] retain];
399         break;
400
401     case wxCURSOR_CROSS:
402         cursor = [[NSCursor crosshairCursor] retain];
403         break;
404
405     case wxCURSOR_SIZENWSE:
406         cursor = wxGetStockCursor(kwxCursorSizeNWSE);
407         break;
408
409     case wxCURSOR_SIZENESW:
410         cursor = wxGetStockCursor(kwxCursorSizeNESW);
411         break;
412
413     case wxCURSOR_SIZEWE:
414         cursor = [[NSCursor resizeLeftRightCursor] retain];
415         break;
416
417     case wxCURSOR_SIZENS:
418         cursor = [[NSCursor resizeUpDownCursor] retain];
419         break;
420
421     case wxCURSOR_SIZING:
422         cursor = wxGetStockCursor(kwxCursorSize);
423         break;
424
425     case wxCURSOR_HAND:
426         cursor = [[NSCursor pointingHandCursor] retain];
427         break;
428         
429     case wxCURSOR_BULLSEYE:
430         cursor = wxGetStockCursor(kwxCursorBullseye);
431         break;
432
433     case wxCURSOR_PENCIL:
434         cursor = wxGetStockCursor(kwxCursorPencil);
435         break;
436
437     case wxCURSOR_MAGNIFIER:
438         cursor = wxGetStockCursor(kwxCursorMagnifier);
439         break;
440
441     case wxCURSOR_NO_ENTRY:
442         cursor = wxGetStockCursor(kwxCursorNoEntry);
443         break;
444
445     case wxCURSOR_PAINT_BRUSH:
446         cursor = wxGetStockCursor(kwxCursorPaintBrush);
447         break;
448
449     case wxCURSOR_POINT_LEFT:
450         cursor = wxGetStockCursor(kwxCursorPointLeft);
451         break;
452
453     case wxCURSOR_POINT_RIGHT:
454         cursor = wxGetStockCursor(kwxCursorPointRight);
455         break;
456
457     case wxCURSOR_QUESTION_ARROW:
458         cursor = wxGetStockCursor(kwxCursorQuestionArrow);
459         break;
460
461     case wxCURSOR_BLANK:
462         cursor = wxGetStockCursor(kwxCursorBlank);
463         break;
464
465     case wxCURSOR_RIGHT_ARROW:
466         cursor = wxGetStockCursor(kwxCursorRightArrow);
467         break;
468
469     case wxCURSOR_SPRAYCAN:
470         cursor = wxGetStockCursor(kwxCursorRoller);
471         break;
472
473     case wxCURSOR_OPEN_HAND:
474         cursor = [[NSCursor openHandCursor] retain];
475         break;
476
477     case wxCURSOR_CLOSED_HAND:
478         cursor = [[NSCursor closedHandCursor] retain];
479         break;
480
481     case wxCURSOR_CHAR:
482     case wxCURSOR_ARROW:
483     case wxCURSOR_LEFT_BUTTON:
484     case wxCURSOR_RIGHT_BUTTON:
485     case wxCURSOR_MIDDLE_BUTTON:
486     default:
487         cursor = [[NSCursor arrowCursor] retain];
488         break;
489     }
490     return cursor;
491 }
492
493 //  C-based style wrapper routines around NSCursor
494 WX_NSCursor  wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
495 {
496     static BOOL    firstTime  = YES;
497     
498     if ( firstTime )
499     {
500         //  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
501         [[[NSWindow alloc] init] release];
502         firstTime = NO;
503     }
504     
505     NSImage    *nsImage  = wxOSXCreateNSImageFromCGImage( cgImageRef );
506     NSCursor  *cursor    = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
507     
508     [nsImage release];
509     
510     return cursor;
511 }
512
513 void  wxMacCocoaSetCursor( WX_NSCursor cursor )
514 {
515     [cursor set];
516 }
517
518 void  wxMacCocoaHideCursor()
519 {
520     [NSCursor hide];
521 }
522
523 void  wxMacCocoaShowCursor()
524 {
525     [NSCursor unhide];
526 }
527
528 #endif
529