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