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