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 #include "qemu/osdep.h"
27 #import <Cocoa/Cocoa.h>
28 #include <crt_externs.h>
30 #include "qemu-common.h"
31 #include "ui/console.h"
33 #include "sysemu/sysemu.h"
34 #include "qmp-commands.h"
35 #include "sysemu/blockdev.h"
36 #include "qemu-version.h"
37 #include <Carbon/Carbon.h>
39 #ifndef MAC_OS_X_VERSION_10_5
40 #define MAC_OS_X_VERSION_10_5 1050
42 #ifndef MAC_OS_X_VERSION_10_6
43 #define MAC_OS_X_VERSION_10_6 1060
45 #ifndef MAC_OS_X_VERSION_10_10
46 #define MAC_OS_X_VERSION_10_10 101000
48 #ifndef MAC_OS_X_VERSION_10_12
49 #define MAC_OS_X_VERSION_10_12 101200
52 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
53 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
54 #define NSEventMaskAny NSAnyEventMask
55 #define NSEventModifierFlagCommand NSCommandKeyMask
56 #define NSEventModifierFlagControl NSControlKeyMask
57 #define NSEventModifierFlagOption NSAlternateKeyMask
58 #define NSEventTypeFlagsChanged NSFlagsChanged
59 #define NSEventTypeKeyUp NSKeyUp
60 #define NSEventTypeKeyDown NSKeyDown
61 #define NSEventTypeMouseMoved NSMouseMoved
62 #define NSEventTypeLeftMouseDown NSLeftMouseDown
63 #define NSEventTypeRightMouseDown NSRightMouseDown
64 #define NSEventTypeOtherMouseDown NSOtherMouseDown
65 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
66 #define NSEventTypeRightMouseDragged NSRightMouseDragged
67 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
68 #define NSEventTypeLeftMouseUp NSLeftMouseUp
69 #define NSEventTypeRightMouseUp NSRightMouseUp
70 #define NSEventTypeOtherMouseUp NSOtherMouseUp
71 #define NSEventTypeScrollWheel NSScrollWheel
72 #define NSTextAlignmentCenter NSCenterTextAlignment
73 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
74 #define NSWindowStyleMaskClosable NSClosableWindowMask
75 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
76 #define NSWindowStyleMaskTitled NSTitledWindowMask
82 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
84 #define COCOA_DEBUG(...) ((void) 0)
87 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
96 NSWindow *normalWindow, *about_window;
97 static DisplayChangeListener *dcl;
98 static int last_buttons;
103 NSTextField *pauseLabel;
104 NSArray * supportedImageFileTypes;
106 // Mac to QKeyCode conversion
107 const int mac_to_qkeycode_map[] = {
108 [kVK_ANSI_A] = Q_KEY_CODE_A,
109 [kVK_ANSI_B] = Q_KEY_CODE_B,
110 [kVK_ANSI_C] = Q_KEY_CODE_C,
111 [kVK_ANSI_D] = Q_KEY_CODE_D,
112 [kVK_ANSI_E] = Q_KEY_CODE_E,
113 [kVK_ANSI_F] = Q_KEY_CODE_F,
114 [kVK_ANSI_G] = Q_KEY_CODE_G,
115 [kVK_ANSI_H] = Q_KEY_CODE_H,
116 [kVK_ANSI_I] = Q_KEY_CODE_I,
117 [kVK_ANSI_J] = Q_KEY_CODE_J,
118 [kVK_ANSI_K] = Q_KEY_CODE_K,
119 [kVK_ANSI_L] = Q_KEY_CODE_L,
120 [kVK_ANSI_M] = Q_KEY_CODE_M,
121 [kVK_ANSI_N] = Q_KEY_CODE_N,
122 [kVK_ANSI_O] = Q_KEY_CODE_O,
123 [kVK_ANSI_P] = Q_KEY_CODE_P,
124 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
125 [kVK_ANSI_R] = Q_KEY_CODE_R,
126 [kVK_ANSI_S] = Q_KEY_CODE_S,
127 [kVK_ANSI_T] = Q_KEY_CODE_T,
128 [kVK_ANSI_U] = Q_KEY_CODE_U,
129 [kVK_ANSI_V] = Q_KEY_CODE_V,
130 [kVK_ANSI_W] = Q_KEY_CODE_W,
131 [kVK_ANSI_X] = Q_KEY_CODE_X,
132 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
133 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
135 [kVK_ANSI_0] = Q_KEY_CODE_0,
136 [kVK_ANSI_1] = Q_KEY_CODE_1,
137 [kVK_ANSI_2] = Q_KEY_CODE_2,
138 [kVK_ANSI_3] = Q_KEY_CODE_3,
139 [kVK_ANSI_4] = Q_KEY_CODE_4,
140 [kVK_ANSI_5] = Q_KEY_CODE_5,
141 [kVK_ANSI_6] = Q_KEY_CODE_6,
142 [kVK_ANSI_7] = Q_KEY_CODE_7,
143 [kVK_ANSI_8] = Q_KEY_CODE_8,
144 [kVK_ANSI_9] = Q_KEY_CODE_9,
146 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
147 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
148 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
149 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
150 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
151 [kVK_Tab] = Q_KEY_CODE_TAB,
152 [kVK_Return] = Q_KEY_CODE_RET,
153 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
154 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
155 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
156 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
157 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
158 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
159 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
160 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
161 [kVK_Shift] = Q_KEY_CODE_SHIFT,
162 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
163 [kVK_Control] = Q_KEY_CODE_CTRL,
164 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
165 [kVK_Option] = Q_KEY_CODE_ALT,
166 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
167 [kVK_Command] = Q_KEY_CODE_META_L,
168 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
169 [kVK_Space] = Q_KEY_CODE_SPC,
171 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
172 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
173 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
174 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
175 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
176 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
177 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
178 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
179 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
180 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
181 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
182 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
183 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
184 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
185 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
186 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
187 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
188 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
190 [kVK_UpArrow] = Q_KEY_CODE_UP,
191 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
192 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
193 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
195 [kVK_Help] = Q_KEY_CODE_INSERT,
196 [kVK_Home] = Q_KEY_CODE_HOME,
197 [kVK_PageUp] = Q_KEY_CODE_PGUP,
198 [kVK_PageDown] = Q_KEY_CODE_PGDN,
199 [kVK_End] = Q_KEY_CODE_END,
200 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
202 [kVK_Escape] = Q_KEY_CODE_ESC,
204 /* The Power key can't be used directly because the operating system uses
205 * it. This key can be emulated by using it in place of another key such as
206 * F1. Don't forget to disable the real key binding.
208 /* [kVK_F1] = Q_KEY_CODE_POWER, */
210 [kVK_F1] = Q_KEY_CODE_F1,
211 [kVK_F2] = Q_KEY_CODE_F2,
212 [kVK_F3] = Q_KEY_CODE_F3,
213 [kVK_F4] = Q_KEY_CODE_F4,
214 [kVK_F5] = Q_KEY_CODE_F5,
215 [kVK_F6] = Q_KEY_CODE_F6,
216 [kVK_F7] = Q_KEY_CODE_F7,
217 [kVK_F8] = Q_KEY_CODE_F8,
218 [kVK_F9] = Q_KEY_CODE_F9,
219 [kVK_F10] = Q_KEY_CODE_F10,
220 [kVK_F11] = Q_KEY_CODE_F11,
221 [kVK_F12] = Q_KEY_CODE_F12,
222 [kVK_F13] = Q_KEY_CODE_PRINT,
223 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
224 [kVK_F15] = Q_KEY_CODE_PAUSE,
227 * The eject and volume keys can't be used here because they are handled at
228 * a lower level than what an Application can see.
232 static int cocoa_keycode_to_qemu(int keycode)
234 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
235 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
238 return mac_to_qkeycode_map[keycode];
241 /* Displays an alert dialog box with the specified message */
242 static void QEMU_Alert(NSString *message)
245 alert = [NSAlert new];
246 [alert setMessageText: message];
250 /* Handles any errors that happen with a device transaction */
251 static void handleAnyDeviceErrors(Error * err)
254 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
255 encoding: NSASCIIStringEncoding]);
261 ------------------------------------------------------
263 ------------------------------------------------------
265 @interface QemuCocoaView : NSView
268 NSWindow *fullScreenWindow;
269 float cx,cy,cw,ch,cdx,cdy;
270 CGDataProviderRef dataProviderRef;
271 int modifiers_state[256];
274 BOOL isAbsoluteEnabled;
275 BOOL isMouseDeassociated;
277 - (void) switchSurface:(DisplaySurface *)surface;
279 - (void) ungrabMouse;
280 - (void) toggleFullScreen:(id)sender;
281 - (void) handleEvent:(NSEvent *)event;
282 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
283 /* The state surrounding mouse grabbing is potentially confusing.
284 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
285 * pointing device an absolute-position one?"], but is only updated on
287 * isMouseGrabbed tracks whether GUI events are directed to the guest;
288 * it controls whether special keys like Cmd get sent to the guest,
289 * and whether we capture the mouse when in non-absolute mode.
290 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
291 * the mouse and mouse cursor position by calling
292 * CGAssociateMouseAndMouseCursorPosition(FALSE)
293 * (which basically happens if we grab in non-absolute mode).
295 - (BOOL) isMouseGrabbed;
296 - (BOOL) isAbsoluteEnabled;
297 - (BOOL) isMouseDeassociated;
300 - (QEMUScreen) gscreen;
301 - (void) raiseAllKeys;
304 QemuCocoaView *cocoaView;
306 @implementation QemuCocoaView
307 - (id)initWithFrame:(NSRect)frameRect
309 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
311 self = [super initWithFrame:frameRect];
314 screen.bitsPerComponent = 8;
315 screen.bitsPerPixel = 32;
316 screen.width = frameRect.size.width;
317 screen.height = frameRect.size.height;
325 COCOA_DEBUG("QemuCocoaView: dealloc\n");
328 CGDataProviderRelease(dataProviderRef);
338 - (BOOL) screenContainsPoint:(NSPoint) p
340 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
351 - (void) unhideCursor
359 - (void) drawRect:(NSRect) rect
361 COCOA_DEBUG("QemuCocoaView: drawRect\n");
363 // get CoreGraphic context
364 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
365 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
366 CGContextSetShouldAntialias (viewContextRef, NO);
368 // draw screen bitmap directly to Core Graphics context
369 if (!dataProviderRef) {
370 // Draw request before any guest device has set up a framebuffer:
371 // just draw an opaque black rectangle
372 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
373 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
375 CGImageRef imageRef = CGImageCreate(
376 screen.width, //width
377 screen.height, //height
378 screen.bitsPerComponent, //bitsPerComponent
379 screen.bitsPerPixel, //bitsPerPixel
380 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
381 #ifdef __LITTLE_ENDIAN__
382 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
383 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
385 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
386 kCGImageAlphaNoneSkipFirst, //bitmapInfo
388 dataProviderRef, //provider
391 kCGRenderingIntentDefault //intent
393 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
394 const NSRect *rectList;
397 CGImageRef clipImageRef;
400 [self getRectsBeingDrawn:&rectList count:&rectCount];
401 for (i = 0; i < rectCount; i++) {
402 clipRect.origin.x = rectList[i].origin.x / cdx;
403 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
404 clipRect.size.width = rectList[i].size.width / cdx;
405 clipRect.size.height = rectList[i].size.height / cdy;
406 clipImageRef = CGImageCreateWithImageInRect(
410 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
411 CGImageRelease (clipImageRef);
413 CGImageRelease (imageRef);
417 - (void) setContentDimensions
419 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
422 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
423 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
425 /* stretches video, but keeps same aspect ratio */
426 if (stretch_video == true) {
427 /* use smallest stretch value - prevents clipping on sides */
428 if (MIN(cdx, cdy) == cdx) {
433 } else { /* No stretching */
436 cw = screen.width * cdx;
437 ch = screen.height * cdy;
438 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
439 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
450 - (void) switchSurface:(DisplaySurface *)surface
452 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
454 int w = surface_width(surface);
455 int h = surface_height(surface);
456 /* cdx == 0 means this is our very first surface, in which case we need
457 * to recalculate the content dimensions even if it happens to be the size
458 * of the initial empty window.
460 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
462 int oldh = screen.height;
464 // Resize before we trigger the redraw, or we'll redraw at the wrong size
465 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
468 [self setContentDimensions];
469 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
472 // update screenBuffer
474 CGDataProviderRelease(dataProviderRef);
476 //sync host window color space with guests
477 screen.bitsPerPixel = surface_bits_per_pixel(surface);
478 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
480 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
484 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
485 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
488 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
489 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
493 [normalWindow center];
497 - (void) toggleFullScreen:(id)sender
499 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
501 if (isFullscreen) { // switch from fullscreen to desktop
502 isFullscreen = FALSE;
504 [self setContentDimensions];
505 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
506 [self exitFullScreenModeWithOptions:nil];
508 [fullScreenWindow close];
509 [normalWindow setContentView: self];
510 [normalWindow makeKeyAndOrderFront: self];
511 [NSMenu setMenuBarVisible:YES];
513 } else { // switch from desktop to fullscreen
515 [normalWindow orderOut: nil]; /* Hide the window */
517 [self setContentDimensions];
518 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
519 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
520 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
521 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
524 [NSMenu setMenuBarVisible:NO];
525 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
526 styleMask:NSWindowStyleMaskBorderless
527 backing:NSBackingStoreBuffered
529 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
530 [fullScreenWindow setHasShadow:NO];
531 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
532 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
533 [[fullScreenWindow contentView] addSubview: self];
534 [fullScreenWindow makeKeyAndOrderFront:self];
539 - (void) handleEvent:(NSEvent *)event
541 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
545 bool mouse_event = false;
546 NSPoint p = [event locationInWindow];
548 switch ([event type]) {
549 case NSEventTypeFlagsChanged:
550 keycode = cocoa_keycode_to_qemu([event keyCode]);
552 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
553 && !isMouseGrabbed) {
554 /* Don't pass command key changes to guest unless mouse is grabbed */
559 // emulate caps lock and num lock keydown and keyup
560 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
561 keycode == Q_KEY_CODE_NUM_LOCK) {
562 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
563 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
564 } else if (qemu_console_is_graphic(NULL)) {
565 if (modifiers_state[keycode] == 0) { // keydown
566 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
567 modifiers_state[keycode] = 1;
569 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
570 modifiers_state[keycode] = 0;
575 // release Mouse grab when pressing ctrl+alt
576 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
580 case NSEventTypeKeyDown:
581 keycode = cocoa_keycode_to_qemu([event keyCode]);
583 // forward command key combos to the host UI unless the mouse is grabbed
584 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
585 [NSApp sendEvent:event];
591 // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
592 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
595 // enable graphic console
596 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: // '1' to '9' keys
597 console_select(keycode - 11);
601 // handle keys for graphic console
602 } else if (qemu_console_is_graphic(NULL)) {
603 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
605 // handlekeys for Monitor
608 switch([event keyCode]) {
610 keysym = QEMU_KEY_HOME;
613 keysym = QEMU_KEY_DELETE;
616 keysym = QEMU_KEY_END;
619 keysym = QEMU_KEY_LEFT;
622 keysym = QEMU_KEY_RIGHT;
625 keysym = QEMU_KEY_DOWN;
628 keysym = QEMU_KEY_UP;
632 NSString *ks = [event characters];
634 keysym = [ks characterAtIndex:0];
638 kbd_put_keysym(keysym);
641 case NSEventTypeKeyUp:
642 keycode = cocoa_keycode_to_qemu([event keyCode]);
644 // don't pass the guest a spurious key-up if we treated this
645 // command-key combo as a host UI action
646 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
650 if (qemu_console_is_graphic(NULL)) {
651 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
654 case NSEventTypeMouseMoved:
655 if (isAbsoluteEnabled) {
656 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
657 if (isMouseGrabbed) {
661 if (!isMouseGrabbed) {
668 case NSEventTypeLeftMouseDown:
669 if ([event modifierFlags] & NSEventModifierFlagCommand) {
670 buttons |= MOUSE_EVENT_RBUTTON;
672 buttons |= MOUSE_EVENT_LBUTTON;
676 case NSEventTypeRightMouseDown:
677 buttons |= MOUSE_EVENT_RBUTTON;
680 case NSEventTypeOtherMouseDown:
681 buttons |= MOUSE_EVENT_MBUTTON;
684 case NSEventTypeLeftMouseDragged:
685 if ([event modifierFlags] & NSEventModifierFlagCommand) {
686 buttons |= MOUSE_EVENT_RBUTTON;
688 buttons |= MOUSE_EVENT_LBUTTON;
692 case NSEventTypeRightMouseDragged:
693 buttons |= MOUSE_EVENT_RBUTTON;
696 case NSEventTypeOtherMouseDragged:
697 buttons |= MOUSE_EVENT_MBUTTON;
700 case NSEventTypeLeftMouseUp:
702 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
703 if([[self window] isKeyWindow]) {
708 case NSEventTypeRightMouseUp:
711 case NSEventTypeOtherMouseUp:
714 case NSEventTypeScrollWheel:
715 if (isMouseGrabbed) {
716 buttons |= ([event deltaY] < 0) ?
717 MOUSE_EVENT_WHEELUP : MOUSE_EVENT_WHEELDN;
722 [NSApp sendEvent:event];
726 /* Don't send button events to the guest unless we've got a
727 * mouse grab or window focus. If we have neither then this event
728 * is the user clicking on the background window to activate and
729 * bring us to the front, which will be done by the sendEvent
730 * call below. We definitely don't want to pass that click through
733 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
734 (last_buttons != buttons)) {
735 static uint32_t bmap[INPUT_BUTTON__MAX] = {
736 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
737 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
738 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
739 [INPUT_BUTTON_WHEEL_UP] = MOUSE_EVENT_WHEELUP,
740 [INPUT_BUTTON_WHEEL_DOWN] = MOUSE_EVENT_WHEELDN,
742 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
743 last_buttons = buttons;
745 if (isMouseGrabbed) {
746 if (isAbsoluteEnabled) {
747 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
748 * The check on screenContainsPoint is to avoid sending out of range values for
749 * clicks in the titlebar.
751 if ([self screenContainsPoint:p]) {
752 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
753 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
756 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
757 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
760 [NSApp sendEvent:event];
762 qemu_input_event_sync();
768 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
772 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
774 [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
777 if (!isAbsoluteEnabled) {
778 isMouseDeassociated = TRUE;
779 CGAssociateMouseAndMouseCursorPosition(FALSE);
781 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
786 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
790 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
792 [normalWindow setTitle:@"QEMU"];
795 if (isMouseDeassociated) {
796 CGAssociateMouseAndMouseCursorPosition(TRUE);
797 isMouseDeassociated = FALSE;
799 isMouseGrabbed = FALSE;
802 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
803 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
804 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
805 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
806 - (float) cdx {return cdx;}
807 - (float) cdy {return cdy;}
808 - (QEMUScreen) gscreen {return screen;}
811 * Makes the target think all down keys are being released.
812 * This prevents a stuck key problem, since we will not see
813 * key up events for those keys after we have lost focus.
815 - (void) raiseAllKeys
818 const int max_index = ARRAY_SIZE(modifiers_state);
820 for (index = 0; index < max_index; index++) {
821 if (modifiers_state[index]) {
822 modifiers_state[index] = 0;
823 qemu_input_event_send_key_qcode(dcl->con, index, false);
832 ------------------------------------------------------
833 QemuCocoaAppController
834 ------------------------------------------------------
836 @interface QemuCocoaAppController : NSObject
837 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
838 <NSWindowDelegate, NSApplicationDelegate>
842 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
843 - (void)doToggleFullScreen:(id)sender;
844 - (void)toggleFullScreen:(id)sender;
845 - (void)showQEMUDoc:(id)sender;
846 - (void)zoomToFit:(id) sender;
847 - (void)displayConsole:(id)sender;
848 - (void)pauseQEMU:(id)sender;
849 - (void)resumeQEMU:(id)sender;
850 - (void)displayPause;
852 - (void)restartQEMU:(id)sender;
853 - (void)powerDownQEMU:(id)sender;
854 - (void)ejectDeviceMedia:(id)sender;
855 - (void)changeDeviceMedia:(id)sender;
857 - (void)openDocumentation:(NSString *)filename;
858 - (IBAction) do_about_menu_item: (id) sender;
859 - (void)make_about_window;
862 @implementation QemuCocoaAppController
865 COCOA_DEBUG("QemuCocoaAppController: init\n");
870 // create a view and add it to the window
871 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
873 fprintf(stderr, "(cocoa) can't create a view\n");
878 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
879 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
880 backing:NSBackingStoreBuffered defer:NO];
882 fprintf(stderr, "(cocoa) can't create window\n");
885 [normalWindow setAcceptsMouseMovedEvents:YES];
886 [normalWindow setTitle:@"QEMU"];
887 [normalWindow setContentView:cocoaView];
888 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
889 [normalWindow useOptimizedDrawing:YES];
891 [normalWindow makeKeyAndOrderFront:self];
892 [normalWindow center];
893 [normalWindow setDelegate: self];
894 stretch_video = false;
896 /* Used for displaying pause on the screen */
897 pauseLabel = [NSTextField new];
898 [pauseLabel setBezeled:YES];
899 [pauseLabel setDrawsBackground:YES];
900 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
901 [pauseLabel setEditable:NO];
902 [pauseLabel setSelectable:NO];
903 [pauseLabel setStringValue: @"Paused"];
904 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
905 [pauseLabel setTextColor: [NSColor blackColor]];
906 [pauseLabel sizeToFit];
908 // set the supported image file types that can be opened
909 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
910 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
912 [self make_about_window];
919 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
926 - (void)applicationDidFinishLaunching: (NSNotification *) note
928 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
929 // launch QEMU, with the global args
930 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
933 - (void)applicationWillTerminate:(NSNotification *)aNotification
935 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
937 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
941 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
946 - (NSApplicationTerminateReply)applicationShouldTerminate:
947 (NSApplication *)sender
949 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
950 return [self verifyQuit];
953 /* Called when the user clicks on a window's close button */
954 - (BOOL)windowShouldClose:(id)sender
956 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
957 [NSApp terminate: sender];
958 /* If the user allows the application to quit then the call to
959 * NSApp terminate will never return. If we get here then the user
960 * cancelled the quit, so we should return NO to not permit the
961 * closing of this window.
966 /* Called when QEMU goes into the background */
967 - (void) applicationWillResignActive: (NSNotification *)aNotification
969 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
970 [cocoaView raiseAllKeys];
973 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
975 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
978 status = qemu_main(argc, argv, *_NSGetEnviron());
982 /* We abstract the method called by the Enter Fullscreen menu item
983 * because Mac OS 10.7 and higher disables it. This is because of the
984 * menu item's old selector's name toggleFullScreen:
986 - (void) doToggleFullScreen:(id)sender
988 [self toggleFullScreen:(id)sender];
991 - (void)toggleFullScreen:(id)sender
993 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
995 [cocoaView toggleFullScreen:sender];
998 /* Tries to find then open the specified filename */
999 - (void) openDocumentation: (NSString *) filename
1001 /* Where to look for local files */
1002 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1003 NSString *full_file_path;
1005 /* iterate thru the possible paths until the file is found */
1007 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1008 full_file_path = [[NSBundle mainBundle] executablePath];
1009 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1010 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1011 path_array[index], filename];
1012 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1017 /* If none of the paths opened a file */
1019 QEMU_Alert(@"Failed to open file");
1022 - (void)showQEMUDoc:(id)sender
1024 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1026 [self openDocumentation: @"qemu-doc.html"];
1029 /* Stretches video to fit host monitor size */
1030 - (void)zoomToFit:(id) sender
1032 stretch_video = !stretch_video;
1033 if (stretch_video == true) {
1034 [sender setState: NSOnState];
1036 [sender setState: NSOffState];
1040 /* Displays the console on the screen */
1041 - (void)displayConsole:(id)sender
1043 console_select([sender tag]);
1046 /* Pause the guest */
1047 - (void)pauseQEMU:(id)sender
1050 [sender setEnabled: NO];
1051 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1052 [self displayPause];
1055 /* Resume running the guest operating system */
1056 - (void)resumeQEMU:(id) sender
1059 [sender setEnabled: NO];
1060 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1064 /* Displays the word pause on the screen */
1065 - (void)displayPause
1067 /* Coordinates have to be calculated each time because the window can change its size */
1068 int xCoord, yCoord, width, height;
1069 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1070 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1071 width = [pauseLabel frame].size.width;
1072 height = [pauseLabel frame].size.height;
1073 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1074 [cocoaView addSubview: pauseLabel];
1077 /* Removes the word pause from the screen */
1080 [pauseLabel removeFromSuperview];
1084 - (void)restartQEMU:(id)sender
1086 qmp_system_reset(NULL);
1089 /* Powers down QEMU */
1090 - (void)powerDownQEMU:(id)sender
1092 qmp_system_powerdown(NULL);
1095 /* Ejects the media.
1096 * Uses sender's tag to figure out the device to eject.
1098 - (void)ejectDeviceMedia:(id)sender
1101 drive = [sender representedObject];
1104 QEMU_Alert(@"Failed to find drive to eject!");
1109 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1110 false, NULL, false, false, &err);
1111 handleAnyDeviceErrors(err);
1114 /* Displays a dialog box asking the user to select an image file to load.
1115 * Uses sender's represented object value to figure out which drive to use.
1117 - (void)changeDeviceMedia:(id)sender
1119 /* Find the drive name */
1121 drive = [sender representedObject];
1124 QEMU_Alert(@"Could not find drive!");
1128 /* Display the file open dialog */
1129 NSOpenPanel * openPanel;
1130 openPanel = [NSOpenPanel openPanel];
1131 [openPanel setCanChooseFiles: YES];
1132 [openPanel setAllowsMultipleSelection: NO];
1133 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1134 if([openPanel runModal] == NSFileHandlingPanelOKButton) {
1135 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1138 QEMU_Alert(@"Failed to convert URL to file path!");
1143 qmp_blockdev_change_medium(true,
1144 [drive cStringUsingEncoding:
1145 NSASCIIStringEncoding],
1147 [file cStringUsingEncoding:
1148 NSASCIIStringEncoding],
1152 handleAnyDeviceErrors(err);
1156 /* Verifies if the user really wants to quit */
1159 NSAlert *alert = [NSAlert new];
1160 [alert autorelease];
1161 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1162 [alert addButtonWithTitle: @"Cancel"];
1163 [alert addButtonWithTitle: @"Quit"];
1164 if([alert runModal] == NSAlertSecondButtonReturn) {
1171 /* The action method for the About menu item */
1172 - (IBAction) do_about_menu_item: (id) sender
1174 [about_window makeKeyAndOrderFront: nil];
1177 /* Create and display the about dialog */
1178 - (void)make_about_window
1180 /* Make the window */
1181 int x = 0, y = 0, about_width = 400, about_height = 200;
1182 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1183 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1184 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1185 NSWindowStyleMaskMiniaturizable
1186 backing:NSBackingStoreBuffered
1188 [about_window setTitle: @"About"];
1189 [about_window setReleasedWhenClosed: NO];
1190 [about_window center];
1191 NSView *superView = [about_window contentView];
1193 /* Create the dimensions of the picture */
1194 int picture_width = 80, picture_height = 80;
1195 x = (about_width - picture_width)/2;
1196 y = about_height - picture_height - 10;
1197 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1199 /* Get the path to the QEMU binary */
1200 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1201 encoding: NSASCIIStringEncoding];
1202 binary_name = [binary_name lastPathComponent];
1203 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1204 [[NSBundle mainBundle] bundlePath], binary_name];
1206 /* Make the picture of QEMU */
1207 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1209 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1211 [picture_view setImage: qemu_image];
1212 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1213 [superView addSubview: picture_view];
1215 /* Make the name label */
1218 int name_width = about_width, name_height = 20;
1219 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1220 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1221 [name_label setEditable: NO];
1222 [name_label setBezeled: NO];
1223 [name_label setDrawsBackground: NO];
1224 [name_label setAlignment: NSTextAlignmentCenter];
1225 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1226 encoding: NSASCIIStringEncoding];
1227 qemu_name = [qemu_name lastPathComponent];
1228 [name_label setStringValue: qemu_name];
1229 [superView addSubview: name_label];
1231 /* Set the version label's attributes */
1234 int version_width = about_width, version_height = 20;
1235 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1236 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1238 [version_label setEditable: NO];
1239 [version_label setBezeled: NO];
1240 [version_label setAlignment: NSTextAlignmentCenter];
1241 [version_label setDrawsBackground: NO];
1243 /* Create the version string*/
1244 NSString *version_string;
1245 version_string = [[NSString alloc] initWithFormat:
1246 @"QEMU emulator version %s%s", QEMU_VERSION, QEMU_PKGVERSION];
1247 [version_label setStringValue: version_string];
1248 [superView addSubview: version_label];
1250 /* Make copyright label */
1253 int copyright_width = about_width, copyright_height = 20;
1254 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1255 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1257 [copyright_label setEditable: NO];
1258 [copyright_label setBezeled: NO];
1259 [copyright_label setDrawsBackground: NO];
1260 [copyright_label setAlignment: NSTextAlignmentCenter];
1261 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1263 [superView addSubview: copyright_label];
1269 int main (int argc, const char * argv[]) {
1272 gArgv = (char **)argv;
1275 /* In case we don't need to display a window, let's not do that */
1276 for (i = 1; i < argc; i++) {
1277 const char *opt = argv[i];
1279 if (opt[0] == '-') {
1280 /* Treat --foo the same as -foo. */
1281 if (opt[1] == '-') {
1284 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1285 !strcmp(opt, "-vnc") ||
1286 !strcmp(opt, "-nographic") ||
1287 !strcmp(opt, "-version") ||
1288 !strcmp(opt, "-curses") ||
1289 !strcmp(opt, "-display") ||
1290 !strcmp(opt, "-qtest")) {
1291 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1296 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1298 // Pull this console process up to being a fully-fledged graphical
1299 // app with a menubar and Dock icon
1300 ProcessSerialNumber psn = { 0, kCurrentProcess };
1301 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1303 [NSApplication sharedApplication];
1307 NSMenuItem *menuItem;
1309 [NSApp setMainMenu:[[NSMenu alloc] init]];
1312 menu = [[NSMenu alloc] initWithTitle:@""];
1313 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1314 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1315 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1316 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1317 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1318 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1319 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1320 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1321 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1322 [menuItem setSubmenu:menu];
1323 [[NSApp mainMenu] addItem:menuItem];
1324 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1327 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1328 [menu setAutoenablesItems: NO];
1329 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1330 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1331 [menu addItem: menuItem];
1332 [menuItem setEnabled: NO];
1333 [menu addItem: [NSMenuItem separatorItem]];
1334 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1335 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1336 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1337 [menuItem setSubmenu:menu];
1338 [[NSApp mainMenu] addItem:menuItem];
1341 menu = [[NSMenu alloc] initWithTitle:@"View"];
1342 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1343 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1344 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1345 [menuItem setSubmenu:menu];
1346 [[NSApp mainMenu] addItem:menuItem];
1349 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1350 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1351 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1352 [menuItem setSubmenu:menu];
1353 [[NSApp mainMenu] addItem:menuItem];
1354 [NSApp setWindowsMenu:menu];
1357 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1358 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1359 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1360 [menuItem setSubmenu:menu];
1361 [[NSApp mainMenu] addItem:menuItem];
1363 // Create an Application controller
1364 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1365 [NSApp setDelegate:appController];
1367 // Start the main event loop
1370 [appController release];
1379 static void cocoa_update(DisplayChangeListener *dcl,
1380 int x, int y, int w, int h)
1382 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1384 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1387 if ([cocoaView cdx] == 1.0) {
1388 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1391 x * [cocoaView cdx],
1392 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1393 w * [cocoaView cdx],
1394 h * [cocoaView cdy]);
1396 [cocoaView setNeedsDisplayInRect:rect];
1401 static void cocoa_switch(DisplayChangeListener *dcl,
1402 DisplaySurface *surface)
1404 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1406 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1407 [cocoaView switchSurface:surface];
1411 static void cocoa_refresh(DisplayChangeListener *dcl)
1413 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1415 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1416 graphic_hw_update(NULL);
1418 if (qemu_input_is_absolute()) {
1419 if (![cocoaView isAbsoluteEnabled]) {
1420 if ([cocoaView isMouseGrabbed]) {
1421 [cocoaView ungrabMouse];
1424 [cocoaView setAbsoluteEnabled:YES];
1427 NSDate *distantPast;
1429 distantPast = [NSDate distantPast];
1431 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1432 inMode: NSDefaultRunLoopMode dequeue:YES];
1434 [cocoaView handleEvent:event];
1436 } while(event != nil);
1440 static void cocoa_cleanup(void)
1442 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1446 static const DisplayChangeListenerOps dcl_ops = {
1447 .dpy_name = "cocoa",
1448 .dpy_gfx_update = cocoa_update,
1449 .dpy_gfx_switch = cocoa_switch,
1450 .dpy_refresh = cocoa_refresh,
1453 /* Returns a name for a given console */
1454 static NSString * getConsoleName(QemuConsole * console)
1456 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1459 /* Add an entry to the View menu for each console */
1460 static void add_console_menu_entries(void)
1463 NSMenuItem *menuItem;
1466 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1468 [menu addItem:[NSMenuItem separatorItem]];
1470 while (qemu_console_lookup_by_index(index) != NULL) {
1471 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1472 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1473 [menuItem setTag: index];
1474 [menu addItem: menuItem];
1479 /* Make menu items for all removable devices.
1480 * Each device is given an 'Eject' and 'Change' menu item.
1482 static void addRemovableDevicesMenuItems(void)
1485 NSMenuItem *menuItem;
1486 BlockInfoList *currentDevice, *pointerToFree;
1487 NSString *deviceName;
1489 currentDevice = qmp_query_block(NULL);
1490 pointerToFree = currentDevice;
1491 if(currentDevice == NULL) {
1493 QEMU_Alert(@"Failed to query for block devices!");
1497 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1499 // Add a separator between related groups of menu items
1500 [menu addItem:[NSMenuItem separatorItem]];
1502 // Set the attributes to the "Removable Media" menu item
1503 NSString *titleString = @"Removable Media";
1504 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1505 NSColor *newColor = [NSColor blackColor];
1506 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1507 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1508 traits:NSBoldFontMask|NSItalicFontMask
1511 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1512 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1513 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1515 // Add the "Removable Media" menu item
1516 menuItem = [NSMenuItem new];
1517 [menuItem setAttributedTitle: attString];
1518 [menuItem setEnabled: NO];
1519 [menu addItem: menuItem];
1521 /* Loop through all the block devices in the emulator */
1522 while (currentDevice) {
1523 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1525 if(currentDevice->value->removable) {
1526 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1527 action: @selector(changeDeviceMedia:)
1528 keyEquivalent: @""];
1529 [menu addItem: menuItem];
1530 [menuItem setRepresentedObject: deviceName];
1531 [menuItem autorelease];
1533 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1534 action: @selector(ejectDeviceMedia:)
1535 keyEquivalent: @""];
1536 [menu addItem: menuItem];
1537 [menuItem setRepresentedObject: deviceName];
1538 [menuItem autorelease];
1540 currentDevice = currentDevice->next;
1542 qapi_free_BlockInfoList(pointerToFree);
1545 void cocoa_display_init(DisplayState *ds, int full_screen)
1547 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1549 /* if fullscreen mode is to be used */
1550 if (full_screen == true) {
1551 [NSApp activateIgnoringOtherApps: YES];
1552 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1555 dcl = g_malloc0(sizeof(DisplayChangeListener));
1557 // register vga output callbacks
1558 dcl->ops = &dcl_ops;
1559 register_displaychangelistener(dcl);
1561 // register cleanup function
1562 atexit(cocoa_cleanup);
1564 /* At this point QEMU has created all the consoles, so we can add View
1565 * menu entries for them.
1567 add_console_menu_entries();
1569 /* Give all removable devices a menu item.
1570 * Has to be called after QEMU has started to
1571 * find out what removable devices it has.
1573 addRemovableDevicesMenuItems();