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