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