ui/cocoa: Clear modifiers whenever possible
[qemu/kevin.git] / ui / cocoa.m
blobf71c59711fa6d6527e0af28aee418708504c014b
1 /*
2  * QEMU Cocoa CG display driver
3  *
4  * Copyright (c) 2008 Mike Kronenberg
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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
22  * THE SOFTWARE.
23  */
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"
32 #include "ui/input.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
51 #endif
53 /* 10.14 deprecates NSOnState and NSOffState in favor of
54  * NSControlStateValueOn/Off, which were introduced in 10.13.
55  * Define for older versions
56  */
57 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
58 #define NSControlStateValueOn NSOnState
59 #define NSControlStateValueOff NSOffState
60 #endif
62 //#define DEBUG
64 #ifdef DEBUG
65 #define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
66 #else
67 #define COCOA_DEBUG(...)  ((void) 0)
68 #endif
70 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
72 typedef struct {
73     int width;
74     int height;
75 } QEMUScreen;
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 NSWindow *normalWindow, *about_window;
86 static const DisplayChangeListenerOps dcl_ops = {
87     .dpy_name          = "cocoa",
88     .dpy_gfx_update = cocoa_update,
89     .dpy_gfx_switch = cocoa_switch,
90     .dpy_refresh = cocoa_refresh,
92 static DisplayChangeListener dcl = {
93     .ops = &dcl_ops,
95 static int last_buttons;
96 static int cursor_hide = 1;
98 int gArgc;
99 char **gArgv;
100 bool stretch_video;
101 NSTextField *pauseLabel;
102 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();
115     if (!locked) {
116         qemu_mutex_lock_iothread();
117     }
118     block();
119     if (!locked) {
120         qemu_mutex_unlock_iothread();
121     }
124 static bool bool_with_iothread_lock(BoolCodeBlock block)
126     bool locked = qemu_mutex_iothread_locked();
127     bool val;
129     if (!locked) {
130         qemu_mutex_lock_iothread();
131     }
132     val = block();
133     if (!locked) {
134         qemu_mutex_unlock_iothread();
135     }
136     return val;
139 // Mac to QKeyCode conversion
140 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.
232      */
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,
258     /*
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.
261      */
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);
268         return 0;
269     }
270     return mac_to_qkeycode_map[keycode];
273 /* Displays an alert dialog box with the specified message */
274 static void QEMU_Alert(NSString *message)
276     NSAlert *alert;
277     alert = [NSAlert new];
278     [alert setMessageText: message];
279     [alert runModal];
282 /* Handles any errors that happen with a device transaction */
283 static void handleAnyDeviceErrors(Error * err)
285     if (err) {
286         QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
287                                       encoding: NSASCIIStringEncoding]);
288         error_free(err);
289     }
293  ------------------------------------------------------
294     QemuCocoaView
295  ------------------------------------------------------
297 @interface QemuCocoaView : NSView
299     QEMUScreen screen;
300     NSWindow *fullScreenWindow;
301     float cx,cy,cw,ch,cdx,cdy;
302     pixman_image_t *pixman_image;
303     QKbdState *kbd;
304     BOOL isMouseGrabbed;
305     BOOL isFullscreen;
306     BOOL isAbsoluteEnabled;
307     BOOL isMouseDeassociated;
309 - (void) switchSurface:(pixman_image_t *)image;
310 - (void) grabMouse;
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
320  *   next refresh.
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).
328  */
329 - (BOOL) isMouseGrabbed;
330 - (BOOL) isAbsoluteEnabled;
331 - (BOOL) isMouseDeassociated;
332 - (float) cdx;
333 - (float) cdy;
334 - (QEMUScreen) gscreen;
335 - (void) raiseAllKeys;
336 @end
338 QemuCocoaView *cocoaView;
340 @implementation QemuCocoaView
341 - (id)initWithFrame:(NSRect)frameRect
343     COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
345     self = [super initWithFrame:frameRect];
346     if (self) {
348         screen.width = frameRect.size.width;
349         screen.height = frameRect.size.height;
350         kbd = qkbd_state_init(dcl.con);
352     }
353     return self;
356 - (void) dealloc
358     COCOA_DEBUG("QemuCocoaView: dealloc\n");
360     if (pixman_image) {
361         pixman_image_unref(pixman_image);
362     }
364     qkbd_state_free(kbd);
365     [super dealloc];
368 - (BOOL) isOpaque
370     return YES;
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];
385     if (!eventWindow) {
386         if (!isFullscreen) {
387             return [[self window] convertRectFromScreen:r].origin;
388         } else {
389             CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
390             CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
391             if (stretch_video) {
392                 loc.x /= cdx;
393                 loc.y /= cdy;
394             }
395             return loc;
396         }
397     } else if ([[self window] isEqual:eventWindow]) {
398         if (!isFullscreen) {
399             return r.origin;
400         } else {
401             CGPoint loc = [self convertPoint:r.origin fromView:nil];
402             if (stretch_video) {
403                 loc.x /= cdx;
404                 loc.y /= cdy;
405             }
406             return loc;
407         }
408     } else {
409         return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
410     }
413 - (void) hideCursor
415     if (!cursor_hide) {
416         return;
417     }
418     [NSCursor hide];
421 - (void) unhideCursor
423     if (!cursor_hide) {
424         return;
425     }
426     [NSCursor unhide];
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
440     if (!pixman_image) {
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));
445     } else {
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(
451             NULL,
452             pixman_image_get_data(pixman_image),
453             stride * h,
454             NULL
455         );
456         CGImageRef imageRef = CGImageCreate(
457             w, //width
458             h, //height
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
465             NULL, //decode
466             0, //interpolate
467             kCGRenderingIntentDefault //intent
468         );
469         // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
470         const NSRect *rectList;
471         NSInteger rectCount;
472         int i;
473         CGImageRef clipImageRef;
474         CGRect clipRect;
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(
483                                                         imageRef,
484                                                         clipRect
485                                                         );
486             CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
487             CGImageRelease (clipImageRef);
488         }
489         CGImageRelease (imageRef);
490         CGDataProviderRelease(dataProviderRef);
491     }
494 - (void) setContentDimensions
496     COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
498     if (isFullscreen) {
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) {
506                 cdy = cdx;
507             } else {
508                 cdx = cdy;
509             }
510         } else {  /* No stretching */
511             cdx = cdy = 1;
512         }
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;
517     } else {
518         cx = 0;
519         cy = 0;
520         cw = screen.width;
521         ch = screen.height;
522         cdx = 1.0;
523         cdy = 1.0;
524     }
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.
536      */
537     bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
539     int oldh = screen.height;
540     if (isResize) {
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);
543         screen.width = w;
544         screen.height = h;
545         [self setContentDimensions];
546         [self setFrame:NSMakeRect(cx, cy, cw, ch)];
547     }
549     // update screenBuffer
550     if (pixman_image) {
551         pixman_image_unref(pixman_image);
552     }
554     pixman_image = image;
556     // update windows
557     if (isFullscreen) {
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];
560     } else {
561         if (qemu_name)
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];
564     }
566     if (isResize) {
567         [normalWindow center];
568     }
571 - (void) toggleFullScreen:(id)sender
573     COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
575     if (isFullscreen) { // switch from fullscreen to desktop
576         isFullscreen = FALSE;
577         [self ungrabMouse];
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
584         isFullscreen = TRUE;
585         [normalWindow orderOut: nil]; /* Hide the window */
586         [self grabMouse];
587         [self setContentDimensions];
588         [NSMenu setMenuBarVisible:NO];
589         fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
590             styleMask:NSWindowStyleMaskBorderless
591             backing:NSBackingStoreBuffered
592             defer:NO];
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];
599     }
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
609     int keysym = 0;
610     int control_key = 0;
612     // if the control key is down
613     if ([event modifierFlags] & NSEventModifierFlagControl) {
614         control_key = 1;
615     }
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,
632     };
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,
645     };
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]];
650         }
651     } else {
652         if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
653             keysym = without_control_translation[[event keyCode]];
654         }
655     }
657     // if not a key that needs translating
658     if (keysym == 0) {
659         NSString *ks = [event characters];
660         if ([ks length] > 0) {
661             keysym = [ks characterAtIndex:0];
662         }
663     }
665     if (keysym) {
666         kbd_put_keysym(keysym);
667     }
670 - (bool) handleEvent:(NSEvent *)event
672     if(!allow_events) {
673         /*
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.)
679          */
680         return false;
681     }
682     return bool_with_iothread_lock(^{
683         return [self handleEventLocked:event];
684     });
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");
691     int buttons = 0;
692     int keycode = 0;
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);
704     }
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);
709     }
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);
713     }
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);
717     }
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);
721     }
723     switch ([event type]) {
724         case NSEventTypeFlagsChanged:
725             switch ([event keyCode]) {
726                 case kVK_Shift:
727                     if (!!(modifiers & NSEventModifierFlagShift)) {
728                         [self toggleKey:Q_KEY_CODE_SHIFT];
729                     }
730                     break;
732                 case kVK_RightShift:
733                     if (!!(modifiers & NSEventModifierFlagShift)) {
734                         [self toggleKey:Q_KEY_CODE_SHIFT_R];
735                     }
736                     break;
738                 case kVK_Control:
739                     if (!!(modifiers & NSEventModifierFlagControl)) {
740                         [self toggleKey:Q_KEY_CODE_CTRL];
741                     }
742                     break;
744                 case kVK_RightControl:
745                     if (!!(modifiers & NSEventModifierFlagControl)) {
746                         [self toggleKey:Q_KEY_CODE_CTRL_R];
747                     }
748                     break;
750                 case kVK_Option:
751                     if (!!(modifiers & NSEventModifierFlagOption)) {
752                         [self toggleKey:Q_KEY_CODE_ALT];
753                     }
754                     break;
756                 case kVK_RightOption:
757                     if (!!(modifiers & NSEventModifierFlagOption)) {
758                         [self toggleKey:Q_KEY_CODE_ALT_R];
759                     }
760                     break;
762                 /* Don't pass command key changes to guest unless mouse is grabbed */
763                 case kVK_Command:
764                     if (isMouseGrabbed &&
765                         !!(modifiers & NSEventModifierFlagCommand)) {
766                         [self toggleKey:Q_KEY_CODE_META_L];
767                     }
768                     break;
770                 case kVK_RightCommand:
771                     if (isMouseGrabbed &&
772                         !!(modifiers & NSEventModifierFlagCommand)) {
773                         [self toggleKey:Q_KEY_CODE_META_R];
774                     }
775                     break;
776             }
777             break;
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)) {
783                 /*
784                  * Prevent the command key from being stuck down in the guest
785                  * when using Command-F to switch to full screen mode.
786                  */
787                 if (keycode == Q_KEY_CODE_F) {
788                     switched_to_fullscreen = true;
789                 }
790                 return false;
791             }
793             // default
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];
800                     switch (key) {
802                         // enable graphic console
803                         case '1' ... '9':
804                             console_select(key - '0' - 1); /* ascii math */
805                             return true;
807                         // release the mouse grab
808                         case 'g':
809                             [self ungrabMouse];
810                             return true;
811                     }
812                 }
813             }
815             if (qemu_console_is_graphic(NULL)) {
816                 qkbd_state_key_event(kbd, keycode, true);
817             } else {
818                 [self handleMonitorInput: event];
819             }
820             break;
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)) {
827                 return true;
828             }
830             if (qemu_console_is_graphic(NULL)) {
831                 qkbd_state_key_event(kbd, keycode, false);
832             }
833             break;
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) {
841                         [self ungrabMouse];
842                     }
843                 } else {
844                     if (!isMouseGrabbed) {
845                         [self grabMouse];
846                     }
847                 }
848             }
849             mouse_event = true;
850             break;
851         case NSEventTypeLeftMouseDown:
852             buttons |= MOUSE_EVENT_LBUTTON;
853             mouse_event = true;
854             break;
855         case NSEventTypeRightMouseDown:
856             buttons |= MOUSE_EVENT_RBUTTON;
857             mouse_event = true;
858             break;
859         case NSEventTypeOtherMouseDown:
860             buttons |= MOUSE_EVENT_MBUTTON;
861             mouse_event = true;
862             break;
863         case NSEventTypeLeftMouseDragged:
864             buttons |= MOUSE_EVENT_LBUTTON;
865             mouse_event = true;
866             break;
867         case NSEventTypeRightMouseDragged:
868             buttons |= MOUSE_EVENT_RBUTTON;
869             mouse_event = true;
870             break;
871         case NSEventTypeOtherMouseDragged:
872             buttons |= MOUSE_EVENT_MBUTTON;
873             mouse_event = true;
874             break;
875         case NSEventTypeLeftMouseUp:
876             mouse_event = true;
877             if (!isMouseGrabbed && [self screenContainsPoint:p]) {
878                 /*
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.
882                  */
883                 if(isFullscreen || [[self window] isKeyWindow]) {
884                     [self grabMouse];
885                 }
886             }
887             break;
888         case NSEventTypeRightMouseUp:
889             mouse_event = true;
890             break;
891         case NSEventTypeOtherMouseUp:
892             mouse_event = true;
893             break;
894         case NSEventTypeScrollWheel:
895             /*
896              * Send wheel events to the guest regardless of window focus.
897              * This is in-line with standard Mac OS X UI behaviour.
898              */
900             /*
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.
904              */
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();
913             }
914             /*
915              * Since deltaY also reports scroll wheel events we prevent mouse
916              * movement code from executing.
917              */
918             mouse_event = false;
919             break;
920         default:
921             return false;
922     }
924     if (mouse_event) {
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
930          * to the guest.
931          */
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
938             };
939             qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
940             last_buttons = buttons;
941         }
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.
947                  */
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);
951                 }
952             } else {
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]);
955             }
956         } else {
957             return false;
958         }
959         qemu_input_event_sync();
960     }
961     return true;
964 - (void) grabMouse
966     COCOA_DEBUG("QemuCocoaView: grabMouse\n");
968     if (!isFullscreen) {
969         if (qemu_name)
970             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
971         else
972             [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
973     }
974     [self hideCursor];
975     if (!isAbsoluteEnabled) {
976         isMouseDeassociated = TRUE;
977         CGAssociateMouseAndMouseCursorPosition(FALSE);
978     }
979     isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
982 - (void) ungrabMouse
984     COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
986     if (!isFullscreen) {
987         if (qemu_name)
988             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
989         else
990             [normalWindow setTitle:@"QEMU"];
991     }
992     [self unhideCursor];
993     if (isMouseDeassociated) {
994         CGAssociateMouseAndMouseCursorPosition(TRUE);
995         isMouseDeassociated = FALSE;
996     }
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.
1012  */
1013 - (void) raiseAllKeys
1015     with_iothread_lock(^{
1016         qkbd_state_lift_all_keys(kbd);
1017     });
1019 @end
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;
1045 - (BOOL)verifyQuit;
1046 - (void)openDocumentation:(NSString *)filename;
1047 - (IBAction) do_about_menu_item: (id) sender;
1048 - (void)make_about_window;
1049 - (void)adjustSpeed:(id)sender;
1050 @end
1052 @implementation QemuCocoaAppController
1053 - (id) init
1055     COCOA_DEBUG("QemuCocoaAppController: init\n");
1057     self = [super init];
1058     if (self) {
1060         // create a view and add it to the window
1061         cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1062         if(!cocoaView) {
1063             error_report("(cocoa) can't create a view");
1064             exit(1);
1065         }
1067         // create a window
1068         normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1069             styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1070             backing:NSBackingStoreBuffered defer:NO];
1071         if(!normalWindow) {
1072             error_report("(cocoa) can't create window");
1073             exit(1);
1074         }
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",
1098                                   @"toast", nil];
1099         [self make_about_window];
1100     }
1101     return self;
1104 - (void) dealloc
1106     COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1108     if (cocoaView)
1109         [cocoaView release];
1110     [super dealloc];
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);
1126     exit(0);
1129 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1131     return YES;
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.
1150      */
1151     return NO;
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:
1164  */
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 */
1186     int index;
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) {
1195             return;
1196         }
1197     }
1199     /* If none of the paths opened a file */
1200     NSBeep();
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];
1217     } else {
1218         [sender setState: NSControlStateValueOff];
1219     }
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(^{
1232         qmp_stop(NULL);
1233     });
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(^{
1243         qmp_cont(NULL);
1244     });
1245     [sender setEnabled: NO];
1246     [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1247     [self removePause];
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 */
1264 - (void)removePause
1266     [pauseLabel removeFromSuperview];
1269 /* Restarts QEMU */
1270 - (void)restartQEMU:(id)sender
1272     with_iothread_lock(^{
1273         qmp_system_reset(NULL);
1274     });
1277 /* Powers down QEMU */
1278 - (void)powerDownQEMU:(id)sender
1280     with_iothread_lock(^{
1281         qmp_system_powerdown(NULL);
1282     });
1285 /* Ejects the media.
1286  * Uses sender's tag to figure out the device to eject.
1287  */
1288 - (void)ejectDeviceMedia:(id)sender
1290     NSString * drive;
1291     drive = [sender representedObject];
1292     if(drive == nil) {
1293         NSBeep();
1294         QEMU_Alert(@"Failed to find drive to eject!");
1295         return;
1296     }
1298     __block Error *err = NULL;
1299     with_iothread_lock(^{
1300         qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1301                   false, NULL, false, false, &err);
1302     });
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.
1308  */
1309 - (void)changeDeviceMedia:(id)sender
1311     /* Find the drive name */
1312     NSString * drive;
1313     drive = [sender representedObject];
1314     if(drive == nil) {
1315         NSBeep();
1316         QEMU_Alert(@"Could not find drive!");
1317         return;
1318     }
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];
1328         if(file == nil) {
1329             NSBeep();
1330             QEMU_Alert(@"Failed to convert URL to file path!");
1331             return;
1332         }
1334         __block Error *err = NULL;
1335         with_iothread_lock(^{
1336             qmp_blockdev_change_medium(true,
1337                                        [drive cStringUsingEncoding:
1338                                                   NSASCIIStringEncoding],
1339                                        false, NULL,
1340                                        [file cStringUsingEncoding:
1341                                                  NSASCIIStringEncoding],
1342                                        true, "raw",
1343                                        false, 0,
1344                                        &err);
1345         });
1346         handleAnyDeviceErrors(err);
1347     }
1350 /* Verifies if the user really wants to quit */
1351 - (BOOL)verifyQuit
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) {
1359         return YES;
1360     } else {
1361         return NO;
1362     }
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
1381                     defer:NO];
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:
1395                                                      picture_rect];
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];
1406     if (bundle) {
1407         x = 0;
1408         y = y - 25;
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];
1419     }
1421     /* Set the version label's attributes */
1422     x = 0;
1423     y = 50;
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:
1427                                                       version_rect];
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 */
1441     x = 0;
1442     y = 35;
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:
1446                                                         copyright_rect];
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",
1452                                      QEMU_COPYRIGHT]];
1453     [superView addSubview: copyright_label];
1456 /* Used by the Speed menu items */
1457 - (void)adjustSpeed:(id)sender
1459     int throttle_pct; /* throttle percentage */
1460     NSMenu *menu;
1462     menu = [sender menu];
1463     if (menu != nil)
1464     {
1465         /* Unselect the currently selected item */
1466         for (NSMenuItem *item in [menu itemArray]) {
1467             if (item.state == NSControlStateValueOn) {
1468                 [item setState: NSControlStateValueOff];
1469                 break;
1470             }
1471         }
1472     }
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);
1482     });
1483     COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1486 @end
1488 @interface QemuApplication : NSApplication
1489 @end
1491 @implementation QemuApplication
1492 - (void)sendEvent:(NSEvent *)event
1494     COCOA_DEBUG("QemuApplication: sendEvent\n");
1495     if (![cocoaView handleEvent:event]) {
1496         [super sendEvent: event];
1497     }
1499 @end
1501 static void create_initial_menus(void)
1503     // Add menus
1504     NSMenu      *menu;
1505     NSMenuItem  *menuItem;
1507     [NSApp setMainMenu:[[NSMenu alloc] init]];
1509     // Application menu
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+)
1524     // Machine menu
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];
1538     // View menu
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];
1546     // Speed menu
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--)
1552     {
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];
1560         }
1562         /* Calculate the throttle percentage */
1563         throttle_pct = -1 * percentage + 100;
1565         [menuItem setTag: throttle_pct];
1566         [menu addItem: menuItem];
1567     }
1568     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1569     [menuItem setSubmenu:menu];
1570     [[NSApp mainMenu] addItem:menuItem];
1572     // Window menu
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];
1580     // Help 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)
1597     NSMenu *menu;
1598     NSMenuItem *menuItem;
1599     int index = 0;
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];
1610         index++;
1611     }
1614 /* Make menu items for all removable devices.
1615  * Each device is given an 'Eject' and 'Change' menu item.
1616  */
1617 static void addRemovableDevicesMenuItems(void)
1619     NSMenu *menu;
1620     NSMenuItem *menuItem;
1621     BlockInfoList *currentDevice, *pointerToFree;
1622     NSString *deviceName;
1624     currentDevice = qmp_query_block(NULL);
1625     pointerToFree = currentDevice;
1626     if(currentDevice == NULL) {
1627         NSBeep();
1628         QEMU_Alert(@"Failed to query for block devices!");
1629         return;
1630     }
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
1644                                           weight:0
1645                                             size:14];
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];
1674         }
1675         currentDevice = currentDevice->next;
1676     }
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:
1686  * in main():
1687  *  create qemu-main thread
1688  *  wait on display_init semaphore
1689  *                                    call qemu_main()
1690  *                                    ...
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
1699  *                                    [...]
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.
1705  */
1707 static void *call_qemu_main(void *opaque)
1709     int status;
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");
1714     exit(status);
1717 int main (int argc, const char * argv[]) {
1718     QemuThread thread;
1720     COCOA_DEBUG("Entered main()\n");
1721     gArgc = argc;
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();
1745     /*
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
1750      * finish.
1751      */
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");
1761     [NSApp run];
1762     COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1764     [appController release];
1765     [pool release];
1767     return 0;
1772 #pragma mark qemu
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(), ^{
1781         NSRect rect;
1782         if ([cocoaView cdx] == 1.0) {
1783             rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1784         } else {
1785             rect = NSMakeRect(
1786                 x * [cocoaView cdx],
1787                 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1788                 w * [cocoaView cdx],
1789                 h * [cocoaView cdy]);
1790         }
1791         [cocoaView setNeedsDisplayInRect:rect];
1792     });
1794     [pool release];
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];
1813     });
1814     [pool release];
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];
1829                 }
1830             }
1831             [cocoaView setAbsoluteEnabled:YES];
1832         });
1833     }
1834     [pool release];
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];
1851         });
1852     }
1853     if (opts->has_show_cursor && opts->show_cursor) {
1854         cursor_hide = 0;
1855     }
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);