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