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 "ui/kbd-state.h"
34 #include "sysemu/sysemu.h"
35 #include "sysemu/runstate.h"
36 #include "sysemu/cpu-throttle.h"
37 #include "qapi/error.h"
38 #include "qapi/qapi-commands-block.h"
39 #include "qapi/qapi-commands-machine.h"
40 #include "qapi/qapi-commands-misc.h"
41 #include "sysemu/blockdev.h"
42 #include "qemu-version.h"
43 #include "qemu/cutils.h"
44 #include "qemu/main-loop.h"
45 #include "qemu/module.h"
46 #include <Carbon/Carbon.h>
47 #include "hw/core/cpu.h"
49 #ifndef MAC_OS_X_VERSION_10_13
50 #define MAC_OS_X_VERSION_10_13 101300
53 /* 10.14 deprecates NSOnState and NSOffState in favor of
54 * NSControlStateValueOn/Off, which were introduced in 10.13.
55 * Define for older versions
57 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
58 #define NSControlStateValueOn NSOnState
59 #define NSControlStateValueOff NSOffState
65 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
67 #define COCOA_DEBUG(...) ((void) 0)
70 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
77 static void cocoa_update(DisplayChangeListener *dcl,
78 int x, int y, int w, int h);
80 static void cocoa_switch(DisplayChangeListener *dcl,
81 DisplaySurface *surface);
83 static void cocoa_refresh(DisplayChangeListener *dcl);
85 static NSWindow *normalWindow, *about_window;
86 static const DisplayChangeListenerOps dcl_ops = {
88 .dpy_gfx_update = cocoa_update,
89 .dpy_gfx_switch = cocoa_switch,
90 .dpy_refresh = cocoa_refresh,
92 static DisplayChangeListener dcl = {
95 static int last_buttons;
96 static int cursor_hide = 1;
100 static bool stretch_video;
101 static NSTextField *pauseLabel;
102 static NSArray * supportedImageFileTypes;
104 static QemuSemaphore display_init_sem;
105 static QemuSemaphore app_started_sem;
106 static bool allow_events;
108 // Utility functions to run specified code block with iothread lock held
109 typedef void (^CodeBlock)(void);
110 typedef bool (^BoolCodeBlock)(void);
112 static void with_iothread_lock(CodeBlock block)
114 bool locked = qemu_mutex_iothread_locked();
116 qemu_mutex_lock_iothread();
120 qemu_mutex_unlock_iothread();
124 static bool bool_with_iothread_lock(BoolCodeBlock block)
126 bool locked = qemu_mutex_iothread_locked();
130 qemu_mutex_lock_iothread();
134 qemu_mutex_unlock_iothread();
139 // Mac to QKeyCode conversion
140 static const int mac_to_qkeycode_map[] = {
141 [kVK_ANSI_A] = Q_KEY_CODE_A,
142 [kVK_ANSI_B] = Q_KEY_CODE_B,
143 [kVK_ANSI_C] = Q_KEY_CODE_C,
144 [kVK_ANSI_D] = Q_KEY_CODE_D,
145 [kVK_ANSI_E] = Q_KEY_CODE_E,
146 [kVK_ANSI_F] = Q_KEY_CODE_F,
147 [kVK_ANSI_G] = Q_KEY_CODE_G,
148 [kVK_ANSI_H] = Q_KEY_CODE_H,
149 [kVK_ANSI_I] = Q_KEY_CODE_I,
150 [kVK_ANSI_J] = Q_KEY_CODE_J,
151 [kVK_ANSI_K] = Q_KEY_CODE_K,
152 [kVK_ANSI_L] = Q_KEY_CODE_L,
153 [kVK_ANSI_M] = Q_KEY_CODE_M,
154 [kVK_ANSI_N] = Q_KEY_CODE_N,
155 [kVK_ANSI_O] = Q_KEY_CODE_O,
156 [kVK_ANSI_P] = Q_KEY_CODE_P,
157 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
158 [kVK_ANSI_R] = Q_KEY_CODE_R,
159 [kVK_ANSI_S] = Q_KEY_CODE_S,
160 [kVK_ANSI_T] = Q_KEY_CODE_T,
161 [kVK_ANSI_U] = Q_KEY_CODE_U,
162 [kVK_ANSI_V] = Q_KEY_CODE_V,
163 [kVK_ANSI_W] = Q_KEY_CODE_W,
164 [kVK_ANSI_X] = Q_KEY_CODE_X,
165 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
166 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
168 [kVK_ANSI_0] = Q_KEY_CODE_0,
169 [kVK_ANSI_1] = Q_KEY_CODE_1,
170 [kVK_ANSI_2] = Q_KEY_CODE_2,
171 [kVK_ANSI_3] = Q_KEY_CODE_3,
172 [kVK_ANSI_4] = Q_KEY_CODE_4,
173 [kVK_ANSI_5] = Q_KEY_CODE_5,
174 [kVK_ANSI_6] = Q_KEY_CODE_6,
175 [kVK_ANSI_7] = Q_KEY_CODE_7,
176 [kVK_ANSI_8] = Q_KEY_CODE_8,
177 [kVK_ANSI_9] = Q_KEY_CODE_9,
179 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
180 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
181 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
182 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
183 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
184 [kVK_Tab] = Q_KEY_CODE_TAB,
185 [kVK_Return] = Q_KEY_CODE_RET,
186 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
187 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
188 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
189 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
190 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
191 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
192 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
193 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
194 [kVK_Space] = Q_KEY_CODE_SPC,
196 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
197 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
198 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
199 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
200 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
201 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
202 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
203 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
204 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
205 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
206 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
207 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
208 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
209 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
210 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
211 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
212 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
213 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
215 [kVK_UpArrow] = Q_KEY_CODE_UP,
216 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
217 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
218 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
220 [kVK_Help] = Q_KEY_CODE_INSERT,
221 [kVK_Home] = Q_KEY_CODE_HOME,
222 [kVK_PageUp] = Q_KEY_CODE_PGUP,
223 [kVK_PageDown] = Q_KEY_CODE_PGDN,
224 [kVK_End] = Q_KEY_CODE_END,
225 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
227 [kVK_Escape] = Q_KEY_CODE_ESC,
229 /* The Power key can't be used directly because the operating system uses
230 * it. This key can be emulated by using it in place of another key such as
231 * F1. Don't forget to disable the real key binding.
233 /* [kVK_F1] = Q_KEY_CODE_POWER, */
235 [kVK_F1] = Q_KEY_CODE_F1,
236 [kVK_F2] = Q_KEY_CODE_F2,
237 [kVK_F3] = Q_KEY_CODE_F3,
238 [kVK_F4] = Q_KEY_CODE_F4,
239 [kVK_F5] = Q_KEY_CODE_F5,
240 [kVK_F6] = Q_KEY_CODE_F6,
241 [kVK_F7] = Q_KEY_CODE_F7,
242 [kVK_F8] = Q_KEY_CODE_F8,
243 [kVK_F9] = Q_KEY_CODE_F9,
244 [kVK_F10] = Q_KEY_CODE_F10,
245 [kVK_F11] = Q_KEY_CODE_F11,
246 [kVK_F12] = Q_KEY_CODE_F12,
247 [kVK_F13] = Q_KEY_CODE_PRINT,
248 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
249 [kVK_F15] = Q_KEY_CODE_PAUSE,
251 // JIS keyboards only
252 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
253 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
254 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
255 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
256 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
259 * The eject and volume keys can't be used here because they are handled at
260 * a lower level than what an Application can see.
264 static int cocoa_keycode_to_qemu(int keycode)
266 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
267 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
270 return mac_to_qkeycode_map[keycode];
273 /* Displays an alert dialog box with the specified message */
274 static void QEMU_Alert(NSString *message)
277 alert = [NSAlert new];
278 [alert setMessageText: message];
282 /* Handles any errors that happen with a device transaction */
283 static void handleAnyDeviceErrors(Error * err)
286 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
287 encoding: NSASCIIStringEncoding]);
293 ------------------------------------------------------
295 ------------------------------------------------------
297 @interface QemuCocoaView : NSView
300 NSWindow *fullScreenWindow;
301 float cx,cy,cw,ch,cdx,cdy;
302 pixman_image_t *pixman_image;
306 BOOL isAbsoluteEnabled;
307 BOOL isMouseDeassociated;
309 - (void) switchSurface:(pixman_image_t *)image;
311 - (void) ungrabMouse;
312 - (void) toggleFullScreen:(id)sender;
313 - (void) handleMonitorInput:(NSEvent *)event;
314 - (bool) handleEvent:(NSEvent *)event;
315 - (bool) handleEventLocked:(NSEvent *)event;
316 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
317 /* The state surrounding mouse grabbing is potentially confusing.
318 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
319 * pointing device an absolute-position one?"], but is only updated on
321 * isMouseGrabbed tracks whether GUI events are directed to the guest;
322 * it controls whether special keys like Cmd get sent to the guest,
323 * and whether we capture the mouse when in non-absolute mode.
324 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
325 * the mouse and mouse cursor position by calling
326 * CGAssociateMouseAndMouseCursorPosition(FALSE)
327 * (which basically happens if we grab in non-absolute mode).
329 - (BOOL) isMouseGrabbed;
330 - (BOOL) isAbsoluteEnabled;
331 - (BOOL) isMouseDeassociated;
334 - (QEMUScreen) gscreen;
335 - (void) raiseAllKeys;
338 QemuCocoaView *cocoaView;
340 @implementation QemuCocoaView
341 - (id)initWithFrame:(NSRect)frameRect
343 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
345 self = [super initWithFrame:frameRect];
348 screen.width = frameRect.size.width;
349 screen.height = frameRect.size.height;
350 kbd = qkbd_state_init(dcl.con);
358 COCOA_DEBUG("QemuCocoaView: dealloc\n");
361 pixman_image_unref(pixman_image);
364 qkbd_state_free(kbd);
373 - (BOOL) screenContainsPoint:(NSPoint) p
375 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
378 /* Get location of event and convert to virtual screen coordinate */
379 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
381 NSWindow *eventWindow = [ev window];
382 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
383 CGRect r = CGRectZero;
384 r.origin = [ev locationInWindow];
387 return [[self window] convertRectFromScreen:r].origin;
389 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
390 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
397 } else if ([[self window] isEqual:eventWindow]) {
401 CGPoint loc = [self convertPoint:r.origin fromView:nil];
409 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
421 - (void) unhideCursor
429 - (void) drawRect:(NSRect) rect
431 COCOA_DEBUG("QemuCocoaView: drawRect\n");
433 // get CoreGraphic context
434 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
436 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
437 CGContextSetShouldAntialias (viewContextRef, NO);
439 // draw screen bitmap directly to Core Graphics context
441 // Draw request before any guest device has set up a framebuffer:
442 // just draw an opaque black rectangle
443 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
444 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
446 int w = pixman_image_get_width(pixman_image);
447 int h = pixman_image_get_height(pixman_image);
448 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
449 int stride = pixman_image_get_stride(pixman_image);
450 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
452 pixman_image_get_data(pixman_image),
456 CGImageRef imageRef = CGImageCreate(
459 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
460 bitsPerPixel, //bitsPerPixel
461 stride, //bytesPerRow
462 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
463 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
464 dataProviderRef, //provider
467 kCGRenderingIntentDefault //intent
469 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
470 const NSRect *rectList;
473 CGImageRef clipImageRef;
476 [self getRectsBeingDrawn:&rectList count:&rectCount];
477 for (i = 0; i < rectCount; i++) {
478 clipRect.origin.x = rectList[i].origin.x / cdx;
479 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
480 clipRect.size.width = rectList[i].size.width / cdx;
481 clipRect.size.height = rectList[i].size.height / cdy;
482 clipImageRef = CGImageCreateWithImageInRect(
486 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
487 CGImageRelease (clipImageRef);
489 CGImageRelease (imageRef);
490 CGDataProviderRelease(dataProviderRef);
494 - (void) setContentDimensions
496 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
499 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
500 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
502 /* stretches video, but keeps same aspect ratio */
503 if (stretch_video == true) {
504 /* use smallest stretch value - prevents clipping on sides */
505 if (MIN(cdx, cdy) == cdx) {
510 } else { /* No stretching */
513 cw = screen.width * cdx;
514 ch = screen.height * cdy;
515 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
516 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
527 - (void) switchSurface:(pixman_image_t *)image
529 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
531 int w = pixman_image_get_width(image);
532 int h = pixman_image_get_height(image);
533 /* cdx == 0 means this is our very first surface, in which case we need
534 * to recalculate the content dimensions even if it happens to be the size
535 * of the initial empty window.
537 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
539 int oldh = screen.height;
541 // Resize before we trigger the redraw, or we'll redraw at the wrong size
542 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
545 [self setContentDimensions];
546 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
549 // update screenBuffer
551 pixman_image_unref(pixman_image);
554 pixman_image = image;
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 [fullScreenWindow close];
580 [normalWindow setContentView: self];
581 [normalWindow makeKeyAndOrderFront: self];
582 [NSMenu setMenuBarVisible:YES];
583 } else { // switch from desktop to fullscreen
585 [normalWindow orderOut: nil]; /* Hide the window */
587 [self setContentDimensions];
588 [NSMenu setMenuBarVisible:NO];
589 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
590 styleMask:NSWindowStyleMaskBorderless
591 backing:NSBackingStoreBuffered
593 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
594 [fullScreenWindow setHasShadow:NO];
595 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
596 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
597 [[fullScreenWindow contentView] addSubview: self];
598 [fullScreenWindow makeKeyAndOrderFront:self];
602 - (void) toggleKey: (int)keycode {
603 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
606 // Does the work of sending input to the monitor
607 - (void) handleMonitorInput:(NSEvent *)event
612 // if the control key is down
613 if ([event modifierFlags] & NSEventModifierFlagControl) {
617 /* translates Macintosh keycodes to QEMU's keysym */
619 int without_control_translation[] = {
620 [0 ... 0xff] = 0, // invalid key
622 [kVK_UpArrow] = QEMU_KEY_UP,
623 [kVK_DownArrow] = QEMU_KEY_DOWN,
624 [kVK_RightArrow] = QEMU_KEY_RIGHT,
625 [kVK_LeftArrow] = QEMU_KEY_LEFT,
626 [kVK_Home] = QEMU_KEY_HOME,
627 [kVK_End] = QEMU_KEY_END,
628 [kVK_PageUp] = QEMU_KEY_PAGEUP,
629 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
630 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
631 [kVK_Delete] = QEMU_KEY_BACKSPACE,
634 int with_control_translation[] = {
635 [0 ... 0xff] = 0, // invalid key
637 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
638 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
639 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
640 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
641 [kVK_Home] = QEMU_KEY_CTRL_HOME,
642 [kVK_End] = QEMU_KEY_CTRL_END,
643 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
644 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
647 if (control_key != 0) { /* If the control key is being used */
648 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
649 keysym = with_control_translation[[event keyCode]];
652 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
653 keysym = without_control_translation[[event keyCode]];
657 // if not a key that needs translating
659 NSString *ks = [event characters];
660 if ([ks length] > 0) {
661 keysym = [ks characterAtIndex:0];
666 kbd_put_keysym(keysym);
670 - (bool) handleEvent:(NSEvent *)event
674 * Just let OSX have all events that arrive before
675 * applicationDidFinishLaunching.
676 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
677 * will not drop until after the app_started_sem is posted. (In theory
678 * there should not be any such events, but OSX Catalina now emits some.)
682 return bool_with_iothread_lock(^{
683 return [self handleEventLocked:event];
687 - (bool) handleEventLocked:(NSEvent *)event
689 /* Return true if we handled the event, false if it should be given to OSX */
690 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
693 bool mouse_event = false;
694 static bool switched_to_fullscreen = false;
695 // Location of event in virtual screen coordinates
696 NSPoint p = [self screenLocationOfEvent:event];
697 NSUInteger modifiers = [event modifierFlags];
699 // emulate caps lock keydown and keyup
700 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
701 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
702 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
703 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
706 if (!(modifiers & NSEventModifierFlagShift)) {
707 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
708 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
710 if (!(modifiers & NSEventModifierFlagControl)) {
711 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
712 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
714 if (!(modifiers & NSEventModifierFlagOption)) {
715 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
716 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
718 if (!(modifiers & NSEventModifierFlagCommand)) {
719 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
720 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
723 switch ([event type]) {
724 case NSEventTypeFlagsChanged:
725 switch ([event keyCode]) {
727 if (!!(modifiers & NSEventModifierFlagShift)) {
728 [self toggleKey:Q_KEY_CODE_SHIFT];
733 if (!!(modifiers & NSEventModifierFlagShift)) {
734 [self toggleKey:Q_KEY_CODE_SHIFT_R];
739 if (!!(modifiers & NSEventModifierFlagControl)) {
740 [self toggleKey:Q_KEY_CODE_CTRL];
744 case kVK_RightControl:
745 if (!!(modifiers & NSEventModifierFlagControl)) {
746 [self toggleKey:Q_KEY_CODE_CTRL_R];
751 if (!!(modifiers & NSEventModifierFlagOption)) {
752 [self toggleKey:Q_KEY_CODE_ALT];
756 case kVK_RightOption:
757 if (!!(modifiers & NSEventModifierFlagOption)) {
758 [self toggleKey:Q_KEY_CODE_ALT_R];
762 /* Don't pass command key changes to guest unless mouse is grabbed */
764 if (isMouseGrabbed &&
765 !!(modifiers & NSEventModifierFlagCommand)) {
766 [self toggleKey:Q_KEY_CODE_META_L];
770 case kVK_RightCommand:
771 if (isMouseGrabbed &&
772 !!(modifiers & NSEventModifierFlagCommand)) {
773 [self toggleKey:Q_KEY_CODE_META_R];
778 case NSEventTypeKeyDown:
779 keycode = cocoa_keycode_to_qemu([event keyCode]);
781 // forward command key combos to the host UI unless the mouse is grabbed
782 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
784 * Prevent the command key from being stuck down in the guest
785 * when using Command-F to switch to full screen mode.
787 if (keycode == Q_KEY_CODE_F) {
788 switched_to_fullscreen = true;
795 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
796 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
797 NSString *keychar = [event charactersIgnoringModifiers];
798 if ([keychar length] == 1) {
799 char key = [keychar characterAtIndex:0];
802 // enable graphic console
804 console_select(key - '0' - 1); /* ascii math */
807 // release the mouse grab
815 if (qemu_console_is_graphic(NULL)) {
816 qkbd_state_key_event(kbd, keycode, true);
818 [self handleMonitorInput: event];
821 case NSEventTypeKeyUp:
822 keycode = cocoa_keycode_to_qemu([event keyCode]);
824 // don't pass the guest a spurious key-up if we treated this
825 // command-key combo as a host UI action
826 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
830 if (qemu_console_is_graphic(NULL)) {
831 qkbd_state_key_event(kbd, keycode, false);
834 case NSEventTypeMouseMoved:
835 if (isAbsoluteEnabled) {
836 // Cursor re-entered into a window might generate events bound to screen coordinates
837 // and `nil` window property, and in full screen mode, current window might not be
838 // key window, where event location alone should suffice.
839 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
840 if (isMouseGrabbed) {
844 if (!isMouseGrabbed) {
851 case NSEventTypeLeftMouseDown:
852 buttons |= MOUSE_EVENT_LBUTTON;
855 case NSEventTypeRightMouseDown:
856 buttons |= MOUSE_EVENT_RBUTTON;
859 case NSEventTypeOtherMouseDown:
860 buttons |= MOUSE_EVENT_MBUTTON;
863 case NSEventTypeLeftMouseDragged:
864 buttons |= MOUSE_EVENT_LBUTTON;
867 case NSEventTypeRightMouseDragged:
868 buttons |= MOUSE_EVENT_RBUTTON;
871 case NSEventTypeOtherMouseDragged:
872 buttons |= MOUSE_EVENT_MBUTTON;
875 case NSEventTypeLeftMouseUp:
877 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
879 * In fullscreen mode, the window of cocoaView may not be the
880 * key window, therefore the position relative to the virtual
881 * screen alone will be sufficient.
883 if(isFullscreen || [[self window] isKeyWindow]) {
888 case NSEventTypeRightMouseUp:
891 case NSEventTypeOtherMouseUp:
894 case NSEventTypeScrollWheel:
896 * Send wheel events to the guest regardless of window focus.
897 * This is in-line with standard Mac OS X UI behaviour.
901 * When deltaY is zero, it means that this scrolling event was
902 * either horizontal, or so fine that it only appears in
903 * scrollingDeltaY. So we drop the event.
905 if ([event deltaY] != 0) {
906 /* Determine if this is a scroll up or scroll down event */
907 buttons = ([event deltaY] > 0) ?
908 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
909 qemu_input_queue_btn(dcl.con, buttons, true);
910 qemu_input_event_sync();
911 qemu_input_queue_btn(dcl.con, buttons, false);
912 qemu_input_event_sync();
915 * Since deltaY also reports scroll wheel events we prevent mouse
916 * movement code from executing.
925 /* Don't send button events to the guest unless we've got a
926 * mouse grab or window focus. If we have neither then this event
927 * is the user clicking on the background window to activate and
928 * bring us to the front, which will be done by the sendEvent
929 * call below. We definitely don't want to pass that click through
932 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
933 (last_buttons != buttons)) {
934 static uint32_t bmap[INPUT_BUTTON__MAX] = {
935 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
936 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
937 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
939 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
940 last_buttons = buttons;
942 if (isMouseGrabbed) {
943 if (isAbsoluteEnabled) {
944 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
945 * The check on screenContainsPoint is to avoid sending out of range values for
946 * clicks in the titlebar.
948 if ([self screenContainsPoint:p]) {
949 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
950 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
953 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
954 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
959 qemu_input_event_sync();
966 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
970 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
972 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
975 if (!isAbsoluteEnabled) {
976 isMouseDeassociated = TRUE;
977 CGAssociateMouseAndMouseCursorPosition(FALSE);
979 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
984 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
988 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
990 [normalWindow setTitle:@"QEMU"];
993 if (isMouseDeassociated) {
994 CGAssociateMouseAndMouseCursorPosition(TRUE);
995 isMouseDeassociated = FALSE;
997 isMouseGrabbed = FALSE;
1000 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
1001 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1002 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1003 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
1004 - (float) cdx {return cdx;}
1005 - (float) cdy {return cdy;}
1006 - (QEMUScreen) gscreen {return screen;}
1009 * Makes the target think all down keys are being released.
1010 * This prevents a stuck key problem, since we will not see
1011 * key up events for those keys after we have lost focus.
1013 - (void) raiseAllKeys
1015 with_iothread_lock(^{
1016 qkbd_state_lift_all_keys(kbd);
1024 ------------------------------------------------------
1025 QemuCocoaAppController
1026 ------------------------------------------------------
1028 @interface QemuCocoaAppController : NSObject
1029 <NSWindowDelegate, NSApplicationDelegate>
1032 - (void)doToggleFullScreen:(id)sender;
1033 - (void)toggleFullScreen:(id)sender;
1034 - (void)showQEMUDoc:(id)sender;
1035 - (void)zoomToFit:(id) sender;
1036 - (void)displayConsole:(id)sender;
1037 - (void)pauseQEMU:(id)sender;
1038 - (void)resumeQEMU:(id)sender;
1039 - (void)displayPause;
1040 - (void)removePause;
1041 - (void)restartQEMU:(id)sender;
1042 - (void)powerDownQEMU:(id)sender;
1043 - (void)ejectDeviceMedia:(id)sender;
1044 - (void)changeDeviceMedia:(id)sender;
1046 - (void)openDocumentation:(NSString *)filename;
1047 - (IBAction) do_about_menu_item: (id) sender;
1048 - (void)make_about_window;
1049 - (void)adjustSpeed:(id)sender;
1052 @implementation QemuCocoaAppController
1055 COCOA_DEBUG("QemuCocoaAppController: init\n");
1057 self = [super init];
1060 // create a view and add it to the window
1061 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1063 error_report("(cocoa) can't create a view");
1068 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1069 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1070 backing:NSBackingStoreBuffered defer:NO];
1072 error_report("(cocoa) can't create window");
1075 [normalWindow setAcceptsMouseMovedEvents:YES];
1076 [normalWindow setTitle:@"QEMU"];
1077 [normalWindow setContentView:cocoaView];
1078 [normalWindow makeKeyAndOrderFront:self];
1079 [normalWindow center];
1080 [normalWindow setDelegate: self];
1081 stretch_video = false;
1083 /* Used for displaying pause on the screen */
1084 pauseLabel = [NSTextField new];
1085 [pauseLabel setBezeled:YES];
1086 [pauseLabel setDrawsBackground:YES];
1087 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1088 [pauseLabel setEditable:NO];
1089 [pauseLabel setSelectable:NO];
1090 [pauseLabel setStringValue: @"Paused"];
1091 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1092 [pauseLabel setTextColor: [NSColor blackColor]];
1093 [pauseLabel sizeToFit];
1095 // set the supported image file types that can be opened
1096 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1097 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1099 [self make_about_window];
1106 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1109 [cocoaView release];
1113 - (void)applicationDidFinishLaunching: (NSNotification *) note
1115 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1116 allow_events = true;
1117 /* Tell cocoa_display_init to proceed */
1118 qemu_sem_post(&app_started_sem);
1121 - (void)applicationWillTerminate:(NSNotification *)aNotification
1123 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1125 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1129 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1134 - (NSApplicationTerminateReply)applicationShouldTerminate:
1135 (NSApplication *)sender
1137 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1138 return [self verifyQuit];
1141 /* Called when the user clicks on a window's close button */
1142 - (BOOL)windowShouldClose:(id)sender
1144 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1145 [NSApp terminate: sender];
1146 /* If the user allows the application to quit then the call to
1147 * NSApp terminate will never return. If we get here then the user
1148 * cancelled the quit, so we should return NO to not permit the
1149 * closing of this window.
1154 /* Called when QEMU goes into the background */
1155 - (void) applicationWillResignActive: (NSNotification *)aNotification
1157 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1158 [cocoaView raiseAllKeys];
1161 /* We abstract the method called by the Enter Fullscreen menu item
1162 * because Mac OS 10.7 and higher disables it. This is because of the
1163 * menu item's old selector's name toggleFullScreen:
1165 - (void) doToggleFullScreen:(id)sender
1167 [self toggleFullScreen:(id)sender];
1170 - (void)toggleFullScreen:(id)sender
1172 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1174 [cocoaView toggleFullScreen:sender];
1177 /* Tries to find then open the specified filename */
1178 - (void) openDocumentation: (NSString *) filename
1180 /* Where to look for local files */
1181 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1182 NSString *full_file_path;
1183 NSURL *full_file_url;
1185 /* iterate thru the possible paths until the file is found */
1187 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1188 full_file_path = [[NSBundle mainBundle] executablePath];
1189 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1190 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1191 path_array[index], filename];
1192 full_file_url = [NSURL fileURLWithPath: full_file_path
1193 isDirectory: false];
1194 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1199 /* If none of the paths opened a file */
1201 QEMU_Alert(@"Failed to open file");
1204 - (void)showQEMUDoc:(id)sender
1206 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1208 [self openDocumentation: @"index.html"];
1211 /* Stretches video to fit host monitor size */
1212 - (void)zoomToFit:(id) sender
1214 stretch_video = !stretch_video;
1215 if (stretch_video == true) {
1216 [sender setState: NSControlStateValueOn];
1218 [sender setState: NSControlStateValueOff];
1222 /* Displays the console on the screen */
1223 - (void)displayConsole:(id)sender
1225 console_select([sender tag]);
1228 /* Pause the guest */
1229 - (void)pauseQEMU:(id)sender
1231 with_iothread_lock(^{
1234 [sender setEnabled: NO];
1235 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1236 [self displayPause];
1239 /* Resume running the guest operating system */
1240 - (void)resumeQEMU:(id) sender
1242 with_iothread_lock(^{
1245 [sender setEnabled: NO];
1246 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1250 /* Displays the word pause on the screen */
1251 - (void)displayPause
1253 /* Coordinates have to be calculated each time because the window can change its size */
1254 int xCoord, yCoord, width, height;
1255 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1256 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1257 width = [pauseLabel frame].size.width;
1258 height = [pauseLabel frame].size.height;
1259 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1260 [cocoaView addSubview: pauseLabel];
1263 /* Removes the word pause from the screen */
1266 [pauseLabel removeFromSuperview];
1270 - (void)restartQEMU:(id)sender
1272 with_iothread_lock(^{
1273 qmp_system_reset(NULL);
1277 /* Powers down QEMU */
1278 - (void)powerDownQEMU:(id)sender
1280 with_iothread_lock(^{
1281 qmp_system_powerdown(NULL);
1285 /* Ejects the media.
1286 * Uses sender's tag to figure out the device to eject.
1288 - (void)ejectDeviceMedia:(id)sender
1291 drive = [sender representedObject];
1294 QEMU_Alert(@"Failed to find drive to eject!");
1298 __block Error *err = NULL;
1299 with_iothread_lock(^{
1300 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1301 false, NULL, false, false, &err);
1303 handleAnyDeviceErrors(err);
1306 /* Displays a dialog box asking the user to select an image file to load.
1307 * Uses sender's represented object value to figure out which drive to use.
1309 - (void)changeDeviceMedia:(id)sender
1311 /* Find the drive name */
1313 drive = [sender representedObject];
1316 QEMU_Alert(@"Could not find drive!");
1320 /* Display the file open dialog */
1321 NSOpenPanel * openPanel;
1322 openPanel = [NSOpenPanel openPanel];
1323 [openPanel setCanChooseFiles: YES];
1324 [openPanel setAllowsMultipleSelection: NO];
1325 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1326 if([openPanel runModal] == NSModalResponseOK) {
1327 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1330 QEMU_Alert(@"Failed to convert URL to file path!");
1334 __block Error *err = NULL;
1335 with_iothread_lock(^{
1336 qmp_blockdev_change_medium(true,
1337 [drive cStringUsingEncoding:
1338 NSASCIIStringEncoding],
1340 [file cStringUsingEncoding:
1341 NSASCIIStringEncoding],
1346 handleAnyDeviceErrors(err);
1350 /* Verifies if the user really wants to quit */
1353 NSAlert *alert = [NSAlert new];
1354 [alert autorelease];
1355 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1356 [alert addButtonWithTitle: @"Cancel"];
1357 [alert addButtonWithTitle: @"Quit"];
1358 if([alert runModal] == NSAlertSecondButtonReturn) {
1365 /* The action method for the About menu item */
1366 - (IBAction) do_about_menu_item: (id) sender
1368 [about_window makeKeyAndOrderFront: nil];
1371 /* Create and display the about dialog */
1372 - (void)make_about_window
1374 /* Make the window */
1375 int x = 0, y = 0, about_width = 400, about_height = 200;
1376 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1377 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1378 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1379 NSWindowStyleMaskMiniaturizable
1380 backing:NSBackingStoreBuffered
1382 [about_window setTitle: @"About"];
1383 [about_window setReleasedWhenClosed: NO];
1384 [about_window center];
1385 NSView *superView = [about_window contentView];
1387 /* Create the dimensions of the picture */
1388 int picture_width = 80, picture_height = 80;
1389 x = (about_width - picture_width)/2;
1390 y = about_height - picture_height - 10;
1391 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1393 /* Make the picture of QEMU */
1394 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1396 char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1397 NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1398 g_free(qemu_image_path_c);
1399 NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
1400 [picture_view setImage: qemu_image];
1401 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1402 [superView addSubview: picture_view];
1404 /* Make the name label */
1405 NSBundle *bundle = [NSBundle mainBundle];
1409 int name_width = about_width, name_height = 20;
1410 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1411 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1412 [name_label setEditable: NO];
1413 [name_label setBezeled: NO];
1414 [name_label setDrawsBackground: NO];
1415 [name_label setAlignment: NSTextAlignmentCenter];
1416 NSString *qemu_name = [[bundle executablePath] lastPathComponent];
1417 [name_label setStringValue: qemu_name];
1418 [superView addSubview: name_label];
1421 /* Set the version label's attributes */
1424 int version_width = about_width, version_height = 20;
1425 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1426 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1428 [version_label setEditable: NO];
1429 [version_label setBezeled: NO];
1430 [version_label setAlignment: NSTextAlignmentCenter];
1431 [version_label setDrawsBackground: NO];
1433 /* Create the version string*/
1434 NSString *version_string;
1435 version_string = [[NSString alloc] initWithFormat:
1436 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1437 [version_label setStringValue: version_string];
1438 [superView addSubview: version_label];
1440 /* Make copyright label */
1443 int copyright_width = about_width, copyright_height = 20;
1444 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1445 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1447 [copyright_label setEditable: NO];
1448 [copyright_label setBezeled: NO];
1449 [copyright_label setDrawsBackground: NO];
1450 [copyright_label setAlignment: NSTextAlignmentCenter];
1451 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1453 [superView addSubview: copyright_label];
1456 /* Used by the Speed menu items */
1457 - (void)adjustSpeed:(id)sender
1459 int throttle_pct; /* throttle percentage */
1462 menu = [sender menu];
1465 /* Unselect the currently selected item */
1466 for (NSMenuItem *item in [menu itemArray]) {
1467 if (item.state == NSControlStateValueOn) {
1468 [item setState: NSControlStateValueOff];
1474 // check the menu item
1475 [sender setState: NSControlStateValueOn];
1477 // get the throttle percentage
1478 throttle_pct = [sender tag];
1480 with_iothread_lock(^{
1481 cpu_throttle_set(throttle_pct);
1483 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1488 @interface QemuApplication : NSApplication
1491 @implementation QemuApplication
1492 - (void)sendEvent:(NSEvent *)event
1494 COCOA_DEBUG("QemuApplication: sendEvent\n");
1495 if (![cocoaView handleEvent:event]) {
1496 [super sendEvent: event];
1501 static void create_initial_menus(void)
1505 NSMenuItem *menuItem;
1507 [NSApp setMainMenu:[[NSMenu alloc] init]];
1510 menu = [[NSMenu alloc] initWithTitle:@""];
1511 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1512 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1513 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1514 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1515 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1516 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1517 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1518 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1519 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1520 [menuItem setSubmenu:menu];
1521 [[NSApp mainMenu] addItem:menuItem];
1522 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1525 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1526 [menu setAutoenablesItems: NO];
1527 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1528 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1529 [menu addItem: menuItem];
1530 [menuItem setEnabled: NO];
1531 [menu addItem: [NSMenuItem separatorItem]];
1532 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1533 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1534 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1535 [menuItem setSubmenu:menu];
1536 [[NSApp mainMenu] addItem:menuItem];
1539 menu = [[NSMenu alloc] initWithTitle:@"View"];
1540 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1541 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1542 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1543 [menuItem setSubmenu:menu];
1544 [[NSApp mainMenu] addItem:menuItem];
1547 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1549 // Add the rest of the Speed menu items
1550 int p, percentage, throttle_pct;
1551 for (p = 10; p >= 0; p--)
1553 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1555 menuItem = [[[NSMenuItem alloc]
1556 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1558 if (percentage == 100) {
1559 [menuItem setState: NSControlStateValueOn];
1562 /* Calculate the throttle percentage */
1563 throttle_pct = -1 * percentage + 100;
1565 [menuItem setTag: throttle_pct];
1566 [menu addItem: menuItem];
1568 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1569 [menuItem setSubmenu:menu];
1570 [[NSApp mainMenu] addItem:menuItem];
1573 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1574 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1575 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1576 [menuItem setSubmenu:menu];
1577 [[NSApp mainMenu] addItem:menuItem];
1578 [NSApp setWindowsMenu:menu];
1581 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1582 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1583 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1584 [menuItem setSubmenu:menu];
1585 [[NSApp mainMenu] addItem:menuItem];
1588 /* Returns a name for a given console */
1589 static NSString * getConsoleName(QemuConsole * console)
1591 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1594 /* Add an entry to the View menu for each console */
1595 static void add_console_menu_entries(void)
1598 NSMenuItem *menuItem;
1601 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1603 [menu addItem:[NSMenuItem separatorItem]];
1605 while (qemu_console_lookup_by_index(index) != NULL) {
1606 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1607 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1608 [menuItem setTag: index];
1609 [menu addItem: menuItem];
1614 /* Make menu items for all removable devices.
1615 * Each device is given an 'Eject' and 'Change' menu item.
1617 static void addRemovableDevicesMenuItems(void)
1620 NSMenuItem *menuItem;
1621 BlockInfoList *currentDevice, *pointerToFree;
1622 NSString *deviceName;
1624 currentDevice = qmp_query_block(NULL);
1625 pointerToFree = currentDevice;
1626 if(currentDevice == NULL) {
1628 QEMU_Alert(@"Failed to query for block devices!");
1632 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1634 // Add a separator between related groups of menu items
1635 [menu addItem:[NSMenuItem separatorItem]];
1637 // Set the attributes to the "Removable Media" menu item
1638 NSString *titleString = @"Removable Media";
1639 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1640 NSColor *newColor = [NSColor blackColor];
1641 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1642 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1643 traits:NSBoldFontMask|NSItalicFontMask
1646 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1647 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1648 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1650 // Add the "Removable Media" menu item
1651 menuItem = [NSMenuItem new];
1652 [menuItem setAttributedTitle: attString];
1653 [menuItem setEnabled: NO];
1654 [menu addItem: menuItem];
1656 /* Loop through all the block devices in the emulator */
1657 while (currentDevice) {
1658 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1660 if(currentDevice->value->removable) {
1661 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1662 action: @selector(changeDeviceMedia:)
1663 keyEquivalent: @""];
1664 [menu addItem: menuItem];
1665 [menuItem setRepresentedObject: deviceName];
1666 [menuItem autorelease];
1668 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1669 action: @selector(ejectDeviceMedia:)
1670 keyEquivalent: @""];
1671 [menu addItem: menuItem];
1672 [menuItem setRepresentedObject: deviceName];
1673 [menuItem autorelease];
1675 currentDevice = currentDevice->next;
1677 qapi_free_BlockInfoList(pointerToFree);
1681 * The startup process for the OSX/Cocoa UI is complicated, because
1682 * OSX insists that the UI runs on the initial main thread, and so we
1683 * need to start a second thread which runs the vl.c qemu_main():
1685 * Initial thread: 2nd thread:
1687 * create qemu-main thread
1688 * wait on display_init semaphore
1691 * in cocoa_display_init():
1692 * post the display_init semaphore
1693 * wait on app_started semaphore
1694 * create application, menus, etc
1695 * enter OSX run loop
1696 * in applicationDidFinishLaunching:
1697 * post app_started semaphore
1698 * tell main thread to fullscreen if needed
1700 * run qemu main-loop
1702 * We do this in two stages so that we don't do the creation of the
1703 * GUI application menus and so on for command line options like --help
1704 * where we want to just print text to stdout and exit immediately.
1707 static void *call_qemu_main(void *opaque)
1711 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1712 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1713 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1717 int main (int argc, const char * argv[]) {
1720 COCOA_DEBUG("Entered main()\n");
1722 gArgv = (char **)argv;
1724 qemu_sem_init(&display_init_sem, 0);
1725 qemu_sem_init(&app_started_sem, 0);
1727 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1728 NULL, QEMU_THREAD_DETACHED);
1730 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1731 qemu_sem_wait(&display_init_sem);
1732 COCOA_DEBUG("Main thread: initializing app\n");
1734 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1736 // Pull this console process up to being a fully-fledged graphical
1737 // app with a menubar and Dock icon
1738 ProcessSerialNumber psn = { 0, kCurrentProcess };
1739 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1741 [QemuApplication sharedApplication];
1743 create_initial_menus();
1746 * Create the menu entries which depend on QEMU state (for consoles
1747 * and removeable devices). These make calls back into QEMU functions,
1748 * which is OK because at this point we know that the second thread
1749 * holds the iothread lock and is synchronously waiting for us to
1752 add_console_menu_entries();
1753 addRemovableDevicesMenuItems();
1755 // Create an Application controller
1756 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1757 [NSApp setDelegate:appController];
1759 // Start the main event loop
1760 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1762 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1764 [appController release];
1773 static void cocoa_update(DisplayChangeListener *dcl,
1774 int x, int y, int w, int h)
1776 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1778 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1780 dispatch_async(dispatch_get_main_queue(), ^{
1782 if ([cocoaView cdx] == 1.0) {
1783 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1786 x * [cocoaView cdx],
1787 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1788 w * [cocoaView cdx],
1789 h * [cocoaView cdy]);
1791 [cocoaView setNeedsDisplayInRect:rect];
1797 static void cocoa_switch(DisplayChangeListener *dcl,
1798 DisplaySurface *surface)
1800 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1801 pixman_image_t *image = surface->image;
1803 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1805 // The DisplaySurface will be freed as soon as this callback returns.
1806 // We take a reference to the underlying pixman image here so it does
1807 // not disappear from under our feet; the switchSurface method will
1808 // deref the old image when it is done with it.
1809 pixman_image_ref(image);
1811 dispatch_async(dispatch_get_main_queue(), ^{
1812 [cocoaView switchSurface:image];
1817 static void cocoa_refresh(DisplayChangeListener *dcl)
1819 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1821 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1822 graphic_hw_update(NULL);
1824 if (qemu_input_is_absolute()) {
1825 dispatch_async(dispatch_get_main_queue(), ^{
1826 if (![cocoaView isAbsoluteEnabled]) {
1827 if ([cocoaView isMouseGrabbed]) {
1828 [cocoaView ungrabMouse];
1831 [cocoaView setAbsoluteEnabled:YES];
1837 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1839 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1841 /* Tell main thread to go ahead and create the app and enter the run loop */
1842 qemu_sem_post(&display_init_sem);
1843 qemu_sem_wait(&app_started_sem);
1844 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1846 /* if fullscreen mode is to be used */
1847 if (opts->has_full_screen && opts->full_screen) {
1848 dispatch_async(dispatch_get_main_queue(), ^{
1849 [NSApp activateIgnoringOtherApps: YES];
1850 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1853 if (opts->has_show_cursor && opts->show_cursor) {
1857 // register vga output callbacks
1858 register_displaychangelistener(&dcl);
1861 static QemuDisplay qemu_display_cocoa = {
1862 .type = DISPLAY_TYPE_COCOA,
1863 .init = cocoa_display_init,
1866 static void register_cocoa(void)
1868 qemu_display_register(&qemu_display_cocoa);
1871 type_init(register_cocoa);