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