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