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