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