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