f5a968aa90689e38089015a8897f2c0ee7be2604
[qemu] / cocoa.m
1 /*
2  * QEMU Cocoa CG display driver
3  *
4  * Copyright (c) 2008 Mike Kronenberg
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 #import <Cocoa/Cocoa.h>
26
27 #include "qemu-common.h"
28 #include "console.h"
29 #include "sysemu.h"
30
31
32 //#define DEBUG
33
34 #ifdef DEBUG
35 #define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
36 #else
37 #define COCOA_DEBUG(...)  ((void) 0)
38 #endif
39
40 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
41 #define COCOA_MOUSE_EVENT \
42         if (isTabletEnabled) { \
43             kbd_mouse_event((int)(p.x * 0x7FFF / (screen.width - 1)), (int)((screen.height - p.y) * 0x7FFF / (screen.height - 1)), 0, buttons); \
44         } else if (isMouseGrabed) { \
45             kbd_mouse_event((int)[event deltaX], (int)[event deltaY], 0, buttons); \
46         } else { \
47             [NSApp sendEvent:event]; \
48         }
49
50 typedef struct {
51     int width;
52     int height;
53     int bitsPerComponent;
54     int bitsPerPixel;
55 } QEMUScreen;
56
57 int qemu_main(int argc, char **argv); // main defined in qemu/vl.c
58 NSWindow *normalWindow;
59 id cocoaView;
60 static void *screenBuffer;
61
62 int gArgc;
63 char **gArgv;
64
65 // keymap conversion
66 int keymap[] =
67 {
68 //  SdlI    macI    macH    SdlH    104xtH  104xtC  sdl
69     30, //  0       0x00    0x1e            A       QZ_a
70     31, //  1       0x01    0x1f            S       QZ_s
71     32, //  2       0x02    0x20            D       QZ_d
72     33, //  3       0x03    0x21            F       QZ_f
73     35, //  4       0x04    0x23            H       QZ_h
74     34, //  5       0x05    0x22            G       QZ_g
75     44, //  6       0x06    0x2c            Z       QZ_z
76     45, //  7       0x07    0x2d            X       QZ_x
77     46, //  8       0x08    0x2e            C       QZ_c
78     47, //  9       0x09    0x2f            V       QZ_v
79     0,  //  10      0x0A    Undefined
80     48, //  11      0x0B    0x30            B       QZ_b
81     16, //  12      0x0C    0x10            Q       QZ_q
82     17, //  13      0x0D    0x11            W       QZ_w
83     18, //  14      0x0E    0x12            E       QZ_e
84     19, //  15      0x0F    0x13            R       QZ_r
85     21, //  16      0x10    0x15            Y       QZ_y
86     20, //  17      0x11    0x14            T       QZ_t
87     2,  //  18      0x12    0x02            1       QZ_1
88     3,  //  19      0x13    0x03            2       QZ_2
89     4,  //  20      0x14    0x04            3       QZ_3
90     5,  //  21      0x15    0x05            4       QZ_4
91     7,  //  22      0x16    0x07            6       QZ_6
92     6,  //  23      0x17    0x06            5       QZ_5
93     13, //  24      0x18    0x0d            =       QZ_EQUALS
94     10, //  25      0x19    0x0a            9       QZ_9
95     8,  //  26      0x1A    0x08            7       QZ_7
96     12, //  27      0x1B    0x0c            -       QZ_MINUS
97     9,  //  28      0x1C    0x09            8       QZ_8
98     11, //  29      0x1D    0x0b            0       QZ_0
99     27, //  30      0x1E    0x1b            ]       QZ_RIGHTBRACKET
100     24, //  31      0x1F    0x18            O       QZ_o
101     22, //  32      0x20    0x16            U       QZ_u
102     26, //  33      0x21    0x1a            [       QZ_LEFTBRACKET
103     23, //  34      0x22    0x17            I       QZ_i
104     25, //  35      0x23    0x19            P       QZ_p
105     28, //  36      0x24    0x1c            ENTER   QZ_RETURN
106     38, //  37      0x25    0x26            L       QZ_l
107     36, //  38      0x26    0x24            J       QZ_j
108     40, //  39      0x27    0x28            '       QZ_QUOTE
109     37, //  40      0x28    0x25            K       QZ_k
110     39, //  41      0x29    0x27            ;       QZ_SEMICOLON
111     43, //  42      0x2A    0x2b            \       QZ_BACKSLASH
112     51, //  43      0x2B    0x33            ,       QZ_COMMA
113     53, //  44      0x2C    0x35            /       QZ_SLASH
114     49, //  45      0x2D    0x31            N       QZ_n
115     50, //  46      0x2E    0x32            M       QZ_m
116     52, //  47      0x2F    0x34            .       QZ_PERIOD
117     15, //  48      0x30    0x0f            TAB     QZ_TAB
118     57, //  49      0x31    0x39            SPACE   QZ_SPACE
119     41, //  50      0x32    0x29            `       QZ_BACKQUOTE
120     14, //  51      0x33    0x0e            BKSP    QZ_BACKSPACE
121     0,  //  52      0x34    Undefined
122     1,  //  53      0x35    0x01            ESC     QZ_ESCAPE
123     0,  //  54      0x36                            QZ_RMETA
124     0,  //  55      0x37                            QZ_LMETA
125     42, //  56      0x38    0x2a            L SHFT  QZ_LSHIFT
126     58, //  57      0x39    0x3a            CAPS    QZ_CAPSLOCK
127     56, //  58      0x3A    0x38            L ALT   QZ_LALT
128     29, //  59      0x3B    0x1d            L CTRL  QZ_LCTRL
129     54, //  60      0x3C    0x36            R SHFT  QZ_RSHIFT
130     184,//  61      0x3D    0xb8    E0,38   R ALT   QZ_RALT
131     157,//  62      0x3E    0x9d    E0,1D   R CTRL  QZ_RCTRL
132     0,  //  63      0x3F    Undefined
133     0,  //  64      0x40    Undefined
134     0,  //  65      0x41    Undefined
135     0,  //  66      0x42    Undefined
136     55, //  67      0x43    0x37            KP *    QZ_KP_MULTIPLY
137     0,  //  68      0x44    Undefined
138     78, //  69      0x45    0x4e            KP +    QZ_KP_PLUS
139     0,  //  70      0x46    Undefined
140     69, //  71      0x47    0x45            NUM     QZ_NUMLOCK
141     0,  //  72      0x48    Undefined
142     0,  //  73      0x49    Undefined
143     0,  //  74      0x4A    Undefined
144     181,//  75      0x4B    0xb5    E0,35   KP /    QZ_KP_DIVIDE
145     152,//  76      0x4C    0x9c    E0,1C   KP EN   QZ_KP_ENTER
146     0,  //  77      0x4D    undefined
147     74, //  78      0x4E    0x4a            KP -    QZ_KP_MINUS
148     0,  //  79      0x4F    Undefined
149     0,  //  80      0x50    Undefined
150     0,  //  81      0x51                            QZ_KP_EQUALS
151     82, //  82      0x52    0x52            KP 0    QZ_KP0
152     79, //  83      0x53    0x4f            KP 1    QZ_KP1
153     80, //  84      0x54    0x50            KP 2    QZ_KP2
154     81, //  85      0x55    0x51            KP 3    QZ_KP3
155     75, //  86      0x56    0x4b            KP 4    QZ_KP4
156     76, //  87      0x57    0x4c            KP 5    QZ_KP5
157     77, //  88      0x58    0x4d            KP 6    QZ_KP6
158     71, //  89      0x59    0x47            KP 7    QZ_KP7
159     0,  //  90      0x5A    Undefined
160     72, //  91      0x5B    0x48            KP 8    QZ_KP8
161     73, //  92      0x5C    0x49            KP 9    QZ_KP9
162     0,  //  93      0x5D    Undefined
163     0,  //  94      0x5E    Undefined
164     0,  //  95      0x5F    Undefined
165     63, //  96      0x60    0x3f            F5      QZ_F5
166     64, //  97      0x61    0x40            F6      QZ_F6
167     65, //  98      0x62    0x41            F7      QZ_F7
168     61, //  99      0x63    0x3d            F3      QZ_F3
169     66, //  100     0x64    0x42            F8      QZ_F8
170     67, //  101     0x65    0x43            F9      QZ_F9
171     0,  //  102     0x66    Undefined
172     87, //  103     0x67    0x57            F11     QZ_F11
173     0,  //  104     0x68    Undefined
174     183,//  105     0x69    0xb7                    QZ_PRINT
175     0,  //  106     0x6A    Undefined
176     70, //  107     0x6B    0x46            SCROLL  QZ_SCROLLOCK
177     0,  //  108     0x6C    Undefined
178     68, //  109     0x6D    0x44            F10     QZ_F10
179     0,  //  110     0x6E    Undefined
180     88, //  111     0x6F    0x58            F12     QZ_F12
181     0,  //  112     0x70    Undefined
182     110,//  113     0x71    0x0                     QZ_PAUSE
183     210,//  114     0x72    0xd2    E0,52   INSERT  QZ_INSERT
184     199,//  115     0x73    0xc7    E0,47   HOME    QZ_HOME
185     201,//  116     0x74    0xc9    E0,49   PG UP   QZ_PAGEUP
186     211,//  117     0x75    0xd3    E0,53   DELETE  QZ_DELETE
187     62, //  118     0x76    0x3e            F4      QZ_F4
188     207,//  119     0x77    0xcf    E0,4f   END     QZ_END
189     60, //  120     0x78    0x3c            F2      QZ_F2
190     209,//  121     0x79    0xd1    E0,51   PG DN   QZ_PAGEDOWN
191     59, //  122     0x7A    0x3b            F1      QZ_F1
192     203,//  123     0x7B    0xcb    e0,4B   L ARROW QZ_LEFT
193     205,//  124     0x7C    0xcd    e0,4D   R ARROW QZ_RIGHT
194     208,//  125     0x7D    0xd0    E0,50   D ARROW QZ_DOWN
195     200,//  126     0x7E    0xc8    E0,48   U ARROW QZ_UP
196 /* completed according to http://www.libsdl.org/cgi/cvsweb.cgi/SDL12/src/video/quartz/SDL_QuartzKeys.h?rev=1.6&content-type=text/x-cvsweb-markup */
197
198 /* Aditional 104 Key XP-Keyboard Scancodes from http://www.computer-engineering.org/ps2keyboard/scancodes1.html */
199 /*
200     219 //          0xdb            e0,5b   L GUI
201     220 //          0xdc            e0,5c   R GUI
202     221 //          0xdd            e0,5d   APPS
203         //              E0,2A,E0,37         PRNT SCRN
204         //              E1,1D,45,E1,9D,C5   PAUSE
205     83  //          0x53    0x53            KP .
206 // ACPI Scan Codes
207     222 //          0xde            E0, 5E  Power
208     223 //          0xdf            E0, 5F  Sleep
209     227 //          0xe3            E0, 63  Wake
210 // Windows Multimedia Scan Codes
211     153 //          0x99            E0, 19  Next Track
212     144 //          0x90            E0, 10  Previous Track
213     164 //          0xa4            E0, 24  Stop
214     162 //          0xa2            E0, 22  Play/Pause
215     160 //          0xa0            E0, 20  Mute
216     176 //          0xb0            E0, 30  Volume Up
217     174 //          0xae            E0, 2E  Volume Down
218     237 //          0xed            E0, 6D  Media Select
219     236 //          0xec            E0, 6C  E-Mail
220     161 //          0xa1            E0, 21  Calculator
221     235 //          0xeb            E0, 6B  My Computer
222     229 //          0xe5            E0, 65  WWW Search
223     178 //          0xb2            E0, 32  WWW Home
224     234 //          0xea            E0, 6A  WWW Back
225     233 //          0xe9            E0, 69  WWW Forward
226     232 //          0xe8            E0, 68  WWW Stop
227     231 //          0xe7            E0, 67  WWW Refresh
228     230 //          0xe6            E0, 66  WWW Favorites
229 */
230 };
231
232 static int cocoa_keycode_to_qemu(int keycode)
233 {
234     if((sizeof(keymap)/sizeof(int)) <= keycode)
235     {
236         printf("(cocoa) warning unknow keycode 0x%x\n", keycode);
237         return 0;
238     }
239     return keymap[keycode];
240 }
241
242
243
244 /*
245  ------------------------------------------------------
246     QemuCocoaView
247  ------------------------------------------------------
248 */
249 @interface QemuCocoaView : NSView
250 {
251     QEMUScreen screen;
252     NSWindow *fullScreenWindow;
253     float cx,cy,cw,ch,cdx,cdy;
254     CGDataProviderRef dataProviderRef;
255     int modifiers_state[256];
256     BOOL isMouseGrabed;
257     BOOL isFullscreen;
258     BOOL isAbsoluteEnabled;
259     BOOL isTabletEnabled;
260 }
261 - (void) resizeContentToWidth:(int)w height:(int)h displayState:(DisplayState *)ds;
262 - (void) grabMouse;
263 - (void) ungrabMouse;
264 - (void) toggleFullScreen:(id)sender;
265 - (void) handleEvent:(NSEvent *)event;
266 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
267 - (BOOL) isMouseGrabed;
268 - (BOOL) isAbsoluteEnabled;
269 - (float) cdx;
270 - (float) cdy;
271 - (QEMUScreen) gscreen;
272 @end
273
274 @implementation QemuCocoaView
275 - (id)initWithFrame:(NSRect)frameRect
276 {
277     COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
278
279     self = [super initWithFrame:frameRect];
280     if (self) {
281
282         screen.bitsPerComponent = 8;
283         screen.bitsPerPixel = 32;
284         screen.width = frameRect.size.width;
285         screen.height = frameRect.size.height;
286
287     }
288     return self;
289 }
290
291 - (void) dealloc
292 {
293     COCOA_DEBUG("QemuCocoaView: dealloc\n");
294
295     if (screenBuffer)
296         free(screenBuffer);
297
298     if (dataProviderRef)
299         CGDataProviderRelease(dataProviderRef);
300
301     [super dealloc];
302 }
303
304 - (BOOL) isOpaque
305 {
306     return YES;
307 }
308
309 - (void) drawRect:(NSRect) rect
310 {
311     COCOA_DEBUG("QemuCocoaView: drawRect\n");
312
313     if ((int)screenBuffer == -1)
314         return;
315
316     // get CoreGraphic context
317     CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
318     CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
319     CGContextSetShouldAntialias (viewContextRef, NO);
320
321     // draw screen bitmap directly to Core Graphics context
322     if (dataProviderRef) {
323         CGImageRef imageRef = CGImageCreate(
324             screen.width, //width
325             screen.height, //height
326             screen.bitsPerComponent, //bitsPerComponent
327             screen.bitsPerPixel, //bitsPerPixel
328             (screen.width * 4), //bytesPerRow
329 #if __LITTLE_ENDIAN__
330             CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
331             kCGImageAlphaNoneSkipLast,
332 #else
333             CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
334             kCGImageAlphaNoneSkipFirst, //bitmapInfo
335 #endif
336             dataProviderRef, //provider
337             NULL, //decode
338             0, //interpolate
339             kCGRenderingIntentDefault //intent
340         );
341
342 // test if host support "CGImageCreateWithImageInRect" at compiletime
343 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
344         if (CGImageCreateWithImageInRect == NULL) { // test if "CGImageCreateWithImageInRect" is supported on host at runtime
345 #endif
346             // compatibility drawing code (draws everything) (OS X < 10.4)
347             CGContextDrawImage (viewContextRef, CGRectMake(0, 0, [self bounds].size.width, [self bounds].size.height), imageRef);
348 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
349         } else {
350             // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
351             const NSRect *rectList;
352             int rectCount;
353             int i;
354             CGImageRef clipImageRef;
355             CGRect clipRect;
356
357             [self getRectsBeingDrawn:&rectList count:&rectCount];
358             for (i = 0; i < rectCount; i++) {
359                 clipRect.origin.x = rectList[i].origin.x / cdx;
360                 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
361                 clipRect.size.width = rectList[i].size.width / cdx;
362                 clipRect.size.height = rectList[i].size.height / cdy;
363                 clipImageRef = CGImageCreateWithImageInRect(imageRef, clipRect);
364                 CGContextDrawImage(viewContextRef, cgrect(rectList[i]), clipImageRef);
365                 CGImageRelease(clipImageRef);
366             }
367         }
368 #endif
369         CGImageRelease (imageRef);
370     }
371 }
372
373 - (void) setContentDimensions
374 {
375     COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
376
377     if (isFullscreen) {
378         cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
379         cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
380         cw = screen.width * cdx;
381         ch = screen.height * cdy;
382         cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
383         cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
384     } else {
385         cx = 0;
386         cy = 0;
387         cw = screen.width;
388         ch = screen.height;
389         cdx = 1.0;
390         cdy = 1.0;
391     }
392 }
393
394 - (void) resizeContentToWidth:(int)w height:(int)h displayState:(DisplayState *)ds
395 {
396     COCOA_DEBUG("QemuCocoaView: resizeContent\n");
397
398     // update screenBuffer
399     if (dataProviderRef)
400         CGDataProviderRelease(dataProviderRef);
401     if (screenBuffer)
402         free(screenBuffer);
403     screenBuffer = malloc( w * 4 * h );
404
405     ds->data = screenBuffer;
406     ds->linesize =  (w * 4);
407     ds->depth = 32;
408     ds->width = w;
409     ds->height = h;
410 #ifdef __LITTLE_ENDIAN__
411     ds->bgr = 1;
412 #else
413     ds->bgr = 0;
414 #endif
415
416     dataProviderRef = CGDataProviderCreateWithData(NULL, screenBuffer, w * 4 * h, NULL);
417
418     // update windows
419     if (isFullscreen) {
420         [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
421         [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + screen.height, w, h + [normalWindow frame].size.height - screen.height) display:NO animate:NO];
422     } else {
423         if (qemu_name)
424             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
425         [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + screen.height, w, h + [normalWindow frame].size.height - screen.height) display:YES animate:NO];
426     }
427     screen.width = w;
428     screen.height = h;
429     [self setContentDimensions];
430     [self setFrame:NSMakeRect(cx, cy, cw, ch)];
431 }
432
433 - (void) toggleFullScreen:(id)sender
434 {
435     COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
436
437     if (isFullscreen) { // switch from fullscreen to desktop
438         isFullscreen = FALSE;
439         [self ungrabMouse];
440         [self setContentDimensions];
441 // test if host support "enterFullScreenMode:withOptions" at compiletime
442 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
443         if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
444             [self exitFullScreenModeWithOptions:nil];
445         } else {
446 #endif
447             [fullScreenWindow close];
448             [normalWindow setContentView: self];
449             [normalWindow makeKeyAndOrderFront: self];
450             [NSMenu setMenuBarVisible:YES];
451 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
452         }
453 #endif
454     } else { // switch from desktop to fullscreen
455         isFullscreen = TRUE;
456         [self grabMouse];
457         [self setContentDimensions];
458 // test if host support "enterFullScreenMode:withOptions" at compiletime
459 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
460         if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
461             [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
462                 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
463                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
464                  nil]];
465         } else {
466 #endif
467             [NSMenu setMenuBarVisible:NO];
468             fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
469                 styleMask:NSBorderlessWindowMask
470                 backing:NSBackingStoreBuffered
471                 defer:NO];
472             [fullScreenWindow setHasShadow:NO];
473             [fullScreenWindow setContentView:self];
474             [fullScreenWindow makeKeyAndOrderFront:self];
475 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
476         }
477 #endif
478     }
479 }
480
481 - (void) handleEvent:(NSEvent *)event
482 {
483     COCOA_DEBUG("QemuCocoaView: handleEvent\n");
484
485     int buttons = 0;
486     int keycode;
487     NSPoint p = [event locationInWindow];
488
489     switch ([event type]) {
490         case NSFlagsChanged:
491             keycode = cocoa_keycode_to_qemu([event keyCode]);
492             if (keycode) {
493                 if (keycode == 58 || keycode == 69) { // emulate caps lock and num lock keydown and keyup
494                     kbd_put_keycode(keycode);
495                     kbd_put_keycode(keycode | 0x80);
496                 } else if (is_graphic_console()) {
497                     if (keycode & 0x80)
498                         kbd_put_keycode(0xe0);
499                     if (modifiers_state[keycode] == 0) { // keydown
500                         kbd_put_keycode(keycode & 0x7f);
501                         modifiers_state[keycode] = 1;
502                     } else { // keyup
503                         kbd_put_keycode(keycode | 0x80);
504                         modifiers_state[keycode] = 0;
505                     }
506                 }
507             }
508
509             // release Mouse grab when pressing ctrl+alt
510             if (!isFullscreen && ([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
511                 [self ungrabMouse];
512             }
513             break;
514         case NSKeyDown:
515
516             // forward command Key Combos
517             if ([event modifierFlags] & NSCommandKeyMask) {
518                 [NSApp sendEvent:event];
519                 return;
520             }
521
522             // default
523             keycode = cocoa_keycode_to_qemu([event keyCode]);
524
525             // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
526             if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
527                 switch (keycode) {
528
529                     // enable graphic console
530                     case 0x02 ... 0x0a: // '1' to '9' keys
531                         console_select(keycode - 0x02);
532                         break;
533                 }
534
535             // handle keys for graphic console
536             } else if (is_graphic_console()) {
537                 if (keycode & 0x80) //check bit for e0 in front
538                     kbd_put_keycode(0xe0);
539                 kbd_put_keycode(keycode & 0x7f); //remove e0 bit in front
540
541             // handlekeys for Monitor
542             } else {
543                 int keysym = 0;
544                 switch([event keyCode]) {
545                 case 115:
546                     keysym = QEMU_KEY_HOME;
547                     break;
548                 case 117:
549                     keysym = QEMU_KEY_DELETE;
550                     break;
551                 case 119:
552                     keysym = QEMU_KEY_END;
553                     break;
554                 case 123:
555                     keysym = QEMU_KEY_LEFT;
556                     break;
557                 case 124:
558                     keysym = QEMU_KEY_RIGHT;
559                     break;
560                 case 125:
561                     keysym = QEMU_KEY_DOWN;
562                     break;
563                 case 126:
564                     keysym = QEMU_KEY_UP;
565                     break;
566                 default:
567                     {
568                         NSString *ks = [event characters];
569                         if ([ks length] > 0)
570                             keysym = [ks characterAtIndex:0];
571                     }
572                 }
573                 if (keysym)
574                     kbd_put_keysym(keysym);
575             }
576             break;
577         case NSKeyUp:
578             keycode = cocoa_keycode_to_qemu([event keyCode]);
579             if (is_graphic_console()) {
580                 if (keycode & 0x80)
581                     kbd_put_keycode(0xe0);
582                 kbd_put_keycode(keycode | 0x80); //add 128 to signal release of key
583             }
584             break;
585         case NSMouseMoved:
586             if (isAbsoluteEnabled) {
587                 if (p.x < 0 || p.x > screen.width || p.y < 0 || p.y > screen.height || ![[self window] isKeyWindow]) {
588                     if (isTabletEnabled) { // if we leave the window, deactivate the tablet
589                         if (cursor_hide) [NSCursor unhide];
590                         isTabletEnabled = FALSE;
591                     }
592                 } else {
593                     if (!isTabletEnabled) { // if we enter the window, activate the tablet
594                         if (cursor_hide) [NSCursor hide];
595                         isTabletEnabled = TRUE;
596                     }
597                 }
598             }
599             COCOA_MOUSE_EVENT
600             break;
601         case NSLeftMouseDown:
602             if ([event modifierFlags] & NSCommandKeyMask) {
603                 buttons |= MOUSE_EVENT_RBUTTON;
604             } else {
605                 buttons |= MOUSE_EVENT_LBUTTON;
606             }
607             COCOA_MOUSE_EVENT
608             break;
609         case NSRightMouseDown:
610             buttons |= MOUSE_EVENT_RBUTTON;
611             COCOA_MOUSE_EVENT
612             break;
613         case NSOtherMouseDown:
614             buttons |= MOUSE_EVENT_MBUTTON;
615             COCOA_MOUSE_EVENT
616             break;
617         case NSLeftMouseDragged:
618             if ([event modifierFlags] & NSCommandKeyMask) {
619                 buttons |= MOUSE_EVENT_RBUTTON;
620             } else {
621                 buttons |= MOUSE_EVENT_LBUTTON;
622             }
623             COCOA_MOUSE_EVENT
624             break;
625         case NSRightMouseDragged:
626             buttons |= MOUSE_EVENT_RBUTTON;
627             COCOA_MOUSE_EVENT
628             break;
629         case NSOtherMouseDragged:
630             buttons |= MOUSE_EVENT_MBUTTON;
631             COCOA_MOUSE_EVENT
632             break;
633         case NSLeftMouseUp:
634             if (isTabletEnabled) {
635                     COCOA_MOUSE_EVENT
636             } else if (!isMouseGrabed) {
637                 if (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height) {
638                     [self grabMouse];
639                 } else {
640                     [NSApp sendEvent:event];
641                 }
642             } else {
643                 COCOA_MOUSE_EVENT
644             }
645             break;
646         case NSRightMouseUp:
647             COCOA_MOUSE_EVENT
648             break;
649         case NSOtherMouseUp:
650             COCOA_MOUSE_EVENT
651             break;
652         case NSScrollWheel:
653             if (isTabletEnabled || isMouseGrabed) {
654                 kbd_mouse_event(0, 0, -[event deltaY], 0);
655             } else {
656                 [NSApp sendEvent:event];
657             }
658             break;
659         default:
660             [NSApp sendEvent:event];
661     }
662 }
663
664 - (void) grabMouse
665 {
666     COCOA_DEBUG("QemuCocoaView: grabMouse\n");
667
668     if (!isFullscreen) {
669         if (qemu_name)
670             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
671         else
672             [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
673     }
674     if (cursor_hide) [NSCursor hide];
675     CGAssociateMouseAndMouseCursorPosition(FALSE);
676     isMouseGrabed = TRUE; // while isMouseGrabed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
677 }
678
679 - (void) ungrabMouse
680 {
681     COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
682
683     if (!isFullscreen) {
684         if (qemu_name)
685             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
686         else
687             [normalWindow setTitle:@"QEMU"];
688     }
689     if (cursor_hide) [NSCursor unhide];
690     CGAssociateMouseAndMouseCursorPosition(TRUE);
691     isMouseGrabed = FALSE;
692 }
693
694 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
695 - (BOOL) isMouseGrabed {return isMouseGrabed;}
696 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
697 - (float) cdx {return cdx;}
698 - (float) cdy {return cdy;}
699 - (QEMUScreen) gscreen {return screen;}
700 @end
701
702
703
704 /*
705  ------------------------------------------------------
706     QemuCocoaAppController
707  ------------------------------------------------------
708 */
709 @interface QemuCocoaAppController : NSObject
710 {
711 }
712 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
713 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
714 - (void)toggleFullScreen:(id)sender;
715 - (void)showQEMUDoc:(id)sender;
716 - (void)showQEMUTec:(id)sender;
717 @end
718
719 @implementation QemuCocoaAppController
720 - (id) init
721 {
722     COCOA_DEBUG("QemuCocoaAppController: init\n");
723
724     self = [super init];
725     if (self) {
726
727         // create a view and add it to the window
728         cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
729         if(!cocoaView) {
730             fprintf(stderr, "(cocoa) can't create a view\n");
731             exit(1);
732         }
733
734         // create a window
735         normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
736             styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
737             backing:NSBackingStoreBuffered defer:NO];
738         if(!normalWindow) {
739             fprintf(stderr, "(cocoa) can't create window\n");
740             exit(1);
741         }
742         [normalWindow setAcceptsMouseMovedEvents:YES];
743         [normalWindow setTitle:[NSString stringWithFormat:@"QEMU"]];
744         [normalWindow setContentView:cocoaView];
745         [normalWindow makeKeyAndOrderFront:self];
746
747     }
748     return self;
749 }
750
751 - (void) dealloc
752 {
753     COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
754
755     if (cocoaView)
756         [cocoaView release];
757     [super dealloc];
758 }
759
760 - (void)applicationDidFinishLaunching: (NSNotification *) note
761 {
762     COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
763
764     // Display an open dialog box if no argument were passed or
765     // if qemu was launched from the finder ( the Finder passes "-psn" )
766     if( gArgc <= 1 || strncmp ((char *)gArgv[1], "-psn", 4) == 0) {
767         NSOpenPanel *op = [[NSOpenPanel alloc] init];
768         [op setPrompt:@"Boot image"];
769         [op setMessage:@"Select the disk image you want to boot.\n\nHit the \"Cancel\" button to quit"];
770         [op beginSheetForDirectory:nil file:nil types:[NSArray arrayWithObjects:@"img",@"iso",@"dmg",@"qcow",@"cow",@"cloop",@"vmdk",nil]
771               modalForWindow:normalWindow modalDelegate:self
772               didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
773     } else {
774         // or Launch Qemu, with the global args
775         [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
776     }
777 }
778
779 - (void)applicationWillTerminate:(NSNotification *)aNotification
780 {
781     COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
782
783     qemu_system_shutdown_request();
784     exit(0);
785 }
786
787 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
788 {
789     COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
790
791     int status;
792     status = qemu_main(argc, argv);
793     exit(status);
794 }
795
796 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
797 {
798     COCOA_DEBUG("QemuCocoaAppController: openPanelDidEnd\n");
799
800     if(returnCode == NSCancelButton) {
801         exit(0);
802     } else if(returnCode == NSOKButton) {
803         const char *bin = "qemu";
804         char *img = (char*)[ [ sheet filename ] cStringUsingEncoding:NSASCIIStringEncoding];
805
806         char **argv = (char**)malloc( sizeof(char*)*3 );
807
808         asprintf(&argv[0], "%s", bin);
809         asprintf(&argv[1], "-hda");
810         asprintf(&argv[2], "%s", img);
811
812         printf("Using argc %d argv %s -hda %s\n", 3, bin, img);
813
814         [self startEmulationWithArgc:3 argv:(char**)argv];
815     }
816 }
817 - (void)toggleFullScreen:(id)sender
818 {
819     COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
820
821     [cocoaView toggleFullScreen:sender];
822 }
823
824 - (void)showQEMUDoc:(id)sender
825 {
826     COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
827
828     [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-doc.html",
829         [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
830 }
831
832 - (void)showQEMUTec:(id)sender
833 {
834     COCOA_DEBUG("QemuCocoaAppController: showQEMUTec\n");
835
836     [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-tech.html",
837         [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
838 }
839 @end
840
841
842
843 // Dock Connection
844 typedef struct CPSProcessSerNum
845 {
846         UInt32                lo;
847         UInt32                hi;
848 } CPSProcessSerNum;
849
850 extern OSErr    CPSGetCurrentProcess( CPSProcessSerNum *psn);
851 extern OSErr    CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
852 extern OSErr    CPSSetFrontProcess( CPSProcessSerNum *psn);
853
854 int main (int argc, const char * argv[]) {
855
856     gArgc = argc;
857     gArgv = (char **)argv;
858     CPSProcessSerNum PSN;
859
860     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
861     [NSApplication sharedApplication];
862
863     if (!CPSGetCurrentProcess(&PSN))
864         if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
865             if (!CPSSetFrontProcess(&PSN))
866                 [NSApplication sharedApplication];
867
868     // Add menus
869     NSMenu      *menu;
870     NSMenuItem  *menuItem;
871
872     [NSApp setMainMenu:[[NSMenu alloc] init]];
873
874     // Application menu
875     menu = [[NSMenu alloc] initWithTitle:@""];
876     [menu addItemWithTitle:@"About QEMU" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; // About QEMU
877     [menu addItem:[NSMenuItem separatorItem]]; //Separator
878     [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
879     menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
880     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
881     [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
882     [menu addItem:[NSMenuItem separatorItem]]; //Separator
883     [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
884     menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
885     [menuItem setSubmenu:menu];
886     [[NSApp mainMenu] addItem:menuItem];
887     [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
888
889     // View menu
890     menu = [[NSMenu alloc] initWithTitle:@"View"];
891     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
892     menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
893     [menuItem setSubmenu:menu];
894     [[NSApp mainMenu] addItem:menuItem];
895
896     // Window menu
897     menu = [[NSMenu alloc] initWithTitle:@"Window"];
898     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
899     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
900     [menuItem setSubmenu:menu];
901     [[NSApp mainMenu] addItem:menuItem];
902     [NSApp setWindowsMenu:menu];
903
904     // Help menu
905     menu = [[NSMenu alloc] initWithTitle:@"Help"];
906     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
907     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Technology" action:@selector(showQEMUTec:) keyEquivalent:@""] autorelease]]; // QEMU Help
908     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
909     [menuItem setSubmenu:menu];
910     [[NSApp mainMenu] addItem:menuItem];
911
912     // Create an Application controller
913     QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
914     [NSApp setDelegate:appController];
915
916     // Start the main event loop
917     [NSApp run];
918
919     [appController release];
920     [pool release];
921
922     return 0;
923 }
924
925
926 #pragma mark qemu
927 static void cocoa_update(DisplayState *ds, int x, int y, int w, int h)
928 {
929     COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
930
931     NSRect rect;
932     if ([cocoaView cdx] == 1.0) {
933         rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
934     } else {
935         rect = NSMakeRect(
936             x * [cocoaView cdx],
937             ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
938             w * [cocoaView cdx],
939             h * [cocoaView cdy]);
940     }
941     [cocoaView setNeedsDisplayInRect:rect];
942 }
943
944 static void cocoa_resize(DisplayState *ds, int w, int h)
945 {
946     COCOA_DEBUG("qemu_cocoa: cocoa_resize\n");
947
948     [cocoaView resizeContentToWidth:w height:h displayState:ds];
949 }
950
951 static void cocoa_refresh(DisplayState *ds)
952 {
953     COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
954
955     if (kbd_mouse_is_absolute()) {
956         if (![cocoaView isAbsoluteEnabled]) {
957             if ([cocoaView isMouseGrabed]) {
958                 [cocoaView ungrabMouse];
959             }
960         }
961         [cocoaView setAbsoluteEnabled:YES];
962     }
963
964     NSDate *distantPast;
965     NSEvent *event;
966     distantPast = [NSDate distantPast];
967     do {
968         event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
969                         inMode: NSDefaultRunLoopMode dequeue:YES];
970         if (event != nil) {
971             [cocoaView handleEvent:event];
972         }
973     } while(event != nil);
974     vga_hw_update();
975 }
976
977 static void cocoa_cleanup(void)
978 {
979     COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
980
981 }
982
983 void cocoa_display_init(DisplayState *ds, int full_screen)
984 {
985     COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
986
987     // register vga outpu callbacks
988     ds->dpy_update = cocoa_update;
989     ds->dpy_resize = cocoa_resize;
990     ds->dpy_refresh = cocoa_refresh;
991
992     // give window a initial Size
993     cocoa_resize(ds, 640, 400);
994
995     // register cleanup function
996     atexit(cocoa_cleanup);
997 }