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 "sysemu/runstate.h"
35 #include "sysemu/cpu-throttle.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-commands-block.h"
38 #include "qapi/qapi-commands-misc.h"
39 #include "sysemu/blockdev.h"
40 #include "qemu-version.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include <Carbon/Carbon.h>
44 #include "hw/core/cpu.h"
46 #ifndef MAC_OS_X_VERSION_10_13
47 #define MAC_OS_X_VERSION_10_13 101300
50 /* 10.14 deprecates NSOnState and NSOffState in favor of
51 * NSControlStateValueOn/Off, which were introduced in 10.13.
52 * Define for older versions
54 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
55 #define NSControlStateValueOn NSOnState
56 #define NSControlStateValueOff NSOffState
62 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
64 #define COCOA_DEBUG(...) ((void) 0)
67 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
76 NSWindow *normalWindow, *about_window;
77 static DisplayChangeListener *dcl;
78 static int last_buttons;
79 static int cursor_hide = 1;
84 NSTextField *pauseLabel;
85 NSArray * supportedImageFileTypes;
87 static QemuSemaphore display_init_sem;
88 static QemuSemaphore app_started_sem;
89 static bool allow_events;
91 // Utility functions to run specified code block with iothread lock held
92 typedef void (^CodeBlock)(void);
93 typedef bool (^BoolCodeBlock)(void);
95 static void with_iothread_lock(CodeBlock block)
97 bool locked = qemu_mutex_iothread_locked();
99 qemu_mutex_lock_iothread();
103 qemu_mutex_unlock_iothread();
107 static bool bool_with_iothread_lock(BoolCodeBlock block)
109 bool locked = qemu_mutex_iothread_locked();
113 qemu_mutex_lock_iothread();
117 qemu_mutex_unlock_iothread();
122 // Mac to QKeyCode conversion
123 const int mac_to_qkeycode_map[] = {
124 [kVK_ANSI_A] = Q_KEY_CODE_A,
125 [kVK_ANSI_B] = Q_KEY_CODE_B,
126 [kVK_ANSI_C] = Q_KEY_CODE_C,
127 [kVK_ANSI_D] = Q_KEY_CODE_D,
128 [kVK_ANSI_E] = Q_KEY_CODE_E,
129 [kVK_ANSI_F] = Q_KEY_CODE_F,
130 [kVK_ANSI_G] = Q_KEY_CODE_G,
131 [kVK_ANSI_H] = Q_KEY_CODE_H,
132 [kVK_ANSI_I] = Q_KEY_CODE_I,
133 [kVK_ANSI_J] = Q_KEY_CODE_J,
134 [kVK_ANSI_K] = Q_KEY_CODE_K,
135 [kVK_ANSI_L] = Q_KEY_CODE_L,
136 [kVK_ANSI_M] = Q_KEY_CODE_M,
137 [kVK_ANSI_N] = Q_KEY_CODE_N,
138 [kVK_ANSI_O] = Q_KEY_CODE_O,
139 [kVK_ANSI_P] = Q_KEY_CODE_P,
140 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
141 [kVK_ANSI_R] = Q_KEY_CODE_R,
142 [kVK_ANSI_S] = Q_KEY_CODE_S,
143 [kVK_ANSI_T] = Q_KEY_CODE_T,
144 [kVK_ANSI_U] = Q_KEY_CODE_U,
145 [kVK_ANSI_V] = Q_KEY_CODE_V,
146 [kVK_ANSI_W] = Q_KEY_CODE_W,
147 [kVK_ANSI_X] = Q_KEY_CODE_X,
148 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
149 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
151 [kVK_ANSI_0] = Q_KEY_CODE_0,
152 [kVK_ANSI_1] = Q_KEY_CODE_1,
153 [kVK_ANSI_2] = Q_KEY_CODE_2,
154 [kVK_ANSI_3] = Q_KEY_CODE_3,
155 [kVK_ANSI_4] = Q_KEY_CODE_4,
156 [kVK_ANSI_5] = Q_KEY_CODE_5,
157 [kVK_ANSI_6] = Q_KEY_CODE_6,
158 [kVK_ANSI_7] = Q_KEY_CODE_7,
159 [kVK_ANSI_8] = Q_KEY_CODE_8,
160 [kVK_ANSI_9] = Q_KEY_CODE_9,
162 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
163 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
164 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
165 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
166 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
167 [kVK_Tab] = Q_KEY_CODE_TAB,
168 [kVK_Return] = Q_KEY_CODE_RET,
169 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
170 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
171 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
172 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
173 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
174 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
175 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
176 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
177 [kVK_Shift] = Q_KEY_CODE_SHIFT,
178 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
179 [kVK_Control] = Q_KEY_CODE_CTRL,
180 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
181 [kVK_Option] = Q_KEY_CODE_ALT,
182 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
183 [kVK_Command] = Q_KEY_CODE_META_L,
184 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
185 [kVK_Space] = Q_KEY_CODE_SPC,
187 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
188 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
189 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
190 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
191 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
192 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
193 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
194 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
195 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
196 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
197 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
198 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
199 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
200 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
201 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
202 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
203 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
204 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
206 [kVK_UpArrow] = Q_KEY_CODE_UP,
207 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
208 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
209 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
211 [kVK_Help] = Q_KEY_CODE_INSERT,
212 [kVK_Home] = Q_KEY_CODE_HOME,
213 [kVK_PageUp] = Q_KEY_CODE_PGUP,
214 [kVK_PageDown] = Q_KEY_CODE_PGDN,
215 [kVK_End] = Q_KEY_CODE_END,
216 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
218 [kVK_Escape] = Q_KEY_CODE_ESC,
220 /* The Power key can't be used directly because the operating system uses
221 * it. This key can be emulated by using it in place of another key such as
222 * F1. Don't forget to disable the real key binding.
224 /* [kVK_F1] = Q_KEY_CODE_POWER, */
226 [kVK_F1] = Q_KEY_CODE_F1,
227 [kVK_F2] = Q_KEY_CODE_F2,
228 [kVK_F3] = Q_KEY_CODE_F3,
229 [kVK_F4] = Q_KEY_CODE_F4,
230 [kVK_F5] = Q_KEY_CODE_F5,
231 [kVK_F6] = Q_KEY_CODE_F6,
232 [kVK_F7] = Q_KEY_CODE_F7,
233 [kVK_F8] = Q_KEY_CODE_F8,
234 [kVK_F9] = Q_KEY_CODE_F9,
235 [kVK_F10] = Q_KEY_CODE_F10,
236 [kVK_F11] = Q_KEY_CODE_F11,
237 [kVK_F12] = Q_KEY_CODE_F12,
238 [kVK_F13] = Q_KEY_CODE_PRINT,
239 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
240 [kVK_F15] = Q_KEY_CODE_PAUSE,
243 * The eject and volume keys can't be used here because they are handled at
244 * a lower level than what an Application can see.
248 static int cocoa_keycode_to_qemu(int keycode)
250 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
251 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
254 return mac_to_qkeycode_map[keycode];
257 /* Displays an alert dialog box with the specified message */
258 static void QEMU_Alert(NSString *message)
261 alert = [NSAlert new];
262 [alert setMessageText: message];
266 /* Handles any errors that happen with a device transaction */
267 static void handleAnyDeviceErrors(Error * err)
270 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
271 encoding: NSASCIIStringEncoding]);
277 ------------------------------------------------------
279 ------------------------------------------------------
281 @interface QemuCocoaView : NSView
284 NSWindow *fullScreenWindow;
285 float cx,cy,cw,ch,cdx,cdy;
286 CGDataProviderRef dataProviderRef;
287 pixman_image_t *pixman_image;
288 BOOL modifiers_state[256];
291 BOOL isAbsoluteEnabled;
292 BOOL isMouseDeassociated;
294 - (void) switchSurface:(pixman_image_t *)image;
296 - (void) ungrabMouse;
297 - (void) toggleFullScreen:(id)sender;
298 - (void) handleMonitorInput:(NSEvent *)event;
299 - (bool) handleEvent:(NSEvent *)event;
300 - (bool) handleEventLocked:(NSEvent *)event;
301 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
302 /* The state surrounding mouse grabbing is potentially confusing.
303 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
304 * pointing device an absolute-position one?"], but is only updated on
306 * isMouseGrabbed tracks whether GUI events are directed to the guest;
307 * it controls whether special keys like Cmd get sent to the guest,
308 * and whether we capture the mouse when in non-absolute mode.
309 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
310 * the mouse and mouse cursor position by calling
311 * CGAssociateMouseAndMouseCursorPosition(FALSE)
312 * (which basically happens if we grab in non-absolute mode).
314 - (BOOL) isMouseGrabbed;
315 - (BOOL) isAbsoluteEnabled;
316 - (BOOL) isMouseDeassociated;
319 - (QEMUScreen) gscreen;
320 - (void) raiseAllKeys;
323 QemuCocoaView *cocoaView;
325 @implementation QemuCocoaView
326 - (id)initWithFrame:(NSRect)frameRect
328 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
330 self = [super initWithFrame:frameRect];
333 screen.bitsPerComponent = 8;
334 screen.bitsPerPixel = 32;
335 screen.width = frameRect.size.width;
336 screen.height = frameRect.size.height;
344 COCOA_DEBUG("QemuCocoaView: dealloc\n");
346 if (dataProviderRef) {
347 CGDataProviderRelease(dataProviderRef);
348 pixman_image_unref(pixman_image);
359 - (BOOL) screenContainsPoint:(NSPoint) p
361 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
364 /* Get location of event and convert to virtual screen coordinate */
365 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
367 NSWindow *eventWindow = [ev window];
368 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
369 CGRect r = CGRectZero;
370 r.origin = [ev locationInWindow];
373 return [[self window] convertRectFromScreen:r].origin;
375 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
376 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
383 } else if ([[self window] isEqual:eventWindow]) {
387 CGPoint loc = [self convertPoint:r.origin fromView:nil];
395 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
407 - (void) unhideCursor
415 - (void) drawRect:(NSRect) rect
417 COCOA_DEBUG("QemuCocoaView: drawRect\n");
419 // get CoreGraphic context
420 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
422 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
423 CGContextSetShouldAntialias (viewContextRef, NO);
425 // draw screen bitmap directly to Core Graphics context
426 if (!dataProviderRef) {
427 // Draw request before any guest device has set up a framebuffer:
428 // just draw an opaque black rectangle
429 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
430 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
432 CGImageRef imageRef = CGImageCreate(
433 screen.width, //width
434 screen.height, //height
435 screen.bitsPerComponent, //bitsPerComponent
436 screen.bitsPerPixel, //bitsPerPixel
437 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
438 #ifdef __LITTLE_ENDIAN__
439 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
440 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
442 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
443 kCGImageAlphaNoneSkipFirst, //bitmapInfo
445 dataProviderRef, //provider
448 kCGRenderingIntentDefault //intent
450 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
451 const NSRect *rectList;
454 CGImageRef clipImageRef;
457 [self getRectsBeingDrawn:&rectList count:&rectCount];
458 for (i = 0; i < rectCount; i++) {
459 clipRect.origin.x = rectList[i].origin.x / cdx;
460 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
461 clipRect.size.width = rectList[i].size.width / cdx;
462 clipRect.size.height = rectList[i].size.height / cdy;
463 clipImageRef = CGImageCreateWithImageInRect(
467 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
468 CGImageRelease (clipImageRef);
470 CGImageRelease (imageRef);
474 - (void) setContentDimensions
476 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
479 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
480 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
482 /* stretches video, but keeps same aspect ratio */
483 if (stretch_video == true) {
484 /* use smallest stretch value - prevents clipping on sides */
485 if (MIN(cdx, cdy) == cdx) {
490 } else { /* No stretching */
493 cw = screen.width * cdx;
494 ch = screen.height * cdy;
495 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
496 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
507 - (void) switchSurface:(pixman_image_t *)image
509 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
511 int w = pixman_image_get_width(image);
512 int h = pixman_image_get_height(image);
513 pixman_format_code_t image_format = pixman_image_get_format(image);
514 /* cdx == 0 means this is our very first surface, in which case we need
515 * to recalculate the content dimensions even if it happens to be the size
516 * of the initial empty window.
518 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
520 int oldh = screen.height;
522 // Resize before we trigger the redraw, or we'll redraw at the wrong size
523 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
526 [self setContentDimensions];
527 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
530 // update screenBuffer
531 if (dataProviderRef) {
532 CGDataProviderRelease(dataProviderRef);
533 pixman_image_unref(pixman_image);
536 //sync host window color space with guests
537 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
538 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
540 pixman_image = image;
541 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
545 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
546 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
549 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
550 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
554 [normalWindow center];
558 - (void) toggleFullScreen:(id)sender
560 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
562 if (isFullscreen) { // switch from fullscreen to desktop
563 isFullscreen = FALSE;
565 [self setContentDimensions];
566 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
567 [self exitFullScreenModeWithOptions:nil];
569 [fullScreenWindow close];
570 [normalWindow setContentView: self];
571 [normalWindow makeKeyAndOrderFront: self];
572 [NSMenu setMenuBarVisible:YES];
574 } else { // switch from desktop to fullscreen
576 [normalWindow orderOut: nil]; /* Hide the window */
578 [self setContentDimensions];
579 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
580 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
581 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
582 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
585 [NSMenu setMenuBarVisible:NO];
586 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
587 styleMask:NSWindowStyleMaskBorderless
588 backing:NSBackingStoreBuffered
590 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
591 [fullScreenWindow setHasShadow:NO];
592 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
593 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
594 [[fullScreenWindow contentView] addSubview: self];
595 [fullScreenWindow makeKeyAndOrderFront:self];
600 - (void) toggleModifier: (int)keycode {
601 // Toggle the stored state.
602 modifiers_state[keycode] = !modifiers_state[keycode];
603 // Send a keyup or keydown depending on the state.
604 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
607 - (void) toggleStatefulModifier: (int)keycode {
608 // Toggle the stored state.
609 modifiers_state[keycode] = !modifiers_state[keycode];
610 // Generate keydown and keyup.
611 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
612 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
615 // Does the work of sending input to the monitor
616 - (void) handleMonitorInput:(NSEvent *)event
621 // if the control key is down
622 if ([event modifierFlags] & NSEventModifierFlagControl) {
626 /* translates Macintosh keycodes to QEMU's keysym */
628 int without_control_translation[] = {
629 [0 ... 0xff] = 0, // invalid key
631 [kVK_UpArrow] = QEMU_KEY_UP,
632 [kVK_DownArrow] = QEMU_KEY_DOWN,
633 [kVK_RightArrow] = QEMU_KEY_RIGHT,
634 [kVK_LeftArrow] = QEMU_KEY_LEFT,
635 [kVK_Home] = QEMU_KEY_HOME,
636 [kVK_End] = QEMU_KEY_END,
637 [kVK_PageUp] = QEMU_KEY_PAGEUP,
638 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
639 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
640 [kVK_Delete] = QEMU_KEY_BACKSPACE,
643 int with_control_translation[] = {
644 [0 ... 0xff] = 0, // invalid key
646 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
647 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
648 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
649 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
650 [kVK_Home] = QEMU_KEY_CTRL_HOME,
651 [kVK_End] = QEMU_KEY_CTRL_END,
652 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
653 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
656 if (control_key != 0) { /* If the control key is being used */
657 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
658 keysym = with_control_translation[[event keyCode]];
661 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
662 keysym = without_control_translation[[event keyCode]];
666 // if not a key that needs translating
668 NSString *ks = [event characters];
669 if ([ks length] > 0) {
670 keysym = [ks characterAtIndex:0];
675 kbd_put_keysym(keysym);
679 - (bool) handleEvent:(NSEvent *)event
683 * Just let OSX have all events that arrive before
684 * applicationDidFinishLaunching.
685 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
686 * will not drop until after the app_started_sem is posted. (In theory
687 * there should not be any such events, but OSX Catalina now emits some.)
691 return bool_with_iothread_lock(^{
692 return [self handleEventLocked:event];
696 - (bool) handleEventLocked:(NSEvent *)event
698 /* Return true if we handled the event, false if it should be given to OSX */
699 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
702 bool mouse_event = false;
703 static bool switched_to_fullscreen = false;
704 // Location of event in virtual screen coordinates
705 NSPoint p = [self screenLocationOfEvent:event];
707 switch ([event type]) {
708 case NSEventTypeFlagsChanged:
709 if ([event keyCode] == 0) {
710 // When the Cocoa keyCode is zero that means keys should be
711 // synthesized based on the values in in the eventModifiers
714 if (qemu_console_is_graphic(NULL)) {
715 NSUInteger modifiers = [event modifierFlags];
717 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
718 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
720 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
721 [self toggleModifier:Q_KEY_CODE_SHIFT];
723 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
724 [self toggleModifier:Q_KEY_CODE_CTRL];
726 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
727 [self toggleModifier:Q_KEY_CODE_ALT];
729 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
730 [self toggleModifier:Q_KEY_CODE_META_L];
734 keycode = cocoa_keycode_to_qemu([event keyCode]);
737 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
738 && !isMouseGrabbed) {
739 /* Don't pass command key changes to guest unless mouse is grabbed */
744 // emulate caps lock and num lock keydown and keyup
745 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
746 keycode == Q_KEY_CODE_NUM_LOCK) {
747 [self toggleStatefulModifier:keycode];
748 } else if (qemu_console_is_graphic(NULL)) {
749 if (switched_to_fullscreen) {
750 switched_to_fullscreen = false;
752 [self toggleModifier:keycode];
758 case NSEventTypeKeyDown:
759 keycode = cocoa_keycode_to_qemu([event keyCode]);
761 // forward command key combos to the host UI unless the mouse is grabbed
762 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
764 * Prevent the command key from being stuck down in the guest
765 * when using Command-F to switch to full screen mode.
767 if (keycode == Q_KEY_CODE_F) {
768 switched_to_fullscreen = true;
775 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
776 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
777 NSString *keychar = [event charactersIgnoringModifiers];
778 if ([keychar length] == 1) {
779 char key = [keychar characterAtIndex:0];
782 // enable graphic console
784 console_select(key - '0' - 1); /* ascii math */
787 // release the mouse grab
795 if (qemu_console_is_graphic(NULL)) {
796 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
798 [self handleMonitorInput: event];
801 case NSEventTypeKeyUp:
802 keycode = cocoa_keycode_to_qemu([event keyCode]);
804 // don't pass the guest a spurious key-up if we treated this
805 // command-key combo as a host UI action
806 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
810 if (qemu_console_is_graphic(NULL)) {
811 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
814 case NSEventTypeMouseMoved:
815 if (isAbsoluteEnabled) {
816 // Cursor re-entered into a window might generate events bound to screen coordinates
817 // and `nil` window property, and in full screen mode, current window might not be
818 // key window, where event location alone should suffice.
819 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
820 if (isMouseGrabbed) {
824 if (!isMouseGrabbed) {
831 case NSEventTypeLeftMouseDown:
832 if ([event modifierFlags] & NSEventModifierFlagCommand) {
833 buttons |= MOUSE_EVENT_RBUTTON;
835 buttons |= MOUSE_EVENT_LBUTTON;
839 case NSEventTypeRightMouseDown:
840 buttons |= MOUSE_EVENT_RBUTTON;
843 case NSEventTypeOtherMouseDown:
844 buttons |= MOUSE_EVENT_MBUTTON;
847 case NSEventTypeLeftMouseDragged:
848 if ([event modifierFlags] & NSEventModifierFlagCommand) {
849 buttons |= MOUSE_EVENT_RBUTTON;
851 buttons |= MOUSE_EVENT_LBUTTON;
855 case NSEventTypeRightMouseDragged:
856 buttons |= MOUSE_EVENT_RBUTTON;
859 case NSEventTypeOtherMouseDragged:
860 buttons |= MOUSE_EVENT_MBUTTON;
863 case NSEventTypeLeftMouseUp:
865 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
867 * In fullscreen mode, the window of cocoaView may not be the
868 * key window, therefore the position relative to the virtual
869 * screen alone will be sufficient.
871 if(isFullscreen || [[self window] isKeyWindow]) {
876 case NSEventTypeRightMouseUp:
879 case NSEventTypeOtherMouseUp:
882 case NSEventTypeScrollWheel:
884 * Send wheel events to the guest regardless of window focus.
885 * This is in-line with standard Mac OS X UI behaviour.
889 * When deltaY is zero, it means that this scrolling event was
890 * either horizontal, or so fine that it only appears in
891 * scrollingDeltaY. So we drop the event.
893 if ([event deltaY] != 0) {
894 /* Determine if this is a scroll up or scroll down event */
895 buttons = ([event deltaY] > 0) ?
896 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
897 qemu_input_queue_btn(dcl->con, buttons, true);
898 qemu_input_event_sync();
899 qemu_input_queue_btn(dcl->con, buttons, false);
900 qemu_input_event_sync();
903 * Since deltaY also reports scroll wheel events we prevent mouse
904 * movement code from executing.
913 /* Don't send button events to the guest unless we've got a
914 * mouse grab or window focus. If we have neither then this event
915 * is the user clicking on the background window to activate and
916 * bring us to the front, which will be done by the sendEvent
917 * call below. We definitely don't want to pass that click through
920 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
921 (last_buttons != buttons)) {
922 static uint32_t bmap[INPUT_BUTTON__MAX] = {
923 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
924 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
925 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
927 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
928 last_buttons = buttons;
930 if (isMouseGrabbed) {
931 if (isAbsoluteEnabled) {
932 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
933 * The check on screenContainsPoint is to avoid sending out of range values for
934 * clicks in the titlebar.
936 if ([self screenContainsPoint:p]) {
937 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
938 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
941 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
942 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
947 qemu_input_event_sync();
954 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
958 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
960 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
963 if (!isAbsoluteEnabled) {
964 isMouseDeassociated = TRUE;
965 CGAssociateMouseAndMouseCursorPosition(FALSE);
967 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
972 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
976 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
978 [normalWindow setTitle:@"QEMU"];
981 if (isMouseDeassociated) {
982 CGAssociateMouseAndMouseCursorPosition(TRUE);
983 isMouseDeassociated = FALSE;
985 isMouseGrabbed = FALSE;
988 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
989 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
990 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
991 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
992 - (float) cdx {return cdx;}
993 - (float) cdy {return cdy;}
994 - (QEMUScreen) gscreen {return screen;}
997 * Makes the target think all down keys are being released.
998 * This prevents a stuck key problem, since we will not see
999 * key up events for those keys after we have lost focus.
1001 - (void) raiseAllKeys
1003 const int max_index = ARRAY_SIZE(modifiers_state);
1005 with_iothread_lock(^{
1008 for (index = 0; index < max_index; index++) {
1009 if (modifiers_state[index]) {
1010 modifiers_state[index] = 0;
1011 qemu_input_event_send_key_qcode(dcl->con, index, false);
1021 ------------------------------------------------------
1022 QemuCocoaAppController
1023 ------------------------------------------------------
1025 @interface QemuCocoaAppController : NSObject
1026 <NSWindowDelegate, NSApplicationDelegate>
1029 - (void)doToggleFullScreen:(id)sender;
1030 - (void)toggleFullScreen:(id)sender;
1031 - (void)showQEMUDoc:(id)sender;
1032 - (void)zoomToFit:(id) sender;
1033 - (void)displayConsole:(id)sender;
1034 - (void)pauseQEMU:(id)sender;
1035 - (void)resumeQEMU:(id)sender;
1036 - (void)displayPause;
1037 - (void)removePause;
1038 - (void)restartQEMU:(id)sender;
1039 - (void)powerDownQEMU:(id)sender;
1040 - (void)ejectDeviceMedia:(id)sender;
1041 - (void)changeDeviceMedia:(id)sender;
1043 - (void)openDocumentation:(NSString *)filename;
1044 - (IBAction) do_about_menu_item: (id) sender;
1045 - (void)make_about_window;
1046 - (void)adjustSpeed:(id)sender;
1049 @implementation QemuCocoaAppController
1052 COCOA_DEBUG("QemuCocoaAppController: init\n");
1054 self = [super init];
1057 // create a view and add it to the window
1058 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1060 fprintf(stderr, "(cocoa) can't create a view\n");
1065 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1066 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1067 backing:NSBackingStoreBuffered defer:NO];
1069 fprintf(stderr, "(cocoa) can't create window\n");
1072 [normalWindow setAcceptsMouseMovedEvents:YES];
1073 [normalWindow setTitle:@"QEMU"];
1074 [normalWindow setContentView:cocoaView];
1075 [normalWindow makeKeyAndOrderFront:self];
1076 [normalWindow center];
1077 [normalWindow setDelegate: self];
1078 stretch_video = false;
1080 /* Used for displaying pause on the screen */
1081 pauseLabel = [NSTextField new];
1082 [pauseLabel setBezeled:YES];
1083 [pauseLabel setDrawsBackground:YES];
1084 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1085 [pauseLabel setEditable:NO];
1086 [pauseLabel setSelectable:NO];
1087 [pauseLabel setStringValue: @"Paused"];
1088 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1089 [pauseLabel setTextColor: [NSColor blackColor]];
1090 [pauseLabel sizeToFit];
1092 // set the supported image file types that can be opened
1093 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1094 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1096 [self make_about_window];
1103 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1106 [cocoaView release];
1110 - (void)applicationDidFinishLaunching: (NSNotification *) note
1112 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1113 allow_events = true;
1114 /* Tell cocoa_display_init to proceed */
1115 qemu_sem_post(&app_started_sem);
1118 - (void)applicationWillTerminate:(NSNotification *)aNotification
1120 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1122 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1126 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1131 - (NSApplicationTerminateReply)applicationShouldTerminate:
1132 (NSApplication *)sender
1134 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1135 return [self verifyQuit];
1138 /* Called when the user clicks on a window's close button */
1139 - (BOOL)windowShouldClose:(id)sender
1141 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1142 [NSApp terminate: sender];
1143 /* If the user allows the application to quit then the call to
1144 * NSApp terminate will never return. If we get here then the user
1145 * cancelled the quit, so we should return NO to not permit the
1146 * closing of this window.
1151 /* Called when QEMU goes into the background */
1152 - (void) applicationWillResignActive: (NSNotification *)aNotification
1154 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1155 [cocoaView raiseAllKeys];
1158 /* We abstract the method called by the Enter Fullscreen menu item
1159 * because Mac OS 10.7 and higher disables it. This is because of the
1160 * menu item's old selector's name toggleFullScreen:
1162 - (void) doToggleFullScreen:(id)sender
1164 [self toggleFullScreen:(id)sender];
1167 - (void)toggleFullScreen:(id)sender
1169 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1171 [cocoaView toggleFullScreen:sender];
1174 /* Tries to find then open the specified filename */
1175 - (void) openDocumentation: (NSString *) filename
1177 /* Where to look for local files */
1178 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../docs/"};
1179 NSString *full_file_path;
1181 /* iterate thru the possible paths until the file is found */
1183 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1184 full_file_path = [[NSBundle mainBundle] executablePath];
1185 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1186 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1187 path_array[index], filename];
1188 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1193 /* If none of the paths opened a file */
1195 QEMU_Alert(@"Failed to open file");
1198 - (void)showQEMUDoc:(id)sender
1200 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1202 [self openDocumentation: @"index.html"];
1205 /* Stretches video to fit host monitor size */
1206 - (void)zoomToFit:(id) sender
1208 stretch_video = !stretch_video;
1209 if (stretch_video == true) {
1210 [sender setState: NSControlStateValueOn];
1212 [sender setState: NSControlStateValueOff];
1216 /* Displays the console on the screen */
1217 - (void)displayConsole:(id)sender
1219 console_select([sender tag]);
1222 /* Pause the guest */
1223 - (void)pauseQEMU:(id)sender
1225 with_iothread_lock(^{
1228 [sender setEnabled: NO];
1229 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1230 [self displayPause];
1233 /* Resume running the guest operating system */
1234 - (void)resumeQEMU:(id) sender
1236 with_iothread_lock(^{
1239 [sender setEnabled: NO];
1240 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1244 /* Displays the word pause on the screen */
1245 - (void)displayPause
1247 /* Coordinates have to be calculated each time because the window can change its size */
1248 int xCoord, yCoord, width, height;
1249 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1250 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1251 width = [pauseLabel frame].size.width;
1252 height = [pauseLabel frame].size.height;
1253 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1254 [cocoaView addSubview: pauseLabel];
1257 /* Removes the word pause from the screen */
1260 [pauseLabel removeFromSuperview];
1264 - (void)restartQEMU:(id)sender
1266 with_iothread_lock(^{
1267 qmp_system_reset(NULL);
1271 /* Powers down QEMU */
1272 - (void)powerDownQEMU:(id)sender
1274 with_iothread_lock(^{
1275 qmp_system_powerdown(NULL);
1279 /* Ejects the media.
1280 * Uses sender's tag to figure out the device to eject.
1282 - (void)ejectDeviceMedia:(id)sender
1285 drive = [sender representedObject];
1288 QEMU_Alert(@"Failed to find drive to eject!");
1292 __block Error *err = NULL;
1293 with_iothread_lock(^{
1294 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1295 false, NULL, false, false, &err);
1297 handleAnyDeviceErrors(err);
1300 /* Displays a dialog box asking the user to select an image file to load.
1301 * Uses sender's represented object value to figure out which drive to use.
1303 - (void)changeDeviceMedia:(id)sender
1305 /* Find the drive name */
1307 drive = [sender representedObject];
1310 QEMU_Alert(@"Could not find drive!");
1314 /* Display the file open dialog */
1315 NSOpenPanel * openPanel;
1316 openPanel = [NSOpenPanel openPanel];
1317 [openPanel setCanChooseFiles: YES];
1318 [openPanel setAllowsMultipleSelection: NO];
1319 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1320 if([openPanel runModal] == NSModalResponseOK) {
1321 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1324 QEMU_Alert(@"Failed to convert URL to file path!");
1328 __block Error *err = NULL;
1329 with_iothread_lock(^{
1330 qmp_blockdev_change_medium(true,
1331 [drive cStringUsingEncoding:
1332 NSASCIIStringEncoding],
1334 [file cStringUsingEncoding:
1335 NSASCIIStringEncoding],
1340 handleAnyDeviceErrors(err);
1344 /* Verifies if the user really wants to quit */
1347 NSAlert *alert = [NSAlert new];
1348 [alert autorelease];
1349 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1350 [alert addButtonWithTitle: @"Cancel"];
1351 [alert addButtonWithTitle: @"Quit"];
1352 if([alert runModal] == NSAlertSecondButtonReturn) {
1359 /* The action method for the About menu item */
1360 - (IBAction) do_about_menu_item: (id) sender
1362 [about_window makeKeyAndOrderFront: nil];
1365 /* Create and display the about dialog */
1366 - (void)make_about_window
1368 /* Make the window */
1369 int x = 0, y = 0, about_width = 400, about_height = 200;
1370 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1371 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1372 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1373 NSWindowStyleMaskMiniaturizable
1374 backing:NSBackingStoreBuffered
1376 [about_window setTitle: @"About"];
1377 [about_window setReleasedWhenClosed: NO];
1378 [about_window center];
1379 NSView *superView = [about_window contentView];
1381 /* Create the dimensions of the picture */
1382 int picture_width = 80, picture_height = 80;
1383 x = (about_width - picture_width)/2;
1384 y = about_height - picture_height - 10;
1385 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1387 /* Get the path to the QEMU binary */
1388 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1389 encoding: NSASCIIStringEncoding];
1390 binary_name = [binary_name lastPathComponent];
1391 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1392 [[NSBundle mainBundle] bundlePath], binary_name];
1394 /* Make the picture of QEMU */
1395 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1397 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1399 [picture_view setImage: qemu_image];
1400 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1401 [superView addSubview: picture_view];
1403 /* Make the name label */
1406 int name_width = about_width, name_height = 20;
1407 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1408 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1409 [name_label setEditable: NO];
1410 [name_label setBezeled: NO];
1411 [name_label setDrawsBackground: NO];
1412 [name_label setAlignment: NSTextAlignmentCenter];
1413 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1414 encoding: NSASCIIStringEncoding];
1415 qemu_name = [qemu_name lastPathComponent];
1416 [name_label setStringValue: qemu_name];
1417 [superView addSubview: name_label];
1419 /* Set the version label's attributes */
1422 int version_width = about_width, version_height = 20;
1423 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1424 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1426 [version_label setEditable: NO];
1427 [version_label setBezeled: NO];
1428 [version_label setAlignment: NSTextAlignmentCenter];
1429 [version_label setDrawsBackground: NO];
1431 /* Create the version string*/
1432 NSString *version_string;
1433 version_string = [[NSString alloc] initWithFormat:
1434 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1435 [version_label setStringValue: version_string];
1436 [superView addSubview: version_label];
1438 /* Make copyright label */
1441 int copyright_width = about_width, copyright_height = 20;
1442 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1443 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1445 [copyright_label setEditable: NO];
1446 [copyright_label setBezeled: NO];
1447 [copyright_label setDrawsBackground: NO];
1448 [copyright_label setAlignment: NSTextAlignmentCenter];
1449 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1451 [superView addSubview: copyright_label];
1454 /* Used by the Speed menu items */
1455 - (void)adjustSpeed:(id)sender
1457 int throttle_pct; /* throttle percentage */
1460 menu = [sender menu];
1463 /* Unselect the currently selected item */
1464 for (NSMenuItem *item in [menu itemArray]) {
1465 if (item.state == NSControlStateValueOn) {
1466 [item setState: NSControlStateValueOff];
1472 // check the menu item
1473 [sender setState: NSControlStateValueOn];
1475 // get the throttle percentage
1476 throttle_pct = [sender tag];
1478 with_iothread_lock(^{
1479 cpu_throttle_set(throttle_pct);
1481 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1486 @interface QemuApplication : NSApplication
1489 @implementation QemuApplication
1490 - (void)sendEvent:(NSEvent *)event
1492 COCOA_DEBUG("QemuApplication: sendEvent\n");
1493 if (![cocoaView handleEvent:event]) {
1494 [super sendEvent: event];
1499 static void create_initial_menus(void)
1503 NSMenuItem *menuItem;
1505 [NSApp setMainMenu:[[NSMenu alloc] init]];
1508 menu = [[NSMenu alloc] initWithTitle:@""];
1509 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1510 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1511 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1512 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1513 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1514 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1515 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1516 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1517 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1518 [menuItem setSubmenu:menu];
1519 [[NSApp mainMenu] addItem:menuItem];
1520 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1523 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1524 [menu setAutoenablesItems: NO];
1525 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1526 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1527 [menu addItem: menuItem];
1528 [menuItem setEnabled: NO];
1529 [menu addItem: [NSMenuItem separatorItem]];
1530 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1531 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1532 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1533 [menuItem setSubmenu:menu];
1534 [[NSApp mainMenu] addItem:menuItem];
1537 menu = [[NSMenu alloc] initWithTitle:@"View"];
1538 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1539 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1540 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1541 [menuItem setSubmenu:menu];
1542 [[NSApp mainMenu] addItem:menuItem];
1545 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1547 // Add the rest of the Speed menu items
1548 int p, percentage, throttle_pct;
1549 for (p = 10; p >= 0; p--)
1551 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1553 menuItem = [[[NSMenuItem alloc]
1554 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1556 if (percentage == 100) {
1557 [menuItem setState: NSControlStateValueOn];
1560 /* Calculate the throttle percentage */
1561 throttle_pct = -1 * percentage + 100;
1563 [menuItem setTag: throttle_pct];
1564 [menu addItem: menuItem];
1566 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1567 [menuItem setSubmenu:menu];
1568 [[NSApp mainMenu] addItem:menuItem];
1571 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1572 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1573 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1574 [menuItem setSubmenu:menu];
1575 [[NSApp mainMenu] addItem:menuItem];
1576 [NSApp setWindowsMenu:menu];
1579 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1580 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1581 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1582 [menuItem setSubmenu:menu];
1583 [[NSApp mainMenu] addItem:menuItem];
1586 /* Returns a name for a given console */
1587 static NSString * getConsoleName(QemuConsole * console)
1589 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1592 /* Add an entry to the View menu for each console */
1593 static void add_console_menu_entries(void)
1596 NSMenuItem *menuItem;
1599 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1601 [menu addItem:[NSMenuItem separatorItem]];
1603 while (qemu_console_lookup_by_index(index) != NULL) {
1604 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1605 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1606 [menuItem setTag: index];
1607 [menu addItem: menuItem];
1612 /* Make menu items for all removable devices.
1613 * Each device is given an 'Eject' and 'Change' menu item.
1615 static void addRemovableDevicesMenuItems(void)
1618 NSMenuItem *menuItem;
1619 BlockInfoList *currentDevice, *pointerToFree;
1620 NSString *deviceName;
1622 currentDevice = qmp_query_block(NULL);
1623 pointerToFree = currentDevice;
1624 if(currentDevice == NULL) {
1626 QEMU_Alert(@"Failed to query for block devices!");
1630 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1632 // Add a separator between related groups of menu items
1633 [menu addItem:[NSMenuItem separatorItem]];
1635 // Set the attributes to the "Removable Media" menu item
1636 NSString *titleString = @"Removable Media";
1637 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1638 NSColor *newColor = [NSColor blackColor];
1639 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1640 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1641 traits:NSBoldFontMask|NSItalicFontMask
1644 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1645 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1646 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1648 // Add the "Removable Media" menu item
1649 menuItem = [NSMenuItem new];
1650 [menuItem setAttributedTitle: attString];
1651 [menuItem setEnabled: NO];
1652 [menu addItem: menuItem];
1654 /* Loop through all the block devices in the emulator */
1655 while (currentDevice) {
1656 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1658 if(currentDevice->value->removable) {
1659 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1660 action: @selector(changeDeviceMedia:)
1661 keyEquivalent: @""];
1662 [menu addItem: menuItem];
1663 [menuItem setRepresentedObject: deviceName];
1664 [menuItem autorelease];
1666 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1667 action: @selector(ejectDeviceMedia:)
1668 keyEquivalent: @""];
1669 [menu addItem: menuItem];
1670 [menuItem setRepresentedObject: deviceName];
1671 [menuItem autorelease];
1673 currentDevice = currentDevice->next;
1675 qapi_free_BlockInfoList(pointerToFree);
1679 * The startup process for the OSX/Cocoa UI is complicated, because
1680 * OSX insists that the UI runs on the initial main thread, and so we
1681 * need to start a second thread which runs the vl.c qemu_main():
1683 * Initial thread: 2nd thread:
1685 * create qemu-main thread
1686 * wait on display_init semaphore
1689 * in cocoa_display_init():
1690 * post the display_init semaphore
1691 * wait on app_started semaphore
1692 * create application, menus, etc
1693 * enter OSX run loop
1694 * in applicationDidFinishLaunching:
1695 * post app_started semaphore
1696 * tell main thread to fullscreen if needed
1698 * run qemu main-loop
1700 * We do this in two stages so that we don't do the creation of the
1701 * GUI application menus and so on for command line options like --help
1702 * where we want to just print text to stdout and exit immediately.
1705 static void *call_qemu_main(void *opaque)
1709 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1710 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1711 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1715 int main (int argc, const char * argv[]) {
1718 COCOA_DEBUG("Entered main()\n");
1720 gArgv = (char **)argv;
1722 qemu_sem_init(&display_init_sem, 0);
1723 qemu_sem_init(&app_started_sem, 0);
1725 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1726 NULL, QEMU_THREAD_DETACHED);
1728 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1729 qemu_sem_wait(&display_init_sem);
1730 COCOA_DEBUG("Main thread: initializing app\n");
1732 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1734 // Pull this console process up to being a fully-fledged graphical
1735 // app with a menubar and Dock icon
1736 ProcessSerialNumber psn = { 0, kCurrentProcess };
1737 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1739 [QemuApplication sharedApplication];
1741 create_initial_menus();
1744 * Create the menu entries which depend on QEMU state (for consoles
1745 * and removeable devices). These make calls back into QEMU functions,
1746 * which is OK because at this point we know that the second thread
1747 * holds the iothread lock and is synchronously waiting for us to
1750 add_console_menu_entries();
1751 addRemovableDevicesMenuItems();
1753 // Create an Application controller
1754 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1755 [NSApp setDelegate:appController];
1757 // Start the main event loop
1758 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1760 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1762 [appController release];
1771 static void cocoa_update(DisplayChangeListener *dcl,
1772 int x, int y, int w, int h)
1774 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1776 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1778 dispatch_async(dispatch_get_main_queue(), ^{
1780 if ([cocoaView cdx] == 1.0) {
1781 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1784 x * [cocoaView cdx],
1785 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1786 w * [cocoaView cdx],
1787 h * [cocoaView cdy]);
1789 [cocoaView setNeedsDisplayInRect:rect];
1795 static void cocoa_switch(DisplayChangeListener *dcl,
1796 DisplaySurface *surface)
1798 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1799 pixman_image_t *image = surface->image;
1801 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1803 // The DisplaySurface will be freed as soon as this callback returns.
1804 // We take a reference to the underlying pixman image here so it does
1805 // not disappear from under our feet; the switchSurface method will
1806 // deref the old image when it is done with it.
1807 pixman_image_ref(image);
1809 dispatch_async(dispatch_get_main_queue(), ^{
1810 [cocoaView switchSurface:image];
1815 static void cocoa_refresh(DisplayChangeListener *dcl)
1817 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1819 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1820 graphic_hw_update(NULL);
1822 if (qemu_input_is_absolute()) {
1823 dispatch_async(dispatch_get_main_queue(), ^{
1824 if (![cocoaView isAbsoluteEnabled]) {
1825 if ([cocoaView isMouseGrabbed]) {
1826 [cocoaView ungrabMouse];
1829 [cocoaView setAbsoluteEnabled:YES];
1835 static void cocoa_cleanup(void)
1837 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1841 static const DisplayChangeListenerOps dcl_ops = {
1842 .dpy_name = "cocoa",
1843 .dpy_gfx_update = cocoa_update,
1844 .dpy_gfx_switch = cocoa_switch,
1845 .dpy_refresh = cocoa_refresh,
1848 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1850 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1852 /* Tell main thread to go ahead and create the app and enter the run loop */
1853 qemu_sem_post(&display_init_sem);
1854 qemu_sem_wait(&app_started_sem);
1855 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1857 /* if fullscreen mode is to be used */
1858 if (opts->has_full_screen && opts->full_screen) {
1859 dispatch_async(dispatch_get_main_queue(), ^{
1860 [NSApp activateIgnoringOtherApps: YES];
1861 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1864 if (opts->has_show_cursor && opts->show_cursor) {
1868 dcl = g_malloc0(sizeof(DisplayChangeListener));
1870 // register vga output callbacks
1871 dcl->ops = &dcl_ops;
1872 register_displaychangelistener(dcl);
1874 // register cleanup function
1875 atexit(cocoa_cleanup);
1878 static QemuDisplay qemu_display_cocoa = {
1879 .type = DISPLAY_TYPE_COCOA,
1880 .init = cocoa_display_init,
1883 static void register_cocoa(void)
1885 qemu_display_register(&qemu_display_cocoa);
1888 type_init(register_cocoa);