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