fixing NSFontDescriptor matching for font weights and styles, fixes #11910
[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     NSDictionary* traitsdict = [NSDictionary dictionaryWithObjectsAndKeys:
197                            [NSNumber numberWithUnsignedInt:traits], NSFontSymbolicTrait,
198                            nil] ;
199      
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,
206             nil]];
207
208     wxMacCocoaRetain(desc);
209     m_nsFontDescriptor = desc;
210 }
211
212 WX_NSFont wxFont::OSXCreateNSFont(const wxNativeFontInfo* info)
213 {
214     NSFont* nsFont;
215     nsFont = [NSFont fontWithDescriptor:info->m_nsFontDescriptor size:info->m_pointSize];
216     wxMacCocoaRetain(nsFont);
217     return nsFont;
218 }
219
220 #endif
221
222 #if wxOSX_USE_IPHONE
223
224 WX_UIFont wxFont::OSXCreateUIFont(wxOSXSystemFont font, wxNativeFontInfo* info)
225 {
226     UIFont* uifont;
227     switch( font )
228     {
229         case wxOSX_SYSTEM_FONT_NORMAL:
230             uifont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
231             break;
232         case wxOSX_SYSTEM_FONT_BOLD:
233             uifont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
234             break;
235         case wxOSX_SYSTEM_FONT_MINI:
236         case wxOSX_SYSTEM_FONT_SMALL:
237             uifont = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
238             break;
239         case wxOSX_SYSTEM_FONT_MINI_BOLD:
240         case wxOSX_SYSTEM_FONT_SMALL_BOLD:
241             uifont = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
242             break;
243         case wxOSX_SYSTEM_FONT_VIEWS:
244         case wxOSX_SYSTEM_FONT_LABELS:
245             uifont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
246             break;
247         default:
248             break;
249     }
250     [uifont retain];
251     if ( info->m_faceName.empty())
252     {
253         wxFontStyle fontstyle = wxFONTSTYLE_NORMAL;
254         wxFontWeight fontweight = wxFONTWEIGHT_NORMAL;
255         bool underlined = false;
256
257         int size = (int) ([uifont pointSize]+0.5);
258         /*
259         NSFontSymbolicTraits traits = [desc symbolicTraits];
260
261         if ( traits & NSFontBoldTrait )
262             fontweight = wxFONTWEIGHT_BOLD ;
263         else
264             fontweight = wxFONTWEIGHT_NORMAL ;
265         if ( traits & NSFontItalicTrait )
266             fontstyle = wxFONTSTYLE_ITALIC ;
267         */
268         wxCFStringRef fontname( wxCFRetain([uifont familyName]) );
269         info->Init(size,wxFONTFAMILY_DEFAULT,fontstyle,fontweight,underlined,
270             fontname.AsString(), wxFONTENCODING_DEFAULT);
271
272     }
273     return uifont;
274 }
275
276 WX_UIFont wxFont::OSXCreateUIFont(const wxNativeFontInfo* info)
277 {
278     UIFont* uiFont;
279     uiFont = [UIFont fontWithName:wxCFStringRef(info->m_faceName).AsNSString() size:info->m_pointSize];
280     wxMacCocoaRetain(uiFont);
281     return uiFont;
282 }
283
284 #endif
285 // ----------------------------------------------------------------------------
286 // NSImage Utils
287 // ----------------------------------------------------------------------------
288
289 #if wxOSX_USE_IPHONE
290
291 WX_UIImage  wxOSXCreateUIImageFromCGImage( CGImageRef image )
292 {
293     UIImage  *newImage = [UIImage imageWithCGImage:image];
294     [newImage autorelease];
295     return( newImage );
296 }
297
298 #endif
299
300 #if wxOSX_USE_COCOA
301
302 //  From "Cocoa Drawing Guide:Working with Images"
303 WX_NSImage  wxOSXCreateNSImageFromCGImage( CGImageRef image )
304 {
305     NSRect      imageRect    = NSMakeRect(0.0, 0.0, 0.0, 0.0);
306
307     // Get the image dimensions.
308     imageRect.size.height = CGImageGetHeight(image);
309     imageRect.size.width = CGImageGetWidth(image);
310
311     // Create a new image to receive the Quartz image data.
312     NSImage  *newImage = [[NSImage alloc] initWithSize:imageRect.size];
313     [newImage lockFocus];
314
315     // Get the Quartz context and draw.
316     CGContextRef  imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
317     CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
318     [newImage unlockFocus];
319
320     /*
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];
326         [bitmapRep release];
327     */
328     [newImage autorelease];
329     return( newImage );
330 }
331
332 CGImageRef wxOSXCreateCGImageFromNSImage( WX_NSImage nsimage )
333 {
334     // based on http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg18065.html
335     
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);
347     CFRelease(context);
348     return image;
349  }
350
351 // ----------------------------------------------------------------------------
352 // NSCursor Utils
353 // ----------------------------------------------------------------------------
354
355 // copied from cursor.mm
356
357 static NSCursor* wxGetStockCursor( short sIndex )
358 {
359     ClassicCursor* pCursor = &gMacCursors[sIndex];
360
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)];
364
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
370         pixelsHigh: 16
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
378
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);
387
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.
398
399     // Fill in the color (black/white) plane
400     for(int i=0; i<16; ++i)
401     {
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;
404     }
405     // Fill in the alpha (i.e. mask) plane
406     for(int i=0; i<16; ++i)
407     {
408         planes[1][2*i  ] = pCursor->mask[i] >> 8 & 0xff;
409         planes[1][2*i+1] = pCursor->mask[i] & 0xff;
410     }
411
412     //add the representation (data) to the image
413     [theImage addRepresentation:theRep];
414
415     //create the new cursor
416     NSCursor* theCursor =  [[NSCursor alloc]  initWithImage:theImage
417                                     hotSpot:NSMakePoint(pCursor->hotspot[1], pCursor->hotspot[0])
418                             ];
419
420     //do the usual cleanups
421     [theRep release];
422     [theImage release];
423
424     //return the new cursor
425     return theCursor;
426 }
427
428 WX_NSCursor wxMacCocoaCreateStockCursor( int cursor_type )
429 {
430     WX_NSCursor cursor = nil;
431     switch (cursor_type)
432     {
433     case wxCURSOR_COPY_ARROW:
434         cursor = [[NSCursor arrowCursor] retain];
435         break;
436
437     case wxCURSOR_WATCH:
438     case wxCURSOR_WAIT:
439         // should be displayed by the system when things are running
440         cursor = [[NSCursor arrowCursor] retain];
441         break;
442
443     case wxCURSOR_IBEAM:
444         cursor = [[NSCursor IBeamCursor] retain];
445         break;
446
447     case wxCURSOR_CROSS:
448         cursor = [[NSCursor crosshairCursor] retain];
449         break;
450
451     case wxCURSOR_SIZENWSE:
452         cursor = wxGetStockCursor(kwxCursorSizeNWSE);
453         break;
454
455     case wxCURSOR_SIZENESW:
456         cursor = wxGetStockCursor(kwxCursorSizeNESW);
457         break;
458
459     case wxCURSOR_SIZEWE:
460         cursor = [[NSCursor resizeLeftRightCursor] retain];
461         break;
462
463     case wxCURSOR_SIZENS:
464         cursor = [[NSCursor resizeUpDownCursor] retain];
465         break;
466
467     case wxCURSOR_SIZING:
468         cursor = wxGetStockCursor(kwxCursorSize);
469         break;
470
471     case wxCURSOR_HAND:
472         cursor = [[NSCursor pointingHandCursor] retain];
473         break;
474
475     case wxCURSOR_BULLSEYE:
476         cursor = wxGetStockCursor(kwxCursorBullseye);
477         break;
478
479     case wxCURSOR_PENCIL:
480         cursor = wxGetStockCursor(kwxCursorPencil);
481         break;
482
483     case wxCURSOR_MAGNIFIER:
484         cursor = wxGetStockCursor(kwxCursorMagnifier);
485         break;
486
487     case wxCURSOR_NO_ENTRY:
488         cursor = wxGetStockCursor(kwxCursorNoEntry);
489         break;
490
491     case wxCURSOR_PAINT_BRUSH:
492         cursor = wxGetStockCursor(kwxCursorPaintBrush);
493         break;
494
495     case wxCURSOR_POINT_LEFT:
496         cursor = wxGetStockCursor(kwxCursorPointLeft);
497         break;
498
499     case wxCURSOR_POINT_RIGHT:
500         cursor = wxGetStockCursor(kwxCursorPointRight);
501         break;
502
503     case wxCURSOR_QUESTION_ARROW:
504         cursor = wxGetStockCursor(kwxCursorQuestionArrow);
505         break;
506
507     case wxCURSOR_BLANK:
508         cursor = wxGetStockCursor(kwxCursorBlank);
509         break;
510
511     case wxCURSOR_RIGHT_ARROW:
512         cursor = wxGetStockCursor(kwxCursorRightArrow);
513         break;
514
515     case wxCURSOR_SPRAYCAN:
516         cursor = wxGetStockCursor(kwxCursorRoller);
517         break;
518
519     case wxCURSOR_OPEN_HAND:
520         cursor = [[NSCursor openHandCursor] retain];
521         break;
522
523     case wxCURSOR_CLOSED_HAND:
524         cursor = [[NSCursor closedHandCursor] retain];
525         break;
526
527     case wxCURSOR_CHAR:
528     case wxCURSOR_ARROW:
529     case wxCURSOR_LEFT_BUTTON:
530     case wxCURSOR_RIGHT_BUTTON:
531     case wxCURSOR_MIDDLE_BUTTON:
532     default:
533         cursor = [[NSCursor arrowCursor] retain];
534         break;
535     }
536     return cursor;
537 }
538
539 //  C-based style wrapper routines around NSCursor
540 WX_NSCursor  wxMacCocoaCreateCursorFromCGImage( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
541 {
542     static BOOL    firstTime  = YES;
543
544     if ( firstTime )
545     {
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];
548         firstTime = NO;
549     }
550
551     NSImage    *nsImage  = wxOSXCreateNSImageFromCGImage( cgImageRef );
552     NSCursor  *cursor    = [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];
553
554     [nsImage release];
555
556     return cursor;
557 }
558
559 void  wxMacCocoaSetCursor( WX_NSCursor cursor )
560 {
561     [cursor set];
562 }
563
564 void  wxMacCocoaHideCursor()
565 {
566     [NSCursor hide];
567 }
568
569 void  wxMacCocoaShowCursor()
570 {
571     [NSCursor unhide];
572 }
573
574 #endif
575