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