Cocoa/DND : added bitmap data type handling in drag'n'drop operations
[blender.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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 NSDragOperationCopy;
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         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid")
858     if (order == GHOST_kWindowOrderTop) {
859                 [m_window makeKeyAndOrderFront:nil];
860     }
861     else {
862                 NSArray *windowsList;
863                 
864                 [m_window orderBack:nil];
865                 
866                 //Check for other blender opened windows and make the frontmost key
867                 windowsList = [NSApp orderedWindows];
868                 if ([windowsList count]) {
869                         [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
870                 }
871     }
872     return GHOST_kSuccess;
873 }
874
875 #pragma mark Drawing context
876
877 /*#define  WAIT_FOR_VSYNC 1*/
878
879 GHOST_TSuccess GHOST_WindowCocoa::swapBuffers()
880 {
881     if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
882         if (m_openGLContext != nil) {
883                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
884                         [m_openGLContext flushBuffer];
885                         [pool drain];
886             return GHOST_kSuccess;
887         }
888     }
889     return GHOST_kFailure;
890 }
891
892 GHOST_TSuccess GHOST_WindowCocoa::updateDrawingContext()
893 {
894         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
895                 if (m_openGLContext != nil) {
896                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
897                         [m_openGLContext update];
898                         [pool drain];
899                         return GHOST_kSuccess;
900                 }
901         }
902         return GHOST_kFailure;
903 }
904
905 GHOST_TSuccess GHOST_WindowCocoa::activateDrawingContext()
906 {
907         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
908                 if (m_openGLContext != nil) {
909                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
910                         [m_openGLContext makeCurrentContext];
911                         
912                         // Disable AA by default
913                         if (m_numOfAASamples > 0) glDisable(GL_MULTISAMPLE_ARB);
914                         [pool drain];
915                         return GHOST_kSuccess;
916                 }
917         }
918         return GHOST_kFailure;
919 }
920
921
922 GHOST_TSuccess GHOST_WindowCocoa::installDrawingContext(GHOST_TDrawingContextType type)
923 {
924         GHOST_TSuccess success = GHOST_kFailure;
925         
926         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
927         
928         NSOpenGLPixelFormat *pixelFormat;
929         NSOpenGLContext *tmpOpenGLContext;
930         
931         /***** Multithreaded opengl code : uncomment for enabling
932         CGLContextObj cglCtx;
933         */
934          
935         switch (type) {
936                 case GHOST_kDrawingContextTypeOpenGL:
937                         if (!getValid()) break;
938                                         
939                         pixelFormat = [m_openGLView pixelFormat];
940                         tmpOpenGLContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat
941                                                                                                                           shareContext:s_firstOpenGLcontext];
942                         if (tmpOpenGLContext == nil) {
943                                 success = GHOST_kFailure;
944                                 break;
945                         }
946                         
947                         //Switch openGL to multhreaded mode
948                         /******* Multithreaded opengl code : uncomment for enabling
949                         cglCtx = (CGLContextObj)[tmpOpenGLContext CGLContextObj];
950                         if (CGLEnable(cglCtx, kCGLCEMPEngine) == kCGLNoError)
951                                 printf("\nSwitched openGL to multithreaded mode");
952                          */
953                         
954                         if (!s_firstOpenGLcontext) s_firstOpenGLcontext = tmpOpenGLContext;
955 #ifdef WAIT_FOR_VSYNC
956                         {
957                                 GLint swapInt = 1;
958                                 /* wait for vsync, to avoid tearing artifacts */
959                                 [tmpOpenGLContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
960                         }
961 #endif
962                         [m_openGLView setOpenGLContext:tmpOpenGLContext];
963                         [tmpOpenGLContext setView:m_openGLView];
964                         
965                         m_openGLContext = tmpOpenGLContext;
966                         break;
967         
968                 case GHOST_kDrawingContextTypeNone:
969                         success = GHOST_kSuccess;
970                         break;
971                 
972                 default:
973                         break;
974         }
975         [pool drain];
976         return success;
977 }
978
979
980 GHOST_TSuccess GHOST_WindowCocoa::removeDrawingContext()
981 {
982         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
983         switch (m_drawingContextType) {
984                 case GHOST_kDrawingContextTypeOpenGL:
985                         if (m_openGLContext)
986                         {
987                                 [m_openGLView clearGLContext];
988                                 if (s_firstOpenGLcontext == m_openGLContext) s_firstOpenGLcontext = nil;
989                                 m_openGLContext = nil;
990                         }
991                         [pool drain];
992                         return GHOST_kSuccess;
993                 case GHOST_kDrawingContextTypeNone:
994                         [pool drain];
995                         return GHOST_kSuccess;
996                         break;
997                 default:
998                         [pool drain];
999                         return GHOST_kFailure;
1000         }
1001 }
1002
1003
1004 GHOST_TSuccess GHOST_WindowCocoa::invalidate()
1005 {
1006         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid")
1007         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1008         [m_openGLView setNeedsDisplay:YES];
1009         [pool drain];
1010         return GHOST_kSuccess;
1011 }
1012
1013 #pragma mark Cursor handling
1014
1015 void GHOST_WindowCocoa::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
1016 {
1017         static bool systemCursorVisible = true;
1018         
1019         NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
1020
1021         NSCursor *tmpCursor =nil;
1022         
1023         if (visible != systemCursorVisible) {
1024                 if (visible) {
1025                         [NSCursor unhide];
1026                         systemCursorVisible = true;
1027                 }
1028                 else {
1029                         [NSCursor hide];
1030                         systemCursorVisible = false;
1031                 }
1032         }
1033
1034         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
1035                 tmpCursor = m_customCursor;
1036         } else {
1037                 switch (cursor) {
1038                         case GHOST_kStandardCursorDestroy:
1039                                 tmpCursor = [NSCursor disappearingItemCursor];
1040                                 break;
1041                         case GHOST_kStandardCursorText:
1042                                 tmpCursor = [NSCursor IBeamCursor];
1043                                 break;
1044                         case GHOST_kStandardCursorCrosshair:
1045                                 tmpCursor = [NSCursor crosshairCursor];
1046                                 break;
1047                         case GHOST_kStandardCursorUpDown:
1048                                 tmpCursor = [NSCursor resizeUpDownCursor];
1049                                 break;
1050                         case GHOST_kStandardCursorLeftRight:
1051                                 tmpCursor = [NSCursor resizeLeftRightCursor];
1052                                 break;
1053                         case GHOST_kStandardCursorTopSide:
1054                                 tmpCursor = [NSCursor resizeUpCursor];
1055                                 break;
1056                         case GHOST_kStandardCursorBottomSide:
1057                                 tmpCursor = [NSCursor resizeDownCursor];
1058                                 break;
1059                         case GHOST_kStandardCursorLeftSide:
1060                                 tmpCursor = [NSCursor resizeLeftCursor];
1061                                 break;
1062                         case GHOST_kStandardCursorRightSide:
1063                                 tmpCursor = [NSCursor resizeRightCursor];
1064                                 break;
1065                         case GHOST_kStandardCursorRightArrow:
1066                         case GHOST_kStandardCursorInfo:
1067                         case GHOST_kStandardCursorLeftArrow:
1068                         case GHOST_kStandardCursorHelp:
1069                         case GHOST_kStandardCursorCycle:
1070                         case GHOST_kStandardCursorSpray:
1071                         case GHOST_kStandardCursorWait:
1072                         case GHOST_kStandardCursorTopLeftCorner:
1073                         case GHOST_kStandardCursorTopRightCorner:
1074                         case GHOST_kStandardCursorBottomRightCorner:
1075                         case GHOST_kStandardCursorBottomLeftCorner:
1076                         case GHOST_kStandardCursorCopy:
1077                         case GHOST_kStandardCursorDefault:
1078                         default:
1079                                 tmpCursor = [NSCursor arrowCursor];
1080                                 break;
1081                 };
1082         }
1083         [tmpCursor set];
1084         [pool drain];
1085 }
1086
1087
1088
1089 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorVisibility(bool visible)
1090 {
1091         if ([m_window isVisible]) {
1092                 loadCursor(visible, getCursorShape());
1093         }
1094         
1095         return GHOST_kSuccess;
1096 }
1097
1098
1099 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
1100 {
1101         GHOST_TSuccess err = GHOST_kSuccess;
1102         
1103         if (mode != GHOST_kGrabDisable)
1104         {
1105                 //No need to perform grab without warp as it is always on in OS X
1106                 if(mode != GHOST_kGrabNormal) {
1107                         GHOST_TInt32 x_old,y_old;
1108                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1109
1110                         m_systemCocoa->getCursorPosition(x_old,y_old);
1111                         screenToClient(x_old, y_old, m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
1112                         //Warp position is stored in client (window base) coordinates
1113                         setCursorGrabAccum(0, 0);
1114                         
1115                         if(mode == GHOST_kGrabHide) {
1116                                 setWindowCursorVisibility(false);
1117                         }
1118                         
1119                         //Make window key if it wasn't to get the mouse move events
1120                         [m_window makeKeyWindow];
1121                         
1122                         //Dissociate cursor position even for warp mode, to allow mouse acceleration to work even when warping the cursor
1123                         err = CGAssociateMouseAndMouseCursorPosition(false) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1124                         
1125                         [pool drain];
1126                 }
1127         }
1128         else {
1129                 if(m_cursorGrab==GHOST_kGrabHide)
1130                 {
1131                         //No need to set again cursor position, as it has not changed for Cocoa
1132                         setWindowCursorVisibility(true);
1133                 }
1134                 
1135                 err = CGAssociateMouseAndMouseCursorPosition(true) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1136                 /* Almost works without but important otherwise the mouse GHOST location can be incorrect on exit */
1137                 setCursorGrabAccum(0, 0);
1138                 m_cursorGrabBounds.m_l= m_cursorGrabBounds.m_r= -1; /* disable */
1139         }
1140         return err;
1141 }
1142         
1143 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorShape(GHOST_TStandardCursor shape)
1144 {
1145         if (m_customCursor) {
1146                 [m_customCursor release];
1147                 m_customCursor = nil;
1148         }
1149
1150         if ([m_window isVisible]) {
1151                 loadCursor(getCursorVisibility(), shape);
1152         }
1153         
1154         return GHOST_kSuccess;
1155 }
1156
1157 /** Reverse the bits in a GHOST_TUns8
1158 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
1159 {
1160         ch= ((ch>>1)&0x55) | ((ch<<1)&0xAA);
1161         ch= ((ch>>2)&0x33) | ((ch<<2)&0xCC);
1162         ch= ((ch>>4)&0x0F) | ((ch<<4)&0xF0);
1163         return ch;
1164 }
1165 */
1166
1167
1168 /** Reverse the bits in a GHOST_TUns16 */
1169 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
1170 {
1171         shrt= ((shrt>>1)&0x5555) | ((shrt<<1)&0xAAAA);
1172         shrt= ((shrt>>2)&0x3333) | ((shrt<<2)&0xCCCC);
1173         shrt= ((shrt>>4)&0x0F0F) | ((shrt<<4)&0xF0F0);
1174         shrt= ((shrt>>8)&0x00FF) | ((shrt<<8)&0xFF00);
1175         return shrt;
1176 }
1177
1178 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 *bitmap, GHOST_TUns8 *mask,
1179                                         int sizex, int sizey, int hotX, int hotY, int fg_color, int bg_color)
1180 {
1181         int y,nbUns16;
1182         NSPoint hotSpotPoint;
1183         NSBitmapImageRep *cursorImageRep;
1184         NSImage *cursorImage;
1185         NSSize imSize;
1186         GHOST_TUns16 *cursorBitmap;
1187         
1188         
1189         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1190         
1191         if (m_customCursor) {
1192                 [m_customCursor release];
1193                 m_customCursor = nil;
1194         }
1195         
1196
1197         cursorImageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
1198                                                                                                                          pixelsWide:sizex
1199                                                                                                                          pixelsHigh:sizey
1200                                                                                                                   bitsPerSample:1 
1201                                                                                                                 samplesPerPixel:2
1202                                                                                                                            hasAlpha:YES
1203                                                                                                                            isPlanar:YES
1204                                                                                                                  colorSpaceName:NSDeviceWhiteColorSpace
1205                                                                                                                         bytesPerRow:(sizex/8 + (sizex%8 >0 ?1:0))
1206                                                                                                                    bitsPerPixel:1];
1207         
1208         
1209         cursorBitmap = (GHOST_TUns16*)[cursorImageRep bitmapData];
1210         nbUns16 = [cursorImageRep bytesPerPlane]/2;
1211         
1212         for (y=0; y<nbUns16; y++) {
1213 #if !defined(__LITTLE_ENDIAN__)
1214                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y]<<0) | (bitmap[2*y+1]<<8));
1215                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y]<<0) | (mask[2*y+1]<<8));
1216 #else
1217                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y+1]<<0) | (bitmap[2*y]<<8));
1218                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y+1]<<0) | (mask[2*y]<<8));
1219 #endif
1220                 
1221         }
1222         
1223         
1224         imSize.width = sizex;
1225         imSize.height= sizey;
1226         cursorImage = [[NSImage alloc] initWithSize:imSize];
1227         [cursorImage addRepresentation:cursorImageRep];
1228         
1229         hotSpotPoint.x = hotX;
1230         hotSpotPoint.y = hotY;
1231         
1232         //foreground and background color parameter is not handled for now (10.6)
1233         m_customCursor = [[NSCursor alloc] initWithImage:cursorImage
1234                                                                                          hotSpot:hotSpotPoint];
1235         
1236         [cursorImageRep release];
1237         [cursorImage release];
1238         
1239         if ([m_window isVisible]) {
1240                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
1241         }
1242         [pool drain];
1243         return GHOST_kSuccess;
1244 }
1245
1246 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2], 
1247                                                                                                 GHOST_TUns8 mask[16][2], int hotX, int hotY)
1248 {
1249         return setWindowCustomCursorShape((GHOST_TUns8*)bitmap, (GHOST_TUns8*) mask, 16, 16, hotX, hotY, 0, 1);
1250 }