rename PoseChannelConstraints to PoseBoneConstraints
[blender-staging.git] / intern / ghost / intern / GHOST_SystemCocoa.mm
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s):      Maarten Gribnau 05/2001
25  *                                      Damien Plisson 09/2009
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #import <Cocoa/Cocoa.h>
31
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/sysctl.h>
35
36 #include "GHOST_SystemCocoa.h"
37
38 #include "GHOST_DisplayManagerCocoa.h"
39 #include "GHOST_EventKey.h"
40 #include "GHOST_EventButton.h"
41 #include "GHOST_EventCursor.h"
42 #include "GHOST_EventWheel.h"
43 #include "GHOST_EventNDOF.h"
44 #include "GHOST_EventDragnDrop.h"
45
46 #include "GHOST_TimerManager.h"
47 #include "GHOST_TimerTask.h"
48 #include "GHOST_WindowManager.h"
49 #include "GHOST_WindowCocoa.h"
50 #include "GHOST_NDOFManager.h"
51 #include "AssertMacros.h"
52
53 #pragma mark KeyMap, mouse converters
54
55
56 /* Keycodes from Carbon include file */
57 /*  
58  *  Summary:
59  *    Virtual keycodes
60  *  
61  *  Discussion:
62  *    These constants are the virtual keycodes defined originally in
63  *    Inside Mac Volume V, pg. V-191. They identify physical keys on a
64  *    keyboard. Those constants with "ANSI" in the name are labeled
65  *    according to the key position on an ANSI-standard US keyboard.
66  *    For example, kVK_ANSI_A indicates the virtual keycode for the key
67  *    with the letter 'A' in the US keyboard layout. Other keyboard
68  *    layouts may have the 'A' key label on a different physical key;
69  *    in this case, pressing 'A' will generate a different virtual
70  *    keycode.
71  */
72 enum {
73         kVK_ANSI_A                    = 0x00,
74         kVK_ANSI_S                    = 0x01,
75         kVK_ANSI_D                    = 0x02,
76         kVK_ANSI_F                    = 0x03,
77         kVK_ANSI_H                    = 0x04,
78         kVK_ANSI_G                    = 0x05,
79         kVK_ANSI_Z                    = 0x06,
80         kVK_ANSI_X                    = 0x07,
81         kVK_ANSI_C                    = 0x08,
82         kVK_ANSI_V                    = 0x09,
83         kVK_ANSI_B                    = 0x0B,
84         kVK_ANSI_Q                    = 0x0C,
85         kVK_ANSI_W                    = 0x0D,
86         kVK_ANSI_E                    = 0x0E,
87         kVK_ANSI_R                    = 0x0F,
88         kVK_ANSI_Y                    = 0x10,
89         kVK_ANSI_T                    = 0x11,
90         kVK_ANSI_1                    = 0x12,
91         kVK_ANSI_2                    = 0x13,
92         kVK_ANSI_3                    = 0x14,
93         kVK_ANSI_4                    = 0x15,
94         kVK_ANSI_6                    = 0x16,
95         kVK_ANSI_5                    = 0x17,
96         kVK_ANSI_Equal                = 0x18,
97         kVK_ANSI_9                    = 0x19,
98         kVK_ANSI_7                    = 0x1A,
99         kVK_ANSI_Minus                = 0x1B,
100         kVK_ANSI_8                    = 0x1C,
101         kVK_ANSI_0                    = 0x1D,
102         kVK_ANSI_RightBracket         = 0x1E,
103         kVK_ANSI_O                    = 0x1F,
104         kVK_ANSI_U                    = 0x20,
105         kVK_ANSI_LeftBracket          = 0x21,
106         kVK_ANSI_I                    = 0x22,
107         kVK_ANSI_P                    = 0x23,
108         kVK_ANSI_L                    = 0x25,
109         kVK_ANSI_J                    = 0x26,
110         kVK_ANSI_Quote                = 0x27,
111         kVK_ANSI_K                    = 0x28,
112         kVK_ANSI_Semicolon            = 0x29,
113         kVK_ANSI_Backslash            = 0x2A,
114         kVK_ANSI_Comma                = 0x2B,
115         kVK_ANSI_Slash                = 0x2C,
116         kVK_ANSI_N                    = 0x2D,
117         kVK_ANSI_M                    = 0x2E,
118         kVK_ANSI_Period               = 0x2F,
119         kVK_ANSI_Grave                = 0x32,
120         kVK_ANSI_KeypadDecimal        = 0x41,
121         kVK_ANSI_KeypadMultiply       = 0x43,
122         kVK_ANSI_KeypadPlus           = 0x45,
123         kVK_ANSI_KeypadClear          = 0x47,
124         kVK_ANSI_KeypadDivide         = 0x4B,
125         kVK_ANSI_KeypadEnter          = 0x4C,
126         kVK_ANSI_KeypadMinus          = 0x4E,
127         kVK_ANSI_KeypadEquals         = 0x51,
128         kVK_ANSI_Keypad0              = 0x52,
129         kVK_ANSI_Keypad1              = 0x53,
130         kVK_ANSI_Keypad2              = 0x54,
131         kVK_ANSI_Keypad3              = 0x55,
132         kVK_ANSI_Keypad4              = 0x56,
133         kVK_ANSI_Keypad5              = 0x57,
134         kVK_ANSI_Keypad6              = 0x58,
135         kVK_ANSI_Keypad7              = 0x59,
136         kVK_ANSI_Keypad8              = 0x5B,
137         kVK_ANSI_Keypad9              = 0x5C
138 };
139
140 /* keycodes for keys that are independent of keyboard layout*/
141 enum {
142         kVK_Return                    = 0x24,
143         kVK_Tab                       = 0x30,
144         kVK_Space                     = 0x31,
145         kVK_Delete                    = 0x33,
146         kVK_Escape                    = 0x35,
147         kVK_Command                   = 0x37,
148         kVK_Shift                     = 0x38,
149         kVK_CapsLock                  = 0x39,
150         kVK_Option                    = 0x3A,
151         kVK_Control                   = 0x3B,
152         kVK_RightShift                = 0x3C,
153         kVK_RightOption               = 0x3D,
154         kVK_RightControl              = 0x3E,
155         kVK_Function                  = 0x3F,
156         kVK_F17                       = 0x40,
157         kVK_VolumeUp                  = 0x48,
158         kVK_VolumeDown                = 0x49,
159         kVK_Mute                      = 0x4A,
160         kVK_F18                       = 0x4F,
161         kVK_F19                       = 0x50,
162         kVK_F20                       = 0x5A,
163         kVK_F5                        = 0x60,
164         kVK_F6                        = 0x61,
165         kVK_F7                        = 0x62,
166         kVK_F3                        = 0x63,
167         kVK_F8                        = 0x64,
168         kVK_F9                        = 0x65,
169         kVK_F11                       = 0x67,
170         kVK_F13                       = 0x69,
171         kVK_F16                       = 0x6A,
172         kVK_F14                       = 0x6B,
173         kVK_F10                       = 0x6D,
174         kVK_F12                       = 0x6F,
175         kVK_F15                       = 0x71,
176         kVK_Help                      = 0x72,
177         kVK_Home                      = 0x73,
178         kVK_PageUp                    = 0x74,
179         kVK_ForwardDelete             = 0x75,
180         kVK_F4                        = 0x76,
181         kVK_End                       = 0x77,
182         kVK_F2                        = 0x78,
183         kVK_PageDown                  = 0x79,
184         kVK_F1                        = 0x7A,
185         kVK_LeftArrow                 = 0x7B,
186         kVK_RightArrow                = 0x7C,
187         kVK_DownArrow                 = 0x7D,
188         kVK_UpArrow                   = 0x7E
189 };
190
191 /* ISO keyboards only*/
192 enum {
193         kVK_ISO_Section               = 0x0A
194 };
195
196 /* JIS keyboards only*/
197 enum {
198         kVK_JIS_Yen                   = 0x5D,
199         kVK_JIS_Underscore            = 0x5E,
200         kVK_JIS_KeypadComma           = 0x5F,
201         kVK_JIS_Eisu                  = 0x66,
202         kVK_JIS_Kana                  = 0x68
203 };
204
205
206 static GHOST_TButtonMask convertButton(int button)
207 {
208         switch (button) {
209                 case 0:
210                         return GHOST_kButtonMaskLeft;
211                 case 1:
212                         return GHOST_kButtonMaskRight;
213                 case 2:
214                         return GHOST_kButtonMaskMiddle;
215                 case 3:
216                         return GHOST_kButtonMaskButton4;
217                 case 4:
218                         return GHOST_kButtonMaskButton5;
219                 default:
220                         return GHOST_kButtonMaskLeft;
221         }
222 }
223
224 /**
225  * Converts Mac rawkey codes (same for Cocoa & Carbon)
226  * into GHOST key codes
227  * @param rawCode The raw physical key code
228  * @param recvChar the character ignoring modifiers (except for shift)
229  * @return Ghost key code
230  */
231 static GHOST_TKey convertKey(int rawCode, unichar recvChar) 
232 {       
233         
234         //printf("\nrecvchar %c 0x%x",recvChar,recvChar);
235         switch (rawCode) {
236                 /*Physical keycodes not used due to map changes in int'l keyboards
237                 case kVK_ANSI_A:        return GHOST_kKeyA;
238                 case kVK_ANSI_B:        return GHOST_kKeyB;
239                 case kVK_ANSI_C:        return GHOST_kKeyC;
240                 case kVK_ANSI_D:        return GHOST_kKeyD;
241                 case kVK_ANSI_E:        return GHOST_kKeyE;
242                 case kVK_ANSI_F:        return GHOST_kKeyF;
243                 case kVK_ANSI_G:        return GHOST_kKeyG;
244                 case kVK_ANSI_H:        return GHOST_kKeyH;
245                 case kVK_ANSI_I:        return GHOST_kKeyI;
246                 case kVK_ANSI_J:        return GHOST_kKeyJ;
247                 case kVK_ANSI_K:        return GHOST_kKeyK;
248                 case kVK_ANSI_L:        return GHOST_kKeyL;
249                 case kVK_ANSI_M:        return GHOST_kKeyM;
250                 case kVK_ANSI_N:        return GHOST_kKeyN;
251                 case kVK_ANSI_O:        return GHOST_kKeyO;
252                 case kVK_ANSI_P:        return GHOST_kKeyP;
253                 case kVK_ANSI_Q:        return GHOST_kKeyQ;
254                 case kVK_ANSI_R:        return GHOST_kKeyR;
255                 case kVK_ANSI_S:        return GHOST_kKeyS;
256                 case kVK_ANSI_T:        return GHOST_kKeyT;
257                 case kVK_ANSI_U:        return GHOST_kKeyU;
258                 case kVK_ANSI_V:        return GHOST_kKeyV;
259                 case kVK_ANSI_W:        return GHOST_kKeyW;
260                 case kVK_ANSI_X:        return GHOST_kKeyX;
261                 case kVK_ANSI_Y:        return GHOST_kKeyY;
262                 case kVK_ANSI_Z:        return GHOST_kKeyZ;*/
263                 
264                 /* Numbers keys mapped to handle some int'l keyboard (e.g. French)*/
265                 case kVK_ISO_Section: return    GHOST_kKeyUnknown;
266                 case kVK_ANSI_1:        return GHOST_kKey1;
267                 case kVK_ANSI_2:        return GHOST_kKey2;
268                 case kVK_ANSI_3:        return GHOST_kKey3;
269                 case kVK_ANSI_4:        return GHOST_kKey4;
270                 case kVK_ANSI_5:        return GHOST_kKey5;
271                 case kVK_ANSI_6:        return GHOST_kKey6;
272                 case kVK_ANSI_7:        return GHOST_kKey7;
273                 case kVK_ANSI_8:        return GHOST_kKey8;
274                 case kVK_ANSI_9:        return GHOST_kKey9;
275                 case kVK_ANSI_0:        return GHOST_kKey0;
276         
277                 case kVK_ANSI_Keypad0:                  return GHOST_kKeyNumpad0;
278                 case kVK_ANSI_Keypad1:                  return GHOST_kKeyNumpad1;
279                 case kVK_ANSI_Keypad2:                  return GHOST_kKeyNumpad2;
280                 case kVK_ANSI_Keypad3:                  return GHOST_kKeyNumpad3;
281                 case kVK_ANSI_Keypad4:                  return GHOST_kKeyNumpad4;
282                 case kVK_ANSI_Keypad5:                  return GHOST_kKeyNumpad5;
283                 case kVK_ANSI_Keypad6:                  return GHOST_kKeyNumpad6;
284                 case kVK_ANSI_Keypad7:                  return GHOST_kKeyNumpad7;
285                 case kVK_ANSI_Keypad8:                  return GHOST_kKeyNumpad8;
286                 case kVK_ANSI_Keypad9:                  return GHOST_kKeyNumpad9;
287                 case kVK_ANSI_KeypadDecimal:    return GHOST_kKeyNumpadPeriod;
288                 case kVK_ANSI_KeypadEnter:              return GHOST_kKeyNumpadEnter;
289                 case kVK_ANSI_KeypadPlus:               return GHOST_kKeyNumpadPlus;
290                 case kVK_ANSI_KeypadMinus:              return GHOST_kKeyNumpadMinus;
291                 case kVK_ANSI_KeypadMultiply:   return GHOST_kKeyNumpadAsterisk;
292                 case kVK_ANSI_KeypadDivide:     return GHOST_kKeyNumpadSlash;
293                 case kVK_ANSI_KeypadClear:              return GHOST_kKeyUnknown;
294
295                 case kVK_F1:                            return GHOST_kKeyF1;
296                 case kVK_F2:                            return GHOST_kKeyF2;
297                 case kVK_F3:                            return GHOST_kKeyF3;
298                 case kVK_F4:                            return GHOST_kKeyF4;
299                 case kVK_F5:                            return GHOST_kKeyF5;
300                 case kVK_F6:                            return GHOST_kKeyF6;
301                 case kVK_F7:                            return GHOST_kKeyF7;
302                 case kVK_F8:                            return GHOST_kKeyF8;
303                 case kVK_F9:                            return GHOST_kKeyF9;
304                 case kVK_F10:                           return GHOST_kKeyF10;
305                 case kVK_F11:                           return GHOST_kKeyF11;
306                 case kVK_F12:                           return GHOST_kKeyF12;
307                 case kVK_F13:                           return GHOST_kKeyF13;
308                 case kVK_F14:                           return GHOST_kKeyF14;
309                 case kVK_F15:                           return GHOST_kKeyF15;
310                 case kVK_F16:                           return GHOST_kKeyF16;
311                 case kVK_F17:                           return GHOST_kKeyF17;
312                 case kVK_F18:                           return GHOST_kKeyF18;
313                 case kVK_F19:                           return GHOST_kKeyF19;
314                 case kVK_F20:                           return GHOST_kKeyF20;
315                         
316                 case kVK_UpArrow:                       return GHOST_kKeyUpArrow;
317                 case kVK_DownArrow:                     return GHOST_kKeyDownArrow;
318                 case kVK_LeftArrow:                     return GHOST_kKeyLeftArrow;
319                 case kVK_RightArrow:            return GHOST_kKeyRightArrow;
320                         
321                 case kVK_Return:                        return GHOST_kKeyEnter;
322                 case kVK_Delete:                        return GHOST_kKeyBackSpace;
323                 case kVK_ForwardDelete:         return GHOST_kKeyDelete;
324                 case kVK_Escape:                        return GHOST_kKeyEsc;
325                 case kVK_Tab:                           return GHOST_kKeyTab;
326                 case kVK_Space:                         return GHOST_kKeySpace;
327                         
328                 case kVK_Home:                          return GHOST_kKeyHome;
329                 case kVK_End:                           return GHOST_kKeyEnd;
330                 case kVK_PageUp:                        return GHOST_kKeyUpPage;
331                 case kVK_PageDown:                      return GHOST_kKeyDownPage;
332                         
333                 /*case kVK_ANSI_Minus:          return GHOST_kKeyMinus;
334                 case kVK_ANSI_Equal:            return GHOST_kKeyEqual;
335                 case kVK_ANSI_Comma:            return GHOST_kKeyComma;
336                 case kVK_ANSI_Period:           return GHOST_kKeyPeriod;
337                 case kVK_ANSI_Slash:            return GHOST_kKeySlash;
338                 case kVK_ANSI_Semicolon:        return GHOST_kKeySemicolon;
339                 case kVK_ANSI_Quote:            return GHOST_kKeyQuote;
340                 case kVK_ANSI_Backslash:        return GHOST_kKeyBackslash;
341                 case kVK_ANSI_LeftBracket:      return GHOST_kKeyLeftBracket;
342                 case kVK_ANSI_RightBracket:     return GHOST_kKeyRightBracket;
343                 case kVK_ANSI_Grave:            return GHOST_kKeyAccentGrave;*/
344                         
345                 case kVK_VolumeUp:
346                 case kVK_VolumeDown:
347                 case kVK_Mute:
348                         return GHOST_kKeyUnknown;
349                         
350                 default:
351                         /*Then detect on character value for "remappable" keys in int'l keyboards*/
352                         if ((recvChar >= 'A') && (recvChar <= 'Z')) {
353                                 return (GHOST_TKey) (recvChar - 'A' + GHOST_kKeyA);
354                         } else if ((recvChar >= 'a') && (recvChar <= 'z')) {
355                                 return (GHOST_TKey) (recvChar - 'a' + GHOST_kKeyA);
356                         } else
357                         switch (recvChar) {
358                                 case '-':       return GHOST_kKeyMinus;
359                                 case '=':       return GHOST_kKeyEqual;
360                                 case ',':       return GHOST_kKeyComma;
361                                 case '.':       return GHOST_kKeyPeriod;
362                                 case '/':       return GHOST_kKeySlash;
363                                 case ';':       return GHOST_kKeySemicolon;
364                                 case '\'':      return GHOST_kKeyQuote;
365                                 case '\\':      return GHOST_kKeyBackslash;
366                                 case '[':       return GHOST_kKeyLeftBracket;
367                                 case ']':       return GHOST_kKeyRightBracket;
368                                 case '`':       return GHOST_kKeyAccentGrave;
369                                 default:
370                                         return GHOST_kKeyUnknown;
371                         }
372         }
373         return GHOST_kKeyUnknown;
374 }
375
376
377 #define FIRSTFILEBUFLG 512
378 static bool g_hasFirstFile = false;
379 static char g_firstFileBuf[512];
380
381 //TODO:Need to investigate this. Function called too early in creator.c to have g_hasFirstFile == true
382 extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG]) { 
383         if (g_hasFirstFile) {
384                 strncpy(buf, g_firstFileBuf, FIRSTFILEBUFLG - 1);
385                 buf[FIRSTFILEBUFLG - 1] = '\0';
386                 return 1;
387         } else {
388                 return 0; 
389         }
390 }
391
392
393 #pragma mark Cocoa objects
394
395 /**
396  * CocoaAppDelegate
397  * ObjC object to capture applicationShouldTerminate, and send quit event
398  **/
399 @interface CocoaAppDelegate : NSObject {
400         GHOST_SystemCocoa *systemCocoa;
401 }
402 - (void)setSystemCocoa:(GHOST_SystemCocoa *)sysCocoa;
403 - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename;
404 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
405 - (void)applicationWillTerminate:(NSNotification *)aNotification;
406 @end
407
408 @implementation CocoaAppDelegate : NSObject
409 -(void)setSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
410 {
411         systemCocoa = sysCocoa;
412 }
413
414 - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
415 {
416         NSLog(@"\nGet open file event from cocoa : %@",filename);
417         systemCocoa->handleDraggingEvent(GHOST_kEventDraggingDropOnIcon, GHOST_kDragnDropTypeFilenames, nil, 0, 0, [NSArray arrayWithObject:filename]);
418         return YES;
419 }
420
421 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
422 {
423         //TODO: implement graceful termination through Cocoa mechanism to avoid session log off to be cancelled
424         //Note that Cmd+Q is already handled by keyhandler
425     if (systemCocoa->handleQuitRequest() == GHOST_kExitNow)
426                 return NSTerminateCancel;//NSTerminateNow;
427         else
428                 return NSTerminateCancel;
429 }
430
431 // To avoid cancelling a log off process, we must use Cocoa termination process
432 // And this function is the only chance to perform clean up
433 // So WM_exit needs to be called directly, as the event loop will never run before termination
434 - (void)applicationWillTerminate:(NSNotification *)aNotification
435 {
436         /*G.afbreek = 0; //Let Cocoa perform the termination at the end
437         WM_exit(C);*/
438 }
439 @end
440
441
442
443 #pragma mark initialization/finalization
444
445
446 GHOST_SystemCocoa::GHOST_SystemCocoa()
447 {
448         m_modifierMask =0;
449         m_pressedMouseButtons =0;
450         m_cursorDelta_x=0;
451         m_cursorDelta_y=0;
452         m_outsideLoopEventProcessed = false;
453         m_displayManager = new GHOST_DisplayManagerCocoa ();
454         GHOST_ASSERT(m_displayManager, "GHOST_SystemCocoa::GHOST_SystemCocoa(): m_displayManager==0\n");
455         m_displayManager->initialize();
456
457         //NSEvent timeStamp is given in system uptime, state start date is boot time
458         int mib[2];
459         struct timeval boottime;
460         size_t len;
461         
462         mib[0] = CTL_KERN;
463         mib[1] = KERN_BOOTTIME;
464         len = sizeof(struct timeval);
465         
466         sysctl(mib, 2, &boottime, &len, NULL, 0);
467         m_start_time = ((boottime.tv_sec*1000)+(boottime.tv_usec/1000));
468         
469         m_ignoreWindowSizedMessages = false;
470 }
471
472 GHOST_SystemCocoa::~GHOST_SystemCocoa()
473 {
474 }
475
476
477 GHOST_TSuccess GHOST_SystemCocoa::init()
478 {
479         
480     GHOST_TSuccess success = GHOST_System::init();
481     if (success) {
482                 //ProcessSerialNumber psn;
483                 
484                 //Carbon stuff to move window & menu to foreground
485                 /*if (!GetCurrentProcess(&psn)) {
486                         TransformProcessType(&psn, kProcessTransformToForegroundApplication);
487                         SetFrontProcess(&psn);
488                 }*/
489                 
490                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
491                 if (NSApp == nil) {
492                         [NSApplication sharedApplication];
493                         
494                         if ([NSApp mainMenu] == nil) {
495                                 NSMenu *mainMenubar = [[NSMenu alloc] init];
496                                 NSMenuItem *menuItem;
497                                 NSMenu *windowMenu;
498                                 NSMenu *appMenu;
499                                 
500                                 //Create the application menu
501                                 appMenu = [[NSMenu alloc] initWithTitle:@"Blender"];
502                                 
503                                 [appMenu addItemWithTitle:@"About Blender" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
504                                 [appMenu addItem:[NSMenuItem separatorItem]];
505                                 
506                                 menuItem = [appMenu addItemWithTitle:@"Hide Blender" action:@selector(hide:) keyEquivalent:@"h"];
507                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
508                                  
509                                 menuItem = [appMenu addItemWithTitle:@"Hide others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
510                                 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
511                                 
512                                 [appMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
513                                 
514                                 menuItem = [appMenu addItemWithTitle:@"Quit Blender" action:@selector(terminate:) keyEquivalent:@"q"];
515                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
516                                 
517                                 menuItem = [[NSMenuItem alloc] init];
518                                 [menuItem setSubmenu:appMenu];
519                                 
520                                 [mainMenubar addItem:menuItem];
521                                 [menuItem release];
522                                 [NSApp performSelector:@selector(setAppleMenu:) withObject:appMenu]; //Needed for 10.5
523                                 [appMenu release];
524                                 
525                                 //Create the window menu
526                                 windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
527                                 
528                                 menuItem = [windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
529                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
530                                 
531                                 [windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
532                                 
533                                 menuItem = [[NSMenuItem alloc] init];
534                                 [menuItem setSubmenu:windowMenu];
535                                 
536                                 [mainMenubar addItem:menuItem];
537                                 [menuItem release];
538                                 
539                                 [NSApp setMainMenu:mainMenubar];
540                                 [NSApp setWindowsMenu:windowMenu];
541                                 [windowMenu release];
542                         }
543                 }
544                 if ([NSApp delegate] == nil) {
545                         CocoaAppDelegate *appDelegate = [[CocoaAppDelegate alloc] init];
546                         [appDelegate setSystemCocoa:this];
547                         [NSApp setDelegate:appDelegate];
548                 }
549                 
550                 [NSApp finishLaunching];
551                                 
552                 [pool drain];
553     }
554     return success;
555 }
556
557
558 #pragma mark window management
559
560 GHOST_TUns64 GHOST_SystemCocoa::getMilliSeconds() const
561 {
562         //Cocoa equivalent exists in 10.6 ([[NSProcessInfo processInfo] systemUptime])
563         struct timeval currentTime;
564         
565         gettimeofday(&currentTime, NULL);
566         
567         //Return timestamp of system uptime
568         
569         return ((currentTime.tv_sec*1000)+(currentTime.tv_usec/1000)-m_start_time);
570 }
571
572
573 GHOST_TUns8 GHOST_SystemCocoa::getNumDisplays() const
574 {
575         //Note that OS X supports monitor hot plug
576         // We do not support multiple monitors at the moment
577         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
578
579         GHOST_TUns8 count = [[NSScreen screens] count];
580
581         [pool drain];
582         return count;
583 }
584
585
586 void GHOST_SystemCocoa::getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const
587 {
588         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
589         //Get visible frame, that is frame excluding dock and top menu bar
590         NSRect frame = [[NSScreen mainScreen] visibleFrame];
591         
592         //Returns max window contents (excluding title bar...)
593         NSRect contentRect = [NSWindow contentRectForFrameRect:frame
594                                                                                                  styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask)];
595         
596         width = contentRect.size.width;
597         height = contentRect.size.height;
598
599         [pool drain];
600 }
601
602
603 GHOST_IWindow* GHOST_SystemCocoa::createWindow(
604         const STR_String& title, 
605         GHOST_TInt32 left,
606         GHOST_TInt32 top,
607         GHOST_TUns32 width,
608         GHOST_TUns32 height,
609         GHOST_TWindowState state,
610         GHOST_TDrawingContextType type,
611         bool stereoVisual,
612         const GHOST_TEmbedderWindowID parentWindow
613 )
614 {
615     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
616         GHOST_IWindow* window = 0;
617         
618         //Get the available rect for including window contents
619         NSRect frame = [[NSScreen mainScreen] visibleFrame];
620         NSRect contentRect = [NSWindow contentRectForFrameRect:frame
621                                                                                                  styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask)];
622         
623         //Ensures window top left is inside this available rect
624         left = left > contentRect.origin.x ? left : contentRect.origin.x;
625         top = top > contentRect.origin.y ? top : contentRect.origin.y;
626         
627         window = new GHOST_WindowCocoa (this, title, left, top, width, height, state, type);
628
629     if (window) {
630         if (window->getValid()) {
631             // Store the pointer to the window 
632             GHOST_ASSERT(m_windowManager, "m_windowManager not initialized");
633             m_windowManager->addWindow(window);
634             m_windowManager->setActiveWindow(window);
635                         //Need to tell window manager the new window is the active one (Cocoa does not send the event activate upon window creation)
636             pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window));
637                         pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window));
638
639         }
640         else {
641                         GHOST_PRINT("GHOST_SystemCocoa::createWindow(): window invalid\n");
642             delete window;
643             window = 0;
644         }
645     }
646         else {
647                 GHOST_PRINT("GHOST_SystemCocoa::createWindow(): could not create window\n");
648         }
649         [pool drain];
650     return window;
651 }
652
653 GHOST_TSuccess GHOST_SystemCocoa::beginFullScreen(const GHOST_DisplaySetting& setting, GHOST_IWindow** window, const bool stereoVisual)
654 {       
655         GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
656
657         *window = currentWindow;
658         
659         return currentWindow->setState(GHOST_kWindowStateFullScreen);
660 }
661
662 GHOST_TSuccess GHOST_SystemCocoa::endFullScreen(void)
663 {       
664         GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
665         
666         return currentWindow->setState(GHOST_kWindowStateNormal);
667 }
668
669
670         
671 /**
672  * @note : returns coordinates in Cocoa screen coordinates
673  */
674 GHOST_TSuccess GHOST_SystemCocoa::getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const
675 {
676     NSPoint mouseLoc = [NSEvent mouseLocation];
677         
678     // Returns the mouse location in screen coordinates
679     x = (GHOST_TInt32)mouseLoc.x;
680     y = (GHOST_TInt32)mouseLoc.y;
681     return GHOST_kSuccess;
682 }
683
684 /**
685  * @note : expect Cocoa screen coordinates
686  */
687 GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y) const
688 {
689         float xf=(float)x, yf=(float)y;
690         GHOST_WindowCocoa* window = (GHOST_WindowCocoa*)m_windowManager->getActiveWindow();
691         NSScreen *windowScreen = window->getScreen();
692         NSRect screenRect = [windowScreen frame];
693         
694         //Set position relative to current screen
695         xf -= screenRect.origin.x;
696         yf -= screenRect.origin.y;
697         
698         //Quartz Display Services uses the old coordinates (top left origin)
699         yf = screenRect.size.height -yf;
700
701         CGDisplayMoveCursorToPoint((CGDirectDisplayID)[[[windowScreen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue], CGPointMake(xf, yf));
702
703     return GHOST_kSuccess;
704 }
705
706
707 GHOST_TSuccess GHOST_SystemCocoa::getModifierKeys(GHOST_ModifierKeys& keys) const
708 {
709         unsigned int modifiers = [[NSApp currentEvent] modifierFlags];
710         //Direct query to modifierFlags can be used in 10.6
711
712     keys.set(GHOST_kModifierKeyCommand, (modifiers & NSCommandKeyMask) ? true : false);
713     keys.set(GHOST_kModifierKeyLeftAlt, (modifiers & NSAlternateKeyMask) ? true : false);
714     keys.set(GHOST_kModifierKeyLeftShift, (modifiers & NSShiftKeyMask) ? true : false);
715     keys.set(GHOST_kModifierKeyLeftControl, (modifiers & NSControlKeyMask) ? true : false);
716         
717     return GHOST_kSuccess;
718 }
719
720 GHOST_TSuccess GHOST_SystemCocoa::getButtons(GHOST_Buttons& buttons) const
721 {
722         buttons.clear();
723     buttons.set(GHOST_kButtonMaskLeft, m_pressedMouseButtons & GHOST_kButtonMaskLeft);
724         buttons.set(GHOST_kButtonMaskRight, m_pressedMouseButtons & GHOST_kButtonMaskRight);
725         buttons.set(GHOST_kButtonMaskMiddle, m_pressedMouseButtons & GHOST_kButtonMaskMiddle);
726         buttons.set(GHOST_kButtonMaskButton4, m_pressedMouseButtons & GHOST_kButtonMaskButton4);
727         buttons.set(GHOST_kButtonMaskButton5, m_pressedMouseButtons & GHOST_kButtonMaskButton5);
728     return GHOST_kSuccess;
729 }
730
731
732
733 #pragma mark Event handlers
734
735 /**
736  * The event queue polling function
737  */
738 bool GHOST_SystemCocoa::processEvents(bool waitForEvent)
739 {
740         bool anyProcessed = false;
741         NSEvent *event;
742         
743         m_outsideLoopEventProcessed = false;
744         
745         //      SetMouseCoalescingEnabled(false, NULL);
746         //TODO : implement timer ??
747         
748         /*do {
749                 GHOST_TimerManager* timerMgr = getTimerManager();
750                 
751                  if (waitForEvent) {
752                  GHOST_TUns64 next = timerMgr->nextFireTime();
753                  double timeOut;
754                  
755                  if (next == GHOST_kFireTimeNever) {
756                  timeOut = kEventDurationForever;
757                  } else {
758                  timeOut = (double)(next - getMilliSeconds())/1000.0;
759                  if (timeOut < 0.0)
760                  timeOut = 0.0;
761                  }
762                  
763                  ::ReceiveNextEvent(0, NULL, timeOut, false, &event);
764                  }
765                  
766                  if (timerMgr->fireTimers(getMilliSeconds())) {
767                  anyProcessed = true;
768                  }*/
769                 
770                 do {
771                         NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
772                         event = [NSApp nextEventMatchingMask:NSAnyEventMask
773                                                                            untilDate:[NSDate distantPast]
774                                                                                   inMode:NSDefaultRunLoopMode
775                                                                                  dequeue:YES];
776                         if (event==nil) {
777                                 [pool drain];
778                                 break;
779                         }
780                         
781                         anyProcessed = true;
782                         
783                         switch ([event type]) {
784                                 case NSKeyDown:
785                                 case NSKeyUp:
786                                 case NSFlagsChanged:
787                                         handleKeyEvent(event);
788                                         
789                                         /* Support system-wide keyboard shortcuts, like Expos√©, ...) =>included in always NSApp sendEvent */
790                                         /*              if (([event modifierFlags] & NSCommandKeyMask) || [event type] == NSFlagsChanged) {
791                                          [NSApp sendEvent:event];
792                                          }*/
793                                         break;
794                                         
795                                 case NSLeftMouseDown:
796                                 case NSLeftMouseUp:
797                                 case NSRightMouseDown:
798                                 case NSRightMouseUp:
799                                 case NSMouseMoved:
800                                 case NSLeftMouseDragged:
801                                 case NSRightMouseDragged:
802                                 case NSScrollWheel:
803                                 case NSOtherMouseDown:
804                                 case NSOtherMouseUp:
805                                 case NSOtherMouseDragged:                               
806                                         handleMouseEvent(event);
807                                         break;
808                                         
809                                 case NSTabletPoint:
810                                 case NSTabletProximity:
811                                         handleTabletEvent(event,[event type]);
812                                         break;
813                                         
814                                         /* Trackpad features, will need OS X 10.6 for implementation
815                                          case NSEventTypeGesture:
816                                          case NSEventTypeMagnify:
817                                          case NSEventTypeSwipe:
818                                          case NSEventTypeRotate:
819                                          case NSEventTypeBeginGesture:
820                                          case NSEventTypeEndGesture:
821                                          break; */
822                                         
823                                         /*Unused events
824                                          NSMouseEntered       = 8,
825                                          NSMouseExited        = 9,
826                                          NSAppKitDefined      = 13,
827                                          NSSystemDefined      = 14,
828                                          NSApplicationDefined = 15,
829                                          NSPeriodic           = 16,
830                                          NSCursorUpdate       = 17,*/
831                                         
832                                 default:
833                                         break;
834                         }
835                         //Resend event to NSApp to ensure Mac wide events are handled
836                         [NSApp sendEvent:event];
837                         [pool drain];
838                 } while (event!= nil);          
839         //} while (waitForEvent && !anyProcessed); Needed only for timer implementation
840         
841         
842         
843     return anyProcessed || m_outsideLoopEventProcessed;
844 }
845
846 //Note: called from NSWindow delegate
847 GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType, GHOST_WindowCocoa* window)
848 {
849         if (!validWindow(window)) {
850                 return GHOST_kFailure;
851         }
852                 switch(eventType) 
853                 {
854                         case GHOST_kEventWindowClose:
855                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window) );
856                                 break;
857                         case GHOST_kEventWindowActivate:
858                                 m_windowManager->setActiveWindow(window);
859                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
860                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window) );
861                                 break;
862                         case GHOST_kEventWindowDeactivate:
863                                 m_windowManager->setWindowInactive(window);
864                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowDeactivate, window) );
865                                 break;
866                         case GHOST_kEventWindowUpdate:
867                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowUpdate, window) );
868                                 break;
869                         case GHOST_kEventWindowSize:
870                                 if (!m_ignoreWindowSizedMessages)
871                                 {
872                                         window->updateDrawingContext();
873                                         pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window) );
874                                 }
875                                 break;
876                         default:
877                                 return GHOST_kFailure;
878                                 break;
879                 }
880         
881         m_outsideLoopEventProcessed = true;
882         return GHOST_kSuccess;
883 }
884
885 //Note: called from NSWindow subclass
886 GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType, GHOST_TDragnDropTypes draggedObjectType,
887                                                                    GHOST_WindowCocoa* window, int mouseX, int mouseY, void* data)
888 {
889         if (!validWindow(window)) {
890                 return GHOST_kFailure;
891         }
892         switch(eventType) 
893         {
894                 case GHOST_kEventDraggingEntered:
895                 case GHOST_kEventDraggingUpdated:
896                 case GHOST_kEventDraggingExited:
897                         pushEvent(new GHOST_EventDragnDrop(getMilliSeconds(),eventType,draggedObjectType,window,mouseX,mouseY,NULL));
898                         break;
899                         
900                 case GHOST_kEventDraggingDropDone:
901                 case GHOST_kEventDraggingDropOnIcon:
902                 {
903                         GHOST_TUns8 * temp_buff;
904                         GHOST_TStringArray *strArray;
905                         NSArray *droppedArray;
906                         size_t pastedTextSize;  
907                         NSString *droppedStr;
908                         GHOST_TEventDataPtr eventData;
909                         int i;
910
911                         if (!data) return GHOST_kFailure;
912                         
913                         switch (draggedObjectType) {
914                                 case GHOST_kDragnDropTypeBitmap:
915                                         //TODO: implement bitmap conversion to a blender friendly format
916                                         return GHOST_kFailure;
917                                         break;
918                                 case GHOST_kDragnDropTypeFilenames:
919                                         droppedArray = (NSArray*)data;
920                                         
921                                         strArray = (GHOST_TStringArray*)malloc(sizeof(GHOST_TStringArray));
922                                         if (!strArray) return GHOST_kFailure;
923                                         
924                                         strArray->count = [droppedArray count];
925                                         if (strArray->count == 0) return GHOST_kFailure;
926                                         
927                                         strArray->strings = (GHOST_TUns8**) malloc(strArray->count*sizeof(GHOST_TUns8*));
928                                         
929                                         for (i=0;i<strArray->count;i++)
930                                         {
931                                                 droppedStr = [droppedArray objectAtIndex:i];
932                                                 
933                                                 pastedTextSize = [droppedStr lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
934                                                 temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
935                                         
936                                                 if (!temp_buff) {
937                                                         strArray->count = i;
938                                                         break;
939                                                 }
940                                         
941                                                 strncpy((char*)temp_buff, [droppedStr cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
942                                                 temp_buff[pastedTextSize] = '\0';
943                                                 
944                                                 strArray->strings[i] = temp_buff;
945                                         }
946
947                                         eventData = (GHOST_TEventDataPtr) strArray;     
948                                         break;
949                                         
950                                 case GHOST_kDragnDropTypeString:
951                                         droppedStr = (NSString*)data;
952                                         pastedTextSize = [droppedStr lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
953                                         
954                                         temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
955                                         
956                                         if (temp_buff == NULL) {
957                                                 return GHOST_kFailure;
958                                         }
959                                         
960                                         strncpy((char*)temp_buff, [droppedStr cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
961                                         
962                                         temp_buff[pastedTextSize] = '\0';
963                                         
964                                         eventData = (GHOST_TEventDataPtr) temp_buff;
965                                         break;
966                                         
967                                 default:
968                                         return GHOST_kFailure;
969                                         break;
970                         }
971                         pushEvent(new GHOST_EventDragnDrop(getMilliSeconds(),eventType,draggedObjectType,window,mouseX,mouseY,eventData));
972                 }
973                         break;
974                 default:
975                         return GHOST_kFailure;
976         }
977         m_outsideLoopEventProcessed = true;
978         return GHOST_kSuccess;
979 }
980
981
982 GHOST_TUns8 GHOST_SystemCocoa::handleQuitRequest()
983 {
984         GHOST_Window* window = (GHOST_Window*)m_windowManager->getActiveWindow();
985         
986         //Discard quit event if we are in cursor grab sequence
987         if (window && (window->getCursorGrabMode() != GHOST_kGrabDisable) && (window->getCursorGrabMode() != GHOST_kGrabNormal))
988                 return GHOST_kExitCancel;
989         
990         //Check open windows if some changes are not saved
991         if (m_windowManager->getAnyModifiedState())
992         {
993                 int shouldQuit = NSRunAlertPanel(@"Exit Blender", @"Some changes have not been saved.\nDo you really want to quit ?",
994                                                                                  @"Cancel", @"Quit Anyway", nil);
995                 if (shouldQuit == NSAlertAlternateReturn)
996                 {
997                         pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL) );
998                         return GHOST_kExitNow;
999                 } else {
1000                         //Give back focus to the blender window if user selected cancel quit
1001                         NSArray *windowsList = [NSApp orderedWindows];
1002                         if ([windowsList count]) {
1003                                 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
1004                         }
1005                 }
1006
1007         }
1008         else {
1009                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL) );
1010                 m_outsideLoopEventProcessed = true;
1011                 return GHOST_kExitNow;
1012         }
1013         
1014         return GHOST_kExitCancel;
1015 }
1016
1017
1018 GHOST_TSuccess GHOST_SystemCocoa::handleTabletEvent(void *eventPtr, short eventType)
1019 {
1020         NSEvent *event = (NSEvent *)eventPtr;
1021         GHOST_IWindow* window = m_windowManager->getActiveWindow();
1022         
1023         if (!window) return GHOST_kFailure;
1024         
1025         GHOST_TabletData& ct=((GHOST_WindowCocoa*)window)->GetCocoaTabletData();
1026         
1027         switch (eventType) {
1028                 case NSTabletPoint:
1029                         ct.Pressure = [event pressure];
1030                         ct.Xtilt = [event tilt].x;
1031                         ct.Ytilt = [event tilt].y;
1032                         break;
1033                 
1034                 case NSTabletProximity:
1035                         ct.Pressure = 0;
1036                         ct.Xtilt = 0;
1037                         ct.Ytilt = 0;
1038                         if ([event isEnteringProximity])
1039                         {
1040                                 //pointer is entering tablet area proximity
1041                                 switch ([event pointingDeviceType]) {
1042                                         case NSPenPointingDevice:
1043                                                 ct.Active = GHOST_kTabletModeStylus;
1044                                                 break;
1045                                         case NSEraserPointingDevice:
1046                                                 ct.Active = GHOST_kTabletModeEraser;
1047                                                 break;
1048                                         case NSCursorPointingDevice:
1049                                         case NSUnknownPointingDevice:
1050                                         default:
1051                                                 ct.Active = GHOST_kTabletModeNone;
1052                                                 break;
1053                                 }
1054                         } else {
1055                                 // pointer is leaving - return to mouse
1056                                 ct.Active = GHOST_kTabletModeNone;
1057                         }
1058                         break;
1059                 
1060                 default:
1061                         GHOST_ASSERT(FALSE,"GHOST_SystemCocoa::handleTabletEvent : unknown event received");
1062                         return GHOST_kFailure;
1063                         break;
1064         }
1065         return GHOST_kSuccess;
1066 }
1067
1068
1069 GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
1070 {
1071         NSEvent *event = (NSEvent *)eventPtr;
1072     GHOST_Window* window = (GHOST_Window*)m_windowManager->getActiveWindow();
1073         
1074         if (!window) {
1075                 return GHOST_kFailure;
1076         }
1077         
1078         switch ([event type])
1079     {
1080                 case NSLeftMouseDown:
1081                 case NSRightMouseDown:
1082                 case NSOtherMouseDown:
1083                         pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonDown, window, convertButton([event buttonNumber])));
1084                         //Handle tablet events combined with mouse events
1085                         switch ([event subtype]) {
1086                                 case NX_SUBTYPE_TABLET_POINT:
1087                                         handleTabletEvent(eventPtr, NSTabletPoint);
1088                                         break;
1089                                 case NX_SUBTYPE_TABLET_PROXIMITY:
1090                                         handleTabletEvent(eventPtr, NSTabletProximity);
1091                                         break;
1092                                 default:
1093                                         //No tablet event included : do nothing
1094                                         break;
1095                         }
1096                         break;
1097                                                 
1098                 case NSLeftMouseUp:
1099                 case NSRightMouseUp:
1100                 case NSOtherMouseUp:
1101                         pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonUp, window, convertButton([event buttonNumber])));
1102                         //Handle tablet events combined with mouse events
1103                         switch ([event subtype]) {
1104                                 case NX_SUBTYPE_TABLET_POINT:
1105                                         handleTabletEvent(eventPtr, NSTabletPoint);
1106                                         break;
1107                                 case NX_SUBTYPE_TABLET_PROXIMITY:
1108                                         handleTabletEvent(eventPtr, NSTabletProximity);
1109                                         break;
1110                                 default:
1111                                         //No tablet event included : do nothing
1112                                         break;
1113                         }
1114                         break;
1115                         
1116                 case NSLeftMouseDragged:
1117                 case NSRightMouseDragged:
1118                 case NSOtherMouseDragged:                               
1119                         //Handle tablet events combined with mouse events
1120                         switch ([event subtype]) {
1121                                 case NX_SUBTYPE_TABLET_POINT:
1122                                         handleTabletEvent(eventPtr, NSTabletPoint);
1123                                         break;
1124                                 case NX_SUBTYPE_TABLET_PROXIMITY:
1125                                         handleTabletEvent(eventPtr, NSTabletProximity);
1126                                         break;
1127                                 default:
1128                                         //No tablet event included : do nothing
1129                                         break;
1130                         }
1131                         
1132                 case NSMouseMoved:
1133                                 switch (window->getCursorGrabMode()) {
1134                                         case GHOST_kGrabHide: //Cursor hidden grab operation : no cursor move
1135                                         {
1136                                                 GHOST_TInt32 x_warp, y_warp, x_accum, y_accum;
1137                                                 
1138                                                 window->getCursorGrabInitPos(x_warp, y_warp);
1139                                                 
1140                                                 window->getCursorGrabAccum(x_accum, y_accum);
1141                                                 x_accum += [event deltaX];
1142                                                 y_accum += -[event deltaY]; //Strange Apple implementation (inverted coordinates for the deltaY) ...
1143                                                 window->setCursorGrabAccum(x_accum, y_accum);
1144                                                 
1145                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_warp+x_accum, y_warp+y_accum));
1146                                         }
1147                                                 break;
1148                                         case GHOST_kGrabWrap: //Wrap cursor at area/window boundaries
1149                                         {
1150                                                 NSPoint mousePos = [event locationInWindow];
1151                                                 GHOST_TInt32 x_mouse= mousePos.x;
1152                                                 GHOST_TInt32 y_mouse= mousePos.y;
1153                                                 GHOST_TInt32 x_accum, y_accum, x_cur, y_cur;
1154                                                 GHOST_Rect bounds, windowBounds, correctedBounds;
1155                                                 
1156                                                 /* fallback to window bounds */
1157                                                 if(window->getCursorGrabBounds(bounds)==GHOST_kFailure)
1158                                                         window->getClientBounds(bounds);
1159                                                 
1160                                                 //Switch back to Cocoa coordinates orientation (y=0 at botton,the same as blender internal btw!), and to client coordinates
1161                                                 window->getClientBounds(windowBounds);
1162                                                 window->screenToClient(bounds.m_l,bounds.m_b, correctedBounds.m_l, correctedBounds.m_t);
1163                                                 window->screenToClient(bounds.m_r, bounds.m_t, correctedBounds.m_r, correctedBounds.m_b);
1164                                                 correctedBounds.m_b = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_b;
1165                                                 correctedBounds.m_t = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_t;
1166                                                 
1167                                                 //Update accumulation counts
1168                                                 window->getCursorGrabAccum(x_accum, y_accum);
1169                                                 x_accum += [event deltaX]-m_cursorDelta_x;
1170                                                 y_accum += -[event deltaY]-m_cursorDelta_y; //Strange Apple implementation (inverted coordinates for the deltaY) ...
1171                                                 window->setCursorGrabAccum(x_accum, y_accum);
1172                                                 
1173                                                 
1174                                                 //Warp mouse cursor if needed
1175                                                 x_mouse += [event deltaX]-m_cursorDelta_x;
1176                                                 y_mouse += -[event deltaY]-m_cursorDelta_y;
1177                                                 correctedBounds.wrapPoint(x_mouse, y_mouse, 2);
1178                                                 
1179                                                 //Compensate for mouse moved event taking cursor position set into account
1180                                                 m_cursorDelta_x = x_mouse-mousePos.x;
1181                                                 m_cursorDelta_y = y_mouse-mousePos.y;
1182                                                 
1183                                                 //Set new cursor position
1184                                                 window->clientToScreen(x_mouse, y_mouse, x_cur, y_cur);
1185                                                 setCursorPosition(x_cur, y_cur); /* wrap */
1186                                                 
1187                                                 //Post event
1188                                                 window->getCursorGrabInitPos(x_cur, y_cur);
1189                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_cur + x_accum, y_cur + y_accum));
1190                                         }
1191                                                 break;
1192                                         default:
1193                                         {
1194                                                 //Normal cursor operation: send mouse position in window
1195                                                 NSPoint mousePos = [event locationInWindow];
1196                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, mousePos.x, mousePos.y));
1197                                                 m_cursorDelta_x=0;
1198                                                 m_cursorDelta_y=0; //Mouse motion occured between two cursor warps, so we can reset the delta counter
1199                                         }
1200                                                 break;
1201                                 }
1202                                 break;
1203                         
1204                 case NSScrollWheel:
1205                         {
1206                                 GHOST_TInt32 delta;
1207                                 
1208                                 double deltaF = [event deltaY];
1209                                 if (deltaF == 0.0) break; //discard trackpad delta=0 events
1210                                 
1211                                 delta = deltaF > 0.0 ? 1 : -1;
1212                                 pushEvent(new GHOST_EventWheel([event timestamp]*1000, window, delta));
1213                         }
1214                         break;
1215                         
1216                 default:
1217                         return GHOST_kFailure;
1218                         break;
1219                 }
1220         
1221         return GHOST_kSuccess;
1222 }
1223
1224
1225 GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
1226 {
1227         NSEvent *event = (NSEvent *)eventPtr;
1228         GHOST_IWindow* window = m_windowManager->getActiveWindow();
1229         unsigned int modifiers;
1230         NSString *characters;
1231         NSData *convertedCharacters;
1232         GHOST_TKey keyCode;
1233         unsigned char ascii;
1234         NSString* charsIgnoringModifiers;
1235
1236         /* Can happen, very rarely - seems to only be when command-H makes
1237          * the window go away and we still get an HKey up. 
1238          */
1239         if (!window) {
1240                 printf("\nW failure");
1241                 return GHOST_kFailure;
1242         }
1243         
1244         switch ([event type]) {
1245                 case NSKeyDown:
1246                 case NSKeyUp:
1247                         charsIgnoringModifiers = [event charactersIgnoringModifiers];
1248                         if ([charsIgnoringModifiers length]>0)
1249                                 keyCode = convertKey([event keyCode],
1250                                                                          [charsIgnoringModifiers characterAtIndex:0]);
1251                         else
1252                                 keyCode = convertKey([event keyCode],0);
1253
1254                                 
1255                         characters = [event characters];
1256                         if ([characters length]>0) { //Check for dead keys
1257                                 //Convert characters to iso latin 1 encoding
1258                                 convertedCharacters = [characters dataUsingEncoding:NSISOLatin1StringEncoding];
1259                                 if ([convertedCharacters length]>0)
1260                                         ascii =((char*)[convertedCharacters bytes])[0];
1261                                 else
1262                                         ascii = 0; //Character not available in iso latin 1 encoding
1263                         }
1264                         else
1265                                 ascii= 0;
1266                         
1267                         if ((keyCode == GHOST_kKeyQ) && (m_modifierMask & NSCommandKeyMask))
1268                                 break; //Cmd-Q is directly handled by Cocoa
1269
1270                         if ([event type] == NSKeyDown) {
1271                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyDown, window, keyCode, ascii) );
1272                                 //printf("\nKey pressed keyCode=%u ascii=%i %c",keyCode,ascii,ascii);
1273                         } else {
1274                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyUp, window, keyCode, ascii) );
1275                         }
1276                         break;
1277         
1278                 case NSFlagsChanged: 
1279                         modifiers = [event modifierFlags];
1280                         if ((modifiers & NSShiftKeyMask) != (m_modifierMask & NSShiftKeyMask)) {
1281                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSShiftKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift) );
1282                         }
1283                         if ((modifiers & NSControlKeyMask) != (m_modifierMask & NSControlKeyMask)) {
1284                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSControlKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl) );
1285                         }
1286                         if ((modifiers & NSAlternateKeyMask) != (m_modifierMask & NSAlternateKeyMask)) {
1287                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSAlternateKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt) );
1288                         }
1289                         if ((modifiers & NSCommandKeyMask) != (m_modifierMask & NSCommandKeyMask)) {
1290                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSCommandKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyCommand) );
1291                         }
1292                         
1293                         m_modifierMask = modifiers;
1294                         break;
1295                         
1296                 default:
1297                         return GHOST_kFailure;
1298                         break;
1299         }
1300         
1301         return GHOST_kSuccess;
1302 }
1303
1304
1305
1306 #pragma mark Clipboard get/set
1307
1308 GHOST_TUns8* GHOST_SystemCocoa::getClipboard(bool selection) const
1309 {
1310         GHOST_TUns8 * temp_buff;
1311         size_t pastedTextSize;  
1312         
1313         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1314         
1315         NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
1316         
1317         if (pasteBoard == nil) {
1318                 [pool drain];
1319                 return NULL;
1320         }
1321         
1322         NSArray *supportedTypes =
1323                 [NSArray arrayWithObjects: NSStringPboardType, nil];
1324         
1325         NSString *bestType = [[NSPasteboard generalPasteboard]
1326                                                   availableTypeFromArray:supportedTypes];
1327         
1328         if (bestType == nil) {
1329                 [pool drain];
1330                 return NULL;
1331         }
1332         
1333         NSString * textPasted = [pasteBoard stringForType:NSStringPboardType];
1334
1335         if (textPasted == nil) {
1336                 [pool drain];
1337                 return NULL;
1338         }
1339         
1340         pastedTextSize = [textPasted lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
1341         
1342         temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
1343
1344         if (temp_buff == NULL) {
1345                 [pool drain];
1346                 return NULL;
1347         }
1348         
1349         strncpy((char*)temp_buff, [textPasted cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
1350         
1351         temp_buff[pastedTextSize] = '\0';
1352         
1353         [pool drain];
1354
1355         if(temp_buff) {
1356                 return temp_buff;
1357         } else {
1358                 return NULL;
1359         }
1360 }
1361
1362 void GHOST_SystemCocoa::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1363 {
1364         NSString *textToCopy;
1365         
1366         if(selection) {return;} // for copying the selection, used on X11
1367
1368         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1369                 
1370         NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
1371         
1372         if (pasteBoard == nil) {
1373                 [pool drain];
1374                 return;
1375         }
1376         
1377         NSArray *supportedTypes = [NSArray arrayWithObject:NSStringPboardType];
1378         
1379         [pasteBoard declareTypes:supportedTypes owner:nil];
1380         
1381         textToCopy = [NSString stringWithCString:buffer encoding:NSISOLatin1StringEncoding];
1382         
1383         [pasteBoard setString:textToCopy forType:NSStringPboardType];
1384         
1385         [pool drain];
1386 }