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