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