2 * QEMU Cocoa CG display driver
4 * Copyright (c) 2008 Mike Kronenberg
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 #import <Cocoa/Cocoa.h>
26 #include <crt_externs.h>
28 #include "qemu-common.h"
29 #include "ui/console.h"
31 #include "sysemu/sysemu.h"
33 #ifndef MAC_OS_X_VERSION_10_4
34 #define MAC_OS_X_VERSION_10_4 1040
36 #ifndef MAC_OS_X_VERSION_10_5
37 #define MAC_OS_X_VERSION_10_5 1050
39 #ifndef MAC_OS_X_VERSION_10_6
40 #define MAC_OS_X_VERSION_10_6 1060
47 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
49 #define COCOA_DEBUG(...) ((void) 0)
52 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
61 NSWindow *normalWindow;
62 static DisplayChangeListener *dcl;
63 static int last_buttons;
72 // SdlI macI macH SdlH 104xtH 104xtC sdl
73 30, // 0 0x00 0x1e A QZ_a
74 31, // 1 0x01 0x1f S QZ_s
75 32, // 2 0x02 0x20 D QZ_d
76 33, // 3 0x03 0x21 F QZ_f
77 35, // 4 0x04 0x23 H QZ_h
78 34, // 5 0x05 0x22 G QZ_g
79 44, // 6 0x06 0x2c Z QZ_z
80 45, // 7 0x07 0x2d X QZ_x
81 46, // 8 0x08 0x2e C QZ_c
82 47, // 9 0x09 0x2f V QZ_v
83 0, // 10 0x0A Undefined
84 48, // 11 0x0B 0x30 B QZ_b
85 16, // 12 0x0C 0x10 Q QZ_q
86 17, // 13 0x0D 0x11 W QZ_w
87 18, // 14 0x0E 0x12 E QZ_e
88 19, // 15 0x0F 0x13 R QZ_r
89 21, // 16 0x10 0x15 Y QZ_y
90 20, // 17 0x11 0x14 T QZ_t
91 2, // 18 0x12 0x02 1 QZ_1
92 3, // 19 0x13 0x03 2 QZ_2
93 4, // 20 0x14 0x04 3 QZ_3
94 5, // 21 0x15 0x05 4 QZ_4
95 7, // 22 0x16 0x07 6 QZ_6
96 6, // 23 0x17 0x06 5 QZ_5
97 13, // 24 0x18 0x0d = QZ_EQUALS
98 10, // 25 0x19 0x0a 9 QZ_9
99 8, // 26 0x1A 0x08 7 QZ_7
100 12, // 27 0x1B 0x0c - QZ_MINUS
101 9, // 28 0x1C 0x09 8 QZ_8
102 11, // 29 0x1D 0x0b 0 QZ_0
103 27, // 30 0x1E 0x1b ] QZ_RIGHTBRACKET
104 24, // 31 0x1F 0x18 O QZ_o
105 22, // 32 0x20 0x16 U QZ_u
106 26, // 33 0x21 0x1a [ QZ_LEFTBRACKET
107 23, // 34 0x22 0x17 I QZ_i
108 25, // 35 0x23 0x19 P QZ_p
109 28, // 36 0x24 0x1c ENTER QZ_RETURN
110 38, // 37 0x25 0x26 L QZ_l
111 36, // 38 0x26 0x24 J QZ_j
112 40, // 39 0x27 0x28 ' QZ_QUOTE
113 37, // 40 0x28 0x25 K QZ_k
114 39, // 41 0x29 0x27 ; QZ_SEMICOLON
115 43, // 42 0x2A 0x2b \ QZ_BACKSLASH
116 51, // 43 0x2B 0x33 , QZ_COMMA
117 53, // 44 0x2C 0x35 / QZ_SLASH
118 49, // 45 0x2D 0x31 N QZ_n
119 50, // 46 0x2E 0x32 M QZ_m
120 52, // 47 0x2F 0x34 . QZ_PERIOD
121 15, // 48 0x30 0x0f TAB QZ_TAB
122 57, // 49 0x31 0x39 SPACE QZ_SPACE
123 41, // 50 0x32 0x29 ` QZ_BACKQUOTE
124 14, // 51 0x33 0x0e BKSP QZ_BACKSPACE
125 0, // 52 0x34 Undefined
126 1, // 53 0x35 0x01 ESC QZ_ESCAPE
127 220, // 54 0x36 0xdc E0,5C R GUI QZ_RMETA
128 219, // 55 0x37 0xdb E0,5B L GUI QZ_LMETA
129 42, // 56 0x38 0x2a L SHFT QZ_LSHIFT
130 58, // 57 0x39 0x3a CAPS QZ_CAPSLOCK
131 56, // 58 0x3A 0x38 L ALT QZ_LALT
132 29, // 59 0x3B 0x1d L CTRL QZ_LCTRL
133 54, // 60 0x3C 0x36 R SHFT QZ_RSHIFT
134 184,// 61 0x3D 0xb8 E0,38 R ALT QZ_RALT
135 157,// 62 0x3E 0x9d E0,1D R CTRL QZ_RCTRL
136 0, // 63 0x3F Undefined
137 0, // 64 0x40 Undefined
138 0, // 65 0x41 Undefined
139 0, // 66 0x42 Undefined
140 55, // 67 0x43 0x37 KP * QZ_KP_MULTIPLY
141 0, // 68 0x44 Undefined
142 78, // 69 0x45 0x4e KP + QZ_KP_PLUS
143 0, // 70 0x46 Undefined
144 69, // 71 0x47 0x45 NUM QZ_NUMLOCK
145 0, // 72 0x48 Undefined
146 0, // 73 0x49 Undefined
147 0, // 74 0x4A Undefined
148 181,// 75 0x4B 0xb5 E0,35 KP / QZ_KP_DIVIDE
149 152,// 76 0x4C 0x9c E0,1C KP EN QZ_KP_ENTER
150 0, // 77 0x4D undefined
151 74, // 78 0x4E 0x4a KP - QZ_KP_MINUS
152 0, // 79 0x4F Undefined
153 0, // 80 0x50 Undefined
154 0, // 81 0x51 QZ_KP_EQUALS
155 82, // 82 0x52 0x52 KP 0 QZ_KP0
156 79, // 83 0x53 0x4f KP 1 QZ_KP1
157 80, // 84 0x54 0x50 KP 2 QZ_KP2
158 81, // 85 0x55 0x51 KP 3 QZ_KP3
159 75, // 86 0x56 0x4b KP 4 QZ_KP4
160 76, // 87 0x57 0x4c KP 5 QZ_KP5
161 77, // 88 0x58 0x4d KP 6 QZ_KP6
162 71, // 89 0x59 0x47 KP 7 QZ_KP7
163 0, // 90 0x5A Undefined
164 72, // 91 0x5B 0x48 KP 8 QZ_KP8
165 73, // 92 0x5C 0x49 KP 9 QZ_KP9
166 0, // 93 0x5D Undefined
167 0, // 94 0x5E Undefined
168 0, // 95 0x5F Undefined
169 63, // 96 0x60 0x3f F5 QZ_F5
170 64, // 97 0x61 0x40 F6 QZ_F6
171 65, // 98 0x62 0x41 F7 QZ_F7
172 61, // 99 0x63 0x3d F3 QZ_F3
173 66, // 100 0x64 0x42 F8 QZ_F8
174 67, // 101 0x65 0x43 F9 QZ_F9
175 0, // 102 0x66 Undefined
176 87, // 103 0x67 0x57 F11 QZ_F11
177 0, // 104 0x68 Undefined
178 183,// 105 0x69 0xb7 QZ_PRINT
179 0, // 106 0x6A Undefined
180 70, // 107 0x6B 0x46 SCROLL QZ_SCROLLOCK
181 0, // 108 0x6C Undefined
182 68, // 109 0x6D 0x44 F10 QZ_F10
183 0, // 110 0x6E Undefined
184 88, // 111 0x6F 0x58 F12 QZ_F12
185 0, // 112 0x70 Undefined
186 110,// 113 0x71 0x0 QZ_PAUSE
187 210,// 114 0x72 0xd2 E0,52 INSERT QZ_INSERT
188 199,// 115 0x73 0xc7 E0,47 HOME QZ_HOME
189 201,// 116 0x74 0xc9 E0,49 PG UP QZ_PAGEUP
190 211,// 117 0x75 0xd3 E0,53 DELETE QZ_DELETE
191 62, // 118 0x76 0x3e F4 QZ_F4
192 207,// 119 0x77 0xcf E0,4f END QZ_END
193 60, // 120 0x78 0x3c F2 QZ_F2
194 209,// 121 0x79 0xd1 E0,51 PG DN QZ_PAGEDOWN
195 59, // 122 0x7A 0x3b F1 QZ_F1
196 203,// 123 0x7B 0xcb e0,4B L ARROW QZ_LEFT
197 205,// 124 0x7C 0xcd e0,4D R ARROW QZ_RIGHT
198 208,// 125 0x7D 0xd0 E0,50 D ARROW QZ_DOWN
199 200,// 126 0x7E 0xc8 E0,48 U ARROW QZ_UP
200 /* 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 */
202 /* Additional 104 Key XP-Keyboard Scancodes from http://www.computer-engineering.org/ps2keyboard/scancodes1.html */
204 221 // 0xdd e0,5d APPS
205 // E0,2A,E0,37 PRNT SCRN
206 // E1,1D,45,E1,9D,C5 PAUSE
209 222 // 0xde E0, 5E Power
210 223 // 0xdf E0, 5F Sleep
211 227 // 0xe3 E0, 63 Wake
212 // Windows Multimedia Scan Codes
213 153 // 0x99 E0, 19 Next Track
214 144 // 0x90 E0, 10 Previous Track
215 164 // 0xa4 E0, 24 Stop
216 162 // 0xa2 E0, 22 Play/Pause
217 160 // 0xa0 E0, 20 Mute
218 176 // 0xb0 E0, 30 Volume Up
219 174 // 0xae E0, 2E Volume Down
220 237 // 0xed E0, 6D Media Select
221 236 // 0xec E0, 6C E-Mail
222 161 // 0xa1 E0, 21 Calculator
223 235 // 0xeb E0, 6B My Computer
224 229 // 0xe5 E0, 65 WWW Search
225 178 // 0xb2 E0, 32 WWW Home
226 234 // 0xea E0, 6A WWW Back
227 233 // 0xe9 E0, 69 WWW Forward
228 232 // 0xe8 E0, 68 WWW Stop
229 231 // 0xe7 E0, 67 WWW Refresh
230 230 // 0xe6 E0, 66 WWW Favorites
234 static int cocoa_keycode_to_qemu(int keycode)
236 if (ARRAY_SIZE(keymap) <= keycode) {
237 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
240 return keymap[keycode];
246 ------------------------------------------------------
248 ------------------------------------------------------
250 @interface QemuCocoaView : NSView
253 NSWindow *fullScreenWindow;
254 float cx,cy,cw,ch,cdx,cdy;
255 CGDataProviderRef dataProviderRef;
256 int modifiers_state[256];
259 BOOL isAbsoluteEnabled;
260 BOOL isMouseDeassociated;
262 - (void) switchSurface:(DisplaySurface *)surface;
264 - (void) ungrabMouse;
265 - (void) toggleFullScreen:(id)sender;
266 - (void) handleEvent:(NSEvent *)event;
267 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
268 /* The state surrounding mouse grabbing is potentially confusing.
269 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
270 * pointing device an absolute-position one?"], but is only updated on
272 * isMouseGrabbed tracks whether GUI events are directed to the guest;
273 * it controls whether special keys like Cmd get sent to the guest,
274 * and whether we capture the mouse when in non-absolute mode.
275 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
276 * the mouse and mouse cursor position by calling
277 * CGAssociateMouseAndMouseCursorPosition(FALSE)
278 * (which basically happens if we grab in non-absolute mode).
280 - (BOOL) isMouseGrabbed;
281 - (BOOL) isAbsoluteEnabled;
282 - (BOOL) isMouseDeassociated;
285 - (QEMUScreen) gscreen;
288 QemuCocoaView *cocoaView;
290 @implementation QemuCocoaView
291 - (id)initWithFrame:(NSRect)frameRect
293 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
295 self = [super initWithFrame:frameRect];
298 screen.bitsPerComponent = 8;
299 screen.bitsPerPixel = 32;
300 screen.width = frameRect.size.width;
301 screen.height = frameRect.size.height;
309 COCOA_DEBUG("QemuCocoaView: dealloc\n");
312 CGDataProviderRelease(dataProviderRef);
322 - (BOOL) screenContainsPoint:(NSPoint) p
324 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
335 - (void) unhideCursor
343 - (void) drawRect:(NSRect) rect
345 COCOA_DEBUG("QemuCocoaView: drawRect\n");
347 // get CoreGraphic context
348 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
349 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
350 CGContextSetShouldAntialias (viewContextRef, NO);
352 // draw screen bitmap directly to Core Graphics context
353 if (!dataProviderRef) {
354 // Draw request before any guest device has set up a framebuffer:
355 // just draw an opaque black rectangle
356 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
357 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
359 CGImageRef imageRef = CGImageCreate(
360 screen.width, //width
361 screen.height, //height
362 screen.bitsPerComponent, //bitsPerComponent
363 screen.bitsPerPixel, //bitsPerPixel
364 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
365 #ifdef __LITTLE_ENDIAN__
366 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
367 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
369 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
370 kCGImageAlphaNoneSkipFirst, //bitmapInfo
372 dataProviderRef, //provider
375 kCGRenderingIntentDefault //intent
377 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
378 const NSRect *rectList;
379 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
385 CGImageRef clipImageRef;
388 [self getRectsBeingDrawn:&rectList count:&rectCount];
389 for (i = 0; i < rectCount; i++) {
390 clipRect.origin.x = rectList[i].origin.x / cdx;
391 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
392 clipRect.size.width = rectList[i].size.width / cdx;
393 clipRect.size.height = rectList[i].size.height / cdy;
394 clipImageRef = CGImageCreateWithImageInRect(
398 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
399 CGImageRelease (clipImageRef);
401 CGImageRelease (imageRef);
405 - (void) setContentDimensions
407 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
410 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
411 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
413 /* stretches video, but keeps same aspect ratio */
414 if (stretch_video == true) {
415 /* use smallest stretch value - prevents clipping on sides */
416 if (MIN(cdx, cdy) == cdx) {
421 } else { /* No stretching */
424 cw = screen.width * cdx;
425 ch = screen.height * cdy;
426 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
427 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
438 - (void) switchSurface:(DisplaySurface *)surface
440 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
442 int w = surface_width(surface);
443 int h = surface_height(surface);
444 /* cdx == 0 means this is our very first surface, in which case we need
445 * to recalculate the content dimensions even if it happens to be the size
446 * of the initial empty window.
448 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
450 int oldh = screen.height;
452 // Resize before we trigger the redraw, or we'll redraw at the wrong size
453 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
456 [self setContentDimensions];
457 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
460 // update screenBuffer
462 CGDataProviderRelease(dataProviderRef);
464 //sync host window color space with guests
465 screen.bitsPerPixel = surface_bits_per_pixel(surface);
466 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
468 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
472 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
473 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
476 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
477 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
481 [normalWindow center];
485 - (void) toggleFullScreen:(id)sender
487 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
489 if (isFullscreen) { // switch from fullscreen to desktop
490 isFullscreen = FALSE;
492 [self setContentDimensions];
493 // test if host supports "exitFullScreenModeWithOptions" at compile time
494 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
495 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
496 [self exitFullScreenModeWithOptions:nil];
499 [fullScreenWindow close];
500 [normalWindow setContentView: self];
501 [normalWindow makeKeyAndOrderFront: self];
502 [NSMenu setMenuBarVisible:YES];
503 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
506 } else { // switch from desktop to fullscreen
508 [normalWindow orderOut: nil]; /* Hide the window */
510 [self setContentDimensions];
511 // test if host supports "enterFullScreenMode:withOptions" at compile time
512 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
513 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
514 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
515 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
516 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
520 [NSMenu setMenuBarVisible:NO];
521 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
522 styleMask:NSBorderlessWindowMask
523 backing:NSBackingStoreBuffered
525 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
526 [fullScreenWindow setHasShadow:NO];
527 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
528 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
529 [[fullScreenWindow contentView] addSubview: self];
530 [fullScreenWindow makeKeyAndOrderFront:self];
531 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
537 - (void) handleEvent:(NSEvent *)event
539 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
543 bool mouse_event = false;
544 NSPoint p = [event locationInWindow];
546 switch ([event type]) {
548 keycode = cocoa_keycode_to_qemu([event keyCode]);
550 if ((keycode == 219 || keycode == 220) && !isMouseGrabbed) {
551 /* Don't pass command key changes to guest unless mouse is grabbed */
556 if (keycode == 58 || keycode == 69) { // emulate caps lock and num lock keydown and keyup
557 qemu_input_event_send_key_number(dcl->con, keycode, true);
558 qemu_input_event_send_key_number(dcl->con, keycode, false);
559 } else if (qemu_console_is_graphic(NULL)) {
560 if (modifiers_state[keycode] == 0) { // keydown
561 qemu_input_event_send_key_number(dcl->con, keycode, true);
562 modifiers_state[keycode] = 1;
564 qemu_input_event_send_key_number(dcl->con, keycode, false);
565 modifiers_state[keycode] = 0;
570 // release Mouse grab when pressing ctrl+alt
571 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
576 keycode = cocoa_keycode_to_qemu([event keyCode]);
578 // forward command key combos to the host UI unless the mouse is grabbed
579 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
580 [NSApp sendEvent:event];
586 // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
587 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
590 // enable graphic console
591 case 0x02 ... 0x0a: // '1' to '9' keys
592 console_select(keycode - 0x02);
596 // handle keys for graphic console
597 } else if (qemu_console_is_graphic(NULL)) {
598 qemu_input_event_send_key_number(dcl->con, keycode, true);
600 // handlekeys for Monitor
603 switch([event keyCode]) {
605 keysym = QEMU_KEY_HOME;
608 keysym = QEMU_KEY_DELETE;
611 keysym = QEMU_KEY_END;
614 keysym = QEMU_KEY_LEFT;
617 keysym = QEMU_KEY_RIGHT;
620 keysym = QEMU_KEY_DOWN;
623 keysym = QEMU_KEY_UP;
627 NSString *ks = [event characters];
629 keysym = [ks characterAtIndex:0];
633 kbd_put_keysym(keysym);
637 keycode = cocoa_keycode_to_qemu([event keyCode]);
639 // don't pass the guest a spurious key-up if we treated this
640 // command-key combo as a host UI action
641 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
645 if (qemu_console_is_graphic(NULL)) {
646 qemu_input_event_send_key_number(dcl->con, keycode, false);
650 if (isAbsoluteEnabled) {
651 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
652 if (isMouseGrabbed) {
656 if (!isMouseGrabbed) {
663 case NSLeftMouseDown:
664 if ([event modifierFlags] & NSCommandKeyMask) {
665 buttons |= MOUSE_EVENT_RBUTTON;
667 buttons |= MOUSE_EVENT_LBUTTON;
671 case NSRightMouseDown:
672 buttons |= MOUSE_EVENT_RBUTTON;
675 case NSOtherMouseDown:
676 buttons |= MOUSE_EVENT_MBUTTON;
679 case NSLeftMouseDragged:
680 if ([event modifierFlags] & NSCommandKeyMask) {
681 buttons |= MOUSE_EVENT_RBUTTON;
683 buttons |= MOUSE_EVENT_LBUTTON;
687 case NSRightMouseDragged:
688 buttons |= MOUSE_EVENT_RBUTTON;
691 case NSOtherMouseDragged:
692 buttons |= MOUSE_EVENT_MBUTTON;
697 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
708 if (isMouseGrabbed) {
709 buttons |= ([event deltaY] < 0) ?
710 MOUSE_EVENT_WHEELUP : MOUSE_EVENT_WHEELDN;
715 [NSApp sendEvent:event];
719 if (last_buttons != buttons) {
720 static uint32_t bmap[INPUT_BUTTON_MAX] = {
721 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
722 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
723 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
724 [INPUT_BUTTON_WHEEL_UP] = MOUSE_EVENT_WHEELUP,
725 [INPUT_BUTTON_WHEEL_DOWN] = MOUSE_EVENT_WHEELDN,
727 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
728 last_buttons = buttons;
730 if (isMouseGrabbed) {
731 if (isAbsoluteEnabled) {
732 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
733 * The check on screenContainsPoint is to avoid sending out of range values for
734 * clicks in the titlebar.
736 if ([self screenContainsPoint:p]) {
737 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, screen.width);
738 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, screen.height);
741 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
742 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
745 [NSApp sendEvent:event];
747 qemu_input_event_sync();
753 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
757 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
759 [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
762 if (!isAbsoluteEnabled) {
763 isMouseDeassociated = TRUE;
764 CGAssociateMouseAndMouseCursorPosition(FALSE);
766 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
771 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
775 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
777 [normalWindow setTitle:@"QEMU"];
780 if (isMouseDeassociated) {
781 CGAssociateMouseAndMouseCursorPosition(TRUE);
782 isMouseDeassociated = FALSE;
784 isMouseGrabbed = FALSE;
787 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
788 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
789 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
790 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
791 - (float) cdx {return cdx;}
792 - (float) cdy {return cdy;}
793 - (QEMUScreen) gscreen {return screen;}
799 ------------------------------------------------------
800 QemuCocoaAppController
801 ------------------------------------------------------
803 @interface QemuCocoaAppController : NSObject
806 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
807 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
808 - (void)doToggleFullScreen:(id)sender;
809 - (void)toggleFullScreen:(id)sender;
810 - (void)showQEMUDoc:(id)sender;
811 - (void)showQEMUTec:(id)sender;
812 - (void)zoomToFit:(id) sender;
815 @implementation QemuCocoaAppController
818 COCOA_DEBUG("QemuCocoaAppController: init\n");
823 // create a view and add it to the window
824 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
826 fprintf(stderr, "(cocoa) can't create a view\n");
831 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
832 styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
833 backing:NSBackingStoreBuffered defer:NO];
835 fprintf(stderr, "(cocoa) can't create window\n");
838 [normalWindow setAcceptsMouseMovedEvents:YES];
839 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU"]];
840 [normalWindow setContentView:cocoaView];
841 [normalWindow useOptimizedDrawing:YES];
842 [normalWindow makeKeyAndOrderFront:self];
843 [normalWindow center];
844 stretch_video = false;
851 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
858 - (void)applicationDidFinishLaunching: (NSNotification *) note
860 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
862 // Display an open dialog box if no arguments were passed or
863 // if qemu was launched from the finder ( the Finder passes "-psn" )
864 if( gArgc <= 1 || strncmp ((char *)gArgv[1], "-psn", 4) == 0) {
865 NSOpenPanel *op = [[NSOpenPanel alloc] init];
866 [op setPrompt:@"Boot image"];
867 [op setMessage:@"Select the disk image you want to boot.\n\nHit the \"Cancel\" button to quit"];
868 NSArray *filetypes = [NSArray arrayWithObjects:@"img", @"iso", @"dmg",
869 @"qcow", @"qcow2", @"cloop", @"vmdk", nil];
870 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
871 [op setAllowedFileTypes:filetypes];
872 [op beginSheetModalForWindow:normalWindow
873 completionHandler:^(NSInteger returnCode)
874 { [self openPanelDidEnd:op
875 returnCode:returnCode contextInfo:NULL ]; } ];
877 // Compatibility code for pre-10.6, using deprecated method
878 [op beginSheetForDirectory:nil file:nil types:filetypes
879 modalForWindow:normalWindow modalDelegate:self
880 didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
883 // or launch QEMU, with the global args
884 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
888 - (void)applicationWillTerminate:(NSNotification *)aNotification
890 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
892 qemu_system_shutdown_request();
896 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
901 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
903 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
906 status = qemu_main(argc, argv, *_NSGetEnviron());
910 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
912 COCOA_DEBUG("QemuCocoaAppController: openPanelDidEnd\n");
914 if(returnCode == NSCancelButton) {
916 } else if(returnCode == NSOKButton) {
917 char *img = (char*)[ [ [ sheet URL ] path ] cStringUsingEncoding:NSASCIIStringEncoding];
919 char **argv = g_new(char *, 4);
923 argv[0] = g_strdup(gArgv[0]);
924 argv[1] = g_strdup("-hda");
925 argv[2] = g_strdup(img);
928 // printf("Using argc %d argv %s -hda %s\n", 3, gArgv[0], img);
930 [self startEmulationWithArgc:3 argv:(char**)argv];
934 /* We abstract the method called by the Enter Fullscreen menu item
935 * because Mac OS 10.7 and higher disables it. This is because of the
936 * menu item's old selector's name toggleFullScreen:
938 - (void) doToggleFullScreen:(id)sender
940 [self toggleFullScreen:(id)sender];
943 - (void)toggleFullScreen:(id)sender
945 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
947 [cocoaView toggleFullScreen:sender];
950 - (void)showQEMUDoc:(id)sender
952 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
954 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-doc.html",
955 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
958 - (void)showQEMUTec:(id)sender
960 COCOA_DEBUG("QemuCocoaAppController: showQEMUTec\n");
962 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-tech.html",
963 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
966 /* Stretches video to fit host monitor size */
967 - (void)zoomToFit:(id) sender
969 stretch_video = !stretch_video;
970 if (stretch_video == true) {
971 [sender setState: NSOnState];
973 [sender setState: NSOffState];
980 int main (int argc, const char * argv[]) {
983 gArgv = (char **)argv;
986 /* In case we don't need to display a window, let's not do that */
987 for (i = 1; i < argc; i++) {
988 const char *opt = argv[i];
991 /* Treat --foo the same as -foo. */
995 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
996 !strcmp(opt, "-vnc") ||
997 !strcmp(opt, "-nographic") ||
998 !strcmp(opt, "-version") ||
999 !strcmp(opt, "-curses") ||
1000 !strcmp(opt, "-qtest")) {
1001 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1006 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1008 // Pull this console process up to being a fully-fledged graphical
1009 // app with a menubar and Dock icon
1010 ProcessSerialNumber psn = { 0, kCurrentProcess };
1011 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1013 [NSApplication sharedApplication];
1017 NSMenuItem *menuItem;
1019 [NSApp setMainMenu:[[NSMenu alloc] init]];
1022 menu = [[NSMenu alloc] initWithTitle:@""];
1023 [menu addItemWithTitle:@"About QEMU" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; // About QEMU
1024 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1025 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1026 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1027 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
1028 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1029 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1030 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1031 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1032 [menuItem setSubmenu:menu];
1033 [[NSApp mainMenu] addItem:menuItem];
1034 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1037 menu = [[NSMenu alloc] initWithTitle:@"View"];
1038 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1039 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1040 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1041 [menuItem setSubmenu:menu];
1042 [[NSApp mainMenu] addItem:menuItem];
1045 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1046 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1047 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1048 [menuItem setSubmenu:menu];
1049 [[NSApp mainMenu] addItem:menuItem];
1050 [NSApp setWindowsMenu:menu];
1053 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1054 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1055 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Technology" action:@selector(showQEMUTec:) keyEquivalent:@""] autorelease]]; // QEMU Help
1056 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1057 [menuItem setSubmenu:menu];
1058 [[NSApp mainMenu] addItem:menuItem];
1060 // Create an Application controller
1061 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1062 [NSApp setDelegate:appController];
1064 // Start the main event loop
1067 [appController release];
1076 static void cocoa_update(DisplayChangeListener *dcl,
1077 int x, int y, int w, int h)
1079 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1081 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1084 if ([cocoaView cdx] == 1.0) {
1085 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1088 x * [cocoaView cdx],
1089 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1090 w * [cocoaView cdx],
1091 h * [cocoaView cdy]);
1093 [cocoaView setNeedsDisplayInRect:rect];
1098 static void cocoa_switch(DisplayChangeListener *dcl,
1099 DisplaySurface *surface)
1101 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1103 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1104 [cocoaView switchSurface:surface];
1108 static void cocoa_refresh(DisplayChangeListener *dcl)
1110 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1112 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1114 if (qemu_input_is_absolute()) {
1115 if (![cocoaView isAbsoluteEnabled]) {
1116 if ([cocoaView isMouseGrabbed]) {
1117 [cocoaView ungrabMouse];
1120 [cocoaView setAbsoluteEnabled:YES];
1123 NSDate *distantPast;
1125 distantPast = [NSDate distantPast];
1127 event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
1128 inMode: NSDefaultRunLoopMode dequeue:YES];
1130 [cocoaView handleEvent:event];
1132 } while(event != nil);
1133 graphic_hw_update(NULL);
1137 static void cocoa_cleanup(void)
1139 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1143 static const DisplayChangeListenerOps dcl_ops = {
1144 .dpy_name = "cocoa",
1145 .dpy_gfx_update = cocoa_update,
1146 .dpy_gfx_switch = cocoa_switch,
1147 .dpy_refresh = cocoa_refresh,
1150 void cocoa_display_init(DisplayState *ds, int full_screen)
1152 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1154 /* if fullscreen mode is to be used */
1155 if (full_screen == true) {
1156 [NSApp activateIgnoringOtherApps: YES];
1157 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1160 dcl = g_malloc0(sizeof(DisplayChangeListener));
1162 // register vga output callbacks
1163 dcl->ops = &dcl_ops;
1164 register_displaychangelistener(dcl);
1166 // register cleanup function
1167 atexit(cocoa_cleanup);