Cocoa : mem leak fix
[blender-staging.git] / intern / ghost / intern / GHOST_WindowCocoa.mm
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s):      Maarten Gribnau 05/2001
25                                         Damien Plisson 10/2009
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <Cocoa/Cocoa.h>
31
32 #ifndef MAC_OS_X_VERSION_10_6
33 //Use of the SetSystemUIMode function (64bit compatible)
34 #include <Carbon/Carbon.h>
35 #endif
36
37 #include <OpenGL/gl.h>
38 /***** Multithreaded opengl code : uncomment for enabling
39 #include <OpenGL/OpenGL.h>
40 */
41
42  
43 #include "GHOST_WindowCocoa.h"
44 #include "GHOST_SystemCocoa.h"
45 #include "GHOST_Debug.h"
46
47
48 #pragma mark Cocoa window delegate object
49 /* live resize ugly patch
50 extern "C" {
51         struct bContext;
52         typedef struct bContext bContext;
53         bContext* ghostC;
54         extern int wm_window_timer(const bContext *C);
55         extern void wm_window_process_events(const bContext *C);
56         extern void wm_event_do_handlers(bContext *C);
57         extern void wm_event_do_notifiers(bContext *C);
58         extern void wm_draw_update(bContext *C);
59 };*/
60 @interface CocoaWindowDelegate : NSObject
61 #ifdef MAC_OS_X_VERSION_10_6
62 <NSWindowDelegate>
63 #endif
64 {
65         GHOST_SystemCocoa *systemCocoa;
66         GHOST_WindowCocoa *associatedWindow;
67 }
68
69 - (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa;
70 - (void)windowWillClose:(NSNotification *)notification;
71 - (void)windowDidBecomeKey:(NSNotification *)notification;
72 - (void)windowDidResignKey:(NSNotification *)notification;
73 - (void)windowDidExpose:(NSNotification *)notification;
74 - (void)windowDidResize:(NSNotification *)notification;
75 - (void)windowDidMove:(NSNotification *)notification;
76 - (void)windowWillMove:(NSNotification *)notification;
77 @end
78
79 @implementation CocoaWindowDelegate : NSObject
80 - (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
81 {
82         systemCocoa = sysCocoa;
83         associatedWindow = winCocoa;
84 }
85
86 - (void)windowWillClose:(NSNotification *)notification
87 {
88         systemCocoa->handleWindowEvent(GHOST_kEventWindowClose, associatedWindow);
89 }
90
91 - (void)windowDidBecomeKey:(NSNotification *)notification
92 {
93         systemCocoa->handleWindowEvent(GHOST_kEventWindowActivate, associatedWindow);
94 }
95
96 - (void)windowDidResignKey:(NSNotification *)notification
97 {
98         systemCocoa->handleWindowEvent(GHOST_kEventWindowDeactivate, associatedWindow);
99 }
100
101 - (void)windowDidExpose:(NSNotification *)notification
102 {
103         systemCocoa->handleWindowEvent(GHOST_kEventWindowUpdate, associatedWindow);
104 }
105
106 - (void)windowDidMove:(NSNotification *)notification
107 {
108         systemCocoa->handleWindowEvent(GHOST_kEventWindowMove, associatedWindow);
109 }
110
111 - (void)windowWillMove:(NSNotification *)notification
112 {
113         systemCocoa->handleWindowEvent(GHOST_kEventWindowMove, associatedWindow);
114 }
115
116 - (void)windowDidResize:(NSNotification *)notification
117 {
118 #ifdef MAC_OS_X_VERSION_10_6
119         //if (![[notification object] inLiveResize]) {
120                 //Send event only once, at end of resize operation (when user has released mouse button)
121 #endif
122                 systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, associatedWindow);
123 #ifdef MAC_OS_X_VERSION_10_6
124         //}
125 #endif
126         /* Live resize ugly patch. Needed because live resize runs in a modal loop, not letting main loop run
127          if ([[notification object] inLiveResize]) {
128                 systemCocoa->dispatchEvents();
129                 wm_window_timer(ghostC);
130                 wm_event_do_handlers(ghostC);
131                 wm_event_do_notifiers(ghostC);
132                 wm_draw_update(ghostC);
133         }*/
134 }
135 @end
136
137 #pragma mark NSWindow subclass
138 //We need to subclass it to tell that even borderless (fullscreen), it can become key (receive user events)
139 @interface CocoaWindow: NSWindow
140 {
141         GHOST_SystemCocoa *systemCocoa;
142         GHOST_WindowCocoa *associatedWindow;
143         GHOST_TDragnDropTypes m_draggedObjectType;
144 }
145 - (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa;
146 @end
147 @implementation CocoaWindow
148 - (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
149 {
150         systemCocoa = sysCocoa;
151         associatedWindow = winCocoa;
152 }
153
154 -(BOOL)canBecomeKeyWindow
155 {
156         return YES;
157 }
158
159 //The drag'n'drop dragging destination methods
160 - (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
161 {
162         NSPoint mouseLocation = [sender draggingLocation];
163         NSPasteboard *draggingPBoard = [sender draggingPasteboard];
164         
165         if ([[draggingPBoard types] containsObject:NSTIFFPboardType]) m_draggedObjectType = GHOST_kDragnDropTypeBitmap;
166         else if ([[draggingPBoard types] containsObject:NSFilenamesPboardType]) m_draggedObjectType = GHOST_kDragnDropTypeFilenames;
167         else if ([[draggingPBoard types] containsObject:NSStringPboardType]) m_draggedObjectType = GHOST_kDragnDropTypeString;
168         else return NSDragOperationNone;
169         
170         associatedWindow->setAcceptDragOperation(FALSE); //Drag operation needs to be accepted explicitly by the event manager
171         systemCocoa->handleDraggingEvent(GHOST_kEventDraggingEntered, m_draggedObjectType, associatedWindow, mouseLocation.x, mouseLocation.y, nil);
172         return NSDragOperationCopy;
173 }
174
175 - (BOOL)wantsPeriodicDraggingUpdates
176 {
177         return NO; //No need to overflow blender event queue. Events shall be sent only on changes
178 }
179
180 - (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
181 {
182         NSPoint mouseLocation = [sender draggingLocation];
183         
184         systemCocoa->handleDraggingEvent(GHOST_kEventDraggingUpdated, m_draggedObjectType, associatedWindow, mouseLocation.x, mouseLocation.y, nil);
185         return associatedWindow->canAcceptDragOperation()?NSDragOperationCopy:NSDragOperationNone;
186 }
187
188 - (void)draggingExited:(id < NSDraggingInfo >)sender
189 {
190         systemCocoa->handleDraggingEvent(GHOST_kEventDraggingExited, m_draggedObjectType, associatedWindow, 0, 0, nil);
191         m_draggedObjectType = GHOST_kDragnDropTypeUnknown;
192 }
193
194 - (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender
195 {
196         if (associatedWindow->canAcceptDragOperation())
197                 return YES;
198         else
199                 return NO;
200 }
201
202 - (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
203 {
204         NSPoint mouseLocation = [sender draggingLocation];
205         NSPasteboard *draggingPBoard = [sender draggingPasteboard];
206         NSImage *droppedImg;
207         id data;
208         
209         switch (m_draggedObjectType) {
210                 case GHOST_kDragnDropTypeBitmap:
211                         if([NSImage canInitWithPasteboard:draggingPBoard]) {
212                                 droppedImg = [[NSImage alloc]initWithPasteboard:draggingPBoard];
213                                 data = droppedImg; //[draggingPBoard dataForType:NSTIFFPboardType];
214                         }
215                         else return NO;
216                         break;
217                 case GHOST_kDragnDropTypeFilenames:
218                         data = [draggingPBoard propertyListForType:NSFilenamesPboardType];
219                         break;
220                 case GHOST_kDragnDropTypeString:
221                         data = [draggingPBoard stringForType:NSStringPboardType];
222                         break;
223                 default:
224                         return NO;
225                         break;
226         }
227         systemCocoa->handleDraggingEvent(GHOST_kEventDraggingDropDone, m_draggedObjectType, associatedWindow, mouseLocation.x, mouseLocation.y, (void*)data);
228         return YES;
229 }
230
231 @end
232
233
234
235 #pragma mark NSOpenGLView subclass
236 //We need to subclass it in order to give Cocoa the feeling key events are trapped
237 @interface CocoaOpenGLView : NSOpenGLView
238 {
239 }
240 @end
241 @implementation CocoaOpenGLView
242
243 - (BOOL)acceptsFirstResponder
244 {
245     return YES;
246 }
247
248 //The trick to prevent Cocoa from complaining (beeping)
249 - (void)keyDown:(NSEvent *)theEvent
250 {}
251
252 #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
253 //Cmd+key are handled differently before 10.5
254 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
255 {
256         NSString *chars = [theEvent charactersIgnoringModifiers];
257         
258         if ([chars length] <1) 
259                 return NO;
260         
261         //Let cocoa handle menu shortcuts
262         switch ([chars characterAtIndex:0]) {
263                 case 'q':
264                 case 'w':
265                 case 'h':
266                 case 'm':
267                 case '<':
268                 case '>':
269                 case '~':
270                 case '`':
271                         return NO;
272                 default:
273                         return YES;
274         }
275 }
276 #endif
277
278 - (BOOL)isOpaque
279 {
280     return YES;
281 }
282
283 @end
284
285
286 #pragma mark initialization / finalization
287
288 NSOpenGLContext* GHOST_WindowCocoa::s_firstOpenGLcontext = nil;
289
290 GHOST_WindowCocoa::GHOST_WindowCocoa(
291         GHOST_SystemCocoa *systemCocoa,
292         const STR_String& title,
293         GHOST_TInt32 left,
294         GHOST_TInt32 top,
295         GHOST_TUns32 width,
296         GHOST_TUns32 height,
297         GHOST_TWindowState state,
298         GHOST_TDrawingContextType type,
299         const bool stereoVisual, const GHOST_TUns16 numOfAASamples
300 ) :
301         GHOST_Window(title, left, top, width, height, state, GHOST_kDrawingContextTypeNone, stereoVisual, numOfAASamples),
302         m_customCursor(0)
303 {
304         NSOpenGLPixelFormatAttribute pixelFormatAttrsWindow[40];
305         NSOpenGLPixelFormat *pixelFormat = nil;
306         int i;
307                 
308         m_systemCocoa = systemCocoa;
309         m_fullScreen = false;
310         
311         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
312         
313
314         //Creates the window
315         NSRect rect;
316         NSSize  minSize;
317         
318         rect.origin.x = left;
319         rect.origin.y = top;
320         rect.size.width = width;
321         rect.size.height = height;
322         
323         m_window = [[CocoaWindow alloc] initWithContentRect:rect
324                                                                                    styleMask:NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask
325                                                                                          backing:NSBackingStoreBuffered defer:NO];
326         if (m_window == nil) {
327                 [pool drain];
328                 return;
329         }
330         
331         [m_window setSystemAndWindowCocoa:systemCocoa windowCocoa:this];
332         
333         //Forbid to resize the window below the blender defined minimum one
334         minSize.width = 320;
335         minSize.height = 240;
336         [m_window setContentMinSize:minSize];
337         
338         setTitle(title);
339         
340         
341         // Pixel Format Attributes for the windowed NSOpenGLContext
342         i=0;
343         pixelFormatAttrsWindow[i++] = NSOpenGLPFADoubleBuffer;
344         
345         // Guarantees the back buffer contents to be valid after a call to NSOpenGLContext object’s flushBuffer
346         // needed for 'Draw Overlap' drawing method
347         pixelFormatAttrsWindow[i++] = NSOpenGLPFABackingStore; 
348         
349         pixelFormatAttrsWindow[i++] = NSOpenGLPFAAccelerated;
350         //pixelFormatAttrsWindow[i++] = NSOpenGLPFAAllowOfflineRenderers,;   // Removed to allow 10.4 builds, and 2 GPUs rendering is not used anyway
351         
352         pixelFormatAttrsWindow[i++] = NSOpenGLPFADepthSize;
353         pixelFormatAttrsWindow[i++] = (NSOpenGLPixelFormatAttribute) 32;
354         
355         if (stereoVisual) pixelFormatAttrsWindow[i++] = NSOpenGLPFAStereo;
356         
357         if (numOfAASamples>0) {
358                 // Multisample anti-aliasing
359                 pixelFormatAttrsWindow[i++] = NSOpenGLPFAMultisample;
360                 
361                 pixelFormatAttrsWindow[i++] = NSOpenGLPFASampleBuffers;
362                 pixelFormatAttrsWindow[i++] = (NSOpenGLPixelFormatAttribute) 1;
363                 
364                 pixelFormatAttrsWindow[i++] = NSOpenGLPFASamples;
365                 pixelFormatAttrsWindow[i++] = (NSOpenGLPixelFormatAttribute) numOfAASamples;
366                 
367                 pixelFormatAttrsWindow[i++] = NSOpenGLPFANoRecovery;
368         }
369         
370         pixelFormatAttrsWindow[i] = (NSOpenGLPixelFormatAttribute) 0;
371         
372         pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttrsWindow];
373         
374         
375         //Fall back to no multisampling if Antialiasing init failed
376         if (pixelFormat == nil) {
377                 i=0;
378                 pixelFormatAttrsWindow[i++] = NSOpenGLPFADoubleBuffer;
379                 
380                 // Guarantees the back buffer contents to be valid after a call to NSOpenGLContext object’s flushBuffer
381                 // needed for 'Draw Overlap' drawing method
382                 pixelFormatAttrsWindow[i++] = NSOpenGLPFABackingStore;
383                 
384                 pixelFormatAttrsWindow[i++] = NSOpenGLPFAAccelerated;
385                 //pixelFormatAttrsWindow[i++] = NSOpenGLPFAAllowOfflineRenderers,;   // Removed to allow 10.4 builds, and 2 GPUs rendering is not used anyway
386                 
387                 pixelFormatAttrsWindow[i++] = NSOpenGLPFADepthSize;
388                 pixelFormatAttrsWindow[i++] = (NSOpenGLPixelFormatAttribute) 32;
389                 
390                 if (stereoVisual) pixelFormatAttrsWindow[i++] = NSOpenGLPFAStereo;
391                 
392                 pixelFormatAttrsWindow[i] = (NSOpenGLPixelFormatAttribute) 0;
393                 
394                 pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttrsWindow];
395                 
396         }
397         
398         if (numOfAASamples>0) { //Set m_numOfAASamples to the actual value
399                 GLint gli;
400                 [pixelFormat getValues:&gli forAttribute:NSOpenGLPFASamples forVirtualScreen:0];
401                 if (m_numOfAASamples != (GHOST_TUns16)gli) {
402                         m_numOfAASamples = (GHOST_TUns16)gli;
403                         printf("GHOST_Window could be created with anti-aliasing of only %i samples\n",m_numOfAASamples);
404                 }
405         }
406                 
407         //Creates the OpenGL View inside the window
408         m_openGLView = [[CocoaOpenGLView alloc] initWithFrame:rect
409                                                                                                  pixelFormat:pixelFormat];
410         
411         [pixelFormat release];
412         
413         m_openGLContext = [m_openGLView openGLContext]; //This context will be replaced by the proper one just after
414         
415         [m_window setContentView:m_openGLView];
416         [m_window setInitialFirstResponder:m_openGLView];
417         
418         [m_window setReleasedWhenClosed:NO]; //To avoid bad pointer exception in case of user closing the window
419         
420         [m_window makeKeyAndOrderFront:nil];
421         
422         setDrawingContextType(type);
423         updateDrawingContext();
424         activateDrawingContext();
425         
426         m_tablet.Active = GHOST_kTabletModeNone;
427         
428         CocoaWindowDelegate *windowDelegate = [[CocoaWindowDelegate alloc] init];
429         [windowDelegate setSystemAndWindowCocoa:systemCocoa windowCocoa:this];
430         [m_window setDelegate:windowDelegate];
431         
432         [m_window setAcceptsMouseMovedEvents:YES];
433         
434         [m_window registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType,
435                                                                                   NSStringPboardType, NSTIFFPboardType, nil]];
436                                                                                   
437         if (state == GHOST_kWindowStateFullScreen)
438                 setState(GHOST_kWindowStateFullScreen);
439                 
440         [pool drain];
441 }
442
443
444 GHOST_WindowCocoa::~GHOST_WindowCocoa()
445 {
446         if (m_customCursor) delete m_customCursor;
447
448     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
449         [m_openGLView release];
450         
451         if (m_window) {
452                 [m_window close];
453                 [[m_window delegate] release];
454                 [m_window release];
455                 m_window = nil;
456         }
457         
458         //Check for other blender opened windows and make the frontmost key
459         NSArray *windowsList = [NSApp orderedWindows];
460         if ([windowsList count]) {
461                 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
462         }
463         [pool drain];
464 }
465
466 #pragma mark accessors
467
468 bool GHOST_WindowCocoa::getValid() const
469 {
470         return (m_window != 0);
471 }
472
473 void* GHOST_WindowCocoa::getOSWindow() const
474 {
475         return (void*)m_window;
476 }
477
478 void GHOST_WindowCocoa::setTitle(const STR_String& title)
479 {
480     GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setTitle(): window invalid")
481         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
482
483         NSString *windowTitle = [[NSString alloc] initWithUTF8String:title];
484         
485         //Set associated file if applicable
486         if ([windowTitle hasPrefix:@"Blender"])
487         {
488                 NSRange fileStrRange;
489                 NSString *associatedFileName;
490                 int len;
491                 
492                 fileStrRange.location = [windowTitle rangeOfString:@"["].location+1;
493                 len = [windowTitle rangeOfString:@"]"].location - fileStrRange.location;
494         
495                 if (len >0)
496                 {
497                         fileStrRange.length = len;
498                         associatedFileName = [windowTitle substringWithRange:fileStrRange];
499                         @try {
500                                 [m_window setRepresentedFilename:associatedFileName];
501                         }
502                         @catch (NSException * e) {
503                                 printf("\nInvalid file path given in window title");
504                         }
505                         [m_window setTitle:[associatedFileName lastPathComponent]];
506                 }
507                 else {
508                         [m_window setTitle:windowTitle];
509                         [m_window setRepresentedFilename:@""];
510                 }
511
512         } else {
513                 [m_window setTitle:windowTitle];
514                 [m_window setRepresentedFilename:@""];
515         }
516
517         
518         [windowTitle release];
519         [pool drain];
520 }
521
522
523 void GHOST_WindowCocoa::getTitle(STR_String& title) const
524 {
525     GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getTitle(): window invalid")
526
527         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
528
529         NSString *windowTitle = [m_window title];
530
531         if (windowTitle != nil) {
532                 title = [windowTitle UTF8String];               
533         }
534         
535         [pool drain];
536 }
537
538
539 void GHOST_WindowCocoa::getWindowBounds(GHOST_Rect& bounds) const
540 {
541         NSRect rect;
542         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getWindowBounds(): window invalid")
543
544         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
545         
546         NSRect screenSize = [[m_window screen] visibleFrame];
547
548         rect = [m_window frame];
549
550         bounds.m_b = screenSize.size.height - (rect.origin.y -screenSize.origin.y);
551         bounds.m_l = rect.origin.x -screenSize.origin.x;
552         bounds.m_r = rect.origin.x-screenSize.origin.x + rect.size.width;
553         bounds.m_t = screenSize.size.height - (rect.origin.y + rect.size.height -screenSize.origin.y);
554         
555         [pool drain];
556 }
557
558
559 void GHOST_WindowCocoa::getClientBounds(GHOST_Rect& bounds) const
560 {
561         NSRect rect;
562         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getClientBounds(): window invalid")
563         
564         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
565         
566         if (!m_fullScreen)
567         {
568                 NSRect screenSize = [[m_window screen] visibleFrame];
569
570                 //Max window contents as screen size (excluding title bar...)
571                 NSRect contentRect = [CocoaWindow contentRectForFrameRect:screenSize
572                                                                                                          styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)];
573
574                 rect = [m_window contentRectForFrameRect:[m_window frame]];
575                 
576                 bounds.m_b = contentRect.size.height - (rect.origin.y -contentRect.origin.y);
577                 bounds.m_l = rect.origin.x -contentRect.origin.x;
578                 bounds.m_r = rect.origin.x-contentRect.origin.x + rect.size.width;
579                 bounds.m_t = contentRect.size.height - (rect.origin.y + rect.size.height -contentRect.origin.y);
580         }
581         else {
582                 NSRect screenSize = [[m_window screen] frame];
583                 
584                 bounds.m_b = screenSize.origin.y + screenSize.size.height;
585                 bounds.m_l = screenSize.origin.x;
586                 bounds.m_r = screenSize.origin.x + screenSize.size.width;
587                 bounds.m_t = screenSize.origin.y;
588         }
589         [pool drain];
590 }
591
592
593 GHOST_TSuccess GHOST_WindowCocoa::setClientWidth(GHOST_TUns32 width)
594 {
595         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientWidth(): window invalid")
596         GHOST_Rect cBnds, wBnds;
597         getClientBounds(cBnds);
598         if (((GHOST_TUns32)cBnds.getWidth()) != width) {
599                 NSSize size;
600                 size.width=width;
601                 size.height=cBnds.getHeight();
602                 [m_window setContentSize:size];
603         }
604         return GHOST_kSuccess;
605 }
606
607
608 GHOST_TSuccess GHOST_WindowCocoa::setClientHeight(GHOST_TUns32 height)
609 {
610         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientHeight(): window invalid")
611         GHOST_Rect cBnds, wBnds;
612         getClientBounds(cBnds);
613         if (((GHOST_TUns32)cBnds.getHeight()) != height) {
614                 NSSize size;
615                 size.width=cBnds.getWidth();
616                 size.height=height;
617                 [m_window setContentSize:size];
618         }
619         return GHOST_kSuccess;
620 }
621
622
623 GHOST_TSuccess GHOST_WindowCocoa::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
624 {
625         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientSize(): window invalid")
626         GHOST_Rect cBnds, wBnds;
627         getClientBounds(cBnds);
628         if ((((GHOST_TUns32)cBnds.getWidth()) != width) ||
629             (((GHOST_TUns32)cBnds.getHeight()) != height)) {
630                 NSSize size;
631                 size.width=width;
632                 size.height=height;
633                 [m_window setContentSize:size];
634         }
635         return GHOST_kSuccess;
636 }
637
638
639 GHOST_TWindowState GHOST_WindowCocoa::getState() const
640 {
641         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid")
642         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
643         GHOST_TWindowState state;
644         if (m_fullScreen) {
645                 state = GHOST_kWindowStateFullScreen;
646         } 
647         else if ([m_window isMiniaturized]) {
648                 state = GHOST_kWindowStateMinimized;
649         }
650         else if ([m_window isZoomed]) {
651                 state = GHOST_kWindowStateMaximized;
652         }
653         else {
654                 state = GHOST_kWindowStateNormal;
655         }
656         [pool drain];
657         return state;
658 }
659
660
661 void GHOST_WindowCocoa::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
662 {
663         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid")
664         
665         NSPoint screenCoord;
666         NSPoint baseCoord;
667         
668         screenCoord.x = inX;
669         screenCoord.y = inY;
670         
671         baseCoord = [m_window convertScreenToBase:screenCoord];
672         
673         outX = baseCoord.x;
674         outY = baseCoord.y;
675 }
676
677
678 void GHOST_WindowCocoa::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
679 {
680         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::clientToScreen(): window invalid")
681         
682         NSPoint screenCoord;
683         NSPoint baseCoord;
684         
685         baseCoord.x = inX;
686         baseCoord.y = inY;
687         
688         screenCoord = [m_window convertBaseToScreen:baseCoord];
689         
690         outX = screenCoord.x;
691         outY = screenCoord.y;
692 }
693
694
695 NSScreen* GHOST_WindowCocoa::getScreen()
696 {
697         return [m_window screen];
698 }
699
700
701 /**
702  * @note Fullscreen switch is not actual fullscreen with display capture. As this capture removes all OS X window manager features.
703  * Instead, the menu bar and the dock are hidden, and the window is made borderless and enlarged.
704  * Thus, process switch, exposé, spaces, ... still work in fullscreen mode
705  */
706 GHOST_TSuccess GHOST_WindowCocoa::setState(GHOST_TWindowState state)
707 {
708         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setState(): window invalid")
709     switch (state) {
710                 case GHOST_kWindowStateMinimized:
711             [m_window miniaturize:nil];
712             break;
713                 case GHOST_kWindowStateMaximized:
714                         [m_window zoom:nil];
715                         break;
716                 
717                 case GHOST_kWindowStateFullScreen:
718                         if (!m_fullScreen)
719                         {
720                                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
721                         
722                                 //This status change needs to be done before Cocoa call to enter fullscreen mode
723                                 //to give window delegate hint not to forward its deactivation to ghost wm that doesn't know view/window difference
724                                 m_fullScreen = true;
725
726 #ifdef MAC_OS_X_VERSION_10_6
727                                 //10.6 provides Cocoa functions to autoshow menu bar, and to change a window style
728                                 //Hide menu & dock if needed
729                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
730                                 {
731                                         [NSApp setPresentationOptions:(NSApplicationPresentationHideDock | NSApplicationPresentationAutoHideMenuBar)];
732                                 }
733                                 //Make window borderless and enlarge it
734                                 [m_window setStyleMask:NSBorderlessWindowMask];
735                                 [m_window setFrame:[[m_window screen] frame] display:YES];
736                                 [m_window makeFirstResponder:m_openGLView];
737 #else
738                                 //With 10.5, we need to create a new window to change its style to borderless
739                                 //Hide menu & dock if needed
740                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
741                                 {
742                                         //Cocoa function in 10.5 does not allow to set the menu bar in auto-show mode [NSMenu setMenuBarVisible:NO];
743                                         //One of the very few 64bit compatible Carbon function
744                                         SetSystemUIMode(kUIModeAllHidden,kUIOptionAutoShowMenuBar);
745                                 }
746                                 //Create a fullscreen borderless window
747                                 CocoaWindow *tmpWindow = [[CocoaWindow alloc]
748                                                                                   initWithContentRect:[[m_window screen] frame]
749                                                                                   styleMask:NSBorderlessWindowMask
750                                                                                   backing:NSBackingStoreBuffered
751                                                                                   defer:YES];
752                                 //Copy current window parameters
753                                 [tmpWindow setTitle:[m_window title]];
754                                 [tmpWindow setRepresentedFilename:[m_window representedFilename]];
755                                 [tmpWindow setReleasedWhenClosed:NO];
756                                 [tmpWindow setAcceptsMouseMovedEvents:YES];
757                                 [tmpWindow setDelegate:[m_window delegate]];
758                                 
759                                 //Assign the openGL view to the new window
760                                 [tmpWindow setContentView:m_openGLView];
761                                 
762                                 //Show the new window
763                                 [tmpWindow makeKeyAndOrderFront:nil];
764                                 //Close and release old window
765                                 [m_window setDelegate:nil]; // To avoid the notification of "window closed" event
766                                 [m_window close];
767                                 [m_window release];
768                                 m_window = tmpWindow;
769 #endif
770                         
771                                 //Tell WM of view new size
772                                 m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, this);
773                                 
774                                 [pool drain];
775                                 }
776                         break;
777                 case GHOST_kWindowStateNormal:
778         default:
779                         if (m_fullScreen)
780                         {
781                                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
782                                 m_fullScreen = false;
783
784                                 //Exit fullscreen
785 #ifdef MAC_OS_X_VERSION_10_6
786                                 //Show again menu & dock if needed
787                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
788                                 {
789                                         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
790                                 }
791                                 //Make window normal and resize it
792                                 [m_window setStyleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)];
793                                 [m_window setFrame:[[m_window screen] visibleFrame] display:YES];
794                                 //TODO for 10.6 only : window title is forgotten after the style change
795                                 [m_window makeFirstResponder:m_openGLView];
796 #else
797                                 //With 10.5, we need to create a new window to change its style to borderless
798                                 //Show menu & dock if needed
799                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
800                                 {
801                                         //Cocoa function in 10.5 does not allow to set the menu bar in auto-show mode [NSMenu setMenuBarVisible:YES];
802                                         SetSystemUIMode(kUIModeNormal, 0); //One of the very few 64bit compatible Carbon function
803                                 }
804                                 //Create a fullscreen borderless window
805                                 CocoaWindow *tmpWindow = [[CocoaWindow alloc]
806                                                                                   initWithContentRect:[[m_window screen] frame]
807                                                                                                         styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)
808                                                                                                           backing:NSBackingStoreBuffered
809                                                                                                                 defer:YES];
810                                 //Copy current window parameters
811                                 [tmpWindow setTitle:[m_window title]];
812                                 [tmpWindow setRepresentedFilename:[m_window representedFilename]];
813                                 [tmpWindow setReleasedWhenClosed:NO];
814                                 [tmpWindow setAcceptsMouseMovedEvents:YES];
815                                 [tmpWindow setDelegate:[m_window delegate]];
816                                 
817                                 //Assign the openGL view to the new window
818                                 [tmpWindow setContentView:m_openGLView];
819                                 
820                                 //Show the new window
821                                 [tmpWindow makeKeyAndOrderFront:nil];
822                                 //Close and release old window
823                                 [m_window setDelegate:nil]; // To avoid the notification of "window closed" event
824                                 [m_window close];
825                                 [m_window release];
826                                 m_window = tmpWindow;
827 #endif
828                         
829                                 //Tell WM of view new size
830                                 m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, this);
831                                 
832                                 [pool drain];
833                         }
834             else if ([m_window isMiniaturized])
835                                 [m_window deminiaturize:nil];
836                         else if ([m_window isZoomed])
837                                 [m_window zoom:nil];
838             break;
839     }
840     return GHOST_kSuccess;
841 }
842
843 GHOST_TSuccess GHOST_WindowCocoa::setModifiedState(bool isUnsavedChanges)
844 {
845         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
846         
847         [m_window setDocumentEdited:isUnsavedChanges];
848         
849         [pool drain];
850         return GHOST_Window::setModifiedState(isUnsavedChanges);
851 }
852
853
854
855 GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order)
856 {
857         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
858         
859         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid")
860     if (order == GHOST_kWindowOrderTop) {
861                 [m_window makeKeyAndOrderFront:nil];
862     }
863     else {
864                 NSArray *windowsList;
865                 
866                 [m_window orderBack:nil];
867                 
868                 //Check for other blender opened windows and make the frontmost key
869                 windowsList = [NSApp orderedWindows];
870                 if ([windowsList count]) {
871                         [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
872                 }
873     }
874         
875         [pool drain];
876     return GHOST_kSuccess;
877 }
878
879 #pragma mark Drawing context
880
881 /*#define  WAIT_FOR_VSYNC 1*/
882
883 GHOST_TSuccess GHOST_WindowCocoa::swapBuffers()
884 {
885     if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
886         if (m_openGLContext != nil) {
887                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
888                         [m_openGLContext flushBuffer];
889                         [pool drain];
890             return GHOST_kSuccess;
891         }
892     }
893     return GHOST_kFailure;
894 }
895
896 GHOST_TSuccess GHOST_WindowCocoa::updateDrawingContext()
897 {
898         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
899                 if (m_openGLContext != nil) {
900                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
901                         [m_openGLContext update];
902                         [pool drain];
903                         return GHOST_kSuccess;
904                 }
905         }
906         return GHOST_kFailure;
907 }
908
909 GHOST_TSuccess GHOST_WindowCocoa::activateDrawingContext()
910 {
911         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
912                 if (m_openGLContext != nil) {
913                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
914                         [m_openGLContext makeCurrentContext];
915                         
916                         // Disable AA by default
917                         if (m_numOfAASamples > 0) glDisable(GL_MULTISAMPLE_ARB);
918                         [pool drain];
919                         return GHOST_kSuccess;
920                 }
921         }
922         return GHOST_kFailure;
923 }
924
925
926 GHOST_TSuccess GHOST_WindowCocoa::installDrawingContext(GHOST_TDrawingContextType type)
927 {
928         GHOST_TSuccess success = GHOST_kFailure;
929         
930         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
931         
932         NSOpenGLPixelFormat *pixelFormat;
933         NSOpenGLContext *tmpOpenGLContext;
934         
935         /***** Multithreaded opengl code : uncomment for enabling
936         CGLContextObj cglCtx;
937         */
938          
939         switch (type) {
940                 case GHOST_kDrawingContextTypeOpenGL:
941                         if (!getValid()) break;
942                                         
943                         pixelFormat = [m_openGLView pixelFormat];
944                         tmpOpenGLContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat
945                                                                                                                           shareContext:s_firstOpenGLcontext];
946                         if (tmpOpenGLContext == nil) {
947                                 success = GHOST_kFailure;
948                                 break;
949                         }
950                         
951                         //Switch openGL to multhreaded mode
952                         /******* Multithreaded opengl code : uncomment for enabling
953                         cglCtx = (CGLContextObj)[tmpOpenGLContext CGLContextObj];
954                         if (CGLEnable(cglCtx, kCGLCEMPEngine) == kCGLNoError)
955                                 printf("\nSwitched openGL to multithreaded mode");
956                          */
957                         
958                         if (!s_firstOpenGLcontext) s_firstOpenGLcontext = tmpOpenGLContext;
959 #ifdef WAIT_FOR_VSYNC
960                         {
961                                 GLint swapInt = 1;
962                                 /* wait for vsync, to avoid tearing artifacts */
963                                 [tmpOpenGLContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
964                         }
965 #endif
966                         [m_openGLView setOpenGLContext:tmpOpenGLContext];
967                         [tmpOpenGLContext setView:m_openGLView];
968                         
969                         m_openGLContext = tmpOpenGLContext;
970                         break;
971         
972                 case GHOST_kDrawingContextTypeNone:
973                         success = GHOST_kSuccess;
974                         break;
975                 
976                 default:
977                         break;
978         }
979         [pool drain];
980         return success;
981 }
982
983
984 GHOST_TSuccess GHOST_WindowCocoa::removeDrawingContext()
985 {
986         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
987         switch (m_drawingContextType) {
988                 case GHOST_kDrawingContextTypeOpenGL:
989                         if (m_openGLContext)
990                         {
991                                 [m_openGLView clearGLContext];
992                                 if (s_firstOpenGLcontext == m_openGLContext) s_firstOpenGLcontext = nil;
993                                 m_openGLContext = nil;
994                         }
995                         [pool drain];
996                         return GHOST_kSuccess;
997                 case GHOST_kDrawingContextTypeNone:
998                         [pool drain];
999                         return GHOST_kSuccess;
1000                         break;
1001                 default:
1002                         [pool drain];
1003                         return GHOST_kFailure;
1004         }
1005 }
1006
1007
1008 GHOST_TSuccess GHOST_WindowCocoa::invalidate()
1009 {
1010         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid")
1011         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1012         [m_openGLView setNeedsDisplay:YES];
1013         [pool drain];
1014         return GHOST_kSuccess;
1015 }
1016
1017 #pragma mark Cursor handling
1018
1019 void GHOST_WindowCocoa::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
1020 {
1021         static bool systemCursorVisible = true;
1022         
1023         NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
1024
1025         NSCursor *tmpCursor =nil;
1026         
1027         if (visible != systemCursorVisible) {
1028                 if (visible) {
1029                         [NSCursor unhide];
1030                         systemCursorVisible = true;
1031                 }
1032                 else {
1033                         [NSCursor hide];
1034                         systemCursorVisible = false;
1035                 }
1036         }
1037
1038         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
1039                 tmpCursor = m_customCursor;
1040         } else {
1041                 switch (cursor) {
1042                         case GHOST_kStandardCursorDestroy:
1043                                 tmpCursor = [NSCursor disappearingItemCursor];
1044                                 break;
1045                         case GHOST_kStandardCursorText:
1046                                 tmpCursor = [NSCursor IBeamCursor];
1047                                 break;
1048                         case GHOST_kStandardCursorCrosshair:
1049                                 tmpCursor = [NSCursor crosshairCursor];
1050                                 break;
1051                         case GHOST_kStandardCursorUpDown:
1052                                 tmpCursor = [NSCursor resizeUpDownCursor];
1053                                 break;
1054                         case GHOST_kStandardCursorLeftRight:
1055                                 tmpCursor = [NSCursor resizeLeftRightCursor];
1056                                 break;
1057                         case GHOST_kStandardCursorTopSide:
1058                                 tmpCursor = [NSCursor resizeUpCursor];
1059                                 break;
1060                         case GHOST_kStandardCursorBottomSide:
1061                                 tmpCursor = [NSCursor resizeDownCursor];
1062                                 break;
1063                         case GHOST_kStandardCursorLeftSide:
1064                                 tmpCursor = [NSCursor resizeLeftCursor];
1065                                 break;
1066                         case GHOST_kStandardCursorRightSide:
1067                                 tmpCursor = [NSCursor resizeRightCursor];
1068                                 break;
1069                         case GHOST_kStandardCursorRightArrow:
1070                         case GHOST_kStandardCursorInfo:
1071                         case GHOST_kStandardCursorLeftArrow:
1072                         case GHOST_kStandardCursorHelp:
1073                         case GHOST_kStandardCursorCycle:
1074                         case GHOST_kStandardCursorSpray:
1075                         case GHOST_kStandardCursorWait:
1076                         case GHOST_kStandardCursorTopLeftCorner:
1077                         case GHOST_kStandardCursorTopRightCorner:
1078                         case GHOST_kStandardCursorBottomRightCorner:
1079                         case GHOST_kStandardCursorBottomLeftCorner:
1080                         case GHOST_kStandardCursorCopy:
1081                         case GHOST_kStandardCursorDefault:
1082                         default:
1083                                 tmpCursor = [NSCursor arrowCursor];
1084                                 break;
1085                 };
1086         }
1087         [tmpCursor set];
1088         [pool drain];
1089 }
1090
1091
1092
1093 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorVisibility(bool visible)
1094 {
1095         if ([m_window isVisible]) {
1096                 loadCursor(visible, getCursorShape());
1097         }
1098         
1099         return GHOST_kSuccess;
1100 }
1101
1102
1103 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
1104 {
1105         GHOST_TSuccess err = GHOST_kSuccess;
1106         
1107         if (mode != GHOST_kGrabDisable)
1108         {
1109                 //No need to perform grab without warp as it is always on in OS X
1110                 if(mode != GHOST_kGrabNormal) {
1111                         GHOST_TInt32 x_old,y_old;
1112                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1113
1114                         m_systemCocoa->getCursorPosition(x_old,y_old);
1115                         screenToClient(x_old, y_old, m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
1116                         //Warp position is stored in client (window base) coordinates
1117                         setCursorGrabAccum(0, 0);
1118                         
1119                         if(mode == GHOST_kGrabHide) {
1120                                 setWindowCursorVisibility(false);
1121                         }
1122                         
1123                         //Make window key if it wasn't to get the mouse move events
1124                         [m_window makeKeyWindow];
1125                         
1126                         //Dissociate cursor position even for warp mode, to allow mouse acceleration to work even when warping the cursor
1127                         err = CGAssociateMouseAndMouseCursorPosition(false) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1128                         
1129                         [pool drain];
1130                 }
1131         }
1132         else {
1133                 if(m_cursorGrab==GHOST_kGrabHide)
1134                 {
1135                         //No need to set again cursor position, as it has not changed for Cocoa
1136                         setWindowCursorVisibility(true);
1137                 }
1138                 
1139                 err = CGAssociateMouseAndMouseCursorPosition(true) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1140                 /* Almost works without but important otherwise the mouse GHOST location can be incorrect on exit */
1141                 setCursorGrabAccum(0, 0);
1142                 m_cursorGrabBounds.m_l= m_cursorGrabBounds.m_r= -1; /* disable */
1143         }
1144         return err;
1145 }
1146         
1147 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorShape(GHOST_TStandardCursor shape)
1148 {
1149         if (m_customCursor) {
1150                 [m_customCursor release];
1151                 m_customCursor = nil;
1152         }
1153
1154         if ([m_window isVisible]) {
1155                 loadCursor(getCursorVisibility(), shape);
1156         }
1157         
1158         return GHOST_kSuccess;
1159 }
1160
1161 /** Reverse the bits in a GHOST_TUns8
1162 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
1163 {
1164         ch= ((ch>>1)&0x55) | ((ch<<1)&0xAA);
1165         ch= ((ch>>2)&0x33) | ((ch<<2)&0xCC);
1166         ch= ((ch>>4)&0x0F) | ((ch<<4)&0xF0);
1167         return ch;
1168 }
1169 */
1170
1171
1172 /** Reverse the bits in a GHOST_TUns16 */
1173 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
1174 {
1175         shrt= ((shrt>>1)&0x5555) | ((shrt<<1)&0xAAAA);
1176         shrt= ((shrt>>2)&0x3333) | ((shrt<<2)&0xCCCC);
1177         shrt= ((shrt>>4)&0x0F0F) | ((shrt<<4)&0xF0F0);
1178         shrt= ((shrt>>8)&0x00FF) | ((shrt<<8)&0xFF00);
1179         return shrt;
1180 }
1181
1182 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 *bitmap, GHOST_TUns8 *mask,
1183                                         int sizex, int sizey, int hotX, int hotY, int fg_color, int bg_color)
1184 {
1185         int y,nbUns16;
1186         NSPoint hotSpotPoint;
1187         NSBitmapImageRep *cursorImageRep;
1188         NSImage *cursorImage;
1189         NSSize imSize;
1190         GHOST_TUns16 *cursorBitmap;
1191         
1192         
1193         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1194         
1195         if (m_customCursor) {
1196                 [m_customCursor release];
1197                 m_customCursor = nil;
1198         }
1199         
1200
1201         cursorImageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
1202                                                                                                                          pixelsWide:sizex
1203                                                                                                                          pixelsHigh:sizey
1204                                                                                                                   bitsPerSample:1 
1205                                                                                                                 samplesPerPixel:2
1206                                                                                                                            hasAlpha:YES
1207                                                                                                                            isPlanar:YES
1208                                                                                                                  colorSpaceName:NSDeviceWhiteColorSpace
1209                                                                                                                         bytesPerRow:(sizex/8 + (sizex%8 >0 ?1:0))
1210                                                                                                                    bitsPerPixel:1];
1211         
1212         
1213         cursorBitmap = (GHOST_TUns16*)[cursorImageRep bitmapData];
1214         nbUns16 = [cursorImageRep bytesPerPlane]/2;
1215         
1216         for (y=0; y<nbUns16; y++) {
1217 #if !defined(__LITTLE_ENDIAN__)
1218                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y]<<0) | (bitmap[2*y+1]<<8));
1219                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y]<<0) | (mask[2*y+1]<<8));
1220 #else
1221                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y+1]<<0) | (bitmap[2*y]<<8));
1222                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y+1]<<0) | (mask[2*y]<<8));
1223 #endif
1224                 
1225         }
1226         
1227         
1228         imSize.width = sizex;
1229         imSize.height= sizey;
1230         cursorImage = [[NSImage alloc] initWithSize:imSize];
1231         [cursorImage addRepresentation:cursorImageRep];
1232         
1233         hotSpotPoint.x = hotX;
1234         hotSpotPoint.y = hotY;
1235         
1236         //foreground and background color parameter is not handled for now (10.6)
1237         m_customCursor = [[NSCursor alloc] initWithImage:cursorImage
1238                                                                                          hotSpot:hotSpotPoint];
1239         
1240         [cursorImageRep release];
1241         [cursorImage release];
1242         
1243         if ([m_window isVisible]) {
1244                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
1245         }
1246         [pool drain];
1247         return GHOST_kSuccess;
1248 }
1249
1250 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2], 
1251                                                                                                 GHOST_TUns8 mask[16][2], int hotX, int hotY)
1252 {
1253         return setWindowCustomCursorShape((GHOST_TUns8*)bitmap, (GHOST_TUns8*) mask, 16, 16, hotX, hotY, 0, 1);
1254 }