xref: /openbmc/qemu/ui/cocoa.m (revision e3a99063)
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 */
24
25#include "qemu/osdep.h"
26
27#import <Cocoa/Cocoa.h>
28#include <crt_externs.h>
29
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 "qapi/error.h"
36#include "qapi/qapi-commands-block.h"
37#include "qapi/qapi-commands-misc.h"
38#include "sysemu/blockdev.h"
39#include "qemu-version.h"
40#include "qemu/main-loop.h"
41#include "qemu/module.h"
42#include <Carbon/Carbon.h>
43#include "hw/core/cpu.h"
44
45#ifndef MAC_OS_X_VERSION_10_13
46#define MAC_OS_X_VERSION_10_13 101300
47#endif
48
49/* 10.14 deprecates NSOnState and NSOffState in favor of
50 * NSControlStateValueOn/Off, which were introduced in 10.13.
51 * Define for older versions
52 */
53#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
54#define NSControlStateValueOn NSOnState
55#define NSControlStateValueOff NSOffState
56#endif
57
58//#define DEBUG
59
60#ifdef DEBUG
61#define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
62#else
63#define COCOA_DEBUG(...)  ((void) 0)
64#endif
65
66#define cgrect(nsrect) (*(CGRect *)&(nsrect))
67
68typedef struct {
69    int width;
70    int height;
71    int bitsPerComponent;
72    int bitsPerPixel;
73} QEMUScreen;
74
75NSWindow *normalWindow, *about_window;
76static DisplayChangeListener *dcl;
77static int last_buttons;
78static int cursor_hide = 1;
79
80int gArgc;
81char **gArgv;
82bool stretch_video;
83NSTextField *pauseLabel;
84NSArray * supportedImageFileTypes;
85
86static QemuSemaphore display_init_sem;
87static QemuSemaphore app_started_sem;
88static bool allow_events;
89
90// Utility functions to run specified code block with iothread lock held
91typedef void (^CodeBlock)(void);
92typedef bool (^BoolCodeBlock)(void);
93
94static void with_iothread_lock(CodeBlock block)
95{
96    bool locked = qemu_mutex_iothread_locked();
97    if (!locked) {
98        qemu_mutex_lock_iothread();
99    }
100    block();
101    if (!locked) {
102        qemu_mutex_unlock_iothread();
103    }
104}
105
106static bool bool_with_iothread_lock(BoolCodeBlock block)
107{
108    bool locked = qemu_mutex_iothread_locked();
109    bool val;
110
111    if (!locked) {
112        qemu_mutex_lock_iothread();
113    }
114    val = block();
115    if (!locked) {
116        qemu_mutex_unlock_iothread();
117    }
118    return val;
119}
120
121// Mac to QKeyCode conversion
122const int mac_to_qkeycode_map[] = {
123    [kVK_ANSI_A] = Q_KEY_CODE_A,
124    [kVK_ANSI_B] = Q_KEY_CODE_B,
125    [kVK_ANSI_C] = Q_KEY_CODE_C,
126    [kVK_ANSI_D] = Q_KEY_CODE_D,
127    [kVK_ANSI_E] = Q_KEY_CODE_E,
128    [kVK_ANSI_F] = Q_KEY_CODE_F,
129    [kVK_ANSI_G] = Q_KEY_CODE_G,
130    [kVK_ANSI_H] = Q_KEY_CODE_H,
131    [kVK_ANSI_I] = Q_KEY_CODE_I,
132    [kVK_ANSI_J] = Q_KEY_CODE_J,
133    [kVK_ANSI_K] = Q_KEY_CODE_K,
134    [kVK_ANSI_L] = Q_KEY_CODE_L,
135    [kVK_ANSI_M] = Q_KEY_CODE_M,
136    [kVK_ANSI_N] = Q_KEY_CODE_N,
137    [kVK_ANSI_O] = Q_KEY_CODE_O,
138    [kVK_ANSI_P] = Q_KEY_CODE_P,
139    [kVK_ANSI_Q] = Q_KEY_CODE_Q,
140    [kVK_ANSI_R] = Q_KEY_CODE_R,
141    [kVK_ANSI_S] = Q_KEY_CODE_S,
142    [kVK_ANSI_T] = Q_KEY_CODE_T,
143    [kVK_ANSI_U] = Q_KEY_CODE_U,
144    [kVK_ANSI_V] = Q_KEY_CODE_V,
145    [kVK_ANSI_W] = Q_KEY_CODE_W,
146    [kVK_ANSI_X] = Q_KEY_CODE_X,
147    [kVK_ANSI_Y] = Q_KEY_CODE_Y,
148    [kVK_ANSI_Z] = Q_KEY_CODE_Z,
149
150    [kVK_ANSI_0] = Q_KEY_CODE_0,
151    [kVK_ANSI_1] = Q_KEY_CODE_1,
152    [kVK_ANSI_2] = Q_KEY_CODE_2,
153    [kVK_ANSI_3] = Q_KEY_CODE_3,
154    [kVK_ANSI_4] = Q_KEY_CODE_4,
155    [kVK_ANSI_5] = Q_KEY_CODE_5,
156    [kVK_ANSI_6] = Q_KEY_CODE_6,
157    [kVK_ANSI_7] = Q_KEY_CODE_7,
158    [kVK_ANSI_8] = Q_KEY_CODE_8,
159    [kVK_ANSI_9] = Q_KEY_CODE_9,
160
161    [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
162    [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
163    [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
164    [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
165    [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
166    [kVK_Tab] = Q_KEY_CODE_TAB,
167    [kVK_Return] = Q_KEY_CODE_RET,
168    [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
169    [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
170    [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
171    [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
172    [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
173    [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
174    [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
175    [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
176    [kVK_Shift] = Q_KEY_CODE_SHIFT,
177    [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
178    [kVK_Control] = Q_KEY_CODE_CTRL,
179    [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
180    [kVK_Option] = Q_KEY_CODE_ALT,
181    [kVK_RightOption] = Q_KEY_CODE_ALT_R,
182    [kVK_Command] = Q_KEY_CODE_META_L,
183    [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
184    [kVK_Space] = Q_KEY_CODE_SPC,
185
186    [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
187    [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
188    [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
189    [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
190    [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
191    [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
192    [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
193    [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
194    [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
195    [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
196    [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
197    [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
198    [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
199    [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
200    [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
201    [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
202    [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
203    [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
204
205    [kVK_UpArrow] = Q_KEY_CODE_UP,
206    [kVK_DownArrow] = Q_KEY_CODE_DOWN,
207    [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
208    [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
209
210    [kVK_Help] = Q_KEY_CODE_INSERT,
211    [kVK_Home] = Q_KEY_CODE_HOME,
212    [kVK_PageUp] = Q_KEY_CODE_PGUP,
213    [kVK_PageDown] = Q_KEY_CODE_PGDN,
214    [kVK_End] = Q_KEY_CODE_END,
215    [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
216
217    [kVK_Escape] = Q_KEY_CODE_ESC,
218
219    /* The Power key can't be used directly because the operating system uses
220     * it. This key can be emulated by using it in place of another key such as
221     * F1. Don't forget to disable the real key binding.
222     */
223    /* [kVK_F1] = Q_KEY_CODE_POWER, */
224
225    [kVK_F1] = Q_KEY_CODE_F1,
226    [kVK_F2] = Q_KEY_CODE_F2,
227    [kVK_F3] = Q_KEY_CODE_F3,
228    [kVK_F4] = Q_KEY_CODE_F4,
229    [kVK_F5] = Q_KEY_CODE_F5,
230    [kVK_F6] = Q_KEY_CODE_F6,
231    [kVK_F7] = Q_KEY_CODE_F7,
232    [kVK_F8] = Q_KEY_CODE_F8,
233    [kVK_F9] = Q_KEY_CODE_F9,
234    [kVK_F10] = Q_KEY_CODE_F10,
235    [kVK_F11] = Q_KEY_CODE_F11,
236    [kVK_F12] = Q_KEY_CODE_F12,
237    [kVK_F13] = Q_KEY_CODE_PRINT,
238    [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
239    [kVK_F15] = Q_KEY_CODE_PAUSE,
240
241    /*
242     * The eject and volume keys can't be used here because they are handled at
243     * a lower level than what an Application can see.
244     */
245};
246
247static int cocoa_keycode_to_qemu(int keycode)
248{
249    if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
250        fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
251        return 0;
252    }
253    return mac_to_qkeycode_map[keycode];
254}
255
256/* Displays an alert dialog box with the specified message */
257static void QEMU_Alert(NSString *message)
258{
259    NSAlert *alert;
260    alert = [NSAlert new];
261    [alert setMessageText: message];
262    [alert runModal];
263}
264
265/* Handles any errors that happen with a device transaction */
266static void handleAnyDeviceErrors(Error * err)
267{
268    if (err) {
269        QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
270                                      encoding: NSASCIIStringEncoding]);
271        error_free(err);
272    }
273}
274
275/*
276 ------------------------------------------------------
277    QemuCocoaView
278 ------------------------------------------------------
279*/
280@interface QemuCocoaView : NSView
281{
282    QEMUScreen screen;
283    NSWindow *fullScreenWindow;
284    float cx,cy,cw,ch,cdx,cdy;
285    CGDataProviderRef dataProviderRef;
286    pixman_image_t *pixman_image;
287    BOOL modifiers_state[256];
288    BOOL isMouseGrabbed;
289    BOOL isFullscreen;
290    BOOL isAbsoluteEnabled;
291    BOOL isMouseDeassociated;
292}
293- (void) switchSurface:(pixman_image_t *)image;
294- (void) grabMouse;
295- (void) ungrabMouse;
296- (void) toggleFullScreen:(id)sender;
297- (void) handleMonitorInput:(NSEvent *)event;
298- (bool) handleEvent:(NSEvent *)event;
299- (bool) handleEventLocked:(NSEvent *)event;
300- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
301/* The state surrounding mouse grabbing is potentially confusing.
302 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
303 *   pointing device an absolute-position one?"], but is only updated on
304 *   next refresh.
305 * isMouseGrabbed tracks whether GUI events are directed to the guest;
306 *   it controls whether special keys like Cmd get sent to the guest,
307 *   and whether we capture the mouse when in non-absolute mode.
308 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
309 *   the mouse and mouse cursor position by calling
310 *   CGAssociateMouseAndMouseCursorPosition(FALSE)
311 *   (which basically happens if we grab in non-absolute mode).
312 */
313- (BOOL) isMouseGrabbed;
314- (BOOL) isAbsoluteEnabled;
315- (BOOL) isMouseDeassociated;
316- (float) cdx;
317- (float) cdy;
318- (QEMUScreen) gscreen;
319- (void) raiseAllKeys;
320@end
321
322QemuCocoaView *cocoaView;
323
324@implementation QemuCocoaView
325- (id)initWithFrame:(NSRect)frameRect
326{
327    COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
328
329    self = [super initWithFrame:frameRect];
330    if (self) {
331
332        screen.bitsPerComponent = 8;
333        screen.bitsPerPixel = 32;
334        screen.width = frameRect.size.width;
335        screen.height = frameRect.size.height;
336
337    }
338    return self;
339}
340
341- (void) dealloc
342{
343    COCOA_DEBUG("QemuCocoaView: dealloc\n");
344
345    if (dataProviderRef) {
346        CGDataProviderRelease(dataProviderRef);
347        pixman_image_unref(pixman_image);
348    }
349
350    [super dealloc];
351}
352
353- (BOOL) isOpaque
354{
355    return YES;
356}
357
358- (BOOL) screenContainsPoint:(NSPoint) p
359{
360    return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
361}
362
363/* Get location of event and convert to virtual screen coordinate */
364- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
365{
366    NSWindow *eventWindow = [ev window];
367    // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
368    CGRect r = CGRectZero;
369    r.origin = [ev locationInWindow];
370    if (!eventWindow) {
371        if (!isFullscreen) {
372            return [[self window] convertRectFromScreen:r].origin;
373        } else {
374            CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
375            CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
376            if (stretch_video) {
377                loc.x /= cdx;
378                loc.y /= cdy;
379            }
380            return loc;
381        }
382    } else if ([[self window] isEqual:eventWindow]) {
383        if (!isFullscreen) {
384            return r.origin;
385        } else {
386            CGPoint loc = [self convertPoint:r.origin fromView:nil];
387            if (stretch_video) {
388                loc.x /= cdx;
389                loc.y /= cdy;
390            }
391            return loc;
392        }
393    } else {
394        return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
395    }
396}
397
398- (void) hideCursor
399{
400    if (!cursor_hide) {
401        return;
402    }
403    [NSCursor hide];
404}
405
406- (void) unhideCursor
407{
408    if (!cursor_hide) {
409        return;
410    }
411    [NSCursor unhide];
412}
413
414- (void) drawRect:(NSRect) rect
415{
416    COCOA_DEBUG("QemuCocoaView: drawRect\n");
417
418    // get CoreGraphic context
419    CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
420
421    CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
422    CGContextSetShouldAntialias (viewContextRef, NO);
423
424    // draw screen bitmap directly to Core Graphics context
425    if (!dataProviderRef) {
426        // Draw request before any guest device has set up a framebuffer:
427        // just draw an opaque black rectangle
428        CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
429        CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
430    } else {
431        CGImageRef imageRef = CGImageCreate(
432            screen.width, //width
433            screen.height, //height
434            screen.bitsPerComponent, //bitsPerComponent
435            screen.bitsPerPixel, //bitsPerPixel
436            (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
437#ifdef __LITTLE_ENDIAN__
438            CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
439            kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
440#else
441            CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
442            kCGImageAlphaNoneSkipFirst, //bitmapInfo
443#endif
444            dataProviderRef, //provider
445            NULL, //decode
446            0, //interpolate
447            kCGRenderingIntentDefault //intent
448        );
449        // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
450        const NSRect *rectList;
451        NSInteger rectCount;
452        int i;
453        CGImageRef clipImageRef;
454        CGRect clipRect;
455
456        [self getRectsBeingDrawn:&rectList count:&rectCount];
457        for (i = 0; i < rectCount; i++) {
458            clipRect.origin.x = rectList[i].origin.x / cdx;
459            clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
460            clipRect.size.width = rectList[i].size.width / cdx;
461            clipRect.size.height = rectList[i].size.height / cdy;
462            clipImageRef = CGImageCreateWithImageInRect(
463                                                        imageRef,
464                                                        clipRect
465                                                        );
466            CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
467            CGImageRelease (clipImageRef);
468        }
469        CGImageRelease (imageRef);
470    }
471}
472
473- (void) setContentDimensions
474{
475    COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
476
477    if (isFullscreen) {
478        cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
479        cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
480
481        /* stretches video, but keeps same aspect ratio */
482        if (stretch_video == true) {
483            /* use smallest stretch value - prevents clipping on sides */
484            if (MIN(cdx, cdy) == cdx) {
485                cdy = cdx;
486            } else {
487                cdx = cdy;
488            }
489        } else {  /* No stretching */
490            cdx = cdy = 1;
491        }
492        cw = screen.width * cdx;
493        ch = screen.height * cdy;
494        cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
495        cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
496    } else {
497        cx = 0;
498        cy = 0;
499        cw = screen.width;
500        ch = screen.height;
501        cdx = 1.0;
502        cdy = 1.0;
503    }
504}
505
506- (void) switchSurface:(pixman_image_t *)image
507{
508    COCOA_DEBUG("QemuCocoaView: switchSurface\n");
509
510    int w = pixman_image_get_width(image);
511    int h = pixman_image_get_height(image);
512    pixman_format_code_t image_format = pixman_image_get_format(image);
513    /* cdx == 0 means this is our very first surface, in which case we need
514     * to recalculate the content dimensions even if it happens to be the size
515     * of the initial empty window.
516     */
517    bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
518
519    int oldh = screen.height;
520    if (isResize) {
521        // Resize before we trigger the redraw, or we'll redraw at the wrong size
522        COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
523        screen.width = w;
524        screen.height = h;
525        [self setContentDimensions];
526        [self setFrame:NSMakeRect(cx, cy, cw, ch)];
527    }
528
529    // update screenBuffer
530    if (dataProviderRef) {
531        CGDataProviderRelease(dataProviderRef);
532        pixman_image_unref(pixman_image);
533    }
534
535    //sync host window color space with guests
536    screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
537    screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
538
539    pixman_image = image;
540    dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
541
542    // update windows
543    if (isFullscreen) {
544        [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
545        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
546    } else {
547        if (qemu_name)
548            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
549        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
550    }
551
552    if (isResize) {
553        [normalWindow center];
554    }
555}
556
557- (void) toggleFullScreen:(id)sender
558{
559    COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
560
561    if (isFullscreen) { // switch from fullscreen to desktop
562        isFullscreen = FALSE;
563        [self ungrabMouse];
564        [self setContentDimensions];
565        if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
566            [self exitFullScreenModeWithOptions:nil];
567        } else {
568            [fullScreenWindow close];
569            [normalWindow setContentView: self];
570            [normalWindow makeKeyAndOrderFront: self];
571            [NSMenu setMenuBarVisible:YES];
572        }
573    } else { // switch from desktop to fullscreen
574        isFullscreen = TRUE;
575        [normalWindow orderOut: nil]; /* Hide the window */
576        [self grabMouse];
577        [self setContentDimensions];
578        if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
579            [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
580                [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
581                [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
582                 nil]];
583        } else {
584            [NSMenu setMenuBarVisible:NO];
585            fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
586                styleMask:NSWindowStyleMaskBorderless
587                backing:NSBackingStoreBuffered
588                defer:NO];
589            [fullScreenWindow setAcceptsMouseMovedEvents: YES];
590            [fullScreenWindow setHasShadow:NO];
591            [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
592            [self setFrame:NSMakeRect(cx, cy, cw, ch)];
593            [[fullScreenWindow contentView] addSubview: self];
594            [fullScreenWindow makeKeyAndOrderFront:self];
595        }
596    }
597}
598
599- (void) toggleModifier: (int)keycode {
600    // Toggle the stored state.
601    modifiers_state[keycode] = !modifiers_state[keycode];
602    // Send a keyup or keydown depending on the state.
603    qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
604}
605
606- (void) toggleStatefulModifier: (int)keycode {
607    // Toggle the stored state.
608    modifiers_state[keycode] = !modifiers_state[keycode];
609    // Generate keydown and keyup.
610    qemu_input_event_send_key_qcode(dcl->con, keycode, true);
611    qemu_input_event_send_key_qcode(dcl->con, keycode, false);
612}
613
614// Does the work of sending input to the monitor
615- (void) handleMonitorInput:(NSEvent *)event
616{
617    int keysym = 0;
618    int control_key = 0;
619
620    // if the control key is down
621    if ([event modifierFlags] & NSEventModifierFlagControl) {
622        control_key = 1;
623    }
624
625    /* translates Macintosh keycodes to QEMU's keysym */
626
627    int without_control_translation[] = {
628        [0 ... 0xff] = 0,   // invalid key
629
630        [kVK_UpArrow]       = QEMU_KEY_UP,
631        [kVK_DownArrow]     = QEMU_KEY_DOWN,
632        [kVK_RightArrow]    = QEMU_KEY_RIGHT,
633        [kVK_LeftArrow]     = QEMU_KEY_LEFT,
634        [kVK_Home]          = QEMU_KEY_HOME,
635        [kVK_End]           = QEMU_KEY_END,
636        [kVK_PageUp]        = QEMU_KEY_PAGEUP,
637        [kVK_PageDown]      = QEMU_KEY_PAGEDOWN,
638        [kVK_ForwardDelete] = QEMU_KEY_DELETE,
639        [kVK_Delete]        = QEMU_KEY_BACKSPACE,
640    };
641
642    int with_control_translation[] = {
643        [0 ... 0xff] = 0,   // invalid key
644
645        [kVK_UpArrow]       = QEMU_KEY_CTRL_UP,
646        [kVK_DownArrow]     = QEMU_KEY_CTRL_DOWN,
647        [kVK_RightArrow]    = QEMU_KEY_CTRL_RIGHT,
648        [kVK_LeftArrow]     = QEMU_KEY_CTRL_LEFT,
649        [kVK_Home]          = QEMU_KEY_CTRL_HOME,
650        [kVK_End]           = QEMU_KEY_CTRL_END,
651        [kVK_PageUp]        = QEMU_KEY_CTRL_PAGEUP,
652        [kVK_PageDown]      = QEMU_KEY_CTRL_PAGEDOWN,
653    };
654
655    if (control_key != 0) { /* If the control key is being used */
656        if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
657            keysym = with_control_translation[[event keyCode]];
658        }
659    } else {
660        if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
661            keysym = without_control_translation[[event keyCode]];
662        }
663    }
664
665    // if not a key that needs translating
666    if (keysym == 0) {
667        NSString *ks = [event characters];
668        if ([ks length] > 0) {
669            keysym = [ks characterAtIndex:0];
670        }
671    }
672
673    if (keysym) {
674        kbd_put_keysym(keysym);
675    }
676}
677
678- (bool) handleEvent:(NSEvent *)event
679{
680    if(!allow_events) {
681        /*
682         * Just let OSX have all events that arrive before
683         * applicationDidFinishLaunching.
684         * This avoids a deadlock on the iothread lock, which cocoa_display_init()
685         * will not drop until after the app_started_sem is posted. (In theory
686         * there should not be any such events, but OSX Catalina now emits some.)
687         */
688        return false;
689    }
690    return bool_with_iothread_lock(^{
691        return [self handleEventLocked:event];
692    });
693}
694
695- (bool) handleEventLocked:(NSEvent *)event
696{
697    /* Return true if we handled the event, false if it should be given to OSX */
698    COCOA_DEBUG("QemuCocoaView: handleEvent\n");
699    int buttons = 0;
700    int keycode = 0;
701    bool mouse_event = false;
702    static bool switched_to_fullscreen = false;
703    // Location of event in virtual screen coordinates
704    NSPoint p = [self screenLocationOfEvent:event];
705
706    switch ([event type]) {
707        case NSEventTypeFlagsChanged:
708            if ([event keyCode] == 0) {
709                // When the Cocoa keyCode is zero that means keys should be
710                // synthesized based on the values in in the eventModifiers
711                // bitmask.
712
713                if (qemu_console_is_graphic(NULL)) {
714                    NSUInteger modifiers = [event modifierFlags];
715
716                    if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
717                        [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
718                    }
719                    if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
720                        [self toggleModifier:Q_KEY_CODE_SHIFT];
721                    }
722                    if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
723                        [self toggleModifier:Q_KEY_CODE_CTRL];
724                    }
725                    if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
726                        [self toggleModifier:Q_KEY_CODE_ALT];
727                    }
728                    if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
729                        [self toggleModifier:Q_KEY_CODE_META_L];
730                    }
731                }
732            } else {
733                keycode = cocoa_keycode_to_qemu([event keyCode]);
734            }
735
736            if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
737               && !isMouseGrabbed) {
738              /* Don't pass command key changes to guest unless mouse is grabbed */
739              keycode = 0;
740            }
741
742            if (keycode) {
743                // emulate caps lock and num lock keydown and keyup
744                if (keycode == Q_KEY_CODE_CAPS_LOCK ||
745                    keycode == Q_KEY_CODE_NUM_LOCK) {
746                    [self toggleStatefulModifier:keycode];
747                } else if (qemu_console_is_graphic(NULL)) {
748                    if (switched_to_fullscreen) {
749                        switched_to_fullscreen = false;
750                    } else {
751                        [self toggleModifier:keycode];
752                    }
753                }
754            }
755
756            break;
757        case NSEventTypeKeyDown:
758            keycode = cocoa_keycode_to_qemu([event keyCode]);
759
760            // forward command key combos to the host UI unless the mouse is grabbed
761            if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
762                /*
763                 * Prevent the command key from being stuck down in the guest
764                 * when using Command-F to switch to full screen mode.
765                 */
766                if (keycode == Q_KEY_CODE_F) {
767                    switched_to_fullscreen = true;
768                }
769                return false;
770            }
771
772            // default
773
774            // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
775            if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
776                NSString *keychar = [event charactersIgnoringModifiers];
777                if ([keychar length] == 1) {
778                    char key = [keychar characterAtIndex:0];
779                    switch (key) {
780
781                        // enable graphic console
782                        case '1' ... '9':
783                            console_select(key - '0' - 1); /* ascii math */
784                            return true;
785
786                        // release the mouse grab
787                        case 'g':
788                            [self ungrabMouse];
789                            return true;
790                    }
791                }
792            }
793
794            if (qemu_console_is_graphic(NULL)) {
795                qemu_input_event_send_key_qcode(dcl->con, keycode, true);
796            } else {
797                [self handleMonitorInput: event];
798            }
799            break;
800        case NSEventTypeKeyUp:
801            keycode = cocoa_keycode_to_qemu([event keyCode]);
802
803            // don't pass the guest a spurious key-up if we treated this
804            // command-key combo as a host UI action
805            if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
806                return true;
807            }
808
809            if (qemu_console_is_graphic(NULL)) {
810                qemu_input_event_send_key_qcode(dcl->con, keycode, false);
811            }
812            break;
813        case NSEventTypeMouseMoved:
814            if (isAbsoluteEnabled) {
815                // Cursor re-entered into a window might generate events bound to screen coordinates
816                // and `nil` window property, and in full screen mode, current window might not be
817                // key window, where event location alone should suffice.
818                if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
819                    if (isMouseGrabbed) {
820                        [self ungrabMouse];
821                    }
822                } else {
823                    if (!isMouseGrabbed) {
824                        [self grabMouse];
825                    }
826                }
827            }
828            mouse_event = true;
829            break;
830        case NSEventTypeLeftMouseDown:
831            if ([event modifierFlags] & NSEventModifierFlagCommand) {
832                buttons |= MOUSE_EVENT_RBUTTON;
833            } else {
834                buttons |= MOUSE_EVENT_LBUTTON;
835            }
836            mouse_event = true;
837            break;
838        case NSEventTypeRightMouseDown:
839            buttons |= MOUSE_EVENT_RBUTTON;
840            mouse_event = true;
841            break;
842        case NSEventTypeOtherMouseDown:
843            buttons |= MOUSE_EVENT_MBUTTON;
844            mouse_event = true;
845            break;
846        case NSEventTypeLeftMouseDragged:
847            if ([event modifierFlags] & NSEventModifierFlagCommand) {
848                buttons |= MOUSE_EVENT_RBUTTON;
849            } else {
850                buttons |= MOUSE_EVENT_LBUTTON;
851            }
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             */
886
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    }
910
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;
949}
950
951- (void) grabMouse
952{
953    COCOA_DEBUG("QemuCocoaView: grabMouse\n");
954
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:]
967}
968
969- (void) ungrabMouse
970{
971    COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
972
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;
985}
986
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;}
994
995/*
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
1001{
1002    const int max_index = ARRAY_SIZE(modifiers_state);
1003
1004    with_iothread_lock(^{
1005        int index;
1006
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    });
1014}
1015@end
1016
1017
1018
1019/*
1020 ------------------------------------------------------
1021    QemuCocoaAppController
1022 ------------------------------------------------------
1023*/
1024@interface QemuCocoaAppController : NSObject
1025                                       <NSWindowDelegate, NSApplicationDelegate>
1026{
1027}
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
1047
1048@implementation QemuCocoaAppController
1049- (id) init
1050{
1051    COCOA_DEBUG("QemuCocoaAppController: init\n");
1052
1053    self = [super init];
1054    if (self) {
1055
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            fprintf(stderr, "(cocoa) can't create a view\n");
1060            exit(1);
1061        }
1062
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            fprintf(stderr, "(cocoa) can't create window\n");
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;
1078
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];
1090
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;
1098}
1099
1100- (void) dealloc
1101{
1102    COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1103
1104    if (cocoaView)
1105        [cocoaView release];
1106    [super dealloc];
1107}
1108
1109- (void)applicationDidFinishLaunching: (NSNotification *) note
1110{
1111    COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1112    allow_events = true;
1113    /* Tell cocoa_display_init to proceed */
1114    qemu_sem_post(&app_started_sem);
1115}
1116
1117- (void)applicationWillTerminate:(NSNotification *)aNotification
1118{
1119    COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1120
1121    qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1122    exit(0);
1123}
1124
1125- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1126{
1127    return YES;
1128}
1129
1130- (NSApplicationTerminateReply)applicationShouldTerminate:
1131                                                         (NSApplication *)sender
1132{
1133    COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1134    return [self verifyQuit];
1135}
1136
1137/* Called when the user clicks on a window's close button */
1138- (BOOL)windowShouldClose:(id)sender
1139{
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;
1148}
1149
1150/* Called when QEMU goes into the background */
1151- (void) applicationWillResignActive: (NSNotification *)aNotification
1152{
1153    COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1154    [cocoaView raiseAllKeys];
1155}
1156
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
1162{
1163    [self toggleFullScreen:(id)sender];
1164}
1165
1166- (void)toggleFullScreen:(id)sender
1167{
1168    COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1169
1170    [cocoaView toggleFullScreen:sender];
1171}
1172
1173/* Tries to find then open the specified filename */
1174- (void) openDocumentation: (NSString *) filename
1175{
1176    /* Where to look for local files */
1177    NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../docs/"};
1178    NSString *full_file_path;
1179
1180    /* iterate thru the possible paths until the file is found */
1181    int index;
1182    for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1183        full_file_path = [[NSBundle mainBundle] executablePath];
1184        full_file_path = [full_file_path stringByDeletingLastPathComponent];
1185        full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1186                          path_array[index], filename];
1187        if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1188            return;
1189        }
1190    }
1191
1192    /* If none of the paths opened a file */
1193    NSBeep();
1194    QEMU_Alert(@"Failed to open file");
1195}
1196
1197- (void)showQEMUDoc:(id)sender
1198{
1199    COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1200
1201    [self openDocumentation: @"index.html"];
1202}
1203
1204/* Stretches video to fit host monitor size */
1205- (void)zoomToFit:(id) sender
1206{
1207    stretch_video = !stretch_video;
1208    if (stretch_video == true) {
1209        [sender setState: NSControlStateValueOn];
1210    } else {
1211        [sender setState: NSControlStateValueOff];
1212    }
1213}
1214
1215/* Displays the console on the screen */
1216- (void)displayConsole:(id)sender
1217{
1218    console_select([sender tag]);
1219}
1220
1221/* Pause the guest */
1222- (void)pauseQEMU:(id)sender
1223{
1224    with_iothread_lock(^{
1225        qmp_stop(NULL);
1226    });
1227    [sender setEnabled: NO];
1228    [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1229    [self displayPause];
1230}
1231
1232/* Resume running the guest operating system */
1233- (void)resumeQEMU:(id) sender
1234{
1235    with_iothread_lock(^{
1236        qmp_cont(NULL);
1237    });
1238    [sender setEnabled: NO];
1239    [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1240    [self removePause];
1241}
1242
1243/* Displays the word pause on the screen */
1244- (void)displayPause
1245{
1246    /* Coordinates have to be calculated each time because the window can change its size */
1247    int xCoord, yCoord, width, height;
1248    xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1249    yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1250    width = [pauseLabel frame].size.width;
1251    height = [pauseLabel frame].size.height;
1252    [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1253    [cocoaView addSubview: pauseLabel];
1254}
1255
1256/* Removes the word pause from the screen */
1257- (void)removePause
1258{
1259    [pauseLabel removeFromSuperview];
1260}
1261
1262/* Restarts QEMU */
1263- (void)restartQEMU:(id)sender
1264{
1265    with_iothread_lock(^{
1266        qmp_system_reset(NULL);
1267    });
1268}
1269
1270/* Powers down QEMU */
1271- (void)powerDownQEMU:(id)sender
1272{
1273    with_iothread_lock(^{
1274        qmp_system_powerdown(NULL);
1275    });
1276}
1277
1278/* Ejects the media.
1279 * Uses sender's tag to figure out the device to eject.
1280 */
1281- (void)ejectDeviceMedia:(id)sender
1282{
1283    NSString * drive;
1284    drive = [sender representedObject];
1285    if(drive == nil) {
1286        NSBeep();
1287        QEMU_Alert(@"Failed to find drive to eject!");
1288        return;
1289    }
1290
1291    __block Error *err = NULL;
1292    with_iothread_lock(^{
1293        qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1294                  false, NULL, false, false, &err);
1295    });
1296    handleAnyDeviceErrors(err);
1297}
1298
1299/* Displays a dialog box asking the user to select an image file to load.
1300 * Uses sender's represented object value to figure out which drive to use.
1301 */
1302- (void)changeDeviceMedia:(id)sender
1303{
1304    /* Find the drive name */
1305    NSString * drive;
1306    drive = [sender representedObject];
1307    if(drive == nil) {
1308        NSBeep();
1309        QEMU_Alert(@"Could not find drive!");
1310        return;
1311    }
1312
1313    /* Display the file open dialog */
1314    NSOpenPanel * openPanel;
1315    openPanel = [NSOpenPanel openPanel];
1316    [openPanel setCanChooseFiles: YES];
1317    [openPanel setAllowsMultipleSelection: NO];
1318    [openPanel setAllowedFileTypes: supportedImageFileTypes];
1319    if([openPanel runModal] == NSModalResponseOK) {
1320        NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1321        if(file == nil) {
1322            NSBeep();
1323            QEMU_Alert(@"Failed to convert URL to file path!");
1324            return;
1325        }
1326
1327        __block Error *err = NULL;
1328        with_iothread_lock(^{
1329            qmp_blockdev_change_medium(true,
1330                                       [drive cStringUsingEncoding:
1331                                                  NSASCIIStringEncoding],
1332                                       false, NULL,
1333                                       [file cStringUsingEncoding:
1334                                                 NSASCIIStringEncoding],
1335                                       true, "raw",
1336                                       false, 0,
1337                                       &err);
1338        });
1339        handleAnyDeviceErrors(err);
1340    }
1341}
1342
1343/* Verifies if the user really wants to quit */
1344- (BOOL)verifyQuit
1345{
1346    NSAlert *alert = [NSAlert new];
1347    [alert autorelease];
1348    [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1349    [alert addButtonWithTitle: @"Cancel"];
1350    [alert addButtonWithTitle: @"Quit"];
1351    if([alert runModal] == NSAlertSecondButtonReturn) {
1352        return YES;
1353    } else {
1354        return NO;
1355    }
1356}
1357
1358/* The action method for the About menu item */
1359- (IBAction) do_about_menu_item: (id) sender
1360{
1361    [about_window makeKeyAndOrderFront: nil];
1362}
1363
1364/* Create and display the about dialog */
1365- (void)make_about_window
1366{
1367    /* Make the window */
1368    int x = 0, y = 0, about_width = 400, about_height = 200;
1369    NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1370    about_window = [[NSWindow alloc] initWithContentRect:window_rect
1371                    styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1372                    NSWindowStyleMaskMiniaturizable
1373                    backing:NSBackingStoreBuffered
1374                    defer:NO];
1375    [about_window setTitle: @"About"];
1376    [about_window setReleasedWhenClosed: NO];
1377    [about_window center];
1378    NSView *superView = [about_window contentView];
1379
1380    /* Create the dimensions of the picture */
1381    int picture_width = 80, picture_height = 80;
1382    x = (about_width - picture_width)/2;
1383    y = about_height - picture_height - 10;
1384    NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1385
1386    /* Get the path to the QEMU binary */
1387    NSString *binary_name = [NSString stringWithCString: gArgv[0]
1388                                      encoding: NSASCIIStringEncoding];
1389    binary_name = [binary_name lastPathComponent];
1390    NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1391    [[NSBundle mainBundle] bundlePath], binary_name];
1392
1393    /* Make the picture of QEMU */
1394    NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1395                                                     picture_rect];
1396    NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1397                                                         program_path];
1398    [picture_view setImage: qemu_image];
1399    [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1400    [superView addSubview: picture_view];
1401
1402    /* Make the name label */
1403    x = 0;
1404    y = y - 25;
1405    int name_width = about_width, name_height = 20;
1406    NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1407    NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1408    [name_label setEditable: NO];
1409    [name_label setBezeled: NO];
1410    [name_label setDrawsBackground: NO];
1411    [name_label setAlignment: NSTextAlignmentCenter];
1412    NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1413                                            encoding: NSASCIIStringEncoding];
1414    qemu_name = [qemu_name lastPathComponent];
1415    [name_label setStringValue: qemu_name];
1416    [superView addSubview: name_label];
1417
1418    /* Set the version label's attributes */
1419    x = 0;
1420    y = 50;
1421    int version_width = about_width, version_height = 20;
1422    NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1423    NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1424                                                      version_rect];
1425    [version_label setEditable: NO];
1426    [version_label setBezeled: NO];
1427    [version_label setAlignment: NSTextAlignmentCenter];
1428    [version_label setDrawsBackground: NO];
1429
1430    /* Create the version string*/
1431    NSString *version_string;
1432    version_string = [[NSString alloc] initWithFormat:
1433    @"QEMU emulator version %s", QEMU_FULL_VERSION];
1434    [version_label setStringValue: version_string];
1435    [superView addSubview: version_label];
1436
1437    /* Make copyright label */
1438    x = 0;
1439    y = 35;
1440    int copyright_width = about_width, copyright_height = 20;
1441    NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1442    NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1443                                                        copyright_rect];
1444    [copyright_label setEditable: NO];
1445    [copyright_label setBezeled: NO];
1446    [copyright_label setDrawsBackground: NO];
1447    [copyright_label setAlignment: NSTextAlignmentCenter];
1448    [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1449                                     QEMU_COPYRIGHT]];
1450    [superView addSubview: copyright_label];
1451}
1452
1453/* Used by the Speed menu items */
1454- (void)adjustSpeed:(id)sender
1455{
1456    int throttle_pct; /* throttle percentage */
1457    NSMenu *menu;
1458
1459    menu = [sender menu];
1460    if (menu != nil)
1461    {
1462        /* Unselect the currently selected item */
1463        for (NSMenuItem *item in [menu itemArray]) {
1464            if (item.state == NSControlStateValueOn) {
1465                [item setState: NSControlStateValueOff];
1466                break;
1467            }
1468        }
1469    }
1470
1471    // check the menu item
1472    [sender setState: NSControlStateValueOn];
1473
1474    // get the throttle percentage
1475    throttle_pct = [sender tag];
1476
1477    with_iothread_lock(^{
1478        cpu_throttle_set(throttle_pct);
1479    });
1480    COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1481}
1482
1483@end
1484
1485@interface QemuApplication : NSApplication
1486@end
1487
1488@implementation QemuApplication
1489- (void)sendEvent:(NSEvent *)event
1490{
1491    COCOA_DEBUG("QemuApplication: sendEvent\n");
1492    if (![cocoaView handleEvent:event]) {
1493        [super sendEvent: event];
1494    }
1495}
1496@end
1497
1498static void create_initial_menus(void)
1499{
1500    // Add menus
1501    NSMenu      *menu;
1502    NSMenuItem  *menuItem;
1503
1504    [NSApp setMainMenu:[[NSMenu alloc] init]];
1505
1506    // Application menu
1507    menu = [[NSMenu alloc] initWithTitle:@""];
1508    [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1509    [menu addItem:[NSMenuItem separatorItem]]; //Separator
1510    [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1511    menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1512    [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1513    [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1514    [menu addItem:[NSMenuItem separatorItem]]; //Separator
1515    [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1516    menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1517    [menuItem setSubmenu:menu];
1518    [[NSApp mainMenu] addItem:menuItem];
1519    [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1520
1521    // Machine menu
1522    menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1523    [menu setAutoenablesItems: NO];
1524    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1525    menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1526    [menu addItem: menuItem];
1527    [menuItem setEnabled: NO];
1528    [menu addItem: [NSMenuItem separatorItem]];
1529    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1530    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1531    menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1532    [menuItem setSubmenu:menu];
1533    [[NSApp mainMenu] addItem:menuItem];
1534
1535    // View menu
1536    menu = [[NSMenu alloc] initWithTitle:@"View"];
1537    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1538    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1539    menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1540    [menuItem setSubmenu:menu];
1541    [[NSApp mainMenu] addItem:menuItem];
1542
1543    // Speed menu
1544    menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1545
1546    // Add the rest of the Speed menu items
1547    int p, percentage, throttle_pct;
1548    for (p = 10; p >= 0; p--)
1549    {
1550        percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1551
1552        menuItem = [[[NSMenuItem alloc]
1553                   initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1554
1555        if (percentage == 100) {
1556            [menuItem setState: NSControlStateValueOn];
1557        }
1558
1559        /* Calculate the throttle percentage */
1560        throttle_pct = -1 * percentage + 100;
1561
1562        [menuItem setTag: throttle_pct];
1563        [menu addItem: menuItem];
1564    }
1565    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1566    [menuItem setSubmenu:menu];
1567    [[NSApp mainMenu] addItem:menuItem];
1568
1569    // Window menu
1570    menu = [[NSMenu alloc] initWithTitle:@"Window"];
1571    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1572    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1573    [menuItem setSubmenu:menu];
1574    [[NSApp mainMenu] addItem:menuItem];
1575    [NSApp setWindowsMenu:menu];
1576
1577    // Help menu
1578    menu = [[NSMenu alloc] initWithTitle:@"Help"];
1579    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1580    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1581    [menuItem setSubmenu:menu];
1582    [[NSApp mainMenu] addItem:menuItem];
1583}
1584
1585/* Returns a name for a given console */
1586static NSString * getConsoleName(QemuConsole * console)
1587{
1588    return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1589}
1590
1591/* Add an entry to the View menu for each console */
1592static void add_console_menu_entries(void)
1593{
1594    NSMenu *menu;
1595    NSMenuItem *menuItem;
1596    int index = 0;
1597
1598    menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1599
1600    [menu addItem:[NSMenuItem separatorItem]];
1601
1602    while (qemu_console_lookup_by_index(index) != NULL) {
1603        menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1604                                               action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1605        [menuItem setTag: index];
1606        [menu addItem: menuItem];
1607        index++;
1608    }
1609}
1610
1611/* Make menu items for all removable devices.
1612 * Each device is given an 'Eject' and 'Change' menu item.
1613 */
1614static void addRemovableDevicesMenuItems(void)
1615{
1616    NSMenu *menu;
1617    NSMenuItem *menuItem;
1618    BlockInfoList *currentDevice, *pointerToFree;
1619    NSString *deviceName;
1620
1621    currentDevice = qmp_query_block(NULL);
1622    pointerToFree = currentDevice;
1623    if(currentDevice == NULL) {
1624        NSBeep();
1625        QEMU_Alert(@"Failed to query for block devices!");
1626        return;
1627    }
1628
1629    menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1630
1631    // Add a separator between related groups of menu items
1632    [menu addItem:[NSMenuItem separatorItem]];
1633
1634    // Set the attributes to the "Removable Media" menu item
1635    NSString *titleString = @"Removable Media";
1636    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1637    NSColor *newColor = [NSColor blackColor];
1638    NSFontManager *fontManager = [NSFontManager sharedFontManager];
1639    NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1640                                          traits:NSBoldFontMask|NSItalicFontMask
1641                                          weight:0
1642                                            size:14];
1643    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1644    [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1645    [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1646
1647    // Add the "Removable Media" menu item
1648    menuItem = [NSMenuItem new];
1649    [menuItem setAttributedTitle: attString];
1650    [menuItem setEnabled: NO];
1651    [menu addItem: menuItem];
1652
1653    /* Loop through all the block devices in the emulator */
1654    while (currentDevice) {
1655        deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1656
1657        if(currentDevice->value->removable) {
1658            menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1659                                                  action: @selector(changeDeviceMedia:)
1660                                           keyEquivalent: @""];
1661            [menu addItem: menuItem];
1662            [menuItem setRepresentedObject: deviceName];
1663            [menuItem autorelease];
1664
1665            menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1666                                                  action: @selector(ejectDeviceMedia:)
1667                                           keyEquivalent: @""];
1668            [menu addItem: menuItem];
1669            [menuItem setRepresentedObject: deviceName];
1670            [menuItem autorelease];
1671        }
1672        currentDevice = currentDevice->next;
1673    }
1674    qapi_free_BlockInfoList(pointerToFree);
1675}
1676
1677/*
1678 * The startup process for the OSX/Cocoa UI is complicated, because
1679 * OSX insists that the UI runs on the initial main thread, and so we
1680 * need to start a second thread which runs the vl.c qemu_main():
1681 *
1682 * Initial thread:                    2nd thread:
1683 * in main():
1684 *  create qemu-main thread
1685 *  wait on display_init semaphore
1686 *                                    call qemu_main()
1687 *                                    ...
1688 *                                    in cocoa_display_init():
1689 *                                     post the display_init semaphore
1690 *                                     wait on app_started semaphore
1691 *  create application, menus, etc
1692 *  enter OSX run loop
1693 * in applicationDidFinishLaunching:
1694 *  post app_started semaphore
1695 *                                     tell main thread to fullscreen if needed
1696 *                                    [...]
1697 *                                    run qemu main-loop
1698 *
1699 * We do this in two stages so that we don't do the creation of the
1700 * GUI application menus and so on for command line options like --help
1701 * where we want to just print text to stdout and exit immediately.
1702 */
1703
1704static void *call_qemu_main(void *opaque)
1705{
1706    int status;
1707
1708    COCOA_DEBUG("Second thread: calling qemu_main()\n");
1709    status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1710    COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1711    exit(status);
1712}
1713
1714int main (int argc, const char * argv[]) {
1715    QemuThread thread;
1716
1717    COCOA_DEBUG("Entered main()\n");
1718    gArgc = argc;
1719    gArgv = (char **)argv;
1720
1721    qemu_sem_init(&display_init_sem, 0);
1722    qemu_sem_init(&app_started_sem, 0);
1723
1724    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1725                       NULL, QEMU_THREAD_DETACHED);
1726
1727    COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1728    qemu_sem_wait(&display_init_sem);
1729    COCOA_DEBUG("Main thread: initializing app\n");
1730
1731    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1732
1733    // Pull this console process up to being a fully-fledged graphical
1734    // app with a menubar and Dock icon
1735    ProcessSerialNumber psn = { 0, kCurrentProcess };
1736    TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1737
1738    [QemuApplication sharedApplication];
1739
1740    create_initial_menus();
1741
1742    /*
1743     * Create the menu entries which depend on QEMU state (for consoles
1744     * and removeable devices). These make calls back into QEMU functions,
1745     * which is OK because at this point we know that the second thread
1746     * holds the iothread lock and is synchronously waiting for us to
1747     * finish.
1748     */
1749    add_console_menu_entries();
1750    addRemovableDevicesMenuItems();
1751
1752    // Create an Application controller
1753    QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1754    [NSApp setDelegate:appController];
1755
1756    // Start the main event loop
1757    COCOA_DEBUG("Main thread: entering OSX run loop\n");
1758    [NSApp run];
1759    COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1760
1761    [appController release];
1762    [pool release];
1763
1764    return 0;
1765}
1766
1767
1768
1769#pragma mark qemu
1770static void cocoa_update(DisplayChangeListener *dcl,
1771                         int x, int y, int w, int h)
1772{
1773    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1774
1775    COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1776
1777    dispatch_async(dispatch_get_main_queue(), ^{
1778        NSRect rect;
1779        if ([cocoaView cdx] == 1.0) {
1780            rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1781        } else {
1782            rect = NSMakeRect(
1783                x * [cocoaView cdx],
1784                ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1785                w * [cocoaView cdx],
1786                h * [cocoaView cdy]);
1787        }
1788        [cocoaView setNeedsDisplayInRect:rect];
1789    });
1790
1791    [pool release];
1792}
1793
1794static void cocoa_switch(DisplayChangeListener *dcl,
1795                         DisplaySurface *surface)
1796{
1797    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1798    pixman_image_t *image = surface->image;
1799
1800    COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1801
1802    // The DisplaySurface will be freed as soon as this callback returns.
1803    // We take a reference to the underlying pixman image here so it does
1804    // not disappear from under our feet; the switchSurface method will
1805    // deref the old image when it is done with it.
1806    pixman_image_ref(image);
1807
1808    dispatch_async(dispatch_get_main_queue(), ^{
1809        [cocoaView switchSurface:image];
1810    });
1811    [pool release];
1812}
1813
1814static void cocoa_refresh(DisplayChangeListener *dcl)
1815{
1816    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1817
1818    COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1819    graphic_hw_update(NULL);
1820
1821    if (qemu_input_is_absolute()) {
1822        dispatch_async(dispatch_get_main_queue(), ^{
1823            if (![cocoaView isAbsoluteEnabled]) {
1824                if ([cocoaView isMouseGrabbed]) {
1825                    [cocoaView ungrabMouse];
1826                }
1827            }
1828            [cocoaView setAbsoluteEnabled:YES];
1829        });
1830    }
1831    [pool release];
1832}
1833
1834static void cocoa_cleanup(void)
1835{
1836    COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1837    g_free(dcl);
1838}
1839
1840static const DisplayChangeListenerOps dcl_ops = {
1841    .dpy_name          = "cocoa",
1842    .dpy_gfx_update = cocoa_update,
1843    .dpy_gfx_switch = cocoa_switch,
1844    .dpy_refresh = cocoa_refresh,
1845};
1846
1847static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1848{
1849    COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1850
1851    /* Tell main thread to go ahead and create the app and enter the run loop */
1852    qemu_sem_post(&display_init_sem);
1853    qemu_sem_wait(&app_started_sem);
1854    COCOA_DEBUG("cocoa_display_init: app start completed\n");
1855
1856    /* if fullscreen mode is to be used */
1857    if (opts->has_full_screen && opts->full_screen) {
1858        dispatch_async(dispatch_get_main_queue(), ^{
1859            [NSApp activateIgnoringOtherApps: YES];
1860            [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1861        });
1862    }
1863    if (opts->has_show_cursor && opts->show_cursor) {
1864        cursor_hide = 0;
1865    }
1866
1867    dcl = g_malloc0(sizeof(DisplayChangeListener));
1868
1869    // register vga output callbacks
1870    dcl->ops = &dcl_ops;
1871    register_displaychangelistener(dcl);
1872
1873    // register cleanup function
1874    atexit(cocoa_cleanup);
1875}
1876
1877static QemuDisplay qemu_display_cocoa = {
1878    .type       = DISPLAY_TYPE_COCOA,
1879    .init       = cocoa_display_init,
1880};
1881
1882static void register_cocoa(void)
1883{
1884    qemu_display_register(&qemu_display_cocoa);
1885}
1886
1887type_init(register_cocoa);
1888