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"
32 #include "qmp-commands.h"
33 #include "sysemu/blockdev.h"
35 #ifndef MAC_OS_X_VERSION_10_5
36 #define MAC_OS_X_VERSION_10_5 1050
38 #ifndef MAC_OS_X_VERSION_10_6
39 #define MAC_OS_X_VERSION_10_6 1060
41 #ifndef MAC_OS_X_VERSION_10_10
42 #define MAC_OS_X_VERSION_10_10 101000
49 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
51 #define COCOA_DEBUG(...) ((void) 0)
54 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
63 NSWindow *normalWindow;
64 static DisplayChangeListener *dcl;
65 static int last_buttons;
70 NSTextField *pauseLabel;
71 NSArray * supportedImageFileTypes;
76 // SdlI macI macH SdlH 104xtH 104xtC sdl
77 30, // 0 0x00 0x1e A QZ_a
78 31, // 1 0x01 0x1f S QZ_s
79 32, // 2 0x02 0x20 D QZ_d
80 33, // 3 0x03 0x21 F QZ_f
81 35, // 4 0x04 0x23 H QZ_h
82 34, // 5 0x05 0x22 G QZ_g
83 44, // 6 0x06 0x2c Z QZ_z
84 45, // 7 0x07 0x2d X QZ_x
85 46, // 8 0x08 0x2e C QZ_c
86 47, // 9 0x09 0x2f V QZ_v
87 0, // 10 0x0A Undefined
88 48, // 11 0x0B 0x30 B QZ_b
89 16, // 12 0x0C 0x10 Q QZ_q
90 17, // 13 0x0D 0x11 W QZ_w
91 18, // 14 0x0E 0x12 E QZ_e
92 19, // 15 0x0F 0x13 R QZ_r
93 21, // 16 0x10 0x15 Y QZ_y
94 20, // 17 0x11 0x14 T QZ_t
95 2, // 18 0x12 0x02 1 QZ_1
96 3, // 19 0x13 0x03 2 QZ_2
97 4, // 20 0x14 0x04 3 QZ_3
98 5, // 21 0x15 0x05 4 QZ_4
99 7, // 22 0x16 0x07 6 QZ_6
100 6, // 23 0x17 0x06 5 QZ_5
101 13, // 24 0x18 0x0d = QZ_EQUALS
102 10, // 25 0x19 0x0a 9 QZ_9
103 8, // 26 0x1A 0x08 7 QZ_7
104 12, // 27 0x1B 0x0c - QZ_MINUS
105 9, // 28 0x1C 0x09 8 QZ_8
106 11, // 29 0x1D 0x0b 0 QZ_0
107 27, // 30 0x1E 0x1b ] QZ_RIGHTBRACKET
108 24, // 31 0x1F 0x18 O QZ_o
109 22, // 32 0x20 0x16 U QZ_u
110 26, // 33 0x21 0x1a [ QZ_LEFTBRACKET
111 23, // 34 0x22 0x17 I QZ_i
112 25, // 35 0x23 0x19 P QZ_p
113 28, // 36 0x24 0x1c ENTER QZ_RETURN
114 38, // 37 0x25 0x26 L QZ_l
115 36, // 38 0x26 0x24 J QZ_j
116 40, // 39 0x27 0x28 ' QZ_QUOTE
117 37, // 40 0x28 0x25 K QZ_k
118 39, // 41 0x29 0x27 ; QZ_SEMICOLON
119 43, // 42 0x2A 0x2b \ QZ_BACKSLASH
120 51, // 43 0x2B 0x33 , QZ_COMMA
121 53, // 44 0x2C 0x35 / QZ_SLASH
122 49, // 45 0x2D 0x31 N QZ_n
123 50, // 46 0x2E 0x32 M QZ_m
124 52, // 47 0x2F 0x34 . QZ_PERIOD
125 15, // 48 0x30 0x0f TAB QZ_TAB
126 57, // 49 0x31 0x39 SPACE QZ_SPACE
127 41, // 50 0x32 0x29 ` QZ_BACKQUOTE
128 14, // 51 0x33 0x0e BKSP QZ_BACKSPACE
129 0, // 52 0x34 Undefined
130 1, // 53 0x35 0x01 ESC QZ_ESCAPE
131 220, // 54 0x36 0xdc E0,5C R GUI QZ_RMETA
132 219, // 55 0x37 0xdb E0,5B L GUI QZ_LMETA
133 42, // 56 0x38 0x2a L SHFT QZ_LSHIFT
134 58, // 57 0x39 0x3a CAPS QZ_CAPSLOCK
135 56, // 58 0x3A 0x38 L ALT QZ_LALT
136 29, // 59 0x3B 0x1d L CTRL QZ_LCTRL
137 54, // 60 0x3C 0x36 R SHFT QZ_RSHIFT
138 184,// 61 0x3D 0xb8 E0,38 R ALT QZ_RALT
139 157,// 62 0x3E 0x9d E0,1D R CTRL QZ_RCTRL
140 0, // 63 0x3F Undefined
141 0, // 64 0x40 Undefined
142 0, // 65 0x41 Undefined
143 0, // 66 0x42 Undefined
144 55, // 67 0x43 0x37 KP * QZ_KP_MULTIPLY
145 0, // 68 0x44 Undefined
146 78, // 69 0x45 0x4e KP + QZ_KP_PLUS
147 0, // 70 0x46 Undefined
148 69, // 71 0x47 0x45 NUM QZ_NUMLOCK
149 0, // 72 0x48 Undefined
150 0, // 73 0x49 Undefined
151 0, // 74 0x4A Undefined
152 181,// 75 0x4B 0xb5 E0,35 KP / QZ_KP_DIVIDE
153 152,// 76 0x4C 0x9c E0,1C KP EN QZ_KP_ENTER
154 0, // 77 0x4D undefined
155 74, // 78 0x4E 0x4a KP - QZ_KP_MINUS
156 0, // 79 0x4F Undefined
157 0, // 80 0x50 Undefined
158 0, // 81 0x51 QZ_KP_EQUALS
159 82, // 82 0x52 0x52 KP 0 QZ_KP0
160 79, // 83 0x53 0x4f KP 1 QZ_KP1
161 80, // 84 0x54 0x50 KP 2 QZ_KP2
162 81, // 85 0x55 0x51 KP 3 QZ_KP3
163 75, // 86 0x56 0x4b KP 4 QZ_KP4
164 76, // 87 0x57 0x4c KP 5 QZ_KP5
165 77, // 88 0x58 0x4d KP 6 QZ_KP6
166 71, // 89 0x59 0x47 KP 7 QZ_KP7
167 0, // 90 0x5A Undefined
168 72, // 91 0x5B 0x48 KP 8 QZ_KP8
169 73, // 92 0x5C 0x49 KP 9 QZ_KP9
170 0, // 93 0x5D Undefined
171 0, // 94 0x5E Undefined
172 0, // 95 0x5F Undefined
173 63, // 96 0x60 0x3f F5 QZ_F5
174 64, // 97 0x61 0x40 F6 QZ_F6
175 65, // 98 0x62 0x41 F7 QZ_F7
176 61, // 99 0x63 0x3d F3 QZ_F3
177 66, // 100 0x64 0x42 F8 QZ_F8
178 67, // 101 0x65 0x43 F9 QZ_F9
179 0, // 102 0x66 Undefined
180 87, // 103 0x67 0x57 F11 QZ_F11
181 0, // 104 0x68 Undefined
182 183,// 105 0x69 0xb7 QZ_PRINT
183 0, // 106 0x6A Undefined
184 70, // 107 0x6B 0x46 SCROLL QZ_SCROLLOCK
185 0, // 108 0x6C Undefined
186 68, // 109 0x6D 0x44 F10 QZ_F10
187 0, // 110 0x6E Undefined
188 88, // 111 0x6F 0x58 F12 QZ_F12
189 0, // 112 0x70 Undefined
190 110,// 113 0x71 0x0 QZ_PAUSE
191 210,// 114 0x72 0xd2 E0,52 INSERT QZ_INSERT
192 199,// 115 0x73 0xc7 E0,47 HOME QZ_HOME
193 201,// 116 0x74 0xc9 E0,49 PG UP QZ_PAGEUP
194 211,// 117 0x75 0xd3 E0,53 DELETE QZ_DELETE
195 62, // 118 0x76 0x3e F4 QZ_F4
196 207,// 119 0x77 0xcf E0,4f END QZ_END
197 60, // 120 0x78 0x3c F2 QZ_F2
198 209,// 121 0x79 0xd1 E0,51 PG DN QZ_PAGEDOWN
199 59, // 122 0x7A 0x3b F1 QZ_F1
200 203,// 123 0x7B 0xcb e0,4B L ARROW QZ_LEFT
201 205,// 124 0x7C 0xcd e0,4D R ARROW QZ_RIGHT
202 208,// 125 0x7D 0xd0 E0,50 D ARROW QZ_DOWN
203 200,// 126 0x7E 0xc8 E0,48 U ARROW QZ_UP
204 /* 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 /* Additional 104 Key XP-Keyboard Scancodes from http://www.computer-engineering.org/ps2keyboard/scancodes1.html */
208 221 // 0xdd e0,5d APPS
209 // E0,2A,E0,37 PRNT SCRN
210 // E1,1D,45,E1,9D,C5 PAUSE
213 222 // 0xde E0, 5E Power
214 223 // 0xdf E0, 5F Sleep
215 227 // 0xe3 E0, 63 Wake
216 // Windows Multimedia Scan Codes
217 153 // 0x99 E0, 19 Next Track
218 144 // 0x90 E0, 10 Previous Track
219 164 // 0xa4 E0, 24 Stop
220 162 // 0xa2 E0, 22 Play/Pause
221 160 // 0xa0 E0, 20 Mute
222 176 // 0xb0 E0, 30 Volume Up
223 174 // 0xae E0, 2E Volume Down
224 237 // 0xed E0, 6D Media Select
225 236 // 0xec E0, 6C E-Mail
226 161 // 0xa1 E0, 21 Calculator
227 235 // 0xeb E0, 6B My Computer
228 229 // 0xe5 E0, 65 WWW Search
229 178 // 0xb2 E0, 32 WWW Home
230 234 // 0xea E0, 6A WWW Back
231 233 // 0xe9 E0, 69 WWW Forward
232 232 // 0xe8 E0, 68 WWW Stop
233 231 // 0xe7 E0, 67 WWW Refresh
234 230 // 0xe6 E0, 66 WWW Favorites
238 static int cocoa_keycode_to_qemu(int keycode)
240 if (ARRAY_SIZE(keymap) <= keycode) {
241 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
244 return keymap[keycode];
247 /* Displays an alert dialog box with the specified message */
248 static void QEMU_Alert(NSString *message)
251 alert = [NSAlert new];
252 [alert setMessageText: message];
256 /* Handles any errors that happen with a device transaction */
257 static void handleAnyDeviceErrors(Error * err)
260 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
261 encoding: NSASCIIStringEncoding]);
267 ------------------------------------------------------
269 ------------------------------------------------------
271 @interface QemuCocoaView : NSView
274 NSWindow *fullScreenWindow;
275 float cx,cy,cw,ch,cdx,cdy;
276 CGDataProviderRef dataProviderRef;
277 int modifiers_state[256];
280 BOOL isAbsoluteEnabled;
281 BOOL isMouseDeassociated;
283 - (void) switchSurface:(DisplaySurface *)surface;
285 - (void) ungrabMouse;
286 - (void) toggleFullScreen:(id)sender;
287 - (void) handleEvent:(NSEvent *)event;
288 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
289 /* The state surrounding mouse grabbing is potentially confusing.
290 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
291 * pointing device an absolute-position one?"], but is only updated on
293 * isMouseGrabbed tracks whether GUI events are directed to the guest;
294 * it controls whether special keys like Cmd get sent to the guest,
295 * and whether we capture the mouse when in non-absolute mode.
296 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
297 * the mouse and mouse cursor position by calling
298 * CGAssociateMouseAndMouseCursorPosition(FALSE)
299 * (which basically happens if we grab in non-absolute mode).
301 - (BOOL) isMouseGrabbed;
302 - (BOOL) isAbsoluteEnabled;
303 - (BOOL) isMouseDeassociated;
306 - (QEMUScreen) gscreen;
307 - (void) raiseAllKeys;
310 QemuCocoaView *cocoaView;
312 @implementation QemuCocoaView
313 - (id)initWithFrame:(NSRect)frameRect
315 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
317 self = [super initWithFrame:frameRect];
320 screen.bitsPerComponent = 8;
321 screen.bitsPerPixel = 32;
322 screen.width = frameRect.size.width;
323 screen.height = frameRect.size.height;
331 COCOA_DEBUG("QemuCocoaView: dealloc\n");
334 CGDataProviderRelease(dataProviderRef);
344 - (BOOL) screenContainsPoint:(NSPoint) p
346 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
357 - (void) unhideCursor
365 - (void) drawRect:(NSRect) rect
367 COCOA_DEBUG("QemuCocoaView: drawRect\n");
369 // get CoreGraphic context
370 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
371 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
372 CGContextSetShouldAntialias (viewContextRef, NO);
374 // draw screen bitmap directly to Core Graphics context
375 if (!dataProviderRef) {
376 // Draw request before any guest device has set up a framebuffer:
377 // just draw an opaque black rectangle
378 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
379 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
381 CGImageRef imageRef = CGImageCreate(
382 screen.width, //width
383 screen.height, //height
384 screen.bitsPerComponent, //bitsPerComponent
385 screen.bitsPerPixel, //bitsPerPixel
386 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
387 #ifdef __LITTLE_ENDIAN__
388 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
389 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
391 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
392 kCGImageAlphaNoneSkipFirst, //bitmapInfo
394 dataProviderRef, //provider
397 kCGRenderingIntentDefault //intent
399 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
400 const NSRect *rectList;
403 CGImageRef clipImageRef;
406 [self getRectsBeingDrawn:&rectList count:&rectCount];
407 for (i = 0; i < rectCount; i++) {
408 clipRect.origin.x = rectList[i].origin.x / cdx;
409 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
410 clipRect.size.width = rectList[i].size.width / cdx;
411 clipRect.size.height = rectList[i].size.height / cdy;
412 clipImageRef = CGImageCreateWithImageInRect(
416 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
417 CGImageRelease (clipImageRef);
419 CGImageRelease (imageRef);
423 - (void) setContentDimensions
425 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
428 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
429 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
431 /* stretches video, but keeps same aspect ratio */
432 if (stretch_video == true) {
433 /* use smallest stretch value - prevents clipping on sides */
434 if (MIN(cdx, cdy) == cdx) {
439 } else { /* No stretching */
442 cw = screen.width * cdx;
443 ch = screen.height * cdy;
444 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
445 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
456 - (void) switchSurface:(DisplaySurface *)surface
458 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
460 int w = surface_width(surface);
461 int h = surface_height(surface);
462 /* cdx == 0 means this is our very first surface, in which case we need
463 * to recalculate the content dimensions even if it happens to be the size
464 * of the initial empty window.
466 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
468 int oldh = screen.height;
470 // Resize before we trigger the redraw, or we'll redraw at the wrong size
471 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
474 [self setContentDimensions];
475 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
478 // update screenBuffer
480 CGDataProviderRelease(dataProviderRef);
482 //sync host window color space with guests
483 screen.bitsPerPixel = surface_bits_per_pixel(surface);
484 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
486 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
490 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
491 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
494 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
495 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
499 [normalWindow center];
503 - (void) toggleFullScreen:(id)sender
505 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
507 if (isFullscreen) { // switch from fullscreen to desktop
508 isFullscreen = FALSE;
510 [self setContentDimensions];
511 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
512 [self exitFullScreenModeWithOptions:nil];
514 [fullScreenWindow close];
515 [normalWindow setContentView: self];
516 [normalWindow makeKeyAndOrderFront: self];
517 [NSMenu setMenuBarVisible:YES];
519 } else { // switch from desktop to fullscreen
521 [normalWindow orderOut: nil]; /* Hide the window */
523 [self setContentDimensions];
524 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
525 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
526 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
527 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
530 [NSMenu setMenuBarVisible:NO];
531 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
532 styleMask:NSBorderlessWindowMask
533 backing:NSBackingStoreBuffered
535 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
536 [fullScreenWindow setHasShadow:NO];
537 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
538 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
539 [[fullScreenWindow contentView] addSubview: self];
540 [fullScreenWindow makeKeyAndOrderFront:self];
545 - (void) handleEvent:(NSEvent *)event
547 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
551 bool mouse_event = false;
552 NSPoint p = [event locationInWindow];
554 switch ([event type]) {
556 keycode = cocoa_keycode_to_qemu([event keyCode]);
558 if ((keycode == 219 || keycode == 220) && !isMouseGrabbed) {
559 /* Don't pass command key changes to guest unless mouse is grabbed */
564 if (keycode == 58 || keycode == 69) { // emulate caps lock and num lock keydown and keyup
565 qemu_input_event_send_key_number(dcl->con, keycode, true);
566 qemu_input_event_send_key_number(dcl->con, keycode, false);
567 } else if (qemu_console_is_graphic(NULL)) {
568 if (modifiers_state[keycode] == 0) { // keydown
569 qemu_input_event_send_key_number(dcl->con, keycode, true);
570 modifiers_state[keycode] = 1;
572 qemu_input_event_send_key_number(dcl->con, keycode, false);
573 modifiers_state[keycode] = 0;
578 // release Mouse grab when pressing ctrl+alt
579 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
584 keycode = cocoa_keycode_to_qemu([event keyCode]);
586 // forward command key combos to the host UI unless the mouse is grabbed
587 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
588 [NSApp sendEvent:event];
594 // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
595 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
598 // enable graphic console
599 case 0x02 ... 0x0a: // '1' to '9' keys
600 console_select(keycode - 0x02);
604 // handle keys for graphic console
605 } else if (qemu_console_is_graphic(NULL)) {
606 qemu_input_event_send_key_number(dcl->con, keycode, true);
608 // handlekeys for Monitor
611 switch([event keyCode]) {
613 keysym = QEMU_KEY_HOME;
616 keysym = QEMU_KEY_DELETE;
619 keysym = QEMU_KEY_END;
622 keysym = QEMU_KEY_LEFT;
625 keysym = QEMU_KEY_RIGHT;
628 keysym = QEMU_KEY_DOWN;
631 keysym = QEMU_KEY_UP;
635 NSString *ks = [event characters];
637 keysym = [ks characterAtIndex:0];
641 kbd_put_keysym(keysym);
645 keycode = cocoa_keycode_to_qemu([event keyCode]);
647 // don't pass the guest a spurious key-up if we treated this
648 // command-key combo as a host UI action
649 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
653 if (qemu_console_is_graphic(NULL)) {
654 qemu_input_event_send_key_number(dcl->con, keycode, false);
658 if (isAbsoluteEnabled) {
659 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
660 if (isMouseGrabbed) {
664 if (!isMouseGrabbed) {
671 case NSLeftMouseDown:
672 if ([event modifierFlags] & NSCommandKeyMask) {
673 buttons |= MOUSE_EVENT_RBUTTON;
675 buttons |= MOUSE_EVENT_LBUTTON;
679 case NSRightMouseDown:
680 buttons |= MOUSE_EVENT_RBUTTON;
683 case NSOtherMouseDown:
684 buttons |= MOUSE_EVENT_MBUTTON;
687 case NSLeftMouseDragged:
688 if ([event modifierFlags] & NSCommandKeyMask) {
689 buttons |= MOUSE_EVENT_RBUTTON;
691 buttons |= MOUSE_EVENT_LBUTTON;
695 case NSRightMouseDragged:
696 buttons |= MOUSE_EVENT_RBUTTON;
699 case NSOtherMouseDragged:
700 buttons |= MOUSE_EVENT_MBUTTON;
705 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
716 if (isMouseGrabbed) {
717 buttons |= ([event deltaY] < 0) ?
718 MOUSE_EVENT_WHEELUP : MOUSE_EVENT_WHEELDN;
723 [NSApp sendEvent:event];
727 /* Don't send button events to the guest unless we've got a
728 * mouse grab or window focus. If we have neither then this event
729 * is the user clicking on the background window to activate and
730 * bring us to the front, which will be done by the sendEvent
731 * call below. We definitely don't want to pass that click through
734 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
735 (last_buttons != buttons)) {
736 static uint32_t bmap[INPUT_BUTTON__MAX] = {
737 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
738 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
739 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
740 [INPUT_BUTTON_WHEELUP] = MOUSE_EVENT_WHEELUP,
741 [INPUT_BUTTON_WHEELDOWN] = MOUSE_EVENT_WHEELDN,
743 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
744 last_buttons = buttons;
746 if (isMouseGrabbed) {
747 if (isAbsoluteEnabled) {
748 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
749 * The check on screenContainsPoint is to avoid sending out of range values for
750 * clicks in the titlebar.
752 if ([self screenContainsPoint:p]) {
753 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, screen.width);
754 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, screen.height);
757 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
758 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
761 [NSApp sendEvent:event];
763 qemu_input_event_sync();
769 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
773 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
775 [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
778 if (!isAbsoluteEnabled) {
779 isMouseDeassociated = TRUE;
780 CGAssociateMouseAndMouseCursorPosition(FALSE);
782 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
787 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
791 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
793 [normalWindow setTitle:@"QEMU"];
796 if (isMouseDeassociated) {
797 CGAssociateMouseAndMouseCursorPosition(TRUE);
798 isMouseDeassociated = FALSE;
800 isMouseGrabbed = FALSE;
803 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
804 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
805 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
806 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
807 - (float) cdx {return cdx;}
808 - (float) cdy {return cdy;}
809 - (QEMUScreen) gscreen {return screen;}
812 * Makes the target think all down keys are being released.
813 * This prevents a stuck key problem, since we will not see
814 * key up events for those keys after we have lost focus.
816 - (void) raiseAllKeys
819 const int max_index = ARRAY_SIZE(modifiers_state);
821 for (index = 0; index < max_index; index++) {
822 if (modifiers_state[index]) {
823 modifiers_state[index] = 0;
824 qemu_input_event_send_key_number(dcl->con, index, false);
833 ------------------------------------------------------
834 QemuCocoaAppController
835 ------------------------------------------------------
837 @interface QemuCocoaAppController : NSObject
838 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
839 <NSWindowDelegate, NSApplicationDelegate>
843 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
844 - (void)doToggleFullScreen:(id)sender;
845 - (void)toggleFullScreen:(id)sender;
846 - (void)showQEMUDoc:(id)sender;
847 - (void)showQEMUTec:(id)sender;
848 - (void)zoomToFit:(id) sender;
849 - (void)displayConsole:(id)sender;
850 - (void)pauseQEMU:(id)sender;
851 - (void)resumeQEMU:(id)sender;
852 - (void)displayPause;
854 - (void)restartQEMU:(id)sender;
855 - (void)powerDownQEMU:(id)sender;
856 - (void)ejectDeviceMedia:(id)sender;
857 - (void)changeDeviceMedia:(id)sender;
861 @implementation QemuCocoaAppController
864 COCOA_DEBUG("QemuCocoaAppController: init\n");
869 // create a view and add it to the window
870 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
872 fprintf(stderr, "(cocoa) can't create a view\n");
877 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
878 styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
879 backing:NSBackingStoreBuffered defer:NO];
881 fprintf(stderr, "(cocoa) can't create window\n");
884 [normalWindow setAcceptsMouseMovedEvents:YES];
885 [normalWindow setTitle:@"QEMU"];
886 [normalWindow setContentView:cocoaView];
887 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
888 [normalWindow useOptimizedDrawing:YES];
890 [normalWindow makeKeyAndOrderFront:self];
891 [normalWindow center];
892 [normalWindow setDelegate: self];
893 stretch_video = false;
895 /* Used for displaying pause on the screen */
896 pauseLabel = [NSTextField new];
897 [pauseLabel setBezeled:YES];
898 [pauseLabel setDrawsBackground:YES];
899 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
900 [pauseLabel setEditable:NO];
901 [pauseLabel setSelectable:NO];
902 [pauseLabel setStringValue: @"Paused"];
903 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
904 [pauseLabel setTextColor: [NSColor blackColor]];
905 [pauseLabel sizeToFit];
907 // set the supported image file types that can be opened
908 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
909 @"qcow", @"qcow2", @"cloop", @"vmdk", nil];
916 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
923 - (void)applicationDidFinishLaunching: (NSNotification *) note
925 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
926 // launch QEMU, with the global args
927 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
930 - (void)applicationWillTerminate:(NSNotification *)aNotification
932 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
934 qemu_system_shutdown_request();
938 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
943 - (NSApplicationTerminateReply)applicationShouldTerminate:
944 (NSApplication *)sender
946 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
947 return [self verifyQuit];
950 /* Called when the user clicks on a window's close button */
951 - (BOOL)windowShouldClose:(id)sender
953 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
954 [NSApp terminate: sender];
955 /* If the user allows the application to quit then the call to
956 * NSApp terminate will never return. If we get here then the user
957 * cancelled the quit, so we should return NO to not permit the
958 * closing of this window.
963 /* Called when QEMU goes into the background */
964 - (void) applicationWillResignActive: (NSNotification *)aNotification
966 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
967 [cocoaView raiseAllKeys];
970 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
972 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
975 status = qemu_main(argc, argv, *_NSGetEnviron());
979 /* We abstract the method called by the Enter Fullscreen menu item
980 * because Mac OS 10.7 and higher disables it. This is because of the
981 * menu item's old selector's name toggleFullScreen:
983 - (void) doToggleFullScreen:(id)sender
985 [self toggleFullScreen:(id)sender];
988 - (void)toggleFullScreen:(id)sender
990 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
992 [cocoaView toggleFullScreen:sender];
995 - (void)showQEMUDoc:(id)sender
997 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
999 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-doc.html",
1000 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
1003 - (void)showQEMUTec:(id)sender
1005 COCOA_DEBUG("QemuCocoaAppController: showQEMUTec\n");
1007 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-tech.html",
1008 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
1011 /* Stretches video to fit host monitor size */
1012 - (void)zoomToFit:(id) sender
1014 stretch_video = !stretch_video;
1015 if (stretch_video == true) {
1016 [sender setState: NSOnState];
1018 [sender setState: NSOffState];
1022 /* Displays the console on the screen */
1023 - (void)displayConsole:(id)sender
1025 console_select([sender tag]);
1028 /* Pause the guest */
1029 - (void)pauseQEMU:(id)sender
1032 [sender setEnabled: NO];
1033 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1034 [self displayPause];
1037 /* Resume running the guest operating system */
1038 - (void)resumeQEMU:(id) sender
1041 [sender setEnabled: NO];
1042 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1046 /* Displays the word pause on the screen */
1047 - (void)displayPause
1049 /* Coordinates have to be calculated each time because the window can change its size */
1050 int xCoord, yCoord, width, height;
1051 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1052 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1053 width = [pauseLabel frame].size.width;
1054 height = [pauseLabel frame].size.height;
1055 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1056 [cocoaView addSubview: pauseLabel];
1059 /* Removes the word pause from the screen */
1062 [pauseLabel removeFromSuperview];
1066 - (void)restartQEMU:(id)sender
1068 qmp_system_reset(NULL);
1071 /* Powers down QEMU */
1072 - (void)powerDownQEMU:(id)sender
1074 qmp_system_powerdown(NULL);
1077 /* Ejects the media.
1078 * Uses sender's tag to figure out the device to eject.
1080 - (void)ejectDeviceMedia:(id)sender
1083 drive = [sender representedObject];
1086 QEMU_Alert(@"Failed to find drive to eject!");
1091 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding], false, false, &err);
1092 handleAnyDeviceErrors(err);
1095 /* Displays a dialog box asking the user to select an image file to load.
1096 * Uses sender's represented object value to figure out which drive to use.
1098 - (void)changeDeviceMedia:(id)sender
1100 /* Find the drive name */
1102 drive = [sender representedObject];
1105 QEMU_Alert(@"Could not find drive!");
1109 /* Display the file open dialog */
1110 NSOpenPanel * openPanel;
1111 openPanel = [NSOpenPanel openPanel];
1112 [openPanel setCanChooseFiles: YES];
1113 [openPanel setAllowsMultipleSelection: NO];
1114 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1115 if([openPanel runModal] == NSFileHandlingPanelOKButton) {
1116 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1119 QEMU_Alert(@"Failed to convert URL to file path!");
1124 qmp_blockdev_change_medium([drive cStringUsingEncoding:
1125 NSASCIIStringEncoding],
1126 [file cStringUsingEncoding:
1127 NSASCIIStringEncoding],
1131 handleAnyDeviceErrors(err);
1135 /* Verifies if the user really wants to quit */
1138 NSAlert *alert = [NSAlert new];
1139 [alert autorelease];
1140 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1141 [alert addButtonWithTitle: @"Cancel"];
1142 [alert addButtonWithTitle: @"Quit"];
1143 if([alert runModal] == NSAlertSecondButtonReturn) {
1153 int main (int argc, const char * argv[]) {
1156 gArgv = (char **)argv;
1159 /* In case we don't need to display a window, let's not do that */
1160 for (i = 1; i < argc; i++) {
1161 const char *opt = argv[i];
1163 if (opt[0] == '-') {
1164 /* Treat --foo the same as -foo. */
1165 if (opt[1] == '-') {
1168 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1169 !strcmp(opt, "-vnc") ||
1170 !strcmp(opt, "-nographic") ||
1171 !strcmp(opt, "-version") ||
1172 !strcmp(opt, "-curses") ||
1173 !strcmp(opt, "-display") ||
1174 !strcmp(opt, "-qtest")) {
1175 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1180 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1182 // Pull this console process up to being a fully-fledged graphical
1183 // app with a menubar and Dock icon
1184 ProcessSerialNumber psn = { 0, kCurrentProcess };
1185 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1187 [NSApplication sharedApplication];
1191 NSMenuItem *menuItem;
1193 [NSApp setMainMenu:[[NSMenu alloc] init]];
1196 menu = [[NSMenu alloc] initWithTitle:@""];
1197 [menu addItemWithTitle:@"About QEMU" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; // About QEMU
1198 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1199 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1200 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1201 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
1202 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1203 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1204 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1205 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1206 [menuItem setSubmenu:menu];
1207 [[NSApp mainMenu] addItem:menuItem];
1208 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1211 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1212 [menu setAutoenablesItems: NO];
1213 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1214 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1215 [menu addItem: menuItem];
1216 [menuItem setEnabled: NO];
1217 [menu addItem: [NSMenuItem separatorItem]];
1218 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1219 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1220 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1221 [menuItem setSubmenu:menu];
1222 [[NSApp mainMenu] addItem:menuItem];
1225 menu = [[NSMenu alloc] initWithTitle:@"View"];
1226 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1227 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1228 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1229 [menuItem setSubmenu:menu];
1230 [[NSApp mainMenu] addItem:menuItem];
1233 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1234 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1235 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1236 [menuItem setSubmenu:menu];
1237 [[NSApp mainMenu] addItem:menuItem];
1238 [NSApp setWindowsMenu:menu];
1241 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1242 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1243 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Technology" action:@selector(showQEMUTec:) keyEquivalent:@""] autorelease]]; // QEMU Help
1244 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1245 [menuItem setSubmenu:menu];
1246 [[NSApp mainMenu] addItem:menuItem];
1248 // Create an Application controller
1249 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1250 [NSApp setDelegate:appController];
1252 // Start the main event loop
1255 [appController release];
1264 static void cocoa_update(DisplayChangeListener *dcl,
1265 int x, int y, int w, int h)
1267 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1269 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1272 if ([cocoaView cdx] == 1.0) {
1273 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1276 x * [cocoaView cdx],
1277 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1278 w * [cocoaView cdx],
1279 h * [cocoaView cdy]);
1281 [cocoaView setNeedsDisplayInRect:rect];
1286 static void cocoa_switch(DisplayChangeListener *dcl,
1287 DisplaySurface *surface)
1289 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1291 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1292 [cocoaView switchSurface:surface];
1296 static void cocoa_refresh(DisplayChangeListener *dcl)
1298 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1300 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1301 graphic_hw_update(NULL);
1303 if (qemu_input_is_absolute()) {
1304 if (![cocoaView isAbsoluteEnabled]) {
1305 if ([cocoaView isMouseGrabbed]) {
1306 [cocoaView ungrabMouse];
1309 [cocoaView setAbsoluteEnabled:YES];
1312 NSDate *distantPast;
1314 distantPast = [NSDate distantPast];
1316 event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
1317 inMode: NSDefaultRunLoopMode dequeue:YES];
1319 [cocoaView handleEvent:event];
1321 } while(event != nil);
1325 static void cocoa_cleanup(void)
1327 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1331 static const DisplayChangeListenerOps dcl_ops = {
1332 .dpy_name = "cocoa",
1333 .dpy_gfx_update = cocoa_update,
1334 .dpy_gfx_switch = cocoa_switch,
1335 .dpy_refresh = cocoa_refresh,
1338 /* Returns a name for a given console */
1339 static NSString * getConsoleName(QemuConsole * console)
1341 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1344 /* Add an entry to the View menu for each console */
1345 static void add_console_menu_entries(void)
1348 NSMenuItem *menuItem;
1351 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1353 [menu addItem:[NSMenuItem separatorItem]];
1355 while (qemu_console_lookup_by_index(index) != NULL) {
1356 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1357 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1358 [menuItem setTag: index];
1359 [menu addItem: menuItem];
1364 /* Make menu items for all removable devices.
1365 * Each device is given an 'Eject' and 'Change' menu item.
1367 static void addRemovableDevicesMenuItems(void)
1370 NSMenuItem *menuItem;
1371 BlockInfoList *currentDevice, *pointerToFree;
1372 NSString *deviceName;
1374 currentDevice = qmp_query_block(NULL);
1375 pointerToFree = currentDevice;
1376 if(currentDevice == NULL) {
1378 QEMU_Alert(@"Failed to query for block devices!");
1382 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1384 // Add a separator between related groups of menu items
1385 [menu addItem:[NSMenuItem separatorItem]];
1387 // Set the attributes to the "Removable Media" menu item
1388 NSString *titleString = @"Removable Media";
1389 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1390 NSColor *newColor = [NSColor blackColor];
1391 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1392 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1393 traits:NSBoldFontMask|NSItalicFontMask
1396 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1397 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1398 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1400 // Add the "Removable Media" menu item
1401 menuItem = [NSMenuItem new];
1402 [menuItem setAttributedTitle: attString];
1403 [menuItem setEnabled: NO];
1404 [menu addItem: menuItem];
1406 /* Loop thru all the block devices in the emulator */
1407 while (currentDevice) {
1408 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1410 if(currentDevice->value->removable) {
1411 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1412 action: @selector(changeDeviceMedia:)
1413 keyEquivalent: @""];
1414 [menu addItem: menuItem];
1415 [menuItem setRepresentedObject: deviceName];
1416 [menuItem autorelease];
1418 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1419 action: @selector(ejectDeviceMedia:)
1420 keyEquivalent: @""];
1421 [menu addItem: menuItem];
1422 [menuItem setRepresentedObject: deviceName];
1423 [menuItem autorelease];
1425 currentDevice = currentDevice->next;
1427 qapi_free_BlockInfoList(pointerToFree);
1430 void cocoa_display_init(DisplayState *ds, int full_screen)
1432 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1434 /* if fullscreen mode is to be used */
1435 if (full_screen == true) {
1436 [NSApp activateIgnoringOtherApps: YES];
1437 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1440 dcl = g_malloc0(sizeof(DisplayChangeListener));
1442 // register vga output callbacks
1443 dcl->ops = &dcl_ops;
1444 register_displaychangelistener(dcl);
1446 // register cleanup function
1447 atexit(cocoa_cleanup);
1449 /* At this point QEMU has created all the consoles, so we can add View
1450 * menu entries for them.
1452 add_console_menu_entries();
1454 /* Give all removable devices a menu item.
1455 * Has to be called after QEMU has started to
1456 * find out what removable devices it has.
1458 addRemovableDevicesMenuItems();