Recreating my GSoC branch.
[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(TRUE); //Drag operation is accepted by default
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         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
597         GHOST_Rect cBnds, wBnds;
598         getClientBounds(cBnds);
599         if (((GHOST_TUns32)cBnds.getWidth()) != width) {
600                 NSSize size;
601                 size.width=width;
602                 size.height=cBnds.getHeight();
603                 [m_window setContentSize:size];
604         }
605         [pool drain];
606         return GHOST_kSuccess;
607 }
608
609
610 GHOST_TSuccess GHOST_WindowCocoa::setClientHeight(GHOST_TUns32 height)
611 {
612         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientHeight(): window invalid")
613         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
614         GHOST_Rect cBnds, wBnds;
615         getClientBounds(cBnds);
616         if (((GHOST_TUns32)cBnds.getHeight()) != height) {
617                 NSSize size;
618                 size.width=cBnds.getWidth();
619                 size.height=height;
620                 [m_window setContentSize:size];
621         }
622         [pool drain];
623         return GHOST_kSuccess;
624 }
625
626
627 GHOST_TSuccess GHOST_WindowCocoa::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
628 {
629         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientSize(): window invalid")
630         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
631         GHOST_Rect cBnds, wBnds;
632         getClientBounds(cBnds);
633         if ((((GHOST_TUns32)cBnds.getWidth()) != width) ||
634             (((GHOST_TUns32)cBnds.getHeight()) != height)) {
635                 NSSize size;
636                 size.width=width;
637                 size.height=height;
638                 [m_window setContentSize:size];
639         }
640         [pool drain];
641         return GHOST_kSuccess;
642 }
643
644
645 GHOST_TWindowState GHOST_WindowCocoa::getState() const
646 {
647         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid")
648         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
649         GHOST_TWindowState state;
650         if (m_fullScreen) {
651                 state = GHOST_kWindowStateFullScreen;
652         } 
653         else if ([m_window isMiniaturized]) {
654                 state = GHOST_kWindowStateMinimized;
655         }
656         else if ([m_window isZoomed]) {
657                 state = GHOST_kWindowStateMaximized;
658         }
659         else {
660                 state = GHOST_kWindowStateNormal;
661         }
662         [pool drain];
663         return state;
664 }
665
666
667 void GHOST_WindowCocoa::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
668 {
669         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid")
670         
671         NSPoint screenCoord;
672         NSPoint baseCoord;
673         
674         screenCoord.x = inX;
675         screenCoord.y = inY;
676         
677         baseCoord = [m_window convertScreenToBase:screenCoord];
678         
679         outX = baseCoord.x;
680         outY = baseCoord.y;
681 }
682
683
684 void GHOST_WindowCocoa::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
685 {
686         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::clientToScreen(): window invalid")
687         
688         NSPoint screenCoord;
689         NSPoint baseCoord;
690         
691         baseCoord.x = inX;
692         baseCoord.y = inY;
693         
694         screenCoord = [m_window convertBaseToScreen:baseCoord];
695         
696         outX = screenCoord.x;
697         outY = screenCoord.y;
698 }
699
700
701 NSScreen* GHOST_WindowCocoa::getScreen()
702 {
703         return [m_window screen];
704 }
705
706
707 /**
708  * @note Fullscreen switch is not actual fullscreen with display capture. As this capture removes all OS X window manager features.
709  * Instead, the menu bar and the dock are hidden, and the window is made borderless and enlarged.
710  * Thus, process switch, exposé, spaces, ... still work in fullscreen mode
711  */
712 GHOST_TSuccess GHOST_WindowCocoa::setState(GHOST_TWindowState state)
713 {
714         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setState(): window invalid")
715     switch (state) {
716                 case GHOST_kWindowStateMinimized:
717             [m_window miniaturize:nil];
718             break;
719                 case GHOST_kWindowStateMaximized:
720                         [m_window zoom:nil];
721                         break;
722                 
723                 case GHOST_kWindowStateFullScreen:
724                         if (!m_fullScreen)
725                         {
726                                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
727                         
728                                 //This status change needs to be done before Cocoa call to enter fullscreen mode
729                                 //to give window delegate hint not to forward its deactivation to ghost wm that doesn't know view/window difference
730                                 m_fullScreen = true;
731
732 #ifdef MAC_OS_X_VERSION_10_6
733                                 //10.6 provides Cocoa functions to autoshow menu bar, and to change a window style
734                                 //Hide menu & dock if needed
735                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
736                                 {
737                                         [NSApp setPresentationOptions:(NSApplicationPresentationHideDock | NSApplicationPresentationAutoHideMenuBar)];
738                                 }
739                                 //Make window borderless and enlarge it
740                                 [m_window setStyleMask:NSBorderlessWindowMask];
741                                 [m_window setFrame:[[m_window screen] frame] display:YES];
742                                 [m_window makeFirstResponder:m_openGLView];
743 #else
744                                 //With 10.5, we need to create a new window to change its style to borderless
745                                 //Hide menu & dock if needed
746                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
747                                 {
748                                         //Cocoa function in 10.5 does not allow to set the menu bar in auto-show mode [NSMenu setMenuBarVisible:NO];
749                                         //One of the very few 64bit compatible Carbon function
750                                         SetSystemUIMode(kUIModeAllHidden,kUIOptionAutoShowMenuBar);
751                                 }
752                                 //Create a fullscreen borderless window
753                                 CocoaWindow *tmpWindow = [[CocoaWindow alloc]
754                                                                                   initWithContentRect:[[m_window screen] frame]
755                                                                                   styleMask:NSBorderlessWindowMask
756                                                                                   backing:NSBackingStoreBuffered
757                                                                                   defer:YES];
758                                 //Copy current window parameters
759                                 [tmpWindow setTitle:[m_window title]];
760                                 [tmpWindow setRepresentedFilename:[m_window representedFilename]];
761                                 [tmpWindow setReleasedWhenClosed:NO];
762                                 [tmpWindow setAcceptsMouseMovedEvents:YES];
763                                 [tmpWindow setDelegate:[m_window delegate]];
764                                 
765                                 //Assign the openGL view to the new window
766                                 [tmpWindow setContentView:m_openGLView];
767                                 
768                                 //Show the new window
769                                 [tmpWindow makeKeyAndOrderFront:nil];
770                                 //Close and release old window
771                                 [m_window setDelegate:nil]; // To avoid the notification of "window closed" event
772                                 [m_window close];
773                                 [m_window release];
774                                 m_window = tmpWindow;
775 #endif
776                         
777                                 //Tell WM of view new size
778                                 m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, this);
779                                 
780                                 [pool drain];
781                                 }
782                         break;
783                 case GHOST_kWindowStateNormal:
784         default:
785                         if (m_fullScreen)
786                         {
787                                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
788                                 m_fullScreen = false;
789
790                                 //Exit fullscreen
791 #ifdef MAC_OS_X_VERSION_10_6
792                                 //Show again menu & dock if needed
793                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
794                                 {
795                                         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
796                                 }
797                                 //Make window normal and resize it
798                                 [m_window setStyleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)];
799                                 [m_window setFrame:[[m_window screen] visibleFrame] display:YES];
800                                 //TODO for 10.6 only : window title is forgotten after the style change
801                                 [m_window makeFirstResponder:m_openGLView];
802 #else
803                                 //With 10.5, we need to create a new window to change its style to borderless
804                                 //Show menu & dock if needed
805                                 if ([[m_window screen] isEqual:[NSScreen mainScreen]])
806                                 {
807                                         //Cocoa function in 10.5 does not allow to set the menu bar in auto-show mode [NSMenu setMenuBarVisible:YES];
808                                         SetSystemUIMode(kUIModeNormal, 0); //One of the very few 64bit compatible Carbon function
809                                 }
810                                 //Create a fullscreen borderless window
811                                 CocoaWindow *tmpWindow = [[CocoaWindow alloc]
812                                                                                   initWithContentRect:[[m_window screen] frame]
813                                                                                                         styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)
814                                                                                                           backing:NSBackingStoreBuffered
815                                                                                                                 defer:YES];
816                                 //Copy current window parameters
817                                 [tmpWindow setTitle:[m_window title]];
818                                 [tmpWindow setRepresentedFilename:[m_window representedFilename]];
819                                 [tmpWindow setReleasedWhenClosed:NO];
820                                 [tmpWindow setAcceptsMouseMovedEvents:YES];
821                                 [tmpWindow setDelegate:[m_window delegate]];
822                                 
823                                 //Assign the openGL view to the new window
824                                 [tmpWindow setContentView:m_openGLView];
825                                 
826                                 //Show the new window
827                                 [tmpWindow makeKeyAndOrderFront:nil];
828                                 //Close and release old window
829                                 [m_window setDelegate:nil]; // To avoid the notification of "window closed" event
830                                 [m_window close];
831                                 [m_window release];
832                                 m_window = tmpWindow;
833 #endif
834                         
835                                 //Tell WM of view new size
836                                 m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, this);
837                                 
838                                 [pool drain];
839                         }
840             else if ([m_window isMiniaturized])
841                                 [m_window deminiaturize:nil];
842                         else if ([m_window isZoomed])
843                                 [m_window zoom:nil];
844             break;
845     }
846     return GHOST_kSuccess;
847 }
848
849 GHOST_TSuccess GHOST_WindowCocoa::setModifiedState(bool isUnsavedChanges)
850 {
851         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
852         
853         [m_window setDocumentEdited:isUnsavedChanges];
854         
855         [pool drain];
856         return GHOST_Window::setModifiedState(isUnsavedChanges);
857 }
858
859
860
861 GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order)
862 {
863         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
864         
865         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid")
866     if (order == GHOST_kWindowOrderTop) {
867                 [m_window makeKeyAndOrderFront:nil];
868     }
869     else {
870                 NSArray *windowsList;
871                 
872                 [m_window orderBack:nil];
873                 
874                 //Check for other blender opened windows and make the frontmost key
875                 windowsList = [NSApp orderedWindows];
876                 if ([windowsList count]) {
877                         [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
878                 }
879     }
880         
881         [pool drain];
882     return GHOST_kSuccess;
883 }
884
885 #pragma mark Drawing context
886
887 /*#define  WAIT_FOR_VSYNC 1*/
888
889 GHOST_TSuccess GHOST_WindowCocoa::swapBuffers()
890 {
891     if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
892         if (m_openGLContext != nil) {
893                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
894                         [m_openGLContext flushBuffer];
895                         [pool drain];
896             return GHOST_kSuccess;
897         }
898     }
899     return GHOST_kFailure;
900 }
901
902 GHOST_TSuccess GHOST_WindowCocoa::updateDrawingContext()
903 {
904         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
905                 if (m_openGLContext != nil) {
906                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
907                         [m_openGLContext update];
908                         [pool drain];
909                         return GHOST_kSuccess;
910                 }
911         }
912         return GHOST_kFailure;
913 }
914
915 GHOST_TSuccess GHOST_WindowCocoa::activateDrawingContext()
916 {
917         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
918                 if (m_openGLContext != nil) {
919                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
920                         [m_openGLContext makeCurrentContext];
921                         
922                         // Disable AA by default
923                         if (m_numOfAASamples > 0) glDisable(GL_MULTISAMPLE_ARB);
924                         [pool drain];
925                         return GHOST_kSuccess;
926                 }
927         }
928         return GHOST_kFailure;
929 }
930
931
932 GHOST_TSuccess GHOST_WindowCocoa::installDrawingContext(GHOST_TDrawingContextType type)
933 {
934         GHOST_TSuccess success = GHOST_kFailure;
935         
936         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
937         
938         NSOpenGLPixelFormat *pixelFormat;
939         NSOpenGLContext *tmpOpenGLContext;
940         
941         /***** Multithreaded opengl code : uncomment for enabling
942         CGLContextObj cglCtx;
943         */
944          
945         switch (type) {
946                 case GHOST_kDrawingContextTypeOpenGL:
947                         if (!getValid()) break;
948                                         
949                         pixelFormat = [m_openGLView pixelFormat];
950                         tmpOpenGLContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat
951                                                                                                                           shareContext:s_firstOpenGLcontext];
952                         if (tmpOpenGLContext == nil) {
953                                 success = GHOST_kFailure;
954                                 break;
955                         }
956                         
957                         //Switch openGL to multhreaded mode
958                         /******* Multithreaded opengl code : uncomment for enabling
959                         cglCtx = (CGLContextObj)[tmpOpenGLContext CGLContextObj];
960                         if (CGLEnable(cglCtx, kCGLCEMPEngine) == kCGLNoError)
961                                 printf("\nSwitched openGL to multithreaded mode");
962                          */
963                         
964                         if (!s_firstOpenGLcontext) s_firstOpenGLcontext = tmpOpenGLContext;
965 #ifdef WAIT_FOR_VSYNC
966                         {
967                                 GLint swapInt = 1;
968                                 /* wait for vsync, to avoid tearing artifacts */
969                                 [tmpOpenGLContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
970                         }
971 #endif
972                         [m_openGLView setOpenGLContext:tmpOpenGLContext];
973                         [tmpOpenGLContext setView:m_openGLView];
974                         
975                         m_openGLContext = tmpOpenGLContext;
976                         break;
977         
978                 case GHOST_kDrawingContextTypeNone:
979                         success = GHOST_kSuccess;
980                         break;
981                 
982                 default:
983                         break;
984         }
985         [pool drain];
986         return success;
987 }
988
989
990 GHOST_TSuccess GHOST_WindowCocoa::removeDrawingContext()
991 {
992         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
993         switch (m_drawingContextType) {
994                 case GHOST_kDrawingContextTypeOpenGL:
995                         if (m_openGLContext)
996                         {
997                                 [m_openGLView clearGLContext];
998                                 if (s_firstOpenGLcontext == m_openGLContext) s_firstOpenGLcontext = nil;
999                                 m_openGLContext = nil;
1000                         }
1001                         [pool drain];
1002                         return GHOST_kSuccess;
1003                 case GHOST_kDrawingContextTypeNone:
1004                         [pool drain];
1005                         return GHOST_kSuccess;
1006                         break;
1007                 default:
1008                         [pool drain];
1009                         return GHOST_kFailure;
1010         }
1011 }
1012
1013
1014 GHOST_TSuccess GHOST_WindowCocoa::invalidate()
1015 {
1016         GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid")
1017         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1018         [m_openGLView setNeedsDisplay:YES];
1019         [pool drain];
1020         return GHOST_kSuccess;
1021 }
1022
1023 #pragma mark Progress bar
1024
1025 GHOST_TSuccess GHOST_WindowCocoa::setProgressBar(float progress)
1026 {
1027         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1028         
1029         if ((progress >=0.0) && (progress <=1.0)) {
1030                 NSImage* dockIcon = [[NSImage alloc] initWithSize:NSMakeSize(128,128)];
1031                 
1032                 [dockIcon lockFocus];
1033         NSRect progressBox = {{4, 4}, {120, 16}};
1034
1035         [[NSImage imageNamed:@"NSApplicationIcon"] dissolveToPoint:NSZeroPoint fraction:1.0];
1036         
1037         // Track & Outline
1038         [[NSColor blackColor] setFill];
1039         NSRectFill(progressBox);
1040         
1041         [[NSColor whiteColor] set];
1042         NSFrameRect(progressBox);
1043         
1044         // Progress fill
1045         progressBox = NSInsetRect(progressBox, 1, 1);
1046         [[NSColor knobColor] setFill];
1047         progressBox.size.width = progressBox.size.width * progress;
1048                 NSRectFill(progressBox);
1049                 
1050                 [dockIcon unlockFocus];
1051                 
1052                 [NSApp setApplicationIconImage:dockIcon];
1053                 [dockIcon release];
1054                 
1055                 m_progressBarVisible = true;
1056         }
1057         
1058         [pool drain];
1059         return GHOST_kSuccess;
1060 }
1061
1062
1063 GHOST_TSuccess GHOST_WindowCocoa::endProgressBar()
1064 {
1065         if (!m_progressBarVisible) return GHOST_kFailure;
1066         m_progressBarVisible = false;
1067         
1068         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1069         
1070         NSImage* dockIcon = [[NSImage alloc] initWithSize:NSMakeSize(128,128)];
1071         [dockIcon lockFocus];
1072         [[NSImage imageNamed:@"NSApplicationIcon"] dissolveToPoint:NSZeroPoint fraction:1.0];
1073         [dockIcon unlockFocus];
1074         [NSApp setApplicationIconImage:dockIcon];
1075         [dockIcon release];
1076         
1077         [pool drain];
1078         return GHOST_kSuccess;
1079 }
1080
1081
1082
1083 #pragma mark Cursor handling
1084
1085 void GHOST_WindowCocoa::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
1086 {
1087         static bool systemCursorVisible = true;
1088         
1089         NSCursor *tmpCursor =nil;
1090         
1091         if (visible != systemCursorVisible) {
1092                 if (visible) {
1093                         [NSCursor unhide];
1094                         systemCursorVisible = true;
1095                 }
1096                 else {
1097                         [NSCursor hide];
1098                         systemCursorVisible = false;
1099                 }
1100         }
1101
1102         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
1103                 tmpCursor = m_customCursor;
1104         } else {
1105                 switch (cursor) {
1106                         case GHOST_kStandardCursorDestroy:
1107                                 tmpCursor = [NSCursor disappearingItemCursor];
1108                                 break;
1109                         case GHOST_kStandardCursorText:
1110                                 tmpCursor = [NSCursor IBeamCursor];
1111                                 break;
1112                         case GHOST_kStandardCursorCrosshair:
1113                                 tmpCursor = [NSCursor crosshairCursor];
1114                                 break;
1115                         case GHOST_kStandardCursorUpDown:
1116                                 tmpCursor = [NSCursor resizeUpDownCursor];
1117                                 break;
1118                         case GHOST_kStandardCursorLeftRight:
1119                                 tmpCursor = [NSCursor resizeLeftRightCursor];
1120                                 break;
1121                         case GHOST_kStandardCursorTopSide:
1122                                 tmpCursor = [NSCursor resizeUpCursor];
1123                                 break;
1124                         case GHOST_kStandardCursorBottomSide:
1125                                 tmpCursor = [NSCursor resizeDownCursor];
1126                                 break;
1127                         case GHOST_kStandardCursorLeftSide:
1128                                 tmpCursor = [NSCursor resizeLeftCursor];
1129                                 break;
1130                         case GHOST_kStandardCursorRightSide:
1131                                 tmpCursor = [NSCursor resizeRightCursor];
1132                                 break;
1133                         case GHOST_kStandardCursorRightArrow:
1134                         case GHOST_kStandardCursorInfo:
1135                         case GHOST_kStandardCursorLeftArrow:
1136                         case GHOST_kStandardCursorHelp:
1137                         case GHOST_kStandardCursorCycle:
1138                         case GHOST_kStandardCursorSpray:
1139                         case GHOST_kStandardCursorWait:
1140                         case GHOST_kStandardCursorTopLeftCorner:
1141                         case GHOST_kStandardCursorTopRightCorner:
1142                         case GHOST_kStandardCursorBottomRightCorner:
1143                         case GHOST_kStandardCursorBottomLeftCorner:
1144                         case GHOST_kStandardCursorCopy:
1145                         case GHOST_kStandardCursorDefault:
1146                         default:
1147                                 tmpCursor = [NSCursor arrowCursor];
1148                                 break;
1149                 };
1150         }
1151         [tmpCursor set];
1152 }
1153
1154
1155
1156 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorVisibility(bool visible)
1157 {
1158         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
1159         
1160         if ([m_window isVisible]) {
1161                 loadCursor(visible, getCursorShape());
1162         }
1163         
1164         [pool drain];
1165         return GHOST_kSuccess;
1166 }
1167
1168
1169 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
1170 {
1171         GHOST_TSuccess err = GHOST_kSuccess;
1172         
1173         if (mode != GHOST_kGrabDisable)
1174         {
1175                 //No need to perform grab without warp as it is always on in OS X
1176                 if(mode != GHOST_kGrabNormal) {
1177                         GHOST_TInt32 x_old,y_old;
1178                         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1179
1180                         m_systemCocoa->getCursorPosition(x_old,y_old);
1181                         screenToClient(x_old, y_old, m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
1182                         //Warp position is stored in client (window base) coordinates
1183                         setCursorGrabAccum(0, 0);
1184                         
1185                         if(mode == GHOST_kGrabHide) {
1186                                 setWindowCursorVisibility(false);
1187                         }
1188                         
1189                         //Make window key if it wasn't to get the mouse move events
1190                         [m_window makeKeyWindow];
1191                         
1192                         //Dissociate cursor position even for warp mode, to allow mouse acceleration to work even when warping the cursor
1193                         err = CGAssociateMouseAndMouseCursorPosition(false) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1194                         
1195                         [pool drain];
1196                 }
1197         }
1198         else {
1199                 if(m_cursorGrab==GHOST_kGrabHide)
1200                 {
1201                         //No need to set again cursor position, as it has not changed for Cocoa
1202                         setWindowCursorVisibility(true);
1203                 }
1204                 
1205                 err = CGAssociateMouseAndMouseCursorPosition(true) == kCGErrorSuccess ? GHOST_kSuccess : GHOST_kFailure;
1206                 /* Almost works without but important otherwise the mouse GHOST location can be incorrect on exit */
1207                 setCursorGrabAccum(0, 0);
1208                 m_cursorGrabBounds.m_l= m_cursorGrabBounds.m_r= -1; /* disable */
1209         }
1210         return err;
1211 }
1212         
1213 GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorShape(GHOST_TStandardCursor shape)
1214 {
1215         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1216
1217         if (m_customCursor) {
1218                 [m_customCursor release];
1219                 m_customCursor = nil;
1220         }
1221
1222         if ([m_window isVisible]) {
1223                 loadCursor(getCursorVisibility(), shape);
1224         }
1225         
1226         [pool drain];
1227         return GHOST_kSuccess;
1228 }
1229
1230 /** Reverse the bits in a GHOST_TUns8
1231 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
1232 {
1233         ch= ((ch>>1)&0x55) | ((ch<<1)&0xAA);
1234         ch= ((ch>>2)&0x33) | ((ch<<2)&0xCC);
1235         ch= ((ch>>4)&0x0F) | ((ch<<4)&0xF0);
1236         return ch;
1237 }
1238 */
1239
1240
1241 /** Reverse the bits in a GHOST_TUns16 */
1242 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
1243 {
1244         shrt= ((shrt>>1)&0x5555) | ((shrt<<1)&0xAAAA);
1245         shrt= ((shrt>>2)&0x3333) | ((shrt<<2)&0xCCCC);
1246         shrt= ((shrt>>4)&0x0F0F) | ((shrt<<4)&0xF0F0);
1247         shrt= ((shrt>>8)&0x00FF) | ((shrt<<8)&0xFF00);
1248         return shrt;
1249 }
1250
1251 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 *bitmap, GHOST_TUns8 *mask,
1252                                         int sizex, int sizey, int hotX, int hotY, int fg_color, int bg_color)
1253 {
1254         int y,nbUns16;
1255         NSPoint hotSpotPoint;
1256         NSBitmapImageRep *cursorImageRep;
1257         NSImage *cursorImage;
1258         NSSize imSize;
1259         GHOST_TUns16 *cursorBitmap;
1260         
1261         
1262         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1263         
1264         if (m_customCursor) {
1265                 [m_customCursor release];
1266                 m_customCursor = nil;
1267         }
1268         
1269
1270         cursorImageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
1271                                                                                                                          pixelsWide:sizex
1272                                                                                                                          pixelsHigh:sizey
1273                                                                                                                   bitsPerSample:1 
1274                                                                                                                 samplesPerPixel:2
1275                                                                                                                            hasAlpha:YES
1276                                                                                                                            isPlanar:YES
1277                                                                                                                  colorSpaceName:NSDeviceWhiteColorSpace
1278                                                                                                                         bytesPerRow:(sizex/8 + (sizex%8 >0 ?1:0))
1279                                                                                                                    bitsPerPixel:1];
1280         
1281         
1282         cursorBitmap = (GHOST_TUns16*)[cursorImageRep bitmapData];
1283         nbUns16 = [cursorImageRep bytesPerPlane]/2;
1284         
1285         for (y=0; y<nbUns16; y++) {
1286 #if !defined(__LITTLE_ENDIAN__)
1287                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y]<<0) | (bitmap[2*y+1]<<8));
1288                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y]<<0) | (mask[2*y+1]<<8));
1289 #else
1290                 cursorBitmap[y] = ~uns16ReverseBits((bitmap[2*y+1]<<0) | (bitmap[2*y]<<8));
1291                 cursorBitmap[nbUns16+y] = uns16ReverseBits((mask[2*y+1]<<0) | (mask[2*y]<<8));
1292 #endif
1293                 
1294         }
1295         
1296         
1297         imSize.width = sizex;
1298         imSize.height= sizey;
1299         cursorImage = [[NSImage alloc] initWithSize:imSize];
1300         [cursorImage addRepresentation:cursorImageRep];
1301         
1302         hotSpotPoint.x = hotX;
1303         hotSpotPoint.y = hotY;
1304         
1305         //foreground and background color parameter is not handled for now (10.6)
1306         m_customCursor = [[NSCursor alloc] initWithImage:cursorImage
1307                                                                                          hotSpot:hotSpotPoint];
1308         
1309         [cursorImageRep release];
1310         [cursorImage release];
1311         
1312         if ([m_window isVisible]) {
1313                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
1314         }
1315         [pool drain];
1316         return GHOST_kSuccess;
1317 }
1318
1319 GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2], 
1320                                                                                                 GHOST_TUns8 mask[16][2], int hotX, int hotY)
1321 {
1322         return setWindowCustomCursorShape((GHOST_TUns8*)bitmap, (GHOST_TUns8*) mask, 16, 16, hotX, hotY, 0, 1);
1323 }