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