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 "qapi/error.h"
35 #include "qapi/qapi-commands-block.h"
36 #include "qapi/qapi-commands-misc.h"
37 #include "sysemu/blockdev.h"
38 #include "qemu-version.h"
39 #include <Carbon/Carbon.h>
42 #ifndef MAC_OS_X_VERSION_10_5
43 #define MAC_OS_X_VERSION_10_5 1050
45 #ifndef MAC_OS_X_VERSION_10_6
46 #define MAC_OS_X_VERSION_10_6 1060
48 #ifndef MAC_OS_X_VERSION_10_9
49 #define MAC_OS_X_VERSION_10_9 1090
51 #ifndef MAC_OS_X_VERSION_10_10
52 #define MAC_OS_X_VERSION_10_10 101000
54 #ifndef MAC_OS_X_VERSION_10_12
55 #define MAC_OS_X_VERSION_10_12 101200
57 #ifndef MAC_OS_X_VERSION_10_13
58 #define MAC_OS_X_VERSION_10_13 101300
61 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
62 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
63 #define NSEventMaskAny NSAnyEventMask
64 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
65 #define NSEventModifierFlagShift NSShiftKeyMask
66 #define NSEventModifierFlagCommand NSCommandKeyMask
67 #define NSEventModifierFlagControl NSControlKeyMask
68 #define NSEventModifierFlagOption NSAlternateKeyMask
69 #define NSEventTypeFlagsChanged NSFlagsChanged
70 #define NSEventTypeKeyUp NSKeyUp
71 #define NSEventTypeKeyDown NSKeyDown
72 #define NSEventTypeMouseMoved NSMouseMoved
73 #define NSEventTypeLeftMouseDown NSLeftMouseDown
74 #define NSEventTypeRightMouseDown NSRightMouseDown
75 #define NSEventTypeOtherMouseDown NSOtherMouseDown
76 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
77 #define NSEventTypeRightMouseDragged NSRightMouseDragged
78 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
79 #define NSEventTypeLeftMouseUp NSLeftMouseUp
80 #define NSEventTypeRightMouseUp NSRightMouseUp
81 #define NSEventTypeOtherMouseUp NSOtherMouseUp
82 #define NSEventTypeScrollWheel NSScrollWheel
83 #define NSTextAlignmentCenter NSCenterTextAlignment
84 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
85 #define NSWindowStyleMaskClosable NSClosableWindowMask
86 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
87 #define NSWindowStyleMaskTitled NSTitledWindowMask
89 /* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
90 * NSModalResponseOK, which was introduced in 10.9. Define
91 * it for older versions.
93 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
94 #define NSModalResponseOK NSFileHandlingPanelOKButton
96 /* 10.14 deprecates NSOnState and NSOffState in favor of
97 * NSControlStateValueOn/Off, which were introduced in 10.13.
98 * Define for older versions
100 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
101 #define NSControlStateValueOn NSOnState
102 #define NSControlStateValueOff NSOffState
108 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
110 #define COCOA_DEBUG(...) ((void) 0)
113 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
118 int bitsPerComponent;
122 NSWindow *normalWindow, *about_window;
123 static DisplayChangeListener *dcl;
124 static int last_buttons;
129 NSTextField *pauseLabel;
130 NSArray * supportedImageFileTypes;
132 static QemuSemaphore display_init_sem;
133 static QemuSemaphore app_started_sem;
135 // Utility functions to run specified code block with iothread lock held
136 typedef void (^CodeBlock)(void);
137 typedef bool (^BoolCodeBlock)(void);
139 static void with_iothread_lock(CodeBlock block)
141 bool locked = qemu_mutex_iothread_locked();
143 qemu_mutex_lock_iothread();
147 qemu_mutex_unlock_iothread();
151 static bool bool_with_iothread_lock(BoolCodeBlock block)
153 bool locked = qemu_mutex_iothread_locked();
157 qemu_mutex_lock_iothread();
161 qemu_mutex_unlock_iothread();
166 // Mac to QKeyCode conversion
167 const int mac_to_qkeycode_map[] = {
168 [kVK_ANSI_A] = Q_KEY_CODE_A,
169 [kVK_ANSI_B] = Q_KEY_CODE_B,
170 [kVK_ANSI_C] = Q_KEY_CODE_C,
171 [kVK_ANSI_D] = Q_KEY_CODE_D,
172 [kVK_ANSI_E] = Q_KEY_CODE_E,
173 [kVK_ANSI_F] = Q_KEY_CODE_F,
174 [kVK_ANSI_G] = Q_KEY_CODE_G,
175 [kVK_ANSI_H] = Q_KEY_CODE_H,
176 [kVK_ANSI_I] = Q_KEY_CODE_I,
177 [kVK_ANSI_J] = Q_KEY_CODE_J,
178 [kVK_ANSI_K] = Q_KEY_CODE_K,
179 [kVK_ANSI_L] = Q_KEY_CODE_L,
180 [kVK_ANSI_M] = Q_KEY_CODE_M,
181 [kVK_ANSI_N] = Q_KEY_CODE_N,
182 [kVK_ANSI_O] = Q_KEY_CODE_O,
183 [kVK_ANSI_P] = Q_KEY_CODE_P,
184 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
185 [kVK_ANSI_R] = Q_KEY_CODE_R,
186 [kVK_ANSI_S] = Q_KEY_CODE_S,
187 [kVK_ANSI_T] = Q_KEY_CODE_T,
188 [kVK_ANSI_U] = Q_KEY_CODE_U,
189 [kVK_ANSI_V] = Q_KEY_CODE_V,
190 [kVK_ANSI_W] = Q_KEY_CODE_W,
191 [kVK_ANSI_X] = Q_KEY_CODE_X,
192 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
193 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
195 [kVK_ANSI_0] = Q_KEY_CODE_0,
196 [kVK_ANSI_1] = Q_KEY_CODE_1,
197 [kVK_ANSI_2] = Q_KEY_CODE_2,
198 [kVK_ANSI_3] = Q_KEY_CODE_3,
199 [kVK_ANSI_4] = Q_KEY_CODE_4,
200 [kVK_ANSI_5] = Q_KEY_CODE_5,
201 [kVK_ANSI_6] = Q_KEY_CODE_6,
202 [kVK_ANSI_7] = Q_KEY_CODE_7,
203 [kVK_ANSI_8] = Q_KEY_CODE_8,
204 [kVK_ANSI_9] = Q_KEY_CODE_9,
206 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
207 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
208 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
209 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
210 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
211 [kVK_Tab] = Q_KEY_CODE_TAB,
212 [kVK_Return] = Q_KEY_CODE_RET,
213 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
214 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
215 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
216 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
217 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
218 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
219 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
220 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
221 [kVK_Shift] = Q_KEY_CODE_SHIFT,
222 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
223 [kVK_Control] = Q_KEY_CODE_CTRL,
224 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
225 [kVK_Option] = Q_KEY_CODE_ALT,
226 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
227 [kVK_Command] = Q_KEY_CODE_META_L,
228 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
229 [kVK_Space] = Q_KEY_CODE_SPC,
231 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
232 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
233 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
234 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
235 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
236 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
237 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
238 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
239 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
240 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
241 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
242 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
243 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
244 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
245 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
246 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
247 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
248 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
250 [kVK_UpArrow] = Q_KEY_CODE_UP,
251 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
252 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
253 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
255 [kVK_Help] = Q_KEY_CODE_INSERT,
256 [kVK_Home] = Q_KEY_CODE_HOME,
257 [kVK_PageUp] = Q_KEY_CODE_PGUP,
258 [kVK_PageDown] = Q_KEY_CODE_PGDN,
259 [kVK_End] = Q_KEY_CODE_END,
260 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
262 [kVK_Escape] = Q_KEY_CODE_ESC,
264 /* The Power key can't be used directly because the operating system uses
265 * it. This key can be emulated by using it in place of another key such as
266 * F1. Don't forget to disable the real key binding.
268 /* [kVK_F1] = Q_KEY_CODE_POWER, */
270 [kVK_F1] = Q_KEY_CODE_F1,
271 [kVK_F2] = Q_KEY_CODE_F2,
272 [kVK_F3] = Q_KEY_CODE_F3,
273 [kVK_F4] = Q_KEY_CODE_F4,
274 [kVK_F5] = Q_KEY_CODE_F5,
275 [kVK_F6] = Q_KEY_CODE_F6,
276 [kVK_F7] = Q_KEY_CODE_F7,
277 [kVK_F8] = Q_KEY_CODE_F8,
278 [kVK_F9] = Q_KEY_CODE_F9,
279 [kVK_F10] = Q_KEY_CODE_F10,
280 [kVK_F11] = Q_KEY_CODE_F11,
281 [kVK_F12] = Q_KEY_CODE_F12,
282 [kVK_F13] = Q_KEY_CODE_PRINT,
283 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
284 [kVK_F15] = Q_KEY_CODE_PAUSE,
287 * The eject and volume keys can't be used here because they are handled at
288 * a lower level than what an Application can see.
292 static int cocoa_keycode_to_qemu(int keycode)
294 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
295 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
298 return mac_to_qkeycode_map[keycode];
301 /* Displays an alert dialog box with the specified message */
302 static void QEMU_Alert(NSString *message)
305 alert = [NSAlert new];
306 [alert setMessageText: message];
310 /* Handles any errors that happen with a device transaction */
311 static void handleAnyDeviceErrors(Error * err)
314 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
315 encoding: NSASCIIStringEncoding]);
321 ------------------------------------------------------
323 ------------------------------------------------------
325 @interface QemuCocoaView : NSView
328 NSWindow *fullScreenWindow;
329 float cx,cy,cw,ch,cdx,cdy;
330 CGDataProviderRef dataProviderRef;
331 pixman_image_t *pixman_image;
332 BOOL modifiers_state[256];
335 BOOL isAbsoluteEnabled;
336 BOOL isMouseDeassociated;
338 - (void) switchSurface:(pixman_image_t *)image;
340 - (void) ungrabMouse;
341 - (void) toggleFullScreen:(id)sender;
342 - (void) handleMonitorInput:(NSEvent *)event;
343 - (bool) handleEvent:(NSEvent *)event;
344 - (bool) handleEventLocked:(NSEvent *)event;
345 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
346 /* The state surrounding mouse grabbing is potentially confusing.
347 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
348 * pointing device an absolute-position one?"], but is only updated on
350 * isMouseGrabbed tracks whether GUI events are directed to the guest;
351 * it controls whether special keys like Cmd get sent to the guest,
352 * and whether we capture the mouse when in non-absolute mode.
353 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
354 * the mouse and mouse cursor position by calling
355 * CGAssociateMouseAndMouseCursorPosition(FALSE)
356 * (which basically happens if we grab in non-absolute mode).
358 - (BOOL) isMouseGrabbed;
359 - (BOOL) isAbsoluteEnabled;
360 - (BOOL) isMouseDeassociated;
363 - (QEMUScreen) gscreen;
364 - (void) raiseAllKeys;
367 QemuCocoaView *cocoaView;
369 @implementation QemuCocoaView
370 - (id)initWithFrame:(NSRect)frameRect
372 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
374 self = [super initWithFrame:frameRect];
377 screen.bitsPerComponent = 8;
378 screen.bitsPerPixel = 32;
379 screen.width = frameRect.size.width;
380 screen.height = frameRect.size.height;
388 COCOA_DEBUG("QemuCocoaView: dealloc\n");
390 if (dataProviderRef) {
391 CGDataProviderRelease(dataProviderRef);
392 pixman_image_unref(pixman_image);
403 - (BOOL) screenContainsPoint:(NSPoint) p
405 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
416 - (void) unhideCursor
424 - (void) drawRect:(NSRect) rect
426 COCOA_DEBUG("QemuCocoaView: drawRect\n");
428 // get CoreGraphic context
429 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
430 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
432 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
435 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
436 CGContextSetShouldAntialias (viewContextRef, NO);
438 // draw screen bitmap directly to Core Graphics context
439 if (!dataProviderRef) {
440 // Draw request before any guest device has set up a framebuffer:
441 // just draw an opaque black rectangle
442 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
443 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
445 CGImageRef imageRef = CGImageCreate(
446 screen.width, //width
447 screen.height, //height
448 screen.bitsPerComponent, //bitsPerComponent
449 screen.bitsPerPixel, //bitsPerPixel
450 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
451 #ifdef __LITTLE_ENDIAN__
452 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
453 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
455 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
456 kCGImageAlphaNoneSkipFirst, //bitmapInfo
458 dataProviderRef, //provider
461 kCGRenderingIntentDefault //intent
463 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
464 const NSRect *rectList;
467 CGImageRef clipImageRef;
470 [self getRectsBeingDrawn:&rectList count:&rectCount];
471 for (i = 0; i < rectCount; i++) {
472 clipRect.origin.x = rectList[i].origin.x / cdx;
473 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
474 clipRect.size.width = rectList[i].size.width / cdx;
475 clipRect.size.height = rectList[i].size.height / cdy;
476 clipImageRef = CGImageCreateWithImageInRect(
480 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
481 CGImageRelease (clipImageRef);
483 CGImageRelease (imageRef);
487 - (void) setContentDimensions
489 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
492 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
493 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
495 /* stretches video, but keeps same aspect ratio */
496 if (stretch_video == true) {
497 /* use smallest stretch value - prevents clipping on sides */
498 if (MIN(cdx, cdy) == cdx) {
503 } else { /* No stretching */
506 cw = screen.width * cdx;
507 ch = screen.height * cdy;
508 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
509 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
520 - (void) switchSurface:(pixman_image_t *)image
522 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
524 int w = pixman_image_get_width(image);
525 int h = pixman_image_get_height(image);
526 pixman_format_code_t image_format = pixman_image_get_format(image);
527 /* cdx == 0 means this is our very first surface, in which case we need
528 * to recalculate the content dimensions even if it happens to be the size
529 * of the initial empty window.
531 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
533 int oldh = screen.height;
535 // Resize before we trigger the redraw, or we'll redraw at the wrong size
536 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
539 [self setContentDimensions];
540 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
543 // update screenBuffer
544 if (dataProviderRef) {
545 CGDataProviderRelease(dataProviderRef);
546 pixman_image_unref(pixman_image);
549 //sync host window color space with guests
550 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
551 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
553 pixman_image = image;
554 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
558 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
559 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
562 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
563 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
567 [normalWindow center];
571 - (void) toggleFullScreen:(id)sender
573 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
575 if (isFullscreen) { // switch from fullscreen to desktop
576 isFullscreen = FALSE;
578 [self setContentDimensions];
579 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
580 [self exitFullScreenModeWithOptions:nil];
582 [fullScreenWindow close];
583 [normalWindow setContentView: self];
584 [normalWindow makeKeyAndOrderFront: self];
585 [NSMenu setMenuBarVisible:YES];
587 } else { // switch from desktop to fullscreen
589 [normalWindow orderOut: nil]; /* Hide the window */
591 [self setContentDimensions];
592 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
593 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
594 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
595 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
598 [NSMenu setMenuBarVisible:NO];
599 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
600 styleMask:NSWindowStyleMaskBorderless
601 backing:NSBackingStoreBuffered
603 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
604 [fullScreenWindow setHasShadow:NO];
605 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
606 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
607 [[fullScreenWindow contentView] addSubview: self];
608 [fullScreenWindow makeKeyAndOrderFront:self];
613 - (void) toggleModifier: (int)keycode {
614 // Toggle the stored state.
615 modifiers_state[keycode] = !modifiers_state[keycode];
616 // Send a keyup or keydown depending on the state.
617 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
620 - (void) toggleStatefulModifier: (int)keycode {
621 // Toggle the stored state.
622 modifiers_state[keycode] = !modifiers_state[keycode];
623 // Generate keydown and keyup.
624 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
625 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
628 // Does the work of sending input to the monitor
629 - (void) handleMonitorInput:(NSEvent *)event
634 // if the control key is down
635 if ([event modifierFlags] & NSEventModifierFlagControl) {
639 /* translates Macintosh keycodes to QEMU's keysym */
641 int without_control_translation[] = {
642 [0 ... 0xff] = 0, // invalid key
644 [kVK_UpArrow] = QEMU_KEY_UP,
645 [kVK_DownArrow] = QEMU_KEY_DOWN,
646 [kVK_RightArrow] = QEMU_KEY_RIGHT,
647 [kVK_LeftArrow] = QEMU_KEY_LEFT,
648 [kVK_Home] = QEMU_KEY_HOME,
649 [kVK_End] = QEMU_KEY_END,
650 [kVK_PageUp] = QEMU_KEY_PAGEUP,
651 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
652 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
653 [kVK_Delete] = QEMU_KEY_BACKSPACE,
656 int with_control_translation[] = {
657 [0 ... 0xff] = 0, // invalid key
659 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
660 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
661 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
662 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
663 [kVK_Home] = QEMU_KEY_CTRL_HOME,
664 [kVK_End] = QEMU_KEY_CTRL_END,
665 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
666 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
669 if (control_key != 0) { /* If the control key is being used */
670 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
671 keysym = with_control_translation[[event keyCode]];
674 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
675 keysym = without_control_translation[[event keyCode]];
679 // if not a key that needs translating
681 NSString *ks = [event characters];
682 if ([ks length] > 0) {
683 keysym = [ks characterAtIndex:0];
688 kbd_put_keysym(keysym);
692 - (bool) handleEvent:(NSEvent *)event
694 return bool_with_iothread_lock(^{
695 return [self handleEventLocked:event];
699 - (bool) handleEventLocked:(NSEvent *)event
701 /* Return true if we handled the event, false if it should be given to OSX */
702 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
705 bool mouse_event = false;
706 static bool switched_to_fullscreen = false;
707 NSPoint p = [event locationInWindow];
709 switch ([event type]) {
710 case NSEventTypeFlagsChanged:
711 if ([event keyCode] == 0) {
712 // When the Cocoa keyCode is zero that means keys should be
713 // synthesized based on the values in in the eventModifiers
716 if (qemu_console_is_graphic(NULL)) {
717 NSUInteger modifiers = [event modifierFlags];
719 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
720 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
722 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
723 [self toggleModifier:Q_KEY_CODE_SHIFT];
725 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
726 [self toggleModifier:Q_KEY_CODE_CTRL];
728 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
729 [self toggleModifier:Q_KEY_CODE_ALT];
731 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
732 [self toggleModifier:Q_KEY_CODE_META_L];
736 keycode = cocoa_keycode_to_qemu([event keyCode]);
739 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
740 && !isMouseGrabbed) {
741 /* Don't pass command key changes to guest unless mouse is grabbed */
746 // emulate caps lock and num lock keydown and keyup
747 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
748 keycode == Q_KEY_CODE_NUM_LOCK) {
749 [self toggleStatefulModifier:keycode];
750 } else if (qemu_console_is_graphic(NULL)) {
751 if (switched_to_fullscreen) {
752 switched_to_fullscreen = false;
754 [self toggleModifier:keycode];
760 case NSEventTypeKeyDown:
761 keycode = cocoa_keycode_to_qemu([event keyCode]);
763 // forward command key combos to the host UI unless the mouse is grabbed
764 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
766 * Prevent the command key from being stuck down in the guest
767 * when using Command-F to switch to full screen mode.
769 if (keycode == Q_KEY_CODE_F) {
770 switched_to_fullscreen = true;
777 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
778 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
779 NSString *keychar = [event charactersIgnoringModifiers];
780 if ([keychar length] == 1) {
781 char key = [keychar characterAtIndex:0];
784 // enable graphic console
786 console_select(key - '0' - 1); /* ascii math */
789 // release the mouse grab
797 if (qemu_console_is_graphic(NULL)) {
798 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
800 [self handleMonitorInput: event];
803 case NSEventTypeKeyUp:
804 keycode = cocoa_keycode_to_qemu([event keyCode]);
806 // don't pass the guest a spurious key-up if we treated this
807 // command-key combo as a host UI action
808 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
812 if (qemu_console_is_graphic(NULL)) {
813 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
816 case NSEventTypeMouseMoved:
817 if (isAbsoluteEnabled) {
818 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
819 if (isMouseGrabbed) {
823 if (!isMouseGrabbed) {
830 case NSEventTypeLeftMouseDown:
831 if ([event modifierFlags] & NSEventModifierFlagCommand) {
832 buttons |= MOUSE_EVENT_RBUTTON;
834 buttons |= MOUSE_EVENT_LBUTTON;
838 case NSEventTypeRightMouseDown:
839 buttons |= MOUSE_EVENT_RBUTTON;
842 case NSEventTypeOtherMouseDown:
843 buttons |= MOUSE_EVENT_MBUTTON;
846 case NSEventTypeLeftMouseDragged:
847 if ([event modifierFlags] & NSEventModifierFlagCommand) {
848 buttons |= MOUSE_EVENT_RBUTTON;
850 buttons |= MOUSE_EVENT_LBUTTON;
854 case NSEventTypeRightMouseDragged:
855 buttons |= MOUSE_EVENT_RBUTTON;
858 case NSEventTypeOtherMouseDragged:
859 buttons |= MOUSE_EVENT_MBUTTON;
862 case NSEventTypeLeftMouseUp:
864 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
865 if([[self window] isKeyWindow]) {
870 case NSEventTypeRightMouseUp:
873 case NSEventTypeOtherMouseUp:
876 case NSEventTypeScrollWheel:
878 * Send wheel events to the guest regardless of window focus.
879 * This is in-line with standard Mac OS X UI behaviour.
883 * When deltaY is zero, it means that this scrolling event was
884 * either horizontal, or so fine that it only appears in
885 * scrollingDeltaY. So we drop the event.
887 if ([event deltaY] != 0) {
888 /* Determine if this is a scroll up or scroll down event */
889 buttons = ([event deltaY] > 0) ?
890 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
891 qemu_input_queue_btn(dcl->con, buttons, true);
892 qemu_input_event_sync();
893 qemu_input_queue_btn(dcl->con, buttons, false);
894 qemu_input_event_sync();
897 * Since deltaY also reports scroll wheel events we prevent mouse
898 * movement code from executing.
907 /* Don't send button events to the guest unless we've got a
908 * mouse grab or window focus. If we have neither then this event
909 * is the user clicking on the background window to activate and
910 * bring us to the front, which will be done by the sendEvent
911 * call below. We definitely don't want to pass that click through
914 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
915 (last_buttons != buttons)) {
916 static uint32_t bmap[INPUT_BUTTON__MAX] = {
917 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
918 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
919 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
921 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
922 last_buttons = buttons;
924 if (isMouseGrabbed) {
925 if (isAbsoluteEnabled) {
926 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
927 * The check on screenContainsPoint is to avoid sending out of range values for
928 * clicks in the titlebar.
930 if ([self screenContainsPoint:p]) {
931 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
932 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
935 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
936 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
941 qemu_input_event_sync();
948 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
952 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
954 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
957 if (!isAbsoluteEnabled) {
958 isMouseDeassociated = TRUE;
959 CGAssociateMouseAndMouseCursorPosition(FALSE);
961 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
966 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
970 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
972 [normalWindow setTitle:@"QEMU"];
975 if (isMouseDeassociated) {
976 CGAssociateMouseAndMouseCursorPosition(TRUE);
977 isMouseDeassociated = FALSE;
979 isMouseGrabbed = FALSE;
982 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
983 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
984 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
985 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
986 - (float) cdx {return cdx;}
987 - (float) cdy {return cdy;}
988 - (QEMUScreen) gscreen {return screen;}
991 * Makes the target think all down keys are being released.
992 * This prevents a stuck key problem, since we will not see
993 * key up events for those keys after we have lost focus.
995 - (void) raiseAllKeys
997 const int max_index = ARRAY_SIZE(modifiers_state);
999 with_iothread_lock(^{
1002 for (index = 0; index < max_index; index++) {
1003 if (modifiers_state[index]) {
1004 modifiers_state[index] = 0;
1005 qemu_input_event_send_key_qcode(dcl->con, index, false);
1015 ------------------------------------------------------
1016 QemuCocoaAppController
1017 ------------------------------------------------------
1019 @interface QemuCocoaAppController : NSObject
1020 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
1021 <NSWindowDelegate, NSApplicationDelegate>
1025 - (void)doToggleFullScreen:(id)sender;
1026 - (void)toggleFullScreen:(id)sender;
1027 - (void)showQEMUDoc:(id)sender;
1028 - (void)zoomToFit:(id) sender;
1029 - (void)displayConsole:(id)sender;
1030 - (void)pauseQEMU:(id)sender;
1031 - (void)resumeQEMU:(id)sender;
1032 - (void)displayPause;
1033 - (void)removePause;
1034 - (void)restartQEMU:(id)sender;
1035 - (void)powerDownQEMU:(id)sender;
1036 - (void)ejectDeviceMedia:(id)sender;
1037 - (void)changeDeviceMedia:(id)sender;
1039 - (void)openDocumentation:(NSString *)filename;
1040 - (IBAction) do_about_menu_item: (id) sender;
1041 - (void)make_about_window;
1042 - (void)adjustSpeed:(id)sender;
1045 @implementation QemuCocoaAppController
1048 COCOA_DEBUG("QemuCocoaAppController: init\n");
1050 self = [super init];
1053 // create a view and add it to the window
1054 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1056 fprintf(stderr, "(cocoa) can't create a view\n");
1061 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1062 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1063 backing:NSBackingStoreBuffered defer:NO];
1065 fprintf(stderr, "(cocoa) can't create window\n");
1068 [normalWindow setAcceptsMouseMovedEvents:YES];
1069 [normalWindow setTitle:@"QEMU"];
1070 [normalWindow setContentView:cocoaView];
1071 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
1072 [normalWindow useOptimizedDrawing:YES];
1074 [normalWindow makeKeyAndOrderFront:self];
1075 [normalWindow center];
1076 [normalWindow setDelegate: self];
1077 stretch_video = false;
1079 /* Used for displaying pause on the screen */
1080 pauseLabel = [NSTextField new];
1081 [pauseLabel setBezeled:YES];
1082 [pauseLabel setDrawsBackground:YES];
1083 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1084 [pauseLabel setEditable:NO];
1085 [pauseLabel setSelectable:NO];
1086 [pauseLabel setStringValue: @"Paused"];
1087 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1088 [pauseLabel setTextColor: [NSColor blackColor]];
1089 [pauseLabel sizeToFit];
1091 // set the supported image file types that can be opened
1092 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1093 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1095 [self make_about_window];
1102 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1105 [cocoaView release];
1109 - (void)applicationDidFinishLaunching: (NSNotification *) note
1111 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1112 /* Tell cocoa_display_init to proceed */
1113 qemu_sem_post(&app_started_sem);
1116 - (void)applicationWillTerminate:(NSNotification *)aNotification
1118 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1120 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1124 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1129 - (NSApplicationTerminateReply)applicationShouldTerminate:
1130 (NSApplication *)sender
1132 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1133 return [self verifyQuit];
1136 /* Called when the user clicks on a window's close button */
1137 - (BOOL)windowShouldClose:(id)sender
1139 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1140 [NSApp terminate: sender];
1141 /* If the user allows the application to quit then the call to
1142 * NSApp terminate will never return. If we get here then the user
1143 * cancelled the quit, so we should return NO to not permit the
1144 * closing of this window.
1149 /* Called when QEMU goes into the background */
1150 - (void) applicationWillResignActive: (NSNotification *)aNotification
1152 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1153 [cocoaView raiseAllKeys];
1156 /* We abstract the method called by the Enter Fullscreen menu item
1157 * because Mac OS 10.7 and higher disables it. This is because of the
1158 * menu item's old selector's name toggleFullScreen:
1160 - (void) doToggleFullScreen:(id)sender
1162 [self toggleFullScreen:(id)sender];
1165 - (void)toggleFullScreen:(id)sender
1167 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1169 [cocoaView toggleFullScreen:sender];
1172 /* Tries to find then open the specified filename */
1173 - (void) openDocumentation: (NSString *) filename
1175 /* Where to look for local files */
1176 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1177 NSString *full_file_path;
1179 /* iterate thru the possible paths until the file is found */
1181 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1182 full_file_path = [[NSBundle mainBundle] executablePath];
1183 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1184 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1185 path_array[index], filename];
1186 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1191 /* If none of the paths opened a file */
1193 QEMU_Alert(@"Failed to open file");
1196 - (void)showQEMUDoc:(id)sender
1198 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1200 [self openDocumentation: @"qemu-doc.html"];
1203 /* Stretches video to fit host monitor size */
1204 - (void)zoomToFit:(id) sender
1206 stretch_video = !stretch_video;
1207 if (stretch_video == true) {
1208 [sender setState: NSControlStateValueOn];
1210 [sender setState: NSControlStateValueOff];
1214 /* Displays the console on the screen */
1215 - (void)displayConsole:(id)sender
1217 console_select([sender tag]);
1220 /* Pause the guest */
1221 - (void)pauseQEMU:(id)sender
1223 with_iothread_lock(^{
1226 [sender setEnabled: NO];
1227 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1228 [self displayPause];
1231 /* Resume running the guest operating system */
1232 - (void)resumeQEMU:(id) sender
1234 with_iothread_lock(^{
1237 [sender setEnabled: NO];
1238 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1242 /* Displays the word pause on the screen */
1243 - (void)displayPause
1245 /* Coordinates have to be calculated each time because the window can change its size */
1246 int xCoord, yCoord, width, height;
1247 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1248 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1249 width = [pauseLabel frame].size.width;
1250 height = [pauseLabel frame].size.height;
1251 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1252 [cocoaView addSubview: pauseLabel];
1255 /* Removes the word pause from the screen */
1258 [pauseLabel removeFromSuperview];
1262 - (void)restartQEMU:(id)sender
1264 with_iothread_lock(^{
1265 qmp_system_reset(NULL);
1269 /* Powers down QEMU */
1270 - (void)powerDownQEMU:(id)sender
1272 with_iothread_lock(^{
1273 qmp_system_powerdown(NULL);
1277 /* Ejects the media.
1278 * Uses sender's tag to figure out the device to eject.
1280 - (void)ejectDeviceMedia:(id)sender
1283 drive = [sender representedObject];
1286 QEMU_Alert(@"Failed to find drive to eject!");
1290 __block Error *err = NULL;
1291 with_iothread_lock(^{
1292 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1293 false, NULL, false, false, &err);
1295 handleAnyDeviceErrors(err);
1298 /* Displays a dialog box asking the user to select an image file to load.
1299 * Uses sender's represented object value to figure out which drive to use.
1301 - (void)changeDeviceMedia:(id)sender
1303 /* Find the drive name */
1305 drive = [sender representedObject];
1308 QEMU_Alert(@"Could not find drive!");
1312 /* Display the file open dialog */
1313 NSOpenPanel * openPanel;
1314 openPanel = [NSOpenPanel openPanel];
1315 [openPanel setCanChooseFiles: YES];
1316 [openPanel setAllowsMultipleSelection: NO];
1317 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1318 if([openPanel runModal] == NSModalResponseOK) {
1319 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1322 QEMU_Alert(@"Failed to convert URL to file path!");
1326 __block Error *err = NULL;
1327 with_iothread_lock(^{
1328 qmp_blockdev_change_medium(true,
1329 [drive cStringUsingEncoding:
1330 NSASCIIStringEncoding],
1332 [file cStringUsingEncoding:
1333 NSASCIIStringEncoding],
1338 handleAnyDeviceErrors(err);
1342 /* Verifies if the user really wants to quit */
1345 NSAlert *alert = [NSAlert new];
1346 [alert autorelease];
1347 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1348 [alert addButtonWithTitle: @"Cancel"];
1349 [alert addButtonWithTitle: @"Quit"];
1350 if([alert runModal] == NSAlertSecondButtonReturn) {
1357 /* The action method for the About menu item */
1358 - (IBAction) do_about_menu_item: (id) sender
1360 [about_window makeKeyAndOrderFront: nil];
1363 /* Create and display the about dialog */
1364 - (void)make_about_window
1366 /* Make the window */
1367 int x = 0, y = 0, about_width = 400, about_height = 200;
1368 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1369 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1370 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1371 NSWindowStyleMaskMiniaturizable
1372 backing:NSBackingStoreBuffered
1374 [about_window setTitle: @"About"];
1375 [about_window setReleasedWhenClosed: NO];
1376 [about_window center];
1377 NSView *superView = [about_window contentView];
1379 /* Create the dimensions of the picture */
1380 int picture_width = 80, picture_height = 80;
1381 x = (about_width - picture_width)/2;
1382 y = about_height - picture_height - 10;
1383 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1385 /* Get the path to the QEMU binary */
1386 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1387 encoding: NSASCIIStringEncoding];
1388 binary_name = [binary_name lastPathComponent];
1389 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1390 [[NSBundle mainBundle] bundlePath], binary_name];
1392 /* Make the picture of QEMU */
1393 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1395 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1397 [picture_view setImage: qemu_image];
1398 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1399 [superView addSubview: picture_view];
1401 /* Make the name label */
1404 int name_width = about_width, name_height = 20;
1405 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1406 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1407 [name_label setEditable: NO];
1408 [name_label setBezeled: NO];
1409 [name_label setDrawsBackground: NO];
1410 [name_label setAlignment: NSTextAlignmentCenter];
1411 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1412 encoding: NSASCIIStringEncoding];
1413 qemu_name = [qemu_name lastPathComponent];
1414 [name_label setStringValue: qemu_name];
1415 [superView addSubview: name_label];
1417 /* Set the version label's attributes */
1420 int version_width = about_width, version_height = 20;
1421 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1422 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1424 [version_label setEditable: NO];
1425 [version_label setBezeled: NO];
1426 [version_label setAlignment: NSTextAlignmentCenter];
1427 [version_label setDrawsBackground: NO];
1429 /* Create the version string*/
1430 NSString *version_string;
1431 version_string = [[NSString alloc] initWithFormat:
1432 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1433 [version_label setStringValue: version_string];
1434 [superView addSubview: version_label];
1436 /* Make copyright label */
1439 int copyright_width = about_width, copyright_height = 20;
1440 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1441 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1443 [copyright_label setEditable: NO];
1444 [copyright_label setBezeled: NO];
1445 [copyright_label setDrawsBackground: NO];
1446 [copyright_label setAlignment: NSTextAlignmentCenter];
1447 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1449 [superView addSubview: copyright_label];
1452 /* Used by the Speed menu items */
1453 - (void)adjustSpeed:(id)sender
1455 int throttle_pct; /* throttle percentage */
1458 menu = [sender menu];
1461 /* Unselect the currently selected item */
1462 for (NSMenuItem *item in [menu itemArray]) {
1463 if (item.state == NSControlStateValueOn) {
1464 [item setState: NSControlStateValueOff];
1470 // check the menu item
1471 [sender setState: NSControlStateValueOn];
1473 // get the throttle percentage
1474 throttle_pct = [sender tag];
1476 with_iothread_lock(^{
1477 cpu_throttle_set(throttle_pct);
1479 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1484 @interface QemuApplication : NSApplication
1487 @implementation QemuApplication
1488 - (void)sendEvent:(NSEvent *)event
1490 COCOA_DEBUG("QemuApplication: sendEvent\n");
1491 if (![cocoaView handleEvent:event]) {
1492 [super sendEvent: event];
1497 static void create_initial_menus(void)
1501 NSMenuItem *menuItem;
1503 [NSApp setMainMenu:[[NSMenu alloc] init]];
1506 menu = [[NSMenu alloc] initWithTitle:@""];
1507 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1508 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1509 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1510 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1511 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1512 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1513 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1514 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1515 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1516 [menuItem setSubmenu:menu];
1517 [[NSApp mainMenu] addItem:menuItem];
1518 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1521 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1522 [menu setAutoenablesItems: NO];
1523 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1524 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1525 [menu addItem: menuItem];
1526 [menuItem setEnabled: NO];
1527 [menu addItem: [NSMenuItem separatorItem]];
1528 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1530 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1531 [menuItem setSubmenu:menu];
1532 [[NSApp mainMenu] addItem:menuItem];
1535 menu = [[NSMenu alloc] initWithTitle:@"View"];
1536 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1537 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1538 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1539 [menuItem setSubmenu:menu];
1540 [[NSApp mainMenu] addItem:menuItem];
1543 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1545 // Add the rest of the Speed menu items
1546 int p, percentage, throttle_pct;
1547 for (p = 10; p >= 0; p--)
1549 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1551 menuItem = [[[NSMenuItem alloc]
1552 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1554 if (percentage == 100) {
1555 [menuItem setState: NSControlStateValueOn];
1558 /* Calculate the throttle percentage */
1559 throttle_pct = -1 * percentage + 100;
1561 [menuItem setTag: throttle_pct];
1562 [menu addItem: menuItem];
1564 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1565 [menuItem setSubmenu:menu];
1566 [[NSApp mainMenu] addItem:menuItem];
1569 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1570 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1571 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1572 [menuItem setSubmenu:menu];
1573 [[NSApp mainMenu] addItem:menuItem];
1574 [NSApp setWindowsMenu:menu];
1577 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1578 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1579 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1580 [menuItem setSubmenu:menu];
1581 [[NSApp mainMenu] addItem:menuItem];
1584 /* Returns a name for a given console */
1585 static NSString * getConsoleName(QemuConsole * console)
1587 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1590 /* Add an entry to the View menu for each console */
1591 static void add_console_menu_entries(void)
1594 NSMenuItem *menuItem;
1597 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1599 [menu addItem:[NSMenuItem separatorItem]];
1601 while (qemu_console_lookup_by_index(index) != NULL) {
1602 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1603 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1604 [menuItem setTag: index];
1605 [menu addItem: menuItem];
1610 /* Make menu items for all removable devices.
1611 * Each device is given an 'Eject' and 'Change' menu item.
1613 static void addRemovableDevicesMenuItems(void)
1616 NSMenuItem *menuItem;
1617 BlockInfoList *currentDevice, *pointerToFree;
1618 NSString *deviceName;
1620 currentDevice = qmp_query_block(NULL);
1621 pointerToFree = currentDevice;
1622 if(currentDevice == NULL) {
1624 QEMU_Alert(@"Failed to query for block devices!");
1628 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1630 // Add a separator between related groups of menu items
1631 [menu addItem:[NSMenuItem separatorItem]];
1633 // Set the attributes to the "Removable Media" menu item
1634 NSString *titleString = @"Removable Media";
1635 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1636 NSColor *newColor = [NSColor blackColor];
1637 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1638 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1639 traits:NSBoldFontMask|NSItalicFontMask
1642 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1643 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1644 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1646 // Add the "Removable Media" menu item
1647 menuItem = [NSMenuItem new];
1648 [menuItem setAttributedTitle: attString];
1649 [menuItem setEnabled: NO];
1650 [menu addItem: menuItem];
1652 /* Loop through all the block devices in the emulator */
1653 while (currentDevice) {
1654 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1656 if(currentDevice->value->removable) {
1657 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1658 action: @selector(changeDeviceMedia:)
1659 keyEquivalent: @""];
1660 [menu addItem: menuItem];
1661 [menuItem setRepresentedObject: deviceName];
1662 [menuItem autorelease];
1664 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1665 action: @selector(ejectDeviceMedia:)
1666 keyEquivalent: @""];
1667 [menu addItem: menuItem];
1668 [menuItem setRepresentedObject: deviceName];
1669 [menuItem autorelease];
1671 currentDevice = currentDevice->next;
1673 qapi_free_BlockInfoList(pointerToFree);
1677 * The startup process for the OSX/Cocoa UI is complicated, because
1678 * OSX insists that the UI runs on the initial main thread, and so we
1679 * need to start a second thread which runs the vl.c qemu_main():
1681 * Initial thread: 2nd thread:
1683 * create qemu-main thread
1684 * wait on display_init semaphore
1687 * in cocoa_display_init():
1688 * post the display_init semaphore
1689 * wait on app_started semaphore
1690 * create application, menus, etc
1691 * enter OSX run loop
1692 * in applicationDidFinishLaunching:
1693 * post app_started semaphore
1694 * tell main thread to fullscreen if needed
1696 * run qemu main-loop
1698 * We do this in two stages so that we don't do the creation of the
1699 * GUI application menus and so on for command line options like --help
1700 * where we want to just print text to stdout and exit immediately.
1703 static void *call_qemu_main(void *opaque)
1707 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1708 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1709 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1713 int main (int argc, const char * argv[]) {
1716 COCOA_DEBUG("Entered main()\n");
1718 gArgv = (char **)argv;
1720 qemu_sem_init(&display_init_sem, 0);
1721 qemu_sem_init(&app_started_sem, 0);
1723 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1724 NULL, QEMU_THREAD_DETACHED);
1726 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1727 qemu_sem_wait(&display_init_sem);
1728 COCOA_DEBUG("Main thread: initializing app\n");
1730 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1732 // Pull this console process up to being a fully-fledged graphical
1733 // app with a menubar and Dock icon
1734 ProcessSerialNumber psn = { 0, kCurrentProcess };
1735 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1737 [QemuApplication sharedApplication];
1739 create_initial_menus();
1742 * Create the menu entries which depend on QEMU state (for consoles
1743 * and removeable devices). These make calls back into QEMU functions,
1744 * which is OK because at this point we know that the second thread
1745 * holds the iothread lock and is synchronously waiting for us to
1748 add_console_menu_entries();
1749 addRemovableDevicesMenuItems();
1751 // Create an Application controller
1752 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1753 [NSApp setDelegate:appController];
1755 // Start the main event loop
1756 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1758 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1760 [appController release];
1769 static void cocoa_update(DisplayChangeListener *dcl,
1770 int x, int y, int w, int h)
1772 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1774 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1776 dispatch_async(dispatch_get_main_queue(), ^{
1778 if ([cocoaView cdx] == 1.0) {
1779 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1782 x * [cocoaView cdx],
1783 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1784 w * [cocoaView cdx],
1785 h * [cocoaView cdy]);
1787 [cocoaView setNeedsDisplayInRect:rect];
1793 static void cocoa_switch(DisplayChangeListener *dcl,
1794 DisplaySurface *surface)
1796 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1797 pixman_image_t *image = surface->image;
1799 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1801 // The DisplaySurface will be freed as soon as this callback returns.
1802 // We take a reference to the underlying pixman image here so it does
1803 // not disappear from under our feet; the switchSurface method will
1804 // deref the old image when it is done with it.
1805 pixman_image_ref(image);
1807 dispatch_async(dispatch_get_main_queue(), ^{
1808 [cocoaView switchSurface:image];
1813 static void cocoa_refresh(DisplayChangeListener *dcl)
1815 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1817 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1818 graphic_hw_update(NULL);
1820 if (qemu_input_is_absolute()) {
1821 dispatch_async(dispatch_get_main_queue(), ^{
1822 if (![cocoaView isAbsoluteEnabled]) {
1823 if ([cocoaView isMouseGrabbed]) {
1824 [cocoaView ungrabMouse];
1827 [cocoaView setAbsoluteEnabled:YES];
1833 static void cocoa_cleanup(void)
1835 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1839 static const DisplayChangeListenerOps dcl_ops = {
1840 .dpy_name = "cocoa",
1841 .dpy_gfx_update = cocoa_update,
1842 .dpy_gfx_switch = cocoa_switch,
1843 .dpy_refresh = cocoa_refresh,
1846 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1848 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1850 /* Tell main thread to go ahead and create the app and enter the run loop */
1851 qemu_sem_post(&display_init_sem);
1852 qemu_sem_wait(&app_started_sem);
1853 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1855 /* if fullscreen mode is to be used */
1856 if (opts->has_full_screen && opts->full_screen) {
1857 dispatch_async(dispatch_get_main_queue(), ^{
1858 [NSApp activateIgnoringOtherApps: YES];
1859 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1863 dcl = g_malloc0(sizeof(DisplayChangeListener));
1865 // register vga output callbacks
1866 dcl->ops = &dcl_ops;
1867 register_displaychangelistener(dcl);
1869 // register cleanup function
1870 atexit(cocoa_cleanup);
1873 static QemuDisplay qemu_display_cocoa = {
1874 .type = DISPLAY_TYPE_COCOA,
1875 .init = cocoa_display_init,
1878 static void register_cocoa(void)
1880 qemu_display_register(&qemu_display_cocoa);
1883 type_init(register_cocoa);