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