ui/cocoa: Show QEMU icon in the about window
[qemu/ar7.git] / ui / cocoa.m
blobe589534fa46023d71fdb1cfe3dee6fb044d6813c
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 "sysemu/sysemu.h"
34 #include "sysemu/runstate.h"
35 #include "sysemu/cpu-throttle.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-commands-block.h"
38 #include "qapi/qapi-commands-machine.h"
39 #include "qapi/qapi-commands-misc.h"
40 #include "sysemu/blockdev.h"
41 #include "qemu-version.h"
42 #include "qemu/cutils.h"
43 #include "qemu/main-loop.h"
44 #include "qemu/module.h"
45 #include <Carbon/Carbon.h>
46 #include "hw/core/cpu.h"
48 #ifndef MAC_OS_X_VERSION_10_13
49 #define MAC_OS_X_VERSION_10_13 101300
50 #endif
52 /* 10.14 deprecates NSOnState and NSOffState in favor of
53  * NSControlStateValueOn/Off, which were introduced in 10.13.
54  * Define for older versions
55  */
56 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
57 #define NSControlStateValueOn NSOnState
58 #define NSControlStateValueOff NSOffState
59 #endif
61 //#define DEBUG
63 #ifdef DEBUG
64 #define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
65 #else
66 #define COCOA_DEBUG(...)  ((void) 0)
67 #endif
69 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
71 typedef struct {
72     int width;
73     int height;
74 } QEMUScreen;
76 static void cocoa_update(DisplayChangeListener *dcl,
77                          int x, int y, int w, int h);
79 static void cocoa_switch(DisplayChangeListener *dcl,
80                          DisplaySurface *surface);
82 static void cocoa_refresh(DisplayChangeListener *dcl);
84 NSWindow *normalWindow, *about_window;
85 static const DisplayChangeListenerOps dcl_ops = {
86     .dpy_name          = "cocoa",
87     .dpy_gfx_update = cocoa_update,
88     .dpy_gfx_switch = cocoa_switch,
89     .dpy_refresh = cocoa_refresh,
91 static DisplayChangeListener dcl = {
92     .ops = &dcl_ops,
94 static int last_buttons;
95 static int cursor_hide = 1;
97 int gArgc;
98 char **gArgv;
99 bool stretch_video;
100 NSTextField *pauseLabel;
101 NSArray * supportedImageFileTypes;
103 static QemuSemaphore display_init_sem;
104 static QemuSemaphore app_started_sem;
105 static bool allow_events;
107 // Utility functions to run specified code block with iothread lock held
108 typedef void (^CodeBlock)(void);
109 typedef bool (^BoolCodeBlock)(void);
111 static void with_iothread_lock(CodeBlock block)
113     bool locked = qemu_mutex_iothread_locked();
114     if (!locked) {
115         qemu_mutex_lock_iothread();
116     }
117     block();
118     if (!locked) {
119         qemu_mutex_unlock_iothread();
120     }
123 static bool bool_with_iothread_lock(BoolCodeBlock block)
125     bool locked = qemu_mutex_iothread_locked();
126     bool val;
128     if (!locked) {
129         qemu_mutex_lock_iothread();
130     }
131     val = block();
132     if (!locked) {
133         qemu_mutex_unlock_iothread();
134     }
135     return val;
138 // Mac to QKeyCode conversion
139 const int mac_to_qkeycode_map[] = {
140     [kVK_ANSI_A] = Q_KEY_CODE_A,
141     [kVK_ANSI_B] = Q_KEY_CODE_B,
142     [kVK_ANSI_C] = Q_KEY_CODE_C,
143     [kVK_ANSI_D] = Q_KEY_CODE_D,
144     [kVK_ANSI_E] = Q_KEY_CODE_E,
145     [kVK_ANSI_F] = Q_KEY_CODE_F,
146     [kVK_ANSI_G] = Q_KEY_CODE_G,
147     [kVK_ANSI_H] = Q_KEY_CODE_H,
148     [kVK_ANSI_I] = Q_KEY_CODE_I,
149     [kVK_ANSI_J] = Q_KEY_CODE_J,
150     [kVK_ANSI_K] = Q_KEY_CODE_K,
151     [kVK_ANSI_L] = Q_KEY_CODE_L,
152     [kVK_ANSI_M] = Q_KEY_CODE_M,
153     [kVK_ANSI_N] = Q_KEY_CODE_N,
154     [kVK_ANSI_O] = Q_KEY_CODE_O,
155     [kVK_ANSI_P] = Q_KEY_CODE_P,
156     [kVK_ANSI_Q] = Q_KEY_CODE_Q,
157     [kVK_ANSI_R] = Q_KEY_CODE_R,
158     [kVK_ANSI_S] = Q_KEY_CODE_S,
159     [kVK_ANSI_T] = Q_KEY_CODE_T,
160     [kVK_ANSI_U] = Q_KEY_CODE_U,
161     [kVK_ANSI_V] = Q_KEY_CODE_V,
162     [kVK_ANSI_W] = Q_KEY_CODE_W,
163     [kVK_ANSI_X] = Q_KEY_CODE_X,
164     [kVK_ANSI_Y] = Q_KEY_CODE_Y,
165     [kVK_ANSI_Z] = Q_KEY_CODE_Z,
167     [kVK_ANSI_0] = Q_KEY_CODE_0,
168     [kVK_ANSI_1] = Q_KEY_CODE_1,
169     [kVK_ANSI_2] = Q_KEY_CODE_2,
170     [kVK_ANSI_3] = Q_KEY_CODE_3,
171     [kVK_ANSI_4] = Q_KEY_CODE_4,
172     [kVK_ANSI_5] = Q_KEY_CODE_5,
173     [kVK_ANSI_6] = Q_KEY_CODE_6,
174     [kVK_ANSI_7] = Q_KEY_CODE_7,
175     [kVK_ANSI_8] = Q_KEY_CODE_8,
176     [kVK_ANSI_9] = Q_KEY_CODE_9,
178     [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
179     [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
180     [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
181     [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
182     [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
183     [kVK_Tab] = Q_KEY_CODE_TAB,
184     [kVK_Return] = Q_KEY_CODE_RET,
185     [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
186     [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
187     [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
188     [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
189     [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
190     [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
191     [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
192     [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
193     [kVK_Shift] = Q_KEY_CODE_SHIFT,
194     [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
195     [kVK_Control] = Q_KEY_CODE_CTRL,
196     [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
197     [kVK_Option] = Q_KEY_CODE_ALT,
198     [kVK_RightOption] = Q_KEY_CODE_ALT_R,
199     [kVK_Command] = Q_KEY_CODE_META_L,
200     [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
201     [kVK_Space] = Q_KEY_CODE_SPC,
203     [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
204     [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
205     [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
206     [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
207     [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
208     [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
209     [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
210     [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
211     [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
212     [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
213     [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
214     [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
215     [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
216     [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
217     [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
218     [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
219     [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
220     [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
222     [kVK_UpArrow] = Q_KEY_CODE_UP,
223     [kVK_DownArrow] = Q_KEY_CODE_DOWN,
224     [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
225     [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
227     [kVK_Help] = Q_KEY_CODE_INSERT,
228     [kVK_Home] = Q_KEY_CODE_HOME,
229     [kVK_PageUp] = Q_KEY_CODE_PGUP,
230     [kVK_PageDown] = Q_KEY_CODE_PGDN,
231     [kVK_End] = Q_KEY_CODE_END,
232     [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
234     [kVK_Escape] = Q_KEY_CODE_ESC,
236     /* The Power key can't be used directly because the operating system uses
237      * it. This key can be emulated by using it in place of another key such as
238      * F1. Don't forget to disable the real key binding.
239      */
240     /* [kVK_F1] = Q_KEY_CODE_POWER, */
242     [kVK_F1] = Q_KEY_CODE_F1,
243     [kVK_F2] = Q_KEY_CODE_F2,
244     [kVK_F3] = Q_KEY_CODE_F3,
245     [kVK_F4] = Q_KEY_CODE_F4,
246     [kVK_F5] = Q_KEY_CODE_F5,
247     [kVK_F6] = Q_KEY_CODE_F6,
248     [kVK_F7] = Q_KEY_CODE_F7,
249     [kVK_F8] = Q_KEY_CODE_F8,
250     [kVK_F9] = Q_KEY_CODE_F9,
251     [kVK_F10] = Q_KEY_CODE_F10,
252     [kVK_F11] = Q_KEY_CODE_F11,
253     [kVK_F12] = Q_KEY_CODE_F12,
254     [kVK_F13] = Q_KEY_CODE_PRINT,
255     [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
256     [kVK_F15] = Q_KEY_CODE_PAUSE,
258     // JIS keyboards only
259     [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
260     [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
261     [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
262     [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
263     [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
265     /*
266      * The eject and volume keys can't be used here because they are handled at
267      * a lower level than what an Application can see.
268      */
271 static int cocoa_keycode_to_qemu(int keycode)
273     if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
274         error_report("(cocoa) warning unknown keycode 0x%x", keycode);
275         return 0;
276     }
277     return mac_to_qkeycode_map[keycode];
280 /* Displays an alert dialog box with the specified message */
281 static void QEMU_Alert(NSString *message)
283     NSAlert *alert;
284     alert = [NSAlert new];
285     [alert setMessageText: message];
286     [alert runModal];
289 /* Handles any errors that happen with a device transaction */
290 static void handleAnyDeviceErrors(Error * err)
292     if (err) {
293         QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
294                                       encoding: NSASCIIStringEncoding]);
295         error_free(err);
296     }
300  ------------------------------------------------------
301     QemuCocoaView
302  ------------------------------------------------------
304 @interface QemuCocoaView : NSView
306     QEMUScreen screen;
307     NSWindow *fullScreenWindow;
308     float cx,cy,cw,ch,cdx,cdy;
309     pixman_image_t *pixman_image;
310     BOOL modifiers_state[256];
311     BOOL isMouseGrabbed;
312     BOOL isFullscreen;
313     BOOL isAbsoluteEnabled;
314     BOOL isMouseDeassociated;
316 - (void) switchSurface:(pixman_image_t *)image;
317 - (void) grabMouse;
318 - (void) ungrabMouse;
319 - (void) toggleFullScreen:(id)sender;
320 - (void) handleMonitorInput:(NSEvent *)event;
321 - (bool) handleEvent:(NSEvent *)event;
322 - (bool) handleEventLocked:(NSEvent *)event;
323 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
324 /* The state surrounding mouse grabbing is potentially confusing.
325  * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
326  *   pointing device an absolute-position one?"], but is only updated on
327  *   next refresh.
328  * isMouseGrabbed tracks whether GUI events are directed to the guest;
329  *   it controls whether special keys like Cmd get sent to the guest,
330  *   and whether we capture the mouse when in non-absolute mode.
331  * isMouseDeassociated tracks whether we've told MacOSX to disassociate
332  *   the mouse and mouse cursor position by calling
333  *   CGAssociateMouseAndMouseCursorPosition(FALSE)
334  *   (which basically happens if we grab in non-absolute mode).
335  */
336 - (BOOL) isMouseGrabbed;
337 - (BOOL) isAbsoluteEnabled;
338 - (BOOL) isMouseDeassociated;
339 - (float) cdx;
340 - (float) cdy;
341 - (QEMUScreen) gscreen;
342 - (void) raiseAllKeys;
343 @end
345 QemuCocoaView *cocoaView;
347 @implementation QemuCocoaView
348 - (id)initWithFrame:(NSRect)frameRect
350     COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
352     self = [super initWithFrame:frameRect];
353     if (self) {
355         screen.width = frameRect.size.width;
356         screen.height = frameRect.size.height;
358     }
359     return self;
362 - (void) dealloc
364     COCOA_DEBUG("QemuCocoaView: dealloc\n");
366     if (pixman_image) {
367         pixman_image_unref(pixman_image);
368     }
370     [super dealloc];
373 - (BOOL) isOpaque
375     return YES;
378 - (BOOL) screenContainsPoint:(NSPoint) p
380     return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
383 /* Get location of event and convert to virtual screen coordinate */
384 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
386     NSWindow *eventWindow = [ev window];
387     // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
388     CGRect r = CGRectZero;
389     r.origin = [ev locationInWindow];
390     if (!eventWindow) {
391         if (!isFullscreen) {
392             return [[self window] convertRectFromScreen:r].origin;
393         } else {
394             CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
395             CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
396             if (stretch_video) {
397                 loc.x /= cdx;
398                 loc.y /= cdy;
399             }
400             return loc;
401         }
402     } else if ([[self window] isEqual:eventWindow]) {
403         if (!isFullscreen) {
404             return r.origin;
405         } else {
406             CGPoint loc = [self convertPoint:r.origin fromView:nil];
407             if (stretch_video) {
408                 loc.x /= cdx;
409                 loc.y /= cdy;
410             }
411             return loc;
412         }
413     } else {
414         return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
415     }
418 - (void) hideCursor
420     if (!cursor_hide) {
421         return;
422     }
423     [NSCursor hide];
426 - (void) unhideCursor
428     if (!cursor_hide) {
429         return;
430     }
431     [NSCursor unhide];
434 - (void) drawRect:(NSRect) rect
436     COCOA_DEBUG("QemuCocoaView: drawRect\n");
438     // get CoreGraphic context
439     CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
441     CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
442     CGContextSetShouldAntialias (viewContextRef, NO);
444     // draw screen bitmap directly to Core Graphics context
445     if (!pixman_image) {
446         // Draw request before any guest device has set up a framebuffer:
447         // just draw an opaque black rectangle
448         CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
449         CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
450     } else {
451         int w = pixman_image_get_width(pixman_image);
452         int h = pixman_image_get_height(pixman_image);
453         int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
454         int stride = pixman_image_get_stride(pixman_image);
455         CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
456             NULL,
457             pixman_image_get_data(pixman_image),
458             stride * h,
459             NULL
460         );
461         CGImageRef imageRef = CGImageCreate(
462             w, //width
463             h, //height
464             DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
465             bitsPerPixel, //bitsPerPixel
466             stride, //bytesPerRow
467             CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
468             kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
469             dataProviderRef, //provider
470             NULL, //decode
471             0, //interpolate
472             kCGRenderingIntentDefault //intent
473         );
474         // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
475         const NSRect *rectList;
476         NSInteger rectCount;
477         int i;
478         CGImageRef clipImageRef;
479         CGRect clipRect;
481         [self getRectsBeingDrawn:&rectList count:&rectCount];
482         for (i = 0; i < rectCount; i++) {
483             clipRect.origin.x = rectList[i].origin.x / cdx;
484             clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
485             clipRect.size.width = rectList[i].size.width / cdx;
486             clipRect.size.height = rectList[i].size.height / cdy;
487             clipImageRef = CGImageCreateWithImageInRect(
488                                                         imageRef,
489                                                         clipRect
490                                                         );
491             CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
492             CGImageRelease (clipImageRef);
493         }
494         CGImageRelease (imageRef);
495         CGDataProviderRelease(dataProviderRef);
496     }
499 - (void) setContentDimensions
501     COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
503     if (isFullscreen) {
504         cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
505         cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
507         /* stretches video, but keeps same aspect ratio */
508         if (stretch_video == true) {
509             /* use smallest stretch value - prevents clipping on sides */
510             if (MIN(cdx, cdy) == cdx) {
511                 cdy = cdx;
512             } else {
513                 cdx = cdy;
514             }
515         } else {  /* No stretching */
516             cdx = cdy = 1;
517         }
518         cw = screen.width * cdx;
519         ch = screen.height * cdy;
520         cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
521         cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
522     } else {
523         cx = 0;
524         cy = 0;
525         cw = screen.width;
526         ch = screen.height;
527         cdx = 1.0;
528         cdy = 1.0;
529     }
532 - (void) switchSurface:(pixman_image_t *)image
534     COCOA_DEBUG("QemuCocoaView: switchSurface\n");
536     int w = pixman_image_get_width(image);
537     int h = pixman_image_get_height(image);
538     /* cdx == 0 means this is our very first surface, in which case we need
539      * to recalculate the content dimensions even if it happens to be the size
540      * of the initial empty window.
541      */
542     bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
544     int oldh = screen.height;
545     if (isResize) {
546         // Resize before we trigger the redraw, or we'll redraw at the wrong size
547         COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
548         screen.width = w;
549         screen.height = h;
550         [self setContentDimensions];
551         [self setFrame:NSMakeRect(cx, cy, cw, ch)];
552     }
554     // update screenBuffer
555     if (pixman_image) {
556         pixman_image_unref(pixman_image);
557     }
559     pixman_image = image;
561     // update windows
562     if (isFullscreen) {
563         [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
564         [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
565     } else {
566         if (qemu_name)
567             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
568         [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
569     }
571     if (isResize) {
572         [normalWindow center];
573     }
576 - (void) toggleFullScreen:(id)sender
578     COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
580     if (isFullscreen) { // switch from fullscreen to desktop
581         isFullscreen = FALSE;
582         [self ungrabMouse];
583         [self setContentDimensions];
584         [fullScreenWindow close];
585         [normalWindow setContentView: self];
586         [normalWindow makeKeyAndOrderFront: self];
587         [NSMenu setMenuBarVisible:YES];
588     } else { // switch from desktop to fullscreen
589         isFullscreen = TRUE;
590         [normalWindow orderOut: nil]; /* Hide the window */
591         [self grabMouse];
592         [self setContentDimensions];
593         [NSMenu setMenuBarVisible:NO];
594         fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
595             styleMask:NSWindowStyleMaskBorderless
596             backing:NSBackingStoreBuffered
597             defer:NO];
598         [fullScreenWindow setAcceptsMouseMovedEvents: YES];
599         [fullScreenWindow setHasShadow:NO];
600         [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
601         [self setFrame:NSMakeRect(cx, cy, cw, ch)];
602         [[fullScreenWindow contentView] addSubview: self];
603         [fullScreenWindow makeKeyAndOrderFront:self];
604     }
607 - (void) toggleModifier: (int)keycode {
608     // Toggle the stored state.
609     modifiers_state[keycode] = !modifiers_state[keycode];
610     // Send a keyup or keydown depending on the state.
611     qemu_input_event_send_key_qcode(dcl.con, keycode, modifiers_state[keycode]);
614 - (void) toggleStatefulModifier: (int)keycode {
615     // Toggle the stored state.
616     modifiers_state[keycode] = !modifiers_state[keycode];
617     // Generate keydown and keyup.
618     qemu_input_event_send_key_qcode(dcl.con, keycode, true);
619     qemu_input_event_send_key_qcode(dcl.con, keycode, false);
622 // Does the work of sending input to the monitor
623 - (void) handleMonitorInput:(NSEvent *)event
625     int keysym = 0;
626     int control_key = 0;
628     // if the control key is down
629     if ([event modifierFlags] & NSEventModifierFlagControl) {
630         control_key = 1;
631     }
633     /* translates Macintosh keycodes to QEMU's keysym */
635     int without_control_translation[] = {
636         [0 ... 0xff] = 0,   // invalid key
638         [kVK_UpArrow]       = QEMU_KEY_UP,
639         [kVK_DownArrow]     = QEMU_KEY_DOWN,
640         [kVK_RightArrow]    = QEMU_KEY_RIGHT,
641         [kVK_LeftArrow]     = QEMU_KEY_LEFT,
642         [kVK_Home]          = QEMU_KEY_HOME,
643         [kVK_End]           = QEMU_KEY_END,
644         [kVK_PageUp]        = QEMU_KEY_PAGEUP,
645         [kVK_PageDown]      = QEMU_KEY_PAGEDOWN,
646         [kVK_ForwardDelete] = QEMU_KEY_DELETE,
647         [kVK_Delete]        = QEMU_KEY_BACKSPACE,
648     };
650     int with_control_translation[] = {
651         [0 ... 0xff] = 0,   // invalid key
653         [kVK_UpArrow]       = QEMU_KEY_CTRL_UP,
654         [kVK_DownArrow]     = QEMU_KEY_CTRL_DOWN,
655         [kVK_RightArrow]    = QEMU_KEY_CTRL_RIGHT,
656         [kVK_LeftArrow]     = QEMU_KEY_CTRL_LEFT,
657         [kVK_Home]          = QEMU_KEY_CTRL_HOME,
658         [kVK_End]           = QEMU_KEY_CTRL_END,
659         [kVK_PageUp]        = QEMU_KEY_CTRL_PAGEUP,
660         [kVK_PageDown]      = QEMU_KEY_CTRL_PAGEDOWN,
661     };
663     if (control_key != 0) { /* If the control key is being used */
664         if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
665             keysym = with_control_translation[[event keyCode]];
666         }
667     } else {
668         if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
669             keysym = without_control_translation[[event keyCode]];
670         }
671     }
673     // if not a key that needs translating
674     if (keysym == 0) {
675         NSString *ks = [event characters];
676         if ([ks length] > 0) {
677             keysym = [ks characterAtIndex:0];
678         }
679     }
681     if (keysym) {
682         kbd_put_keysym(keysym);
683     }
686 - (bool) handleEvent:(NSEvent *)event
688     if(!allow_events) {
689         /*
690          * Just let OSX have all events that arrive before
691          * applicationDidFinishLaunching.
692          * This avoids a deadlock on the iothread lock, which cocoa_display_init()
693          * will not drop until after the app_started_sem is posted. (In theory
694          * there should not be any such events, but OSX Catalina now emits some.)
695          */
696         return false;
697     }
698     return bool_with_iothread_lock(^{
699         return [self handleEventLocked:event];
700     });
703 - (bool) handleEventLocked:(NSEvent *)event
705     /* Return true if we handled the event, false if it should be given to OSX */
706     COCOA_DEBUG("QemuCocoaView: handleEvent\n");
707     int buttons = 0;
708     int keycode = 0;
709     bool mouse_event = false;
710     static bool switched_to_fullscreen = false;
711     // Location of event in virtual screen coordinates
712     NSPoint p = [self screenLocationOfEvent:event];
714     switch ([event type]) {
715         case NSEventTypeFlagsChanged:
716             if ([event keyCode] == 0) {
717                 // When the Cocoa keyCode is zero that means keys should be
718                 // synthesized based on the values in in the eventModifiers
719                 // bitmask.
721                 if (qemu_console_is_graphic(NULL)) {
722                     NSUInteger modifiers = [event modifierFlags];
724                     if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
725                         [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
726                     }
727                     if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
728                         [self toggleModifier:Q_KEY_CODE_SHIFT];
729                     }
730                     if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
731                         [self toggleModifier:Q_KEY_CODE_CTRL];
732                     }
733                     if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
734                         [self toggleModifier:Q_KEY_CODE_ALT];
735                     }
736                     if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
737                         [self toggleModifier:Q_KEY_CODE_META_L];
738                     }
739                 }
740             } else {
741                 keycode = cocoa_keycode_to_qemu([event keyCode]);
742             }
744             if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
745                && !isMouseGrabbed) {
746               /* Don't pass command key changes to guest unless mouse is grabbed */
747               keycode = 0;
748             }
750             if (keycode) {
751                 // emulate caps lock and num lock keydown and keyup
752                 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
753                     keycode == Q_KEY_CODE_NUM_LOCK) {
754                     [self toggleStatefulModifier:keycode];
755                 } else if (qemu_console_is_graphic(NULL)) {
756                     if (switched_to_fullscreen) {
757                         switched_to_fullscreen = false;
758                     } else {
759                         [self toggleModifier:keycode];
760                     }
761                 }
762             }
764             break;
765         case NSEventTypeKeyDown:
766             keycode = cocoa_keycode_to_qemu([event keyCode]);
768             // forward command key combos to the host UI unless the mouse is grabbed
769             if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
770                 /*
771                  * Prevent the command key from being stuck down in the guest
772                  * when using Command-F to switch to full screen mode.
773                  */
774                 if (keycode == Q_KEY_CODE_F) {
775                     switched_to_fullscreen = true;
776                 }
777                 return false;
778             }
780             // default
782             // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
783             if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
784                 NSString *keychar = [event charactersIgnoringModifiers];
785                 if ([keychar length] == 1) {
786                     char key = [keychar characterAtIndex:0];
787                     switch (key) {
789                         // enable graphic console
790                         case '1' ... '9':
791                             console_select(key - '0' - 1); /* ascii math */
792                             return true;
794                         // release the mouse grab
795                         case 'g':
796                             [self ungrabMouse];
797                             return true;
798                     }
799                 }
800             }
802             if (qemu_console_is_graphic(NULL)) {
803                 qemu_input_event_send_key_qcode(dcl.con, keycode, true);
804             } else {
805                 [self handleMonitorInput: event];
806             }
807             break;
808         case NSEventTypeKeyUp:
809             keycode = cocoa_keycode_to_qemu([event keyCode]);
811             // don't pass the guest a spurious key-up if we treated this
812             // command-key combo as a host UI action
813             if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
814                 return true;
815             }
817             if (qemu_console_is_graphic(NULL)) {
818                 qemu_input_event_send_key_qcode(dcl.con, keycode, false);
819             }
820             break;
821         case NSEventTypeMouseMoved:
822             if (isAbsoluteEnabled) {
823                 // Cursor re-entered into a window might generate events bound to screen coordinates
824                 // and `nil` window property, and in full screen mode, current window might not be
825                 // key window, where event location alone should suffice.
826                 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
827                     if (isMouseGrabbed) {
828                         [self ungrabMouse];
829                     }
830                 } else {
831                     if (!isMouseGrabbed) {
832                         [self grabMouse];
833                     }
834                 }
835             }
836             mouse_event = true;
837             break;
838         case NSEventTypeLeftMouseDown:
839             buttons |= MOUSE_EVENT_LBUTTON;
840             mouse_event = true;
841             break;
842         case NSEventTypeRightMouseDown:
843             buttons |= MOUSE_EVENT_RBUTTON;
844             mouse_event = true;
845             break;
846         case NSEventTypeOtherMouseDown:
847             buttons |= MOUSE_EVENT_MBUTTON;
848             mouse_event = true;
849             break;
850         case NSEventTypeLeftMouseDragged:
851             buttons |= MOUSE_EVENT_LBUTTON;
852             mouse_event = true;
853             break;
854         case NSEventTypeRightMouseDragged:
855             buttons |= MOUSE_EVENT_RBUTTON;
856             mouse_event = true;
857             break;
858         case NSEventTypeOtherMouseDragged:
859             buttons |= MOUSE_EVENT_MBUTTON;
860             mouse_event = true;
861             break;
862         case NSEventTypeLeftMouseUp:
863             mouse_event = true;
864             if (!isMouseGrabbed && [self screenContainsPoint:p]) {
865                 /*
866                  * In fullscreen mode, the window of cocoaView may not be the
867                  * key window, therefore the position relative to the virtual
868                  * screen alone will be sufficient.
869                  */
870                 if(isFullscreen || [[self window] isKeyWindow]) {
871                     [self grabMouse];
872                 }
873             }
874             break;
875         case NSEventTypeRightMouseUp:
876             mouse_event = true;
877             break;
878         case NSEventTypeOtherMouseUp:
879             mouse_event = true;
880             break;
881         case NSEventTypeScrollWheel:
882             /*
883              * Send wheel events to the guest regardless of window focus.
884              * This is in-line with standard Mac OS X UI behaviour.
885              */
887             /*
888              * When deltaY is zero, it means that this scrolling event was
889              * either horizontal, or so fine that it only appears in
890              * scrollingDeltaY. So we drop the event.
891              */
892             if ([event deltaY] != 0) {
893             /* Determine if this is a scroll up or scroll down event */
894                 buttons = ([event deltaY] > 0) ?
895                     INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
896                 qemu_input_queue_btn(dcl.con, buttons, true);
897                 qemu_input_event_sync();
898                 qemu_input_queue_btn(dcl.con, buttons, false);
899                 qemu_input_event_sync();
900             }
901             /*
902              * Since deltaY also reports scroll wheel events we prevent mouse
903              * movement code from executing.
904              */
905             mouse_event = false;
906             break;
907         default:
908             return false;
909     }
911     if (mouse_event) {
912         /* Don't send button events to the guest unless we've got a
913          * mouse grab or window focus. If we have neither then this event
914          * is the user clicking on the background window to activate and
915          * bring us to the front, which will be done by the sendEvent
916          * call below. We definitely don't want to pass that click through
917          * to the guest.
918          */
919         if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
920             (last_buttons != buttons)) {
921             static uint32_t bmap[INPUT_BUTTON__MAX] = {
922                 [INPUT_BUTTON_LEFT]       = MOUSE_EVENT_LBUTTON,
923                 [INPUT_BUTTON_MIDDLE]     = MOUSE_EVENT_MBUTTON,
924                 [INPUT_BUTTON_RIGHT]      = MOUSE_EVENT_RBUTTON
925             };
926             qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
927             last_buttons = buttons;
928         }
929         if (isMouseGrabbed) {
930             if (isAbsoluteEnabled) {
931                 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
932                  * The check on screenContainsPoint is to avoid sending out of range values for
933                  * clicks in the titlebar.
934                  */
935                 if ([self screenContainsPoint:p]) {
936                     qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
937                     qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
938                 }
939             } else {
940                 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
941                 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
942             }
943         } else {
944             return false;
945         }
946         qemu_input_event_sync();
947     }
948     return true;
951 - (void) grabMouse
953     COCOA_DEBUG("QemuCocoaView: grabMouse\n");
955     if (!isFullscreen) {
956         if (qemu_name)
957             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
958         else
959             [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
960     }
961     [self hideCursor];
962     if (!isAbsoluteEnabled) {
963         isMouseDeassociated = TRUE;
964         CGAssociateMouseAndMouseCursorPosition(FALSE);
965     }
966     isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
969 - (void) ungrabMouse
971     COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
973     if (!isFullscreen) {
974         if (qemu_name)
975             [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
976         else
977             [normalWindow setTitle:@"QEMU"];
978     }
979     [self unhideCursor];
980     if (isMouseDeassociated) {
981         CGAssociateMouseAndMouseCursorPosition(TRUE);
982         isMouseDeassociated = FALSE;
983     }
984     isMouseGrabbed = FALSE;
987 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
988 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
989 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
990 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
991 - (float) cdx {return cdx;}
992 - (float) cdy {return cdy;}
993 - (QEMUScreen) gscreen {return screen;}
996  * Makes the target think all down keys are being released.
997  * This prevents a stuck key problem, since we will not see
998  * key up events for those keys after we have lost focus.
999  */
1000 - (void) raiseAllKeys
1002     const int max_index = ARRAY_SIZE(modifiers_state);
1004     with_iothread_lock(^{
1005         int index;
1007         for (index = 0; index < max_index; index++) {
1008             if (modifiers_state[index]) {
1009                 modifiers_state[index] = 0;
1010                 qemu_input_event_send_key_qcode(dcl.con, index, false);
1011             }
1012         }
1013     });
1015 @end
1020  ------------------------------------------------------
1021     QemuCocoaAppController
1022  ------------------------------------------------------
1024 @interface QemuCocoaAppController : NSObject
1025                                        <NSWindowDelegate, NSApplicationDelegate>
1028 - (void)doToggleFullScreen:(id)sender;
1029 - (void)toggleFullScreen:(id)sender;
1030 - (void)showQEMUDoc:(id)sender;
1031 - (void)zoomToFit:(id) sender;
1032 - (void)displayConsole:(id)sender;
1033 - (void)pauseQEMU:(id)sender;
1034 - (void)resumeQEMU:(id)sender;
1035 - (void)displayPause;
1036 - (void)removePause;
1037 - (void)restartQEMU:(id)sender;
1038 - (void)powerDownQEMU:(id)sender;
1039 - (void)ejectDeviceMedia:(id)sender;
1040 - (void)changeDeviceMedia:(id)sender;
1041 - (BOOL)verifyQuit;
1042 - (void)openDocumentation:(NSString *)filename;
1043 - (IBAction) do_about_menu_item: (id) sender;
1044 - (void)make_about_window;
1045 - (void)adjustSpeed:(id)sender;
1046 @end
1048 @implementation QemuCocoaAppController
1049 - (id) init
1051     COCOA_DEBUG("QemuCocoaAppController: init\n");
1053     self = [super init];
1054     if (self) {
1056         // create a view and add it to the window
1057         cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1058         if(!cocoaView) {
1059             error_report("(cocoa) can't create a view");
1060             exit(1);
1061         }
1063         // create a window
1064         normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1065             styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1066             backing:NSBackingStoreBuffered defer:NO];
1067         if(!normalWindow) {
1068             error_report("(cocoa) can't create window");
1069             exit(1);
1070         }
1071         [normalWindow setAcceptsMouseMovedEvents:YES];
1072         [normalWindow setTitle:@"QEMU"];
1073         [normalWindow setContentView:cocoaView];
1074         [normalWindow makeKeyAndOrderFront:self];
1075         [normalWindow center];
1076         [normalWindow setDelegate: self];
1077         stretch_video = false;
1079         /* Used for displaying pause on the screen */
1080         pauseLabel = [NSTextField new];
1081         [pauseLabel setBezeled:YES];
1082         [pauseLabel setDrawsBackground:YES];
1083         [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1084         [pauseLabel setEditable:NO];
1085         [pauseLabel setSelectable:NO];
1086         [pauseLabel setStringValue: @"Paused"];
1087         [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1088         [pauseLabel setTextColor: [NSColor blackColor]];
1089         [pauseLabel sizeToFit];
1091         // set the supported image file types that can be opened
1092         supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1093                                  @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1094                                   @"toast", nil];
1095         [self make_about_window];
1096     }
1097     return self;
1100 - (void) dealloc
1102     COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1104     if (cocoaView)
1105         [cocoaView release];
1106     [super dealloc];
1109 - (void)applicationDidFinishLaunching: (NSNotification *) note
1111     COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1112     allow_events = true;
1113     /* Tell cocoa_display_init to proceed */
1114     qemu_sem_post(&app_started_sem);
1117 - (void)applicationWillTerminate:(NSNotification *)aNotification
1119     COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1121     qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1122     exit(0);
1125 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1127     return YES;
1130 - (NSApplicationTerminateReply)applicationShouldTerminate:
1131                                                          (NSApplication *)sender
1133     COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1134     return [self verifyQuit];
1137 /* Called when the user clicks on a window's close button */
1138 - (BOOL)windowShouldClose:(id)sender
1140     COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1141     [NSApp terminate: sender];
1142     /* If the user allows the application to quit then the call to
1143      * NSApp terminate will never return. If we get here then the user
1144      * cancelled the quit, so we should return NO to not permit the
1145      * closing of this window.
1146      */
1147     return NO;
1150 /* Called when QEMU goes into the background */
1151 - (void) applicationWillResignActive: (NSNotification *)aNotification
1153     COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1154     [cocoaView raiseAllKeys];
1157 /* We abstract the method called by the Enter Fullscreen menu item
1158  * because Mac OS 10.7 and higher disables it. This is because of the
1159  * menu item's old selector's name toggleFullScreen:
1160  */
1161 - (void) doToggleFullScreen:(id)sender
1163     [self toggleFullScreen:(id)sender];
1166 - (void)toggleFullScreen:(id)sender
1168     COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1170     [cocoaView toggleFullScreen:sender];
1173 /* Tries to find then open the specified filename */
1174 - (void) openDocumentation: (NSString *) filename
1176     /* Where to look for local files */
1177     NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1178     NSString *full_file_path;
1179     NSURL *full_file_url;
1181     /* iterate thru the possible paths until the file is found */
1182     int index;
1183     for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1184         full_file_path = [[NSBundle mainBundle] executablePath];
1185         full_file_path = [full_file_path stringByDeletingLastPathComponent];
1186         full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1187                           path_array[index], filename];
1188         full_file_url = [NSURL fileURLWithPath: full_file_path
1189                                    isDirectory: false];
1190         if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1191             return;
1192         }
1193     }
1195     /* If none of the paths opened a file */
1196     NSBeep();
1197     QEMU_Alert(@"Failed to open file");
1200 - (void)showQEMUDoc:(id)sender
1202     COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1204     [self openDocumentation: @"index.html"];
1207 /* Stretches video to fit host monitor size */
1208 - (void)zoomToFit:(id) sender
1210     stretch_video = !stretch_video;
1211     if (stretch_video == true) {
1212         [sender setState: NSControlStateValueOn];
1213     } else {
1214         [sender setState: NSControlStateValueOff];
1215     }
1218 /* Displays the console on the screen */
1219 - (void)displayConsole:(id)sender
1221     console_select([sender tag]);
1224 /* Pause the guest */
1225 - (void)pauseQEMU:(id)sender
1227     with_iothread_lock(^{
1228         qmp_stop(NULL);
1229     });
1230     [sender setEnabled: NO];
1231     [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1232     [self displayPause];
1235 /* Resume running the guest operating system */
1236 - (void)resumeQEMU:(id) sender
1238     with_iothread_lock(^{
1239         qmp_cont(NULL);
1240     });
1241     [sender setEnabled: NO];
1242     [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1243     [self removePause];
1246 /* Displays the word pause on the screen */
1247 - (void)displayPause
1249     /* Coordinates have to be calculated each time because the window can change its size */
1250     int xCoord, yCoord, width, height;
1251     xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1252     yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1253     width = [pauseLabel frame].size.width;
1254     height = [pauseLabel frame].size.height;
1255     [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1256     [cocoaView addSubview: pauseLabel];
1259 /* Removes the word pause from the screen */
1260 - (void)removePause
1262     [pauseLabel removeFromSuperview];
1265 /* Restarts QEMU */
1266 - (void)restartQEMU:(id)sender
1268     with_iothread_lock(^{
1269         qmp_system_reset(NULL);
1270     });
1273 /* Powers down QEMU */
1274 - (void)powerDownQEMU:(id)sender
1276     with_iothread_lock(^{
1277         qmp_system_powerdown(NULL);
1278     });
1281 /* Ejects the media.
1282  * Uses sender's tag to figure out the device to eject.
1283  */
1284 - (void)ejectDeviceMedia:(id)sender
1286     NSString * drive;
1287     drive = [sender representedObject];
1288     if(drive == nil) {
1289         NSBeep();
1290         QEMU_Alert(@"Failed to find drive to eject!");
1291         return;
1292     }
1294     __block Error *err = NULL;
1295     with_iothread_lock(^{
1296         qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1297                   false, NULL, false, false, &err);
1298     });
1299     handleAnyDeviceErrors(err);
1302 /* Displays a dialog box asking the user to select an image file to load.
1303  * Uses sender's represented object value to figure out which drive to use.
1304  */
1305 - (void)changeDeviceMedia:(id)sender
1307     /* Find the drive name */
1308     NSString * drive;
1309     drive = [sender representedObject];
1310     if(drive == nil) {
1311         NSBeep();
1312         QEMU_Alert(@"Could not find drive!");
1313         return;
1314     }
1316     /* Display the file open dialog */
1317     NSOpenPanel * openPanel;
1318     openPanel = [NSOpenPanel openPanel];
1319     [openPanel setCanChooseFiles: YES];
1320     [openPanel setAllowsMultipleSelection: NO];
1321     [openPanel setAllowedFileTypes: supportedImageFileTypes];
1322     if([openPanel runModal] == NSModalResponseOK) {
1323         NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1324         if(file == nil) {
1325             NSBeep();
1326             QEMU_Alert(@"Failed to convert URL to file path!");
1327             return;
1328         }
1330         __block Error *err = NULL;
1331         with_iothread_lock(^{
1332             qmp_blockdev_change_medium(true,
1333                                        [drive cStringUsingEncoding:
1334                                                   NSASCIIStringEncoding],
1335                                        false, NULL,
1336                                        [file cStringUsingEncoding:
1337                                                  NSASCIIStringEncoding],
1338                                        true, "raw",
1339                                        false, 0,
1340                                        &err);
1341         });
1342         handleAnyDeviceErrors(err);
1343     }
1346 /* Verifies if the user really wants to quit */
1347 - (BOOL)verifyQuit
1349     NSAlert *alert = [NSAlert new];
1350     [alert autorelease];
1351     [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1352     [alert addButtonWithTitle: @"Cancel"];
1353     [alert addButtonWithTitle: @"Quit"];
1354     if([alert runModal] == NSAlertSecondButtonReturn) {
1355         return YES;
1356     } else {
1357         return NO;
1358     }
1361 /* The action method for the About menu item */
1362 - (IBAction) do_about_menu_item: (id) sender
1364     [about_window makeKeyAndOrderFront: nil];
1367 /* Create and display the about dialog */
1368 - (void)make_about_window
1370     /* Make the window */
1371     int x = 0, y = 0, about_width = 400, about_height = 200;
1372     NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1373     about_window = [[NSWindow alloc] initWithContentRect:window_rect
1374                     styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1375                     NSWindowStyleMaskMiniaturizable
1376                     backing:NSBackingStoreBuffered
1377                     defer:NO];
1378     [about_window setTitle: @"About"];
1379     [about_window setReleasedWhenClosed: NO];
1380     [about_window center];
1381     NSView *superView = [about_window contentView];
1383     /* Create the dimensions of the picture */
1384     int picture_width = 80, picture_height = 80;
1385     x = (about_width - picture_width)/2;
1386     y = about_height - picture_height - 10;
1387     NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1389     /* Make the picture of QEMU */
1390     NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1391                                                      picture_rect];
1392     char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1393     NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1394     g_free(qemu_image_path_c);
1395     NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
1396     [picture_view setImage: qemu_image];
1397     [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1398     [superView addSubview: picture_view];
1400     /* Make the name label */
1401     x = 0;
1402     y = y - 25;
1403     int name_width = about_width, name_height = 20;
1404     NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1405     NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1406     [name_label setEditable: NO];
1407     [name_label setBezeled: NO];
1408     [name_label setDrawsBackground: NO];
1409     [name_label setAlignment: NSTextAlignmentCenter];
1410     NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1411                                             encoding: NSASCIIStringEncoding];
1412     qemu_name = [qemu_name lastPathComponent];
1413     [name_label setStringValue: qemu_name];
1414     [superView addSubview: name_label];
1416     /* Set the version label's attributes */
1417     x = 0;
1418     y = 50;
1419     int version_width = about_width, version_height = 20;
1420     NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1421     NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1422                                                       version_rect];
1423     [version_label setEditable: NO];
1424     [version_label setBezeled: NO];
1425     [version_label setAlignment: NSTextAlignmentCenter];
1426     [version_label setDrawsBackground: NO];
1428     /* Create the version string*/
1429     NSString *version_string;
1430     version_string = [[NSString alloc] initWithFormat:
1431     @"QEMU emulator version %s", QEMU_FULL_VERSION];
1432     [version_label setStringValue: version_string];
1433     [superView addSubview: version_label];
1435     /* Make copyright label */
1436     x = 0;
1437     y = 35;
1438     int copyright_width = about_width, copyright_height = 20;
1439     NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1440     NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1441                                                         copyright_rect];
1442     [copyright_label setEditable: NO];
1443     [copyright_label setBezeled: NO];
1444     [copyright_label setDrawsBackground: NO];
1445     [copyright_label setAlignment: NSTextAlignmentCenter];
1446     [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1447                                      QEMU_COPYRIGHT]];
1448     [superView addSubview: copyright_label];
1451 /* Used by the Speed menu items */
1452 - (void)adjustSpeed:(id)sender
1454     int throttle_pct; /* throttle percentage */
1455     NSMenu *menu;
1457     menu = [sender menu];
1458     if (menu != nil)
1459     {
1460         /* Unselect the currently selected item */
1461         for (NSMenuItem *item in [menu itemArray]) {
1462             if (item.state == NSControlStateValueOn) {
1463                 [item setState: NSControlStateValueOff];
1464                 break;
1465             }
1466         }
1467     }
1469     // check the menu item
1470     [sender setState: NSControlStateValueOn];
1472     // get the throttle percentage
1473     throttle_pct = [sender tag];
1475     with_iothread_lock(^{
1476         cpu_throttle_set(throttle_pct);
1477     });
1478     COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1481 @end
1483 @interface QemuApplication : NSApplication
1484 @end
1486 @implementation QemuApplication
1487 - (void)sendEvent:(NSEvent *)event
1489     COCOA_DEBUG("QemuApplication: sendEvent\n");
1490     if (![cocoaView handleEvent:event]) {
1491         [super sendEvent: event];
1492     }
1494 @end
1496 static void create_initial_menus(void)
1498     // Add menus
1499     NSMenu      *menu;
1500     NSMenuItem  *menuItem;
1502     [NSApp setMainMenu:[[NSMenu alloc] init]];
1504     // Application menu
1505     menu = [[NSMenu alloc] initWithTitle:@""];
1506     [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1507     [menu addItem:[NSMenuItem separatorItem]]; //Separator
1508     [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1509     menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1510     [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1511     [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1512     [menu addItem:[NSMenuItem separatorItem]]; //Separator
1513     [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1514     menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1515     [menuItem setSubmenu:menu];
1516     [[NSApp mainMenu] addItem:menuItem];
1517     [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1519     // Machine menu
1520     menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1521     [menu setAutoenablesItems: NO];
1522     [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1523     menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1524     [menu addItem: menuItem];
1525     [menuItem setEnabled: NO];
1526     [menu addItem: [NSMenuItem separatorItem]];
1527     [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1528     [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1529     menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1530     [menuItem setSubmenu:menu];
1531     [[NSApp mainMenu] addItem:menuItem];
1533     // View menu
1534     menu = [[NSMenu alloc] initWithTitle:@"View"];
1535     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1536     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1537     menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1538     [menuItem setSubmenu:menu];
1539     [[NSApp mainMenu] addItem:menuItem];
1541     // Speed menu
1542     menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1544     // Add the rest of the Speed menu items
1545     int p, percentage, throttle_pct;
1546     for (p = 10; p >= 0; p--)
1547     {
1548         percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1550         menuItem = [[[NSMenuItem alloc]
1551                    initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1553         if (percentage == 100) {
1554             [menuItem setState: NSControlStateValueOn];
1555         }
1557         /* Calculate the throttle percentage */
1558         throttle_pct = -1 * percentage + 100;
1560         [menuItem setTag: throttle_pct];
1561         [menu addItem: menuItem];
1562     }
1563     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1564     [menuItem setSubmenu:menu];
1565     [[NSApp mainMenu] addItem:menuItem];
1567     // Window menu
1568     menu = [[NSMenu alloc] initWithTitle:@"Window"];
1569     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1570     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1571     [menuItem setSubmenu:menu];
1572     [[NSApp mainMenu] addItem:menuItem];
1573     [NSApp setWindowsMenu:menu];
1575     // Help menu
1576     menu = [[NSMenu alloc] initWithTitle:@"Help"];
1577     [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1578     menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1579     [menuItem setSubmenu:menu];
1580     [[NSApp mainMenu] addItem:menuItem];
1583 /* Returns a name for a given console */
1584 static NSString * getConsoleName(QemuConsole * console)
1586     return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1589 /* Add an entry to the View menu for each console */
1590 static void add_console_menu_entries(void)
1592     NSMenu *menu;
1593     NSMenuItem *menuItem;
1594     int index = 0;
1596     menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1598     [menu addItem:[NSMenuItem separatorItem]];
1600     while (qemu_console_lookup_by_index(index) != NULL) {
1601         menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1602                                                action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1603         [menuItem setTag: index];
1604         [menu addItem: menuItem];
1605         index++;
1606     }
1609 /* Make menu items for all removable devices.
1610  * Each device is given an 'Eject' and 'Change' menu item.
1611  */
1612 static void addRemovableDevicesMenuItems(void)
1614     NSMenu *menu;
1615     NSMenuItem *menuItem;
1616     BlockInfoList *currentDevice, *pointerToFree;
1617     NSString *deviceName;
1619     currentDevice = qmp_query_block(NULL);
1620     pointerToFree = currentDevice;
1621     if(currentDevice == NULL) {
1622         NSBeep();
1623         QEMU_Alert(@"Failed to query for block devices!");
1624         return;
1625     }
1627     menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1629     // Add a separator between related groups of menu items
1630     [menu addItem:[NSMenuItem separatorItem]];
1632     // Set the attributes to the "Removable Media" menu item
1633     NSString *titleString = @"Removable Media";
1634     NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1635     NSColor *newColor = [NSColor blackColor];
1636     NSFontManager *fontManager = [NSFontManager sharedFontManager];
1637     NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1638                                           traits:NSBoldFontMask|NSItalicFontMask
1639                                           weight:0
1640                                             size:14];
1641     [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1642     [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1643     [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1645     // Add the "Removable Media" menu item
1646     menuItem = [NSMenuItem new];
1647     [menuItem setAttributedTitle: attString];
1648     [menuItem setEnabled: NO];
1649     [menu addItem: menuItem];
1651     /* Loop through all the block devices in the emulator */
1652     while (currentDevice) {
1653         deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1655         if(currentDevice->value->removable) {
1656             menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1657                                                   action: @selector(changeDeviceMedia:)
1658                                            keyEquivalent: @""];
1659             [menu addItem: menuItem];
1660             [menuItem setRepresentedObject: deviceName];
1661             [menuItem autorelease];
1663             menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1664                                                   action: @selector(ejectDeviceMedia:)
1665                                            keyEquivalent: @""];
1666             [menu addItem: menuItem];
1667             [menuItem setRepresentedObject: deviceName];
1668             [menuItem autorelease];
1669         }
1670         currentDevice = currentDevice->next;
1671     }
1672     qapi_free_BlockInfoList(pointerToFree);
1676  * The startup process for the OSX/Cocoa UI is complicated, because
1677  * OSX insists that the UI runs on the initial main thread, and so we
1678  * need to start a second thread which runs the vl.c qemu_main():
1680  * Initial thread:                    2nd thread:
1681  * in main():
1682  *  create qemu-main thread
1683  *  wait on display_init semaphore
1684  *                                    call qemu_main()
1685  *                                    ...
1686  *                                    in cocoa_display_init():
1687  *                                     post the display_init semaphore
1688  *                                     wait on app_started semaphore
1689  *  create application, menus, etc
1690  *  enter OSX run loop
1691  * in applicationDidFinishLaunching:
1692  *  post app_started semaphore
1693  *                                     tell main thread to fullscreen if needed
1694  *                                    [...]
1695  *                                    run qemu main-loop
1697  * We do this in two stages so that we don't do the creation of the
1698  * GUI application menus and so on for command line options like --help
1699  * where we want to just print text to stdout and exit immediately.
1700  */
1702 static void *call_qemu_main(void *opaque)
1704     int status;
1706     COCOA_DEBUG("Second thread: calling qemu_main()\n");
1707     status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1708     COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1709     exit(status);
1712 int main (int argc, const char * argv[]) {
1713     QemuThread thread;
1715     COCOA_DEBUG("Entered main()\n");
1716     gArgc = argc;
1717     gArgv = (char **)argv;
1719     qemu_sem_init(&display_init_sem, 0);
1720     qemu_sem_init(&app_started_sem, 0);
1722     qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1723                        NULL, QEMU_THREAD_DETACHED);
1725     COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1726     qemu_sem_wait(&display_init_sem);
1727     COCOA_DEBUG("Main thread: initializing app\n");
1729     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1731     // Pull this console process up to being a fully-fledged graphical
1732     // app with a menubar and Dock icon
1733     ProcessSerialNumber psn = { 0, kCurrentProcess };
1734     TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1736     [QemuApplication sharedApplication];
1738     create_initial_menus();
1740     /*
1741      * Create the menu entries which depend on QEMU state (for consoles
1742      * and removeable devices). These make calls back into QEMU functions,
1743      * which is OK because at this point we know that the second thread
1744      * holds the iothread lock and is synchronously waiting for us to
1745      * finish.
1746      */
1747     add_console_menu_entries();
1748     addRemovableDevicesMenuItems();
1750     // Create an Application controller
1751     QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1752     [NSApp setDelegate:appController];
1754     // Start the main event loop
1755     COCOA_DEBUG("Main thread: entering OSX run loop\n");
1756     [NSApp run];
1757     COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1759     [appController release];
1760     [pool release];
1762     return 0;
1767 #pragma mark qemu
1768 static void cocoa_update(DisplayChangeListener *dcl,
1769                          int x, int y, int w, int h)
1771     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1773     COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1775     dispatch_async(dispatch_get_main_queue(), ^{
1776         NSRect rect;
1777         if ([cocoaView cdx] == 1.0) {
1778             rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1779         } else {
1780             rect = NSMakeRect(
1781                 x * [cocoaView cdx],
1782                 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1783                 w * [cocoaView cdx],
1784                 h * [cocoaView cdy]);
1785         }
1786         [cocoaView setNeedsDisplayInRect:rect];
1787     });
1789     [pool release];
1792 static void cocoa_switch(DisplayChangeListener *dcl,
1793                          DisplaySurface *surface)
1795     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1796     pixman_image_t *image = surface->image;
1798     COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1800     // The DisplaySurface will be freed as soon as this callback returns.
1801     // We take a reference to the underlying pixman image here so it does
1802     // not disappear from under our feet; the switchSurface method will
1803     // deref the old image when it is done with it.
1804     pixman_image_ref(image);
1806     dispatch_async(dispatch_get_main_queue(), ^{
1807         [cocoaView switchSurface:image];
1808     });
1809     [pool release];
1812 static void cocoa_refresh(DisplayChangeListener *dcl)
1814     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1816     COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1817     graphic_hw_update(NULL);
1819     if (qemu_input_is_absolute()) {
1820         dispatch_async(dispatch_get_main_queue(), ^{
1821             if (![cocoaView isAbsoluteEnabled]) {
1822                 if ([cocoaView isMouseGrabbed]) {
1823                     [cocoaView ungrabMouse];
1824                 }
1825             }
1826             [cocoaView setAbsoluteEnabled:YES];
1827         });
1828     }
1829     [pool release];
1832 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1834     COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1836     /* Tell main thread to go ahead and create the app and enter the run loop */
1837     qemu_sem_post(&display_init_sem);
1838     qemu_sem_wait(&app_started_sem);
1839     COCOA_DEBUG("cocoa_display_init: app start completed\n");
1841     /* if fullscreen mode is to be used */
1842     if (opts->has_full_screen && opts->full_screen) {
1843         dispatch_async(dispatch_get_main_queue(), ^{
1844             [NSApp activateIgnoringOtherApps: YES];
1845             [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1846         });
1847     }
1848     if (opts->has_show_cursor && opts->show_cursor) {
1849         cursor_hide = 0;
1850     }
1852     // register vga output callbacks
1853     register_displaychangelistener(&dcl);
1856 static QemuDisplay qemu_display_cocoa = {
1857     .type       = DISPLAY_TYPE_COCOA,
1858     .init       = cocoa_display_init,
1861 static void register_cocoa(void)
1863     qemu_display_register(&qemu_display_cocoa);
1866 type_init(register_cocoa);