Drag and drop 2.5 integration! Finally, slashdot regulars can use
[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_isGestureInProgress = false;
520         m_cursorDelta_x=0;
521         m_cursorDelta_y=0;
522         m_outsideLoopEventProcessed = false;
523         m_needDelayedApplicationBecomeActiveEventProcessing = false;
524         m_displayManager = new GHOST_DisplayManagerCocoa ();
525         GHOST_ASSERT(m_displayManager, "GHOST_SystemCocoa::GHOST_SystemCocoa(): m_displayManager==0\n");
526         m_displayManager->initialize();
527
528         //NSEvent timeStamp is given in system uptime, state start date is boot time
529         mib[0] = CTL_KERN;
530         mib[1] = KERN_BOOTTIME;
531         len = sizeof(struct timeval);
532         
533         sysctl(mib, 2, &boottime, &len, NULL, 0);
534         m_start_time = ((boottime.tv_sec*1000)+(boottime.tv_usec/1000));
535         
536         //Detect multitouch trackpad
537         mib[0] = CTL_HW;
538         mib[1] = HW_MODEL;
539         sysctl( mib, 2, NULL, &len, NULL, 0 );
540         rstring = (char*)malloc( len );
541         sysctl( mib, 2, rstring, &len, NULL, 0 );
542         
543         //Hack on MacBook revision, as multitouch avail. function missing
544         if (strstr(rstring,"MacBookAir") ||
545                 (strstr(rstring,"MacBook") && (rstring[strlen(rstring)-3]>='5') && (rstring[strlen(rstring)-3]<='9')))
546                 m_hasMultiTouchTrackpad = true;
547         else m_hasMultiTouchTrackpad = false;
548         
549         free( rstring );
550         rstring = NULL;
551         
552         m_ignoreWindowSizedMessages = false;
553 }
554
555 GHOST_SystemCocoa::~GHOST_SystemCocoa()
556 {
557 }
558
559
560 GHOST_TSuccess GHOST_SystemCocoa::init()
561 {
562         
563     GHOST_TSuccess success = GHOST_System::init();
564     if (success) {
565                 //ProcessSerialNumber psn;
566                 
567                 //Carbon stuff to move window & menu to foreground
568                 /*if (!GetCurrentProcess(&psn)) {
569                         TransformProcessType(&psn, kProcessTransformToForegroundApplication);
570                         SetFrontProcess(&psn);
571                 }*/
572                 
573                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
574                 if (NSApp == nil) {
575                         [NSApplication sharedApplication];
576                         
577                         if ([NSApp mainMenu] == nil) {
578                                 NSMenu *mainMenubar = [[NSMenu alloc] init];
579                                 NSMenuItem *menuItem;
580                                 NSMenu *windowMenu;
581                                 NSMenu *appMenu;
582                                 
583                                 //Create the application menu
584                                 appMenu = [[NSMenu alloc] initWithTitle:@"Blender"];
585                                 
586                                 [appMenu addItemWithTitle:@"About Blender" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
587                                 [appMenu addItem:[NSMenuItem separatorItem]];
588                                 
589                                 menuItem = [appMenu addItemWithTitle:@"Hide Blender" action:@selector(hide:) keyEquivalent:@"h"];
590                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
591                                  
592                                 menuItem = [appMenu addItemWithTitle:@"Hide others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
593                                 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
594                                 
595                                 [appMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
596                                 
597                                 menuItem = [appMenu addItemWithTitle:@"Quit Blender" action:@selector(terminate:) keyEquivalent:@"q"];
598                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
599                                 
600                                 menuItem = [[NSMenuItem alloc] init];
601                                 [menuItem setSubmenu:appMenu];
602                                 
603                                 [mainMenubar addItem:menuItem];
604                                 [menuItem release];
605                                 [NSApp performSelector:@selector(setAppleMenu:) withObject:appMenu]; //Needed for 10.5
606                                 [appMenu release];
607                                 
608                                 //Create the window menu
609                                 windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
610                                 
611                                 menuItem = [windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
612                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
613                                 
614                                 [windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
615                                 
616                                 menuItem = [windowMenu addItemWithTitle:@"Close" action:@selector(performClose:) keyEquivalent:@"w"];
617                                 [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
618                                 
619                                 menuItem = [[NSMenuItem alloc] init];
620                                 [menuItem setSubmenu:windowMenu];
621                                 
622                                 [mainMenubar addItem:menuItem];
623                                 [menuItem release];
624                                 
625                                 [NSApp setMainMenu:mainMenubar];
626                                 [NSApp setWindowsMenu:windowMenu];
627                                 [windowMenu release];
628                         }
629                 }
630                 if ([NSApp delegate] == nil) {
631                         CocoaAppDelegate *appDelegate = [[CocoaAppDelegate alloc] init];
632                         [appDelegate setSystemCocoa:this];
633                         [NSApp setDelegate:appDelegate];
634                 }
635                 
636                 [NSApp finishLaunching];
637                 
638                 [pool drain];
639     }
640     return success;
641 }
642
643
644 #pragma mark window management
645
646 GHOST_TUns64 GHOST_SystemCocoa::getMilliSeconds() const
647 {
648         //Cocoa equivalent exists in 10.6 ([[NSProcessInfo processInfo] systemUptime])
649         struct timeval currentTime;
650         
651         gettimeofday(&currentTime, NULL);
652         
653         //Return timestamp of system uptime
654         
655         return ((currentTime.tv_sec*1000)+(currentTime.tv_usec/1000)-m_start_time);
656 }
657
658
659 GHOST_TUns8 GHOST_SystemCocoa::getNumDisplays() const
660 {
661         //Note that OS X supports monitor hot plug
662         // We do not support multiple monitors at the moment
663         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
664
665         GHOST_TUns8 count = [[NSScreen screens] count];
666
667         [pool drain];
668         return count;
669 }
670
671
672 void GHOST_SystemCocoa::getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const
673 {
674         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
675         //Get visible frame, that is frame excluding dock and top menu bar
676         NSRect frame = [[NSScreen mainScreen] visibleFrame];
677         
678         //Returns max window contents (excluding title bar...)
679         NSRect contentRect = [NSWindow contentRectForFrameRect:frame
680                                                                                                  styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask)];
681         
682         width = contentRect.size.width;
683         height = contentRect.size.height;
684
685         [pool drain];
686 }
687
688
689 GHOST_IWindow* GHOST_SystemCocoa::createWindow(
690         const STR_String& title, 
691         GHOST_TInt32 left,
692         GHOST_TInt32 top,
693         GHOST_TUns32 width,
694         GHOST_TUns32 height,
695         GHOST_TWindowState state,
696         GHOST_TDrawingContextType type,
697         bool stereoVisual,
698         const GHOST_TUns16 numOfAASamples,
699         const GHOST_TEmbedderWindowID parentWindow
700 )
701 {
702     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
703         GHOST_IWindow* window = 0;
704         
705         //Get the available rect for including window contents
706         NSRect frame = [[NSScreen mainScreen] visibleFrame];
707         NSRect contentRect = [NSWindow contentRectForFrameRect:frame
708                                                                                                  styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask)];
709         
710         //Ensures window top left is inside this available rect
711         left = left > contentRect.origin.x ? left : contentRect.origin.x;
712         top = top > contentRect.origin.y ? top : contentRect.origin.y;
713         
714         window = new GHOST_WindowCocoa (this, title, left, top, width, height, state, type, stereoVisual, numOfAASamples);
715
716     if (window) {
717         if (window->getValid()) {
718             // Store the pointer to the window 
719             GHOST_ASSERT(m_windowManager, "m_windowManager not initialized");
720             m_windowManager->addWindow(window);
721             m_windowManager->setActiveWindow(window);
722                         //Need to tell window manager the new window is the active one (Cocoa does not send the event activate upon window creation)
723             pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window));
724                         pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window));
725
726         }
727         else {
728                         GHOST_PRINT("GHOST_SystemCocoa::createWindow(): window invalid\n");
729             delete window;
730             window = 0;
731         }
732     }
733         else {
734                 GHOST_PRINT("GHOST_SystemCocoa::createWindow(): could not create window\n");
735         }
736         [pool drain];
737     return window;
738 }
739
740 GHOST_TSuccess GHOST_SystemCocoa::beginFullScreen(const GHOST_DisplaySetting& setting, GHOST_IWindow** window, const bool stereoVisual)
741 {       
742         GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
743
744         *window = currentWindow;
745         
746         return currentWindow->setState(GHOST_kWindowStateFullScreen);
747 }
748
749 GHOST_TSuccess GHOST_SystemCocoa::endFullScreen(void)
750 {       
751         GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
752         
753         return currentWindow->setState(GHOST_kWindowStateNormal);
754 }
755
756
757         
758 /**
759  * @note : returns coordinates in Cocoa screen coordinates
760  */
761 GHOST_TSuccess GHOST_SystemCocoa::getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const
762 {
763     NSPoint mouseLoc = [NSEvent mouseLocation];
764         
765     // Returns the mouse location in screen coordinates
766     x = (GHOST_TInt32)mouseLoc.x;
767     y = (GHOST_TInt32)mouseLoc.y;
768     return GHOST_kSuccess;
769 }
770
771 /**
772  * @note : expect Cocoa screen coordinates
773  */
774 GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y) const
775 {
776         float xf=(float)x, yf=(float)y;
777         GHOST_WindowCocoa* window = (GHOST_WindowCocoa*)m_windowManager->getActiveWindow();
778         NSScreen *windowScreen = window->getScreen();
779         NSRect screenRect = [windowScreen frame];
780         
781         //Set position relative to current screen
782         xf -= screenRect.origin.x;
783         yf -= screenRect.origin.y;
784         
785         //Quartz Display Services uses the old coordinates (top left origin)
786         yf = screenRect.size.height -yf;
787
788         CGDisplayMoveCursorToPoint((CGDirectDisplayID)[[[windowScreen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue], CGPointMake(xf, yf));
789
790     return GHOST_kSuccess;
791 }
792
793
794 GHOST_TSuccess GHOST_SystemCocoa::getModifierKeys(GHOST_ModifierKeys& keys) const
795 {
796         keys.set(GHOST_kModifierKeyCommand, (m_modifierMask & NSCommandKeyMask) ? true : false);
797         keys.set(GHOST_kModifierKeyLeftAlt, (m_modifierMask & NSAlternateKeyMask) ? true : false);
798         keys.set(GHOST_kModifierKeyLeftShift, (m_modifierMask & NSShiftKeyMask) ? true : false);
799         keys.set(GHOST_kModifierKeyLeftControl, (m_modifierMask & NSControlKeyMask) ? true : false);
800         
801     return GHOST_kSuccess;
802 }
803
804 GHOST_TSuccess GHOST_SystemCocoa::getButtons(GHOST_Buttons& buttons) const
805 {
806         buttons.clear();
807     buttons.set(GHOST_kButtonMaskLeft, m_pressedMouseButtons & GHOST_kButtonMaskLeft);
808         buttons.set(GHOST_kButtonMaskRight, m_pressedMouseButtons & GHOST_kButtonMaskRight);
809         buttons.set(GHOST_kButtonMaskMiddle, m_pressedMouseButtons & GHOST_kButtonMaskMiddle);
810         buttons.set(GHOST_kButtonMaskButton4, m_pressedMouseButtons & GHOST_kButtonMaskButton4);
811         buttons.set(GHOST_kButtonMaskButton5, m_pressedMouseButtons & GHOST_kButtonMaskButton5);
812     return GHOST_kSuccess;
813 }
814
815
816
817 #pragma mark Event handlers
818
819 /**
820  * The event queue polling function
821  */
822 bool GHOST_SystemCocoa::processEvents(bool waitForEvent)
823 {
824         bool anyProcessed = false;
825         NSEvent *event;
826         
827         //      SetMouseCoalescingEnabled(false, NULL);
828         //TODO : implement timer ??
829         
830         /*do {
831                 GHOST_TimerManager* timerMgr = getTimerManager();
832                 
833                  if (waitForEvent) {
834                  GHOST_TUns64 next = timerMgr->nextFireTime();
835                  double timeOut;
836                  
837                  if (next == GHOST_kFireTimeNever) {
838                  timeOut = kEventDurationForever;
839                  } else {
840                  timeOut = (double)(next - getMilliSeconds())/1000.0;
841                  if (timeOut < 0.0)
842                  timeOut = 0.0;
843                  }
844                  
845                  ::ReceiveNextEvent(0, NULL, timeOut, false, &event);
846                  }
847                  
848                  if (timerMgr->fireTimers(getMilliSeconds())) {
849                  anyProcessed = true;
850                  }*/
851                 
852                 do {
853                         NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
854                         event = [NSApp nextEventMatchingMask:NSAnyEventMask
855                                                                            untilDate:[NSDate distantPast]
856                                                                                   inMode:NSDefaultRunLoopMode
857                                                                                  dequeue:YES];
858                         if (event==nil) {
859                                 [pool drain];
860                                 break;
861                         }
862                         
863                         anyProcessed = true;
864                         
865                         switch ([event type]) {
866                                 case NSKeyDown:
867                                 case NSKeyUp:
868                                 case NSFlagsChanged:
869                                         handleKeyEvent(event);
870                                         
871                                         /* Support system-wide keyboard shortcuts, like Expos√©, ...) =>included in always NSApp sendEvent */
872                                         /*              if (([event modifierFlags] & NSCommandKeyMask) || [event type] == NSFlagsChanged) {
873                                          [NSApp sendEvent:event];
874                                          }*/
875                                         break;
876                                         
877                                 case NSLeftMouseDown:
878                                 case NSLeftMouseUp:
879                                 case NSRightMouseDown:
880                                 case NSRightMouseUp:
881                                 case NSMouseMoved:
882                                 case NSLeftMouseDragged:
883                                 case NSRightMouseDragged:
884                                 case NSScrollWheel:
885                                 case NSOtherMouseDown:
886                                 case NSOtherMouseUp:
887                                 case NSOtherMouseDragged:
888                                 case NSEventTypeMagnify:
889                                 case NSEventTypeRotate:
890                                 case NSEventTypeBeginGesture:
891                                 case NSEventTypeEndGesture:
892                                         handleMouseEvent(event);
893                                         break;
894                                         
895                                 case NSTabletPoint:
896                                 case NSTabletProximity:
897                                         handleTabletEvent(event,[event type]);
898                                         break;
899                                         
900                                         /* Trackpad features, fired only from OS X 10.5.2
901                                          case NSEventTypeGesture:
902                                          case NSEventTypeSwipe:
903                                          break; */
904                                         
905                                         /*Unused events
906                                          NSMouseEntered       = 8,
907                                          NSMouseExited        = 9,
908                                          NSAppKitDefined      = 13,
909                                          NSSystemDefined      = 14,
910                                          NSApplicationDefined = 15,
911                                          NSPeriodic           = 16,
912                                          NSCursorUpdate       = 17,*/
913                                         
914                                 default:
915                                         break;
916                         }
917                         //Resend event to NSApp to ensure Mac wide events are handled
918                         [NSApp sendEvent:event];
919                         [pool drain];
920                 } while (event!= nil);          
921         //} while (waitForEvent && !anyProcessed); Needed only for timer implementation
922         
923         if (m_needDelayedApplicationBecomeActiveEventProcessing) handleApplicationBecomeActiveEvent();
924         
925         if (m_outsideLoopEventProcessed) {
926                 m_outsideLoopEventProcessed = false;
927                 return true;
928         }
929         
930     return anyProcessed;
931 }
932
933 //Note: called from NSApplication delegate
934 GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
935 {
936         //Update the modifiers key mask, as its status may have changed when the application was not active
937         //(that is when update events are sent to another application)
938         unsigned int modifiers;
939         GHOST_IWindow* window = m_windowManager->getActiveWindow();
940         
941         if (!window) {
942                 m_needDelayedApplicationBecomeActiveEventProcessing = true;
943                 return GHOST_kFailure;
944         }
945         else m_needDelayedApplicationBecomeActiveEventProcessing = false;
946
947 #ifdef MAC_OS_X_VERSION_10_6
948         modifiers = [NSEvent modifierFlags];
949 #else
950         //If build against an older SDK, check if running on 10.6 to use the correct function
951         if ([NSEvent respondsToSelector:@selector(modifierFlags)]) {
952                 modifiers = [NSEvent modifierFlags];
953         }
954         else {
955                 //TODO: need to find a better workaround for the missing cocoa "getModifierFlag" function in 10.4/10.5
956                 modifiers = 0;
957         }
958 #endif
959         
960         /* Discard erroneous 10.6 modifiers values reported when switching back from spaces */
961         if ((modifiers & NSDeviceIndependentModifierFlagsMask) == 0xb00000) modifiers = 0;
962         
963         if ((modifiers & NSShiftKeyMask) != (m_modifierMask & NSShiftKeyMask)) {
964                 pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSShiftKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift) );
965         }
966         if ((modifiers & NSControlKeyMask) != (m_modifierMask & NSControlKeyMask)) {
967                 pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSControlKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl) );
968         }
969         if ((modifiers & NSAlternateKeyMask) != (m_modifierMask & NSAlternateKeyMask)) {
970                 pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSAlternateKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt) );
971         }
972         if ((modifiers & NSCommandKeyMask) != (m_modifierMask & NSCommandKeyMask)) {
973                 pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSCommandKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyCommand) );
974         }
975         
976         m_modifierMask = modifiers;
977         
978         m_outsideLoopEventProcessed = true;
979         return GHOST_kSuccess;
980 }
981
982 //Note: called from NSWindow delegate
983 GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType, GHOST_WindowCocoa* window)
984 {
985         if (!validWindow(window)) {
986                 return GHOST_kFailure;
987         }
988                 switch(eventType) 
989                 {
990                         case GHOST_kEventWindowClose:
991                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window) );
992                                 break;
993                         case GHOST_kEventWindowActivate:
994                                 m_windowManager->setActiveWindow(window);
995                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
996                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window) );
997                                 break;
998                         case GHOST_kEventWindowDeactivate:
999                                 m_windowManager->setWindowInactive(window);
1000                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowDeactivate, window) );
1001                                 break;
1002                         case GHOST_kEventWindowUpdate:
1003                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowUpdate, window) );
1004                                 break;
1005                         case GHOST_kEventWindowMove:
1006                                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowMove, window) );
1007                                 break;
1008                         case GHOST_kEventWindowSize:
1009                                 if (!m_ignoreWindowSizedMessages)
1010                                 {
1011                                         window->updateDrawingContext();
1012                                         pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window) );
1013                                 }
1014                                 break;
1015                         default:
1016                                 return GHOST_kFailure;
1017                                 break;
1018                 }
1019         
1020         m_outsideLoopEventProcessed = true;
1021         return GHOST_kSuccess;
1022 }
1023
1024 //Note: called from NSWindow subclass
1025 GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType, GHOST_TDragnDropTypes draggedObjectType,
1026                                                                    GHOST_WindowCocoa* window, int mouseX, int mouseY, void* data)
1027 {
1028         if (!validWindow(window) && (eventType != GHOST_kEventDraggingDropOnIcon)) {
1029                 return GHOST_kFailure;
1030         }
1031         switch(eventType) 
1032         {
1033                 case GHOST_kEventDraggingEntered:
1034                 case GHOST_kEventDraggingUpdated:
1035                 case GHOST_kEventDraggingExited:
1036                         pushEvent(new GHOST_EventDragnDrop(getMilliSeconds(),eventType,draggedObjectType,window,mouseX,mouseY,NULL));
1037                         break;
1038                         
1039                 case GHOST_kEventDraggingDropDone:
1040                 case GHOST_kEventDraggingDropOnIcon:
1041                 {
1042                         GHOST_TUns8 * temp_buff;
1043                         GHOST_TStringArray *strArray;
1044                         NSArray *droppedArray;
1045                         size_t pastedTextSize;  
1046                         NSString *droppedStr;
1047                         GHOST_TEventDataPtr eventData;
1048                         int i;
1049
1050                         if (!data) return GHOST_kFailure;
1051                         
1052                         switch (draggedObjectType) {
1053                                 case GHOST_kDragnDropTypeBitmap:
1054                                         //TODO: implement bitmap conversion to a blender friendly format
1055                                         return GHOST_kFailure;
1056                                         break;
1057                                 case GHOST_kDragnDropTypeFilenames:
1058                                         droppedArray = (NSArray*)data;
1059                                         
1060                                         strArray = (GHOST_TStringArray*)malloc(sizeof(GHOST_TStringArray));
1061                                         if (!strArray) return GHOST_kFailure;
1062                                         
1063                                         strArray->count = [droppedArray count];
1064                                         if (strArray->count == 0) return GHOST_kFailure;
1065                                         
1066                                         strArray->strings = (GHOST_TUns8**) malloc(strArray->count*sizeof(GHOST_TUns8*));
1067                                         
1068                                         for (i=0;i<strArray->count;i++)
1069                                         {
1070                                                 droppedStr = [droppedArray objectAtIndex:i];
1071                                                 
1072                                                 pastedTextSize = [droppedStr lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
1073                                                 temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
1074                                         
1075                                                 if (!temp_buff) {
1076                                                         strArray->count = i;
1077                                                         break;
1078                                                 }
1079                                         
1080                                                 strncpy((char*)temp_buff, [droppedStr cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
1081                                                 temp_buff[pastedTextSize] = '\0';
1082                                                 
1083                                                 strArray->strings[i] = temp_buff;
1084                                         }
1085
1086                                         eventData = (GHOST_TEventDataPtr) strArray;     
1087                                         break;
1088                                         
1089                                 case GHOST_kDragnDropTypeString:
1090                                         droppedStr = (NSString*)data;
1091                                         pastedTextSize = [droppedStr lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
1092                                         
1093                                         temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
1094                                         
1095                                         if (temp_buff == NULL) {
1096                                                 return GHOST_kFailure;
1097                                         }
1098                                         
1099                                         strncpy((char*)temp_buff, [droppedStr cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
1100                                         
1101                                         temp_buff[pastedTextSize] = '\0';
1102                                         
1103                                         eventData = (GHOST_TEventDataPtr) temp_buff;
1104                                         break;
1105                                         
1106                                 default:
1107                                         return GHOST_kFailure;
1108                                         break;
1109                         }
1110                         pushEvent(new GHOST_EventDragnDrop(getMilliSeconds(),eventType,draggedObjectType,window,mouseX,mouseY,eventData));
1111                 }
1112                         break;
1113                 default:
1114                         return GHOST_kFailure;
1115         }
1116         m_outsideLoopEventProcessed = true;
1117         return GHOST_kSuccess;
1118 }
1119
1120
1121 GHOST_TUns8 GHOST_SystemCocoa::handleQuitRequest()
1122 {
1123         GHOST_Window* window = (GHOST_Window*)m_windowManager->getActiveWindow();
1124         
1125         //Discard quit event if we are in cursor grab sequence
1126         if (window && (window->getCursorGrabMode() != GHOST_kGrabDisable) && (window->getCursorGrabMode() != GHOST_kGrabNormal))
1127                 return GHOST_kExitCancel;
1128         
1129         //Check open windows if some changes are not saved
1130         if (m_windowManager->getAnyModifiedState())
1131         {
1132                 int shouldQuit = NSRunAlertPanel(@"Exit Blender", @"Some changes have not been saved.\nDo you really want to quit ?",
1133                                                                                  @"Cancel", @"Quit Anyway", nil);
1134                 if (shouldQuit == NSAlertAlternateReturn)
1135                 {
1136                         pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL) );
1137                         return GHOST_kExitNow;
1138                 } else {
1139                         //Give back focus to the blender window if user selected cancel quit
1140                         NSArray *windowsList = [NSApp orderedWindows];
1141                         if ([windowsList count]) {
1142                                 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
1143                         }
1144                 }
1145
1146         }
1147         else {
1148                 pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL) );
1149                 m_outsideLoopEventProcessed = true;
1150                 return GHOST_kExitNow;
1151         }
1152         
1153         return GHOST_kExitCancel;
1154 }
1155
1156 bool GHOST_SystemCocoa::handleOpenDocumentRequest(void *filepathStr)
1157 {
1158         NSString *filepath = (NSString*)filepathStr;
1159         int confirmOpen = NSAlertAlternateReturn;
1160         NSArray *windowsList;
1161         
1162         //Check open windows if some changes are not saved
1163         if (m_windowManager->getAnyModifiedState())
1164         {
1165                 confirmOpen = NSRunAlertPanel([NSString stringWithFormat:@"Opening %@",[filepath lastPathComponent]],
1166                                                                                  @"Current document has not been saved.\nDo you really want to proceed?",
1167                                                                                  @"Cancel", @"Open", nil);
1168         }
1169
1170         //Give back focus to the blender window
1171         windowsList = [NSApp orderedWindows];
1172         if ([windowsList count]) {
1173                 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
1174         }
1175
1176         if (confirmOpen == NSAlertAlternateReturn)
1177         {
1178                 handleDraggingEvent(GHOST_kEventDraggingDropOnIcon,GHOST_kDragnDropTypeFilenames,NULL,0,0, [NSArray arrayWithObject:filepath]);
1179                 return YES;
1180         }
1181         else return NO;
1182 }
1183
1184 GHOST_TSuccess GHOST_SystemCocoa::handleTabletEvent(void *eventPtr, short eventType)
1185 {
1186         NSEvent *event = (NSEvent *)eventPtr;
1187         GHOST_IWindow* window = m_windowManager->getActiveWindow();
1188         
1189         if (!window) return GHOST_kFailure;
1190         
1191         GHOST_TabletData& ct=((GHOST_WindowCocoa*)window)->GetCocoaTabletData();
1192         
1193         switch (eventType) {
1194                 case NSTabletPoint:
1195                         ct.Pressure = [event pressure];
1196                         ct.Xtilt = [event tilt].x;
1197                         ct.Ytilt = [event tilt].y;
1198                         break;
1199                 
1200                 case NSTabletProximity:
1201                         ct.Pressure = 0;
1202                         ct.Xtilt = 0;
1203                         ct.Ytilt = 0;
1204                         if ([event isEnteringProximity])
1205                         {
1206                                 //pointer is entering tablet area proximity
1207                                 switch ([event pointingDeviceType]) {
1208                                         case NSPenPointingDevice:
1209                                                 ct.Active = GHOST_kTabletModeStylus;
1210                                                 break;
1211                                         case NSEraserPointingDevice:
1212                                                 ct.Active = GHOST_kTabletModeEraser;
1213                                                 break;
1214                                         case NSCursorPointingDevice:
1215                                         case NSUnknownPointingDevice:
1216                                         default:
1217                                                 ct.Active = GHOST_kTabletModeNone;
1218                                                 break;
1219                                 }
1220                         } else {
1221                                 // pointer is leaving - return to mouse
1222                                 ct.Active = GHOST_kTabletModeNone;
1223                         }
1224                         break;
1225                 
1226                 default:
1227                         GHOST_ASSERT(FALSE,"GHOST_SystemCocoa::handleTabletEvent : unknown event received");
1228                         return GHOST_kFailure;
1229                         break;
1230         }
1231         return GHOST_kSuccess;
1232 }
1233
1234
1235 GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
1236 {
1237         NSEvent *event = (NSEvent *)eventPtr;
1238     GHOST_Window* window = (GHOST_Window*)m_windowManager->getActiveWindow();
1239         
1240         if (!window) {
1241                 return GHOST_kFailure;
1242         }
1243         
1244         switch ([event type])
1245     {
1246                 case NSLeftMouseDown:
1247                 case NSRightMouseDown:
1248                 case NSOtherMouseDown:
1249                         pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonDown, window, convertButton([event buttonNumber])));
1250                         //Handle tablet events combined with mouse events
1251                         switch ([event subtype]) {
1252                                 case NX_SUBTYPE_TABLET_POINT:
1253                                         handleTabletEvent(eventPtr, NSTabletPoint);
1254                                         break;
1255                                 case NX_SUBTYPE_TABLET_PROXIMITY:
1256                                         handleTabletEvent(eventPtr, NSTabletProximity);
1257                                         break;
1258                                 default:
1259                                         //No tablet event included : do nothing
1260                                         break;
1261                         }
1262                         break;
1263                                                 
1264                 case NSLeftMouseUp:
1265                 case NSRightMouseUp:
1266                 case NSOtherMouseUp:
1267                         pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonUp, window, convertButton([event buttonNumber])));
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                         break;
1281                         
1282                 case NSLeftMouseDragged:
1283                 case NSRightMouseDragged:
1284                 case NSOtherMouseDragged:                               
1285                         //Handle tablet events combined with mouse events
1286                         switch ([event subtype]) {
1287                                 case NX_SUBTYPE_TABLET_POINT:
1288                                         handleTabletEvent(eventPtr, NSTabletPoint);
1289                                         break;
1290                                 case NX_SUBTYPE_TABLET_PROXIMITY:
1291                                         handleTabletEvent(eventPtr, NSTabletProximity);
1292                                         break;
1293                                 default:
1294                                         //No tablet event included : do nothing
1295                                         break;
1296                         }
1297                         
1298                 case NSMouseMoved:
1299                                 switch (window->getCursorGrabMode()) {
1300                                         case GHOST_kGrabHide: //Cursor hidden grab operation : no cursor move
1301                                         {
1302                                                 GHOST_TInt32 x_warp, y_warp, x_accum, y_accum;
1303                                                 
1304                                                 window->getCursorGrabInitPos(x_warp, y_warp);
1305                                                 
1306                                                 window->getCursorGrabAccum(x_accum, y_accum);
1307                                                 x_accum += [event deltaX];
1308                                                 y_accum += -[event deltaY]; //Strange Apple implementation (inverted coordinates for the deltaY) ...
1309                                                 window->setCursorGrabAccum(x_accum, y_accum);
1310                                                 
1311                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_warp+x_accum, y_warp+y_accum));
1312                                         }
1313                                                 break;
1314                                         case GHOST_kGrabWrap: //Wrap cursor at area/window boundaries
1315                                         {
1316                                                 NSPoint mousePos = [event locationInWindow];
1317                                                 GHOST_TInt32 x_mouse= mousePos.x;
1318                                                 GHOST_TInt32 y_mouse= mousePos.y;
1319                                                 GHOST_TInt32 x_accum, y_accum, x_cur, y_cur;
1320                                                 GHOST_Rect bounds, windowBounds, correctedBounds;
1321                                                 
1322                                                 /* fallback to window bounds */
1323                                                 if(window->getCursorGrabBounds(bounds)==GHOST_kFailure)
1324                                                         window->getClientBounds(bounds);
1325                                                 
1326                                                 //Switch back to Cocoa coordinates orientation (y=0 at botton,the same as blender internal btw!), and to client coordinates
1327                                                 window->getClientBounds(windowBounds);
1328                                                 window->screenToClient(bounds.m_l,bounds.m_b, correctedBounds.m_l, correctedBounds.m_t);
1329                                                 window->screenToClient(bounds.m_r, bounds.m_t, correctedBounds.m_r, correctedBounds.m_b);
1330                                                 correctedBounds.m_b = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_b;
1331                                                 correctedBounds.m_t = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_t;
1332                                                 
1333                                                 //Update accumulation counts
1334                                                 window->getCursorGrabAccum(x_accum, y_accum);
1335                                                 x_accum += [event deltaX]-m_cursorDelta_x;
1336                                                 y_accum += -[event deltaY]-m_cursorDelta_y; //Strange Apple implementation (inverted coordinates for the deltaY) ...
1337                                                 window->setCursorGrabAccum(x_accum, y_accum);
1338                                                 
1339                                                 
1340                                                 //Warp mouse cursor if needed
1341                                                 x_mouse += [event deltaX]-m_cursorDelta_x;
1342                                                 y_mouse += -[event deltaY]-m_cursorDelta_y;
1343                                                 correctedBounds.wrapPoint(x_mouse, y_mouse, 2);
1344                                                 
1345                                                 //Compensate for mouse moved event taking cursor position set into account
1346                                                 m_cursorDelta_x = x_mouse-mousePos.x;
1347                                                 m_cursorDelta_y = y_mouse-mousePos.y;
1348                                                 
1349                                                 //Set new cursor position
1350                                                 window->clientToScreen(x_mouse, y_mouse, x_cur, y_cur);
1351                                                 setCursorPosition(x_cur, y_cur); /* wrap */
1352                                                 
1353                                                 //Post event
1354                                                 window->getCursorGrabInitPos(x_cur, y_cur);
1355                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_cur + x_accum, y_cur + y_accum));
1356                                         }
1357                                                 break;
1358                                         default:
1359                                         {
1360                                                 //Normal cursor operation: send mouse position in window
1361                                                 NSPoint mousePos = [event locationInWindow];
1362                                                 pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, mousePos.x, mousePos.y));
1363                                                 m_cursorDelta_x=0;
1364                                                 m_cursorDelta_y=0; //Mouse motion occured between two cursor warps, so we can reset the delta counter
1365                                         }
1366                                                 break;
1367                                 }
1368                                 break;
1369                         
1370                 case NSScrollWheel:
1371                         {
1372                                 /* Send trackpad event if inside a trackpad gesture, send wheel event otherwise */
1373                                 if (!m_hasMultiTouchTrackpad || !m_isGestureInProgress) {
1374                                         GHOST_TInt32 delta;
1375                                         
1376                                         double deltaF = [event deltaY];
1377                                         if (deltaF == 0.0) break; //discard trackpad delta=0 events
1378                                         
1379                                         delta = deltaF > 0.0 ? 1 : -1;
1380                                         pushEvent(new GHOST_EventWheel([event timestamp]*1000, window, delta));
1381                                 }
1382                                 else {
1383                                         NSPoint mousePos = [event locationInWindow];
1384                                         double dx = [event deltaX];
1385                                         double dy = -[event deltaY];
1386                                         
1387                                         const double deltaMax = 50.0;
1388                                         
1389                                         if ((dx == 0) && (dy == 0)) break;
1390                                         
1391                                         /* Quadratic acceleration */
1392                                         dx = dx*(fabs(dx)+0.5);
1393                                         if (dx<0.0) dx-=0.5; else dx+=0.5;
1394                                         if (dx< -deltaMax) dx= -deltaMax; else if (dx>deltaMax) dx=deltaMax;
1395                                         
1396                                         dy = dy*(fabs(dy)+0.5);
1397                                         if (dy<0.0) dy-=0.5; else dy+=0.5;
1398                                         if (dy< -deltaMax) dy= -deltaMax; else if (dy>deltaMax) dy=deltaMax;
1399
1400                                         pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventScroll, mousePos.x, mousePos.y, dx, dy));
1401                                 }
1402                         }
1403                         break;
1404                         
1405                 case NSEventTypeMagnify:
1406                         {
1407                                 NSPoint mousePos = [event locationInWindow];
1408                                 pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventMagnify, mousePos.x, mousePos.y,
1409                                                                                                   [event magnification]*250.0 + 0.1, 0));
1410                         }
1411                         break;
1412
1413                 case NSEventTypeRotate:
1414                         {
1415                                 NSPoint mousePos = [event locationInWindow];
1416                                 pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventRotate, mousePos.x, mousePos.y,
1417                                                                                                   -[event rotation] * 5.0, 0));
1418                         }
1419                 case NSEventTypeBeginGesture:
1420                         m_isGestureInProgress = true;
1421                         break;
1422                 case NSEventTypeEndGesture:
1423                         m_isGestureInProgress = false;
1424                         break;
1425                 default:
1426                         return GHOST_kFailure;
1427                         break;
1428                 }
1429         
1430         return GHOST_kSuccess;
1431 }
1432
1433
1434 GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
1435 {
1436         NSEvent *event = (NSEvent *)eventPtr;
1437         GHOST_IWindow* window = m_windowManager->getActiveWindow();
1438         unsigned int modifiers;
1439         NSString *characters;
1440         NSData *convertedCharacters;
1441         GHOST_TKey keyCode;
1442         unsigned char ascii;
1443         NSString* charsIgnoringModifiers;
1444
1445         /* Can happen, very rarely - seems to only be when command-H makes
1446          * the window go away and we still get an HKey up. 
1447          */
1448         if (!window) {
1449                 //printf("\nW failure");
1450                 return GHOST_kFailure;
1451         }
1452         
1453         switch ([event type]) {
1454                 case NSKeyDown:
1455                 case NSKeyUp:
1456                         charsIgnoringModifiers = [event charactersIgnoringModifiers];
1457                         if ([charsIgnoringModifiers length]>0)
1458                                 keyCode = convertKey([event keyCode],
1459                                                                          [charsIgnoringModifiers characterAtIndex:0]);
1460                         else
1461                                 keyCode = convertKey([event keyCode],0);
1462
1463                                 
1464                         characters = [event characters];
1465                         if ([characters length]>0) { //Check for dead keys
1466                                 //Convert characters to iso latin 1 encoding
1467                                 convertedCharacters = [characters dataUsingEncoding:NSISOLatin1StringEncoding];
1468                                 if ([convertedCharacters length]>0)
1469                                         ascii =((char*)[convertedCharacters bytes])[0];
1470                                 else
1471                                         ascii = 0; //Character not available in iso latin 1 encoding
1472                         }
1473                         else
1474                                 ascii= 0;
1475                         
1476                         if ((keyCode == GHOST_kKeyQ) && (m_modifierMask & NSCommandKeyMask))
1477                                 break; //Cmd-Q is directly handled by Cocoa
1478
1479                         if ([event type] == NSKeyDown) {
1480                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyDown, window, keyCode, ascii) );
1481                                 //printf("\nKey pressed keyCode=%u ascii=%i %c",keyCode,ascii,ascii);
1482                         } else {
1483                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyUp, window, keyCode, ascii) );
1484                         }
1485                         break;
1486         
1487                 case NSFlagsChanged: 
1488                         modifiers = [event modifierFlags];
1489                         if ((modifiers & NSShiftKeyMask) != (m_modifierMask & NSShiftKeyMask)) {
1490                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSShiftKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift) );
1491                         }
1492                         if ((modifiers & NSControlKeyMask) != (m_modifierMask & NSControlKeyMask)) {
1493                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSControlKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl) );
1494                         }
1495                         if ((modifiers & NSAlternateKeyMask) != (m_modifierMask & NSAlternateKeyMask)) {
1496                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSAlternateKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt) );
1497                         }
1498                         if ((modifiers & NSCommandKeyMask) != (m_modifierMask & NSCommandKeyMask)) {
1499                                 pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSCommandKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyCommand) );
1500                         }
1501                         
1502                         m_modifierMask = modifiers;
1503                         break;
1504                         
1505                 default:
1506                         return GHOST_kFailure;
1507                         break;
1508         }
1509         
1510         return GHOST_kSuccess;
1511 }
1512
1513
1514
1515 #pragma mark Clipboard get/set
1516
1517 GHOST_TUns8* GHOST_SystemCocoa::getClipboard(bool selection) const
1518 {
1519         GHOST_TUns8 * temp_buff;
1520         size_t pastedTextSize;  
1521         
1522         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1523         
1524         NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
1525         
1526         if (pasteBoard == nil) {
1527                 [pool drain];
1528                 return NULL;
1529         }
1530         
1531         NSArray *supportedTypes =
1532                 [NSArray arrayWithObjects: NSStringPboardType, nil];
1533         
1534         NSString *bestType = [[NSPasteboard generalPasteboard]
1535                                                   availableTypeFromArray:supportedTypes];
1536         
1537         if (bestType == nil) {
1538                 [pool drain];
1539                 return NULL;
1540         }
1541         
1542         NSString * textPasted = [pasteBoard stringForType:NSStringPboardType];
1543
1544         if (textPasted == nil) {
1545                 [pool drain];
1546                 return NULL;
1547         }
1548         
1549         pastedTextSize = [textPasted lengthOfBytesUsingEncoding:NSISOLatin1StringEncoding];
1550         
1551         temp_buff = (GHOST_TUns8*) malloc(pastedTextSize+1); 
1552
1553         if (temp_buff == NULL) {
1554                 [pool drain];
1555                 return NULL;
1556         }
1557         
1558         strncpy((char*)temp_buff, [textPasted cStringUsingEncoding:NSISOLatin1StringEncoding], pastedTextSize);
1559         
1560         temp_buff[pastedTextSize] = '\0';
1561         
1562         [pool drain];
1563
1564         if(temp_buff) {
1565                 return temp_buff;
1566         } else {
1567                 return NULL;
1568         }
1569 }
1570
1571 void GHOST_SystemCocoa::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1572 {
1573         NSString *textToCopy;
1574         
1575         if(selection) {return;} // for copying the selection, used on X11
1576
1577         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1578                 
1579         NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
1580         
1581         if (pasteBoard == nil) {
1582                 [pool drain];
1583                 return;
1584         }
1585         
1586         NSArray *supportedTypes = [NSArray arrayWithObject:NSStringPboardType];
1587         
1588         [pasteBoard declareTypes:supportedTypes owner:nil];
1589         
1590         textToCopy = [NSString stringWithCString:buffer encoding:NSISOLatin1StringEncoding];
1591         
1592         [pasteBoard setString:textToCopy forType:NSStringPboardType];
1593         
1594         [pool drain];
1595 }