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