xref: /openbmc/qemu/ui/cocoa.m (revision a2c2d44a)
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/clipboard.h"
32#include "ui/console.h"
33#include "ui/input.h"
34#include "ui/kbd-state.h"
35#include "sysemu/sysemu.h"
36#include "sysemu/runstate.h"
37#include "sysemu/cpu-throttle.h"
38#include "qapi/error.h"
39#include "qapi/qapi-commands-block.h"
40#include "qapi/qapi-commands-machine.h"
41#include "qapi/qapi-commands-misc.h"
42#include "sysemu/blockdev.h"
43#include "qemu-version.h"
44#include "qemu/cutils.h"
45#include "qemu/main-loop.h"
46#include "qemu/module.h"
47#include <Carbon/Carbon.h>
48#include "hw/core/cpu.h"
49
50#ifndef MAC_OS_X_VERSION_10_13
51#define MAC_OS_X_VERSION_10_13 101300
52#endif
53
54/* 10.14 deprecates NSOnState and NSOffState in favor of
55 * NSControlStateValueOn/Off, which were introduced in 10.13.
56 * Define for older versions
57 */
58#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
59#define NSControlStateValueOn NSOnState
60#define NSControlStateValueOff NSOffState
61#endif
62
63//#define DEBUG
64
65#ifdef DEBUG
66#define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
67#else
68#define COCOA_DEBUG(...)  ((void) 0)
69#endif
70
71#define cgrect(nsrect) (*(CGRect *)&(nsrect))
72
73typedef struct {
74    int width;
75    int height;
76} QEMUScreen;
77
78static void cocoa_update(DisplayChangeListener *dcl,
79                         int x, int y, int w, int h);
80
81static void cocoa_switch(DisplayChangeListener *dcl,
82                         DisplaySurface *surface);
83
84static void cocoa_refresh(DisplayChangeListener *dcl);
85
86static NSWindow *normalWindow;
87static const DisplayChangeListenerOps dcl_ops = {
88    .dpy_name          = "cocoa",
89    .dpy_gfx_update = cocoa_update,
90    .dpy_gfx_switch = cocoa_switch,
91    .dpy_refresh = cocoa_refresh,
92};
93static DisplayChangeListener dcl = {
94    .ops = &dcl_ops,
95};
96static int last_buttons;
97static int cursor_hide = 1;
98static int left_command_key_enabled = 1;
99static bool swap_opt_cmd;
100
101static int gArgc;
102static char **gArgv;
103static bool stretch_video;
104static NSTextField *pauseLabel;
105
106static QemuSemaphore display_init_sem;
107static QemuSemaphore app_started_sem;
108static bool allow_events;
109
110static NSInteger cbchangecount = -1;
111static QemuClipboardInfo *cbinfo;
112static QemuEvent cbevent;
113
114// Utility functions to run specified code block with iothread lock held
115typedef void (^CodeBlock)(void);
116typedef bool (^BoolCodeBlock)(void);
117
118static void with_iothread_lock(CodeBlock block)
119{
120    bool locked = qemu_mutex_iothread_locked();
121    if (!locked) {
122        qemu_mutex_lock_iothread();
123    }
124    block();
125    if (!locked) {
126        qemu_mutex_unlock_iothread();
127    }
128}
129
130static bool bool_with_iothread_lock(BoolCodeBlock block)
131{
132    bool locked = qemu_mutex_iothread_locked();
133    bool val;
134
135    if (!locked) {
136        qemu_mutex_lock_iothread();
137    }
138    val = block();
139    if (!locked) {
140        qemu_mutex_unlock_iothread();
141    }
142    return val;
143}
144
145// Mac to QKeyCode conversion
146static const int mac_to_qkeycode_map[] = {
147    [kVK_ANSI_A] = Q_KEY_CODE_A,
148    [kVK_ANSI_B] = Q_KEY_CODE_B,
149    [kVK_ANSI_C] = Q_KEY_CODE_C,
150    [kVK_ANSI_D] = Q_KEY_CODE_D,
151    [kVK_ANSI_E] = Q_KEY_CODE_E,
152    [kVK_ANSI_F] = Q_KEY_CODE_F,
153    [kVK_ANSI_G] = Q_KEY_CODE_G,
154    [kVK_ANSI_H] = Q_KEY_CODE_H,
155    [kVK_ANSI_I] = Q_KEY_CODE_I,
156    [kVK_ANSI_J] = Q_KEY_CODE_J,
157    [kVK_ANSI_K] = Q_KEY_CODE_K,
158    [kVK_ANSI_L] = Q_KEY_CODE_L,
159    [kVK_ANSI_M] = Q_KEY_CODE_M,
160    [kVK_ANSI_N] = Q_KEY_CODE_N,
161    [kVK_ANSI_O] = Q_KEY_CODE_O,
162    [kVK_ANSI_P] = Q_KEY_CODE_P,
163    [kVK_ANSI_Q] = Q_KEY_CODE_Q,
164    [kVK_ANSI_R] = Q_KEY_CODE_R,
165    [kVK_ANSI_S] = Q_KEY_CODE_S,
166    [kVK_ANSI_T] = Q_KEY_CODE_T,
167    [kVK_ANSI_U] = Q_KEY_CODE_U,
168    [kVK_ANSI_V] = Q_KEY_CODE_V,
169    [kVK_ANSI_W] = Q_KEY_CODE_W,
170    [kVK_ANSI_X] = Q_KEY_CODE_X,
171    [kVK_ANSI_Y] = Q_KEY_CODE_Y,
172    [kVK_ANSI_Z] = Q_KEY_CODE_Z,
173
174    [kVK_ANSI_0] = Q_KEY_CODE_0,
175    [kVK_ANSI_1] = Q_KEY_CODE_1,
176    [kVK_ANSI_2] = Q_KEY_CODE_2,
177    [kVK_ANSI_3] = Q_KEY_CODE_3,
178    [kVK_ANSI_4] = Q_KEY_CODE_4,
179    [kVK_ANSI_5] = Q_KEY_CODE_5,
180    [kVK_ANSI_6] = Q_KEY_CODE_6,
181    [kVK_ANSI_7] = Q_KEY_CODE_7,
182    [kVK_ANSI_8] = Q_KEY_CODE_8,
183    [kVK_ANSI_9] = Q_KEY_CODE_9,
184
185    [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
186    [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
187    [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
188    [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
189    [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
190    [kVK_Tab] = Q_KEY_CODE_TAB,
191    [kVK_Return] = Q_KEY_CODE_RET,
192    [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
193    [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
194    [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
195    [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
196    [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
197    [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
198    [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
199    [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
200    [kVK_Space] = Q_KEY_CODE_SPC,
201
202    [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
203    [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
204    [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
205    [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
206    [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
207    [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
208    [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
209    [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
210    [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
211    [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
212    [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
213    [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
214    [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
215    [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
216    [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
217    [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
218    [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
219    [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
220
221    [kVK_UpArrow] = Q_KEY_CODE_UP,
222    [kVK_DownArrow] = Q_KEY_CODE_DOWN,
223    [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
224    [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
225
226    [kVK_Help] = Q_KEY_CODE_INSERT,
227    [kVK_Home] = Q_KEY_CODE_HOME,
228    [kVK_PageUp] = Q_KEY_CODE_PGUP,
229    [kVK_PageDown] = Q_KEY_CODE_PGDN,
230    [kVK_End] = Q_KEY_CODE_END,
231    [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
232
233    [kVK_Escape] = Q_KEY_CODE_ESC,
234
235    /* The Power key can't be used directly because the operating system uses
236     * it. This key can be emulated by using it in place of another key such as
237     * F1. Don't forget to disable the real key binding.
238     */
239    /* [kVK_F1] = Q_KEY_CODE_POWER, */
240
241    [kVK_F1] = Q_KEY_CODE_F1,
242    [kVK_F2] = Q_KEY_CODE_F2,
243    [kVK_F3] = Q_KEY_CODE_F3,
244    [kVK_F4] = Q_KEY_CODE_F4,
245    [kVK_F5] = Q_KEY_CODE_F5,
246    [kVK_F6] = Q_KEY_CODE_F6,
247    [kVK_F7] = Q_KEY_CODE_F7,
248    [kVK_F8] = Q_KEY_CODE_F8,
249    [kVK_F9] = Q_KEY_CODE_F9,
250    [kVK_F10] = Q_KEY_CODE_F10,
251    [kVK_F11] = Q_KEY_CODE_F11,
252    [kVK_F12] = Q_KEY_CODE_F12,
253    [kVK_F13] = Q_KEY_CODE_PRINT,
254    [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
255    [kVK_F15] = Q_KEY_CODE_PAUSE,
256
257    // JIS keyboards only
258    [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
259    [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
260    [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
261    [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
262    [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
263
264    /*
265     * The eject and volume keys can't be used here because they are handled at
266     * a lower level than what an Application can see.
267     */
268};
269
270static int cocoa_keycode_to_qemu(int keycode)
271{
272    if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
273        error_report("(cocoa) warning unknown keycode 0x%x", keycode);
274        return 0;
275    }
276    return mac_to_qkeycode_map[keycode];
277}
278
279/* Displays an alert dialog box with the specified message */
280static void QEMU_Alert(NSString *message)
281{
282    NSAlert *alert;
283    alert = [NSAlert new];
284    [alert setMessageText: message];
285    [alert runModal];
286}
287
288/* Handles any errors that happen with a device transaction */
289static void handleAnyDeviceErrors(Error * err)
290{
291    if (err) {
292        QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
293                                      encoding: NSASCIIStringEncoding]);
294        error_free(err);
295    }
296}
297
298/*
299 ------------------------------------------------------
300    QemuCocoaView
301 ------------------------------------------------------
302*/
303@interface QemuCocoaView : NSView
304{
305    QEMUScreen screen;
306    NSWindow *fullScreenWindow;
307    float cx,cy,cw,ch,cdx,cdy;
308    pixman_image_t *pixman_image;
309    QKbdState *kbd;
310    BOOL isMouseGrabbed;
311    BOOL isFullscreen;
312    BOOL isAbsoluteEnabled;
313    CFMachPortRef eventsTap;
314}
315- (void) switchSurface:(pixman_image_t *)image;
316- (void) grabMouse;
317- (void) ungrabMouse;
318- (void) toggleFullScreen:(id)sender;
319- (void) setFullGrab:(id)sender;
320- (void) handleMonitorInput:(NSEvent *)event;
321- (bool) handleEvent:(NSEvent *)event;
322- (bool) handleEventLocked:(NSEvent *)event;
323- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
324/* The state surrounding mouse grabbing is potentially confusing.
325 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
326 *   pointing device an absolute-position one?"], but is only updated on
327 *   next refresh.
328 * isMouseGrabbed tracks whether GUI events are directed to the guest;
329 *   it controls whether special keys like Cmd get sent to the guest,
330 *   and whether we capture the mouse when in non-absolute mode.
331 */
332- (BOOL) isMouseGrabbed;
333- (BOOL) isAbsoluteEnabled;
334- (float) cdx;
335- (float) cdy;
336- (QEMUScreen) gscreen;
337- (void) raiseAllKeys;
338@end
339
340QemuCocoaView *cocoaView;
341
342static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
343{
344    QemuCocoaView *cocoaView = userInfo;
345    NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
346    if ([cocoaView isMouseGrabbed] && [cocoaView handleEvent:event]) {
347        COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
348        return NULL;
349    }
350    COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
351
352    return cgEvent;
353}
354
355@implementation QemuCocoaView
356- (id)initWithFrame:(NSRect)frameRect
357{
358    COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
359
360    self = [super initWithFrame:frameRect];
361    if (self) {
362
363        screen.width = frameRect.size.width;
364        screen.height = frameRect.size.height;
365        kbd = qkbd_state_init(dcl.con);
366
367    }
368    return self;
369}
370
371- (void) dealloc
372{
373    COCOA_DEBUG("QemuCocoaView: dealloc\n");
374
375    if (pixman_image) {
376        pixman_image_unref(pixman_image);
377    }
378
379    qkbd_state_free(kbd);
380
381    if (eventsTap) {
382        CFRelease(eventsTap);
383    }
384
385    [super dealloc];
386}
387
388- (BOOL) isOpaque
389{
390    return YES;
391}
392
393- (BOOL) screenContainsPoint:(NSPoint) p
394{
395    return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
396}
397
398/* Get location of event and convert to virtual screen coordinate */
399- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
400{
401    NSWindow *eventWindow = [ev window];
402    // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
403    CGRect r = CGRectZero;
404    r.origin = [ev locationInWindow];
405    if (!eventWindow) {
406        if (!isFullscreen) {
407            return [[self window] convertRectFromScreen:r].origin;
408        } else {
409            CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
410            CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
411            if (stretch_video) {
412                loc.x /= cdx;
413                loc.y /= cdy;
414            }
415            return loc;
416        }
417    } else if ([[self window] isEqual:eventWindow]) {
418        if (!isFullscreen) {
419            return r.origin;
420        } else {
421            CGPoint loc = [self convertPoint:r.origin fromView:nil];
422            if (stretch_video) {
423                loc.x /= cdx;
424                loc.y /= cdy;
425            }
426            return loc;
427        }
428    } else {
429        return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
430    }
431}
432
433- (void) hideCursor
434{
435    if (!cursor_hide) {
436        return;
437    }
438    [NSCursor hide];
439}
440
441- (void) unhideCursor
442{
443    if (!cursor_hide) {
444        return;
445    }
446    [NSCursor unhide];
447}
448
449- (void) drawRect:(NSRect) rect
450{
451    COCOA_DEBUG("QemuCocoaView: drawRect\n");
452
453    // get CoreGraphic context
454    CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
455
456    CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
457    CGContextSetShouldAntialias (viewContextRef, NO);
458
459    // draw screen bitmap directly to Core Graphics context
460    if (!pixman_image) {
461        // Draw request before any guest device has set up a framebuffer:
462        // just draw an opaque black rectangle
463        CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
464        CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
465    } else {
466        int w = pixman_image_get_width(pixman_image);
467        int h = pixman_image_get_height(pixman_image);
468        int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
469        int stride = pixman_image_get_stride(pixman_image);
470        CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
471            NULL,
472            pixman_image_get_data(pixman_image),
473            stride * h,
474            NULL
475        );
476        CGImageRef imageRef = CGImageCreate(
477            w, //width
478            h, //height
479            DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
480            bitsPerPixel, //bitsPerPixel
481            stride, //bytesPerRow
482            CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
483            kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
484            dataProviderRef, //provider
485            NULL, //decode
486            0, //interpolate
487            kCGRenderingIntentDefault //intent
488        );
489        // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
490        const NSRect *rectList;
491        NSInteger rectCount;
492        int i;
493        CGImageRef clipImageRef;
494        CGRect clipRect;
495
496        [self getRectsBeingDrawn:&rectList count:&rectCount];
497        for (i = 0; i < rectCount; i++) {
498            clipRect.origin.x = rectList[i].origin.x / cdx;
499            clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
500            clipRect.size.width = rectList[i].size.width / cdx;
501            clipRect.size.height = rectList[i].size.height / cdy;
502            clipImageRef = CGImageCreateWithImageInRect(
503                                                        imageRef,
504                                                        clipRect
505                                                        );
506            CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
507            CGImageRelease (clipImageRef);
508        }
509        CGImageRelease (imageRef);
510        CGDataProviderRelease(dataProviderRef);
511    }
512}
513
514- (void) setContentDimensions
515{
516    COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
517
518    if (isFullscreen) {
519        cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
520        cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
521
522        /* stretches video, but keeps same aspect ratio */
523        if (stretch_video == true) {
524            /* use smallest stretch value - prevents clipping on sides */
525            if (MIN(cdx, cdy) == cdx) {
526                cdy = cdx;
527            } else {
528                cdx = cdy;
529            }
530        } else {  /* No stretching */
531            cdx = cdy = 1;
532        }
533        cw = screen.width * cdx;
534        ch = screen.height * cdy;
535        cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
536        cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
537    } else {
538        cx = 0;
539        cy = 0;
540        cw = screen.width;
541        ch = screen.height;
542        cdx = 1.0;
543        cdy = 1.0;
544    }
545}
546
547- (void) updateUIInfoLocked
548{
549    /* Must be called with the iothread lock, i.e. via updateUIInfo */
550    NSSize frameSize;
551    QemuUIInfo info;
552
553    if (!qemu_console_is_graphic(dcl.con)) {
554        return;
555    }
556
557    if ([self window]) {
558        NSDictionary *description = [[[self window] screen] deviceDescription];
559        CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
560        NSSize screenSize = [[[self window] screen] frame].size;
561        CGSize screenPhysicalSize = CGDisplayScreenSize(display);
562
563        frameSize = isFullscreen ? screenSize : [self frame].size;
564        info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
565        info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
566    } else {
567        frameSize = [self frame].size;
568        info.width_mm = 0;
569        info.height_mm = 0;
570    }
571
572    info.xoff = 0;
573    info.yoff = 0;
574    info.width = frameSize.width;
575    info.height = frameSize.height;
576
577    dpy_set_ui_info(dcl.con, &info, TRUE);
578}
579
580- (void) updateUIInfo
581{
582    if (!allow_events) {
583        /*
584         * Don't try to tell QEMU about UI information in the application
585         * startup phase -- we haven't yet registered dcl with the QEMU UI
586         * layer, and also trying to take the iothread lock would deadlock.
587         * When cocoa_display_init() does register the dcl, the UI layer
588         * will call cocoa_switch(), which will call updateUIInfo, so
589         * we don't lose any information here.
590         */
591        return;
592    }
593
594    with_iothread_lock(^{
595        [self updateUIInfoLocked];
596    });
597}
598
599- (void)viewDidMoveToWindow
600{
601    [self updateUIInfo];
602}
603
604- (void) switchSurface:(pixman_image_t *)image
605{
606    COCOA_DEBUG("QemuCocoaView: switchSurface\n");
607
608    int w = pixman_image_get_width(image);
609    int h = pixman_image_get_height(image);
610    /* cdx == 0 means this is our very first surface, in which case we need
611     * to recalculate the content dimensions even if it happens to be the size
612     * of the initial empty window.
613     */
614    bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
615
616    int oldh = screen.height;
617    if (isResize) {
618        // Resize before we trigger the redraw, or we'll redraw at the wrong size
619        COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
620        screen.width = w;
621        screen.height = h;
622        [self setContentDimensions];
623        [self setFrame:NSMakeRect(cx, cy, cw, ch)];
624    }
625
626    // update screenBuffer
627    if (pixman_image) {
628        pixman_image_unref(pixman_image);
629    }
630
631    pixman_image = image;
632
633    // update windows
634    if (isFullscreen) {
635        [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
636        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
637    } else {
638        if (qemu_name)
639            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
640        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
641    }
642
643    if (isResize) {
644        [normalWindow center];
645    }
646}
647
648- (void) toggleFullScreen:(id)sender
649{
650    COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
651
652    if (isFullscreen) { // switch from fullscreen to desktop
653        isFullscreen = FALSE;
654        [self ungrabMouse];
655        [self setContentDimensions];
656        [fullScreenWindow close];
657        [normalWindow setContentView: self];
658        [normalWindow makeKeyAndOrderFront: self];
659        [NSMenu setMenuBarVisible:YES];
660    } else { // switch from desktop to fullscreen
661        isFullscreen = TRUE;
662        [normalWindow orderOut: nil]; /* Hide the window */
663        [self grabMouse];
664        [self setContentDimensions];
665        [NSMenu setMenuBarVisible:NO];
666        fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
667            styleMask:NSWindowStyleMaskBorderless
668            backing:NSBackingStoreBuffered
669            defer:NO];
670        [fullScreenWindow setAcceptsMouseMovedEvents: YES];
671        [fullScreenWindow setHasShadow:NO];
672        [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
673        [self setFrame:NSMakeRect(cx, cy, cw, ch)];
674        [[fullScreenWindow contentView] addSubview: self];
675        [fullScreenWindow makeKeyAndOrderFront:self];
676    }
677}
678
679- (void) setFullGrab:(id)sender
680{
681    COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
682
683    CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
684    eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
685                                 mask, handleTapEvent, self);
686    if (!eventsTap) {
687        warn_report("Could not create event tap, system key combos will not be captured.\n");
688        return;
689    } else {
690        COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
691    }
692
693    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
694    if (!runLoop) {
695        warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
696        return;
697    }
698
699    CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
700    if (!tapEventsSrc ) {
701        warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
702        return;
703    }
704
705    CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
706    CFRelease(tapEventsSrc);
707}
708
709- (void) toggleKey: (int)keycode {
710    qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
711}
712
713// Does the work of sending input to the monitor
714- (void) handleMonitorInput:(NSEvent *)event
715{
716    int keysym = 0;
717    int control_key = 0;
718
719    // if the control key is down
720    if ([event modifierFlags] & NSEventModifierFlagControl) {
721        control_key = 1;
722    }
723
724    /* translates Macintosh keycodes to QEMU's keysym */
725
726    static const int without_control_translation[] = {
727        [0 ... 0xff] = 0,   // invalid key
728
729        [kVK_UpArrow]       = QEMU_KEY_UP,
730        [kVK_DownArrow]     = QEMU_KEY_DOWN,
731        [kVK_RightArrow]    = QEMU_KEY_RIGHT,
732        [kVK_LeftArrow]     = QEMU_KEY_LEFT,
733        [kVK_Home]          = QEMU_KEY_HOME,
734        [kVK_End]           = QEMU_KEY_END,
735        [kVK_PageUp]        = QEMU_KEY_PAGEUP,
736        [kVK_PageDown]      = QEMU_KEY_PAGEDOWN,
737        [kVK_ForwardDelete] = QEMU_KEY_DELETE,
738        [kVK_Delete]        = QEMU_KEY_BACKSPACE,
739    };
740
741    static const int with_control_translation[] = {
742        [0 ... 0xff] = 0,   // invalid key
743
744        [kVK_UpArrow]       = QEMU_KEY_CTRL_UP,
745        [kVK_DownArrow]     = QEMU_KEY_CTRL_DOWN,
746        [kVK_RightArrow]    = QEMU_KEY_CTRL_RIGHT,
747        [kVK_LeftArrow]     = QEMU_KEY_CTRL_LEFT,
748        [kVK_Home]          = QEMU_KEY_CTRL_HOME,
749        [kVK_End]           = QEMU_KEY_CTRL_END,
750        [kVK_PageUp]        = QEMU_KEY_CTRL_PAGEUP,
751        [kVK_PageDown]      = QEMU_KEY_CTRL_PAGEDOWN,
752    };
753
754    if (control_key != 0) { /* If the control key is being used */
755        if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
756            keysym = with_control_translation[[event keyCode]];
757        }
758    } else {
759        if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
760            keysym = without_control_translation[[event keyCode]];
761        }
762    }
763
764    // if not a key that needs translating
765    if (keysym == 0) {
766        NSString *ks = [event characters];
767        if ([ks length] > 0) {
768            keysym = [ks characterAtIndex:0];
769        }
770    }
771
772    if (keysym) {
773        kbd_put_keysym(keysym);
774    }
775}
776
777- (bool) handleEvent:(NSEvent *)event
778{
779    if(!allow_events) {
780        /*
781         * Just let OSX have all events that arrive before
782         * applicationDidFinishLaunching.
783         * This avoids a deadlock on the iothread lock, which cocoa_display_init()
784         * will not drop until after the app_started_sem is posted. (In theory
785         * there should not be any such events, but OSX Catalina now emits some.)
786         */
787        return false;
788    }
789    return bool_with_iothread_lock(^{
790        return [self handleEventLocked:event];
791    });
792}
793
794- (bool) handleEventLocked:(NSEvent *)event
795{
796    /* Return true if we handled the event, false if it should be given to OSX */
797    COCOA_DEBUG("QemuCocoaView: handleEvent\n");
798    int buttons = 0;
799    int keycode = 0;
800    bool mouse_event = false;
801    static bool switched_to_fullscreen = false;
802    // Location of event in virtual screen coordinates
803    NSPoint p = [self screenLocationOfEvent:event];
804    NSUInteger modifiers = [event modifierFlags];
805
806    /*
807     * Check -[NSEvent modifierFlags] here.
808     *
809     * There is a NSEventType for an event notifying the change of
810     * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
811     * are performed for any events because a modifier state may change while
812     * the application is inactive (i.e. no events fire) and we don't want to
813     * wait for another modifier state change to detect such a change.
814     *
815     * NSEventModifierFlagCapsLock requires a special treatment. The other flags
816     * are handled in similar manners.
817     *
818     * NSEventModifierFlagCapsLock
819     * ---------------------------
820     *
821     * If CapsLock state is changed, "up" and "down" events will be fired in
822     * sequence, effectively updates CapsLock state on the guest.
823     *
824     * The other flags
825     * ---------------
826     *
827     * If a flag is not set, fire "up" events for all keys which correspond to
828     * the flag. Note that "down" events are not fired here because the flags
829     * checked here do not tell what exact keys are down.
830     *
831     * If one of the keys corresponding to a flag is down, we rely on
832     * -[NSEvent keyCode] of an event whose -[NSEvent type] is
833     * NSEventTypeFlagsChanged to know the exact key which is down, which has
834     * the following two downsides:
835     * - It does not work when the application is inactive as described above.
836     * - It malfactions *after* the modifier state is changed while the
837     *   application is inactive. It is because -[NSEvent keyCode] does not tell
838     *   if the key is up or down, and requires to infer the current state from
839     *   the previous state. It is still possible to fix such a malfanction by
840     *   completely leaving your hands from the keyboard, which hopefully makes
841     *   this implementation usable enough.
842     */
843    if (!!(modifiers & NSEventModifierFlagCapsLock) !=
844        qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
845        qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
846        qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
847    }
848
849    if (!(modifiers & NSEventModifierFlagShift)) {
850        qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
851        qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
852    }
853    if (!(modifiers & NSEventModifierFlagControl)) {
854        qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
855        qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
856    }
857    if (!(modifiers & NSEventModifierFlagOption)) {
858        if (swap_opt_cmd) {
859            qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
860            qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
861        } else {
862            qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
863            qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
864        }
865    }
866    if (!(modifiers & NSEventModifierFlagCommand)) {
867        if (swap_opt_cmd) {
868            qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
869            qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
870        } else {
871            qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
872            qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
873        }
874    }
875
876    switch ([event type]) {
877        case NSEventTypeFlagsChanged:
878            switch ([event keyCode]) {
879                case kVK_Shift:
880                    if (!!(modifiers & NSEventModifierFlagShift)) {
881                        [self toggleKey:Q_KEY_CODE_SHIFT];
882                    }
883                    break;
884
885                case kVK_RightShift:
886                    if (!!(modifiers & NSEventModifierFlagShift)) {
887                        [self toggleKey:Q_KEY_CODE_SHIFT_R];
888                    }
889                    break;
890
891                case kVK_Control:
892                    if (!!(modifiers & NSEventModifierFlagControl)) {
893                        [self toggleKey:Q_KEY_CODE_CTRL];
894                    }
895                    break;
896
897                case kVK_RightControl:
898                    if (!!(modifiers & NSEventModifierFlagControl)) {
899                        [self toggleKey:Q_KEY_CODE_CTRL_R];
900                    }
901                    break;
902
903                case kVK_Option:
904                    if (!!(modifiers & NSEventModifierFlagOption)) {
905                        if (swap_opt_cmd) {
906                            [self toggleKey:Q_KEY_CODE_META_L];
907                        } else {
908                            [self toggleKey:Q_KEY_CODE_ALT];
909                        }
910                    }
911                    break;
912
913                case kVK_RightOption:
914                    if (!!(modifiers & NSEventModifierFlagOption)) {
915                        if (swap_opt_cmd) {
916                            [self toggleKey:Q_KEY_CODE_META_R];
917                        } else {
918                            [self toggleKey:Q_KEY_CODE_ALT_R];
919                        }
920                    }
921                    break;
922
923                /* Don't pass command key changes to guest unless mouse is grabbed */
924                case kVK_Command:
925                    if (isMouseGrabbed &&
926                        !!(modifiers & NSEventModifierFlagCommand)) {
927                        if (swap_opt_cmd) {
928                            [self toggleKey:Q_KEY_CODE_ALT];
929                        } else {
930                            [self toggleKey:Q_KEY_CODE_META_L];
931                        }
932                    }
933                    break;
934
935                case kVK_RightCommand:
936                    if (isMouseGrabbed &&
937                        !!(modifiers & NSEventModifierFlagCommand)) {
938                        if (swap_opt_cmd) {
939                            [self toggleKey:Q_KEY_CODE_ALT_R];
940                        } else {
941                            [self toggleKey:Q_KEY_CODE_META_R];
942                        }
943                    }
944                    break;
945            }
946            break;
947        case NSEventTypeKeyDown:
948            keycode = cocoa_keycode_to_qemu([event keyCode]);
949
950            // forward command key combos to the host UI unless the mouse is grabbed
951            if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
952                /*
953                 * Prevent the command key from being stuck down in the guest
954                 * when using Command-F to switch to full screen mode.
955                 */
956                if (keycode == Q_KEY_CODE_F) {
957                    switched_to_fullscreen = true;
958                }
959                return false;
960            }
961
962            // default
963
964            // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
965            if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
966                NSString *keychar = [event charactersIgnoringModifiers];
967                if ([keychar length] == 1) {
968                    char key = [keychar characterAtIndex:0];
969                    switch (key) {
970
971                        // enable graphic console
972                        case '1' ... '9':
973                            console_select(key - '0' - 1); /* ascii math */
974                            return true;
975
976                        // release the mouse grab
977                        case 'g':
978                            [self ungrabMouse];
979                            return true;
980                    }
981                }
982            }
983
984            if (qemu_console_is_graphic(NULL)) {
985                qkbd_state_key_event(kbd, keycode, true);
986            } else {
987                [self handleMonitorInput: event];
988            }
989            break;
990        case NSEventTypeKeyUp:
991            keycode = cocoa_keycode_to_qemu([event keyCode]);
992
993            // don't pass the guest a spurious key-up if we treated this
994            // command-key combo as a host UI action
995            if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
996                return true;
997            }
998
999            if (qemu_console_is_graphic(NULL)) {
1000                qkbd_state_key_event(kbd, keycode, false);
1001            }
1002            break;
1003        case NSEventTypeMouseMoved:
1004            if (isAbsoluteEnabled) {
1005                // Cursor re-entered into a window might generate events bound to screen coordinates
1006                // and `nil` window property, and in full screen mode, current window might not be
1007                // key window, where event location alone should suffice.
1008                if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
1009                    if (isMouseGrabbed) {
1010                        [self ungrabMouse];
1011                    }
1012                } else {
1013                    if (!isMouseGrabbed) {
1014                        [self grabMouse];
1015                    }
1016                }
1017            }
1018            mouse_event = true;
1019            break;
1020        case NSEventTypeLeftMouseDown:
1021            buttons |= MOUSE_EVENT_LBUTTON;
1022            mouse_event = true;
1023            break;
1024        case NSEventTypeRightMouseDown:
1025            buttons |= MOUSE_EVENT_RBUTTON;
1026            mouse_event = true;
1027            break;
1028        case NSEventTypeOtherMouseDown:
1029            buttons |= MOUSE_EVENT_MBUTTON;
1030            mouse_event = true;
1031            break;
1032        case NSEventTypeLeftMouseDragged:
1033            buttons |= MOUSE_EVENT_LBUTTON;
1034            mouse_event = true;
1035            break;
1036        case NSEventTypeRightMouseDragged:
1037            buttons |= MOUSE_EVENT_RBUTTON;
1038            mouse_event = true;
1039            break;
1040        case NSEventTypeOtherMouseDragged:
1041            buttons |= MOUSE_EVENT_MBUTTON;
1042            mouse_event = true;
1043            break;
1044        case NSEventTypeLeftMouseUp:
1045            mouse_event = true;
1046            if (!isMouseGrabbed && [self screenContainsPoint:p]) {
1047                /*
1048                 * In fullscreen mode, the window of cocoaView may not be the
1049                 * key window, therefore the position relative to the virtual
1050                 * screen alone will be sufficient.
1051                 */
1052                if(isFullscreen || [[self window] isKeyWindow]) {
1053                    [self grabMouse];
1054                }
1055            }
1056            break;
1057        case NSEventTypeRightMouseUp:
1058            mouse_event = true;
1059            break;
1060        case NSEventTypeOtherMouseUp:
1061            mouse_event = true;
1062            break;
1063        case NSEventTypeScrollWheel:
1064            /*
1065             * Send wheel events to the guest regardless of window focus.
1066             * This is in-line with standard Mac OS X UI behaviour.
1067             */
1068
1069            /*
1070             * We shouldn't have got a scroll event when deltaY and delta Y
1071             * are zero, hence no harm in dropping the event
1072             */
1073            if ([event deltaY] != 0 || [event deltaX] != 0) {
1074            /* Determine if this is a scroll up or scroll down event */
1075                if ([event deltaY] != 0) {
1076                  buttons = ([event deltaY] > 0) ?
1077                    INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1078                } else if ([event deltaX] != 0) {
1079                  buttons = ([event deltaX] > 0) ?
1080                    INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1081                }
1082
1083                qemu_input_queue_btn(dcl.con, buttons, true);
1084                qemu_input_event_sync();
1085                qemu_input_queue_btn(dcl.con, buttons, false);
1086                qemu_input_event_sync();
1087            }
1088
1089            /*
1090             * Since deltaX/deltaY also report scroll wheel events we prevent mouse
1091             * movement code from executing.
1092             */
1093            mouse_event = false;
1094            break;
1095        default:
1096            return false;
1097    }
1098
1099    if (mouse_event) {
1100        /* Don't send button events to the guest unless we've got a
1101         * mouse grab or window focus. If we have neither then this event
1102         * is the user clicking on the background window to activate and
1103         * bring us to the front, which will be done by the sendEvent
1104         * call below. We definitely don't want to pass that click through
1105         * to the guest.
1106         */
1107        if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1108            (last_buttons != buttons)) {
1109            static uint32_t bmap[INPUT_BUTTON__MAX] = {
1110                [INPUT_BUTTON_LEFT]       = MOUSE_EVENT_LBUTTON,
1111                [INPUT_BUTTON_MIDDLE]     = MOUSE_EVENT_MBUTTON,
1112                [INPUT_BUTTON_RIGHT]      = MOUSE_EVENT_RBUTTON
1113            };
1114            qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1115            last_buttons = buttons;
1116        }
1117        if (isMouseGrabbed) {
1118            if (isAbsoluteEnabled) {
1119                /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1120                 * The check on screenContainsPoint is to avoid sending out of range values for
1121                 * clicks in the titlebar.
1122                 */
1123                if ([self screenContainsPoint:p]) {
1124                    qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1125                    qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1126                }
1127            } else {
1128                qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1129                qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1130            }
1131        } else {
1132            return false;
1133        }
1134        qemu_input_event_sync();
1135    }
1136    return true;
1137}
1138
1139- (void) grabMouse
1140{
1141    COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1142
1143    if (!isFullscreen) {
1144        if (qemu_name)
1145            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1146        else
1147            [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1148    }
1149    [self hideCursor];
1150    CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1151    isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1152}
1153
1154- (void) ungrabMouse
1155{
1156    COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1157
1158    if (!isFullscreen) {
1159        if (qemu_name)
1160            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1161        else
1162            [normalWindow setTitle:@"QEMU"];
1163    }
1164    [self unhideCursor];
1165    CGAssociateMouseAndMouseCursorPosition(TRUE);
1166    isMouseGrabbed = FALSE;
1167}
1168
1169- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1170    isAbsoluteEnabled = tIsAbsoluteEnabled;
1171    if (isMouseGrabbed) {
1172        CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1173    }
1174}
1175- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1176- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1177- (float) cdx {return cdx;}
1178- (float) cdy {return cdy;}
1179- (QEMUScreen) gscreen {return screen;}
1180
1181/*
1182 * Makes the target think all down keys are being released.
1183 * This prevents a stuck key problem, since we will not see
1184 * key up events for those keys after we have lost focus.
1185 */
1186- (void) raiseAllKeys
1187{
1188    with_iothread_lock(^{
1189        qkbd_state_lift_all_keys(kbd);
1190    });
1191}
1192@end
1193
1194
1195
1196/*
1197 ------------------------------------------------------
1198    QemuCocoaAppController
1199 ------------------------------------------------------
1200*/
1201@interface QemuCocoaAppController : NSObject
1202                                       <NSWindowDelegate, NSApplicationDelegate>
1203{
1204}
1205- (void)doToggleFullScreen:(id)sender;
1206- (void)toggleFullScreen:(id)sender;
1207- (void)showQEMUDoc:(id)sender;
1208- (void)zoomToFit:(id) sender;
1209- (void)displayConsole:(id)sender;
1210- (void)pauseQEMU:(id)sender;
1211- (void)resumeQEMU:(id)sender;
1212- (void)displayPause;
1213- (void)removePause;
1214- (void)restartQEMU:(id)sender;
1215- (void)powerDownQEMU:(id)sender;
1216- (void)ejectDeviceMedia:(id)sender;
1217- (void)changeDeviceMedia:(id)sender;
1218- (BOOL)verifyQuit;
1219- (void)openDocumentation:(NSString *)filename;
1220- (IBAction) do_about_menu_item: (id) sender;
1221- (void)adjustSpeed:(id)sender;
1222@end
1223
1224@implementation QemuCocoaAppController
1225- (id) init
1226{
1227    COCOA_DEBUG("QemuCocoaAppController: init\n");
1228
1229    self = [super init];
1230    if (self) {
1231
1232        // create a view and add it to the window
1233        cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1234        if(!cocoaView) {
1235            error_report("(cocoa) can't create a view");
1236            exit(1);
1237        }
1238
1239        // create a window
1240        normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1241            styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1242            backing:NSBackingStoreBuffered defer:NO];
1243        if(!normalWindow) {
1244            error_report("(cocoa) can't create window");
1245            exit(1);
1246        }
1247        [normalWindow setAcceptsMouseMovedEvents:YES];
1248        [normalWindow setTitle:@"QEMU"];
1249        [normalWindow setContentView:cocoaView];
1250        [normalWindow makeKeyAndOrderFront:self];
1251        [normalWindow center];
1252        [normalWindow setDelegate: self];
1253        stretch_video = false;
1254
1255        /* Used for displaying pause on the screen */
1256        pauseLabel = [NSTextField new];
1257        [pauseLabel setBezeled:YES];
1258        [pauseLabel setDrawsBackground:YES];
1259        [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1260        [pauseLabel setEditable:NO];
1261        [pauseLabel setSelectable:NO];
1262        [pauseLabel setStringValue: @"Paused"];
1263        [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1264        [pauseLabel setTextColor: [NSColor blackColor]];
1265        [pauseLabel sizeToFit];
1266    }
1267    return self;
1268}
1269
1270- (void) dealloc
1271{
1272    COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1273
1274    if (cocoaView)
1275        [cocoaView release];
1276    [super dealloc];
1277}
1278
1279- (void)applicationDidFinishLaunching: (NSNotification *) note
1280{
1281    COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1282    allow_events = true;
1283    /* Tell cocoa_display_init to proceed */
1284    qemu_sem_post(&app_started_sem);
1285}
1286
1287- (void)applicationWillTerminate:(NSNotification *)aNotification
1288{
1289    COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1290
1291    qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1292
1293    /*
1294     * Sleep here, because returning will cause OSX to kill us
1295     * immediately; the QEMU main loop will handle the shutdown
1296     * request and terminate the process.
1297     */
1298    [NSThread sleepForTimeInterval:INFINITY];
1299}
1300
1301- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1302{
1303    return YES;
1304}
1305
1306- (NSApplicationTerminateReply)applicationShouldTerminate:
1307                                                         (NSApplication *)sender
1308{
1309    COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1310    return [self verifyQuit];
1311}
1312
1313- (void)windowDidChangeScreen:(NSNotification *)notification
1314{
1315    [cocoaView updateUIInfo];
1316}
1317
1318- (void)windowDidResize:(NSNotification *)notification
1319{
1320    [cocoaView updateUIInfo];
1321}
1322
1323/* Called when the user clicks on a window's close button */
1324- (BOOL)windowShouldClose:(id)sender
1325{
1326    COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1327    [NSApp terminate: sender];
1328    /* If the user allows the application to quit then the call to
1329     * NSApp terminate will never return. If we get here then the user
1330     * cancelled the quit, so we should return NO to not permit the
1331     * closing of this window.
1332     */
1333    return NO;
1334}
1335
1336/* Called when QEMU goes into the background */
1337- (void) applicationWillResignActive: (NSNotification *)aNotification
1338{
1339    COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1340    [cocoaView ungrabMouse];
1341    [cocoaView raiseAllKeys];
1342}
1343
1344/* We abstract the method called by the Enter Fullscreen menu item
1345 * because Mac OS 10.7 and higher disables it. This is because of the
1346 * menu item's old selector's name toggleFullScreen:
1347 */
1348- (void) doToggleFullScreen:(id)sender
1349{
1350    [self toggleFullScreen:(id)sender];
1351}
1352
1353- (void)toggleFullScreen:(id)sender
1354{
1355    COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1356
1357    [cocoaView toggleFullScreen:sender];
1358}
1359
1360- (void) setFullGrab:(id)sender
1361{
1362    COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1363
1364    [cocoaView setFullGrab:sender];
1365}
1366
1367/* Tries to find then open the specified filename */
1368- (void) openDocumentation: (NSString *) filename
1369{
1370    /* Where to look for local files */
1371    NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1372    NSString *full_file_path;
1373    NSURL *full_file_url;
1374
1375    /* iterate thru the possible paths until the file is found */
1376    int index;
1377    for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1378        full_file_path = [[NSBundle mainBundle] executablePath];
1379        full_file_path = [full_file_path stringByDeletingLastPathComponent];
1380        full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1381                          path_array[index], filename];
1382        full_file_url = [NSURL fileURLWithPath: full_file_path
1383                                   isDirectory: false];
1384        if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1385            return;
1386        }
1387    }
1388
1389    /* If none of the paths opened a file */
1390    NSBeep();
1391    QEMU_Alert(@"Failed to open file");
1392}
1393
1394- (void)showQEMUDoc:(id)sender
1395{
1396    COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1397
1398    [self openDocumentation: @"index.html"];
1399}
1400
1401/* Stretches video to fit host monitor size */
1402- (void)zoomToFit:(id) sender
1403{
1404    stretch_video = !stretch_video;
1405    if (stretch_video == true) {
1406        [sender setState: NSControlStateValueOn];
1407    } else {
1408        [sender setState: NSControlStateValueOff];
1409    }
1410}
1411
1412/* Displays the console on the screen */
1413- (void)displayConsole:(id)sender
1414{
1415    console_select([sender tag]);
1416}
1417
1418/* Pause the guest */
1419- (void)pauseQEMU:(id)sender
1420{
1421    with_iothread_lock(^{
1422        qmp_stop(NULL);
1423    });
1424    [sender setEnabled: NO];
1425    [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1426    [self displayPause];
1427}
1428
1429/* Resume running the guest operating system */
1430- (void)resumeQEMU:(id) sender
1431{
1432    with_iothread_lock(^{
1433        qmp_cont(NULL);
1434    });
1435    [sender setEnabled: NO];
1436    [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1437    [self removePause];
1438}
1439
1440/* Displays the word pause on the screen */
1441- (void)displayPause
1442{
1443    /* Coordinates have to be calculated each time because the window can change its size */
1444    int xCoord, yCoord, width, height;
1445    xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1446    yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1447    width = [pauseLabel frame].size.width;
1448    height = [pauseLabel frame].size.height;
1449    [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1450    [cocoaView addSubview: pauseLabel];
1451}
1452
1453/* Removes the word pause from the screen */
1454- (void)removePause
1455{
1456    [pauseLabel removeFromSuperview];
1457}
1458
1459/* Restarts QEMU */
1460- (void)restartQEMU:(id)sender
1461{
1462    with_iothread_lock(^{
1463        qmp_system_reset(NULL);
1464    });
1465}
1466
1467/* Powers down QEMU */
1468- (void)powerDownQEMU:(id)sender
1469{
1470    with_iothread_lock(^{
1471        qmp_system_powerdown(NULL);
1472    });
1473}
1474
1475/* Ejects the media.
1476 * Uses sender's tag to figure out the device to eject.
1477 */
1478- (void)ejectDeviceMedia:(id)sender
1479{
1480    NSString * drive;
1481    drive = [sender representedObject];
1482    if(drive == nil) {
1483        NSBeep();
1484        QEMU_Alert(@"Failed to find drive to eject!");
1485        return;
1486    }
1487
1488    __block Error *err = NULL;
1489    with_iothread_lock(^{
1490        qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1491                  false, NULL, false, false, &err);
1492    });
1493    handleAnyDeviceErrors(err);
1494}
1495
1496/* Displays a dialog box asking the user to select an image file to load.
1497 * Uses sender's represented object value to figure out which drive to use.
1498 */
1499- (void)changeDeviceMedia:(id)sender
1500{
1501    /* Find the drive name */
1502    NSString * drive;
1503    drive = [sender representedObject];
1504    if(drive == nil) {
1505        NSBeep();
1506        QEMU_Alert(@"Could not find drive!");
1507        return;
1508    }
1509
1510    /* Display the file open dialog */
1511    NSOpenPanel * openPanel;
1512    openPanel = [NSOpenPanel openPanel];
1513    [openPanel setCanChooseFiles: YES];
1514    [openPanel setAllowsMultipleSelection: NO];
1515    if([openPanel runModal] == NSModalResponseOK) {
1516        NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1517        if(file == nil) {
1518            NSBeep();
1519            QEMU_Alert(@"Failed to convert URL to file path!");
1520            return;
1521        }
1522
1523        __block Error *err = NULL;
1524        with_iothread_lock(^{
1525            qmp_blockdev_change_medium(true,
1526                                       [drive cStringUsingEncoding:
1527                                                  NSASCIIStringEncoding],
1528                                       false, NULL,
1529                                       [file cStringUsingEncoding:
1530                                                 NSASCIIStringEncoding],
1531                                       true, "raw",
1532                                       false, 0,
1533                                       &err);
1534        });
1535        handleAnyDeviceErrors(err);
1536    }
1537}
1538
1539/* Verifies if the user really wants to quit */
1540- (BOOL)verifyQuit
1541{
1542    NSAlert *alert = [NSAlert new];
1543    [alert autorelease];
1544    [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1545    [alert addButtonWithTitle: @"Cancel"];
1546    [alert addButtonWithTitle: @"Quit"];
1547    if([alert runModal] == NSAlertSecondButtonReturn) {
1548        return YES;
1549    } else {
1550        return NO;
1551    }
1552}
1553
1554/* The action method for the About menu item */
1555- (IBAction) do_about_menu_item: (id) sender
1556{
1557    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1558    char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1559    NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1560    g_free(icon_path_c);
1561    NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1562    NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1563    NSString *copyright = @QEMU_COPYRIGHT;
1564    NSDictionary *options;
1565    if (icon) {
1566        options = @{
1567            NSAboutPanelOptionApplicationIcon : icon,
1568            NSAboutPanelOptionApplicationVersion : version,
1569            @"Copyright" : copyright,
1570        };
1571        [icon release];
1572    } else {
1573        options = @{
1574            NSAboutPanelOptionApplicationVersion : version,
1575            @"Copyright" : copyright,
1576        };
1577    }
1578    [NSApp orderFrontStandardAboutPanelWithOptions:options];
1579    [pool release];
1580}
1581
1582/* Used by the Speed menu items */
1583- (void)adjustSpeed:(id)sender
1584{
1585    int throttle_pct; /* throttle percentage */
1586    NSMenu *menu;
1587
1588    menu = [sender menu];
1589    if (menu != nil)
1590    {
1591        /* Unselect the currently selected item */
1592        for (NSMenuItem *item in [menu itemArray]) {
1593            if (item.state == NSControlStateValueOn) {
1594                [item setState: NSControlStateValueOff];
1595                break;
1596            }
1597        }
1598    }
1599
1600    // check the menu item
1601    [sender setState: NSControlStateValueOn];
1602
1603    // get the throttle percentage
1604    throttle_pct = [sender tag];
1605
1606    with_iothread_lock(^{
1607        cpu_throttle_set(throttle_pct);
1608    });
1609    COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1610}
1611
1612@end
1613
1614@interface QemuApplication : NSApplication
1615@end
1616
1617@implementation QemuApplication
1618- (void)sendEvent:(NSEvent *)event
1619{
1620    COCOA_DEBUG("QemuApplication: sendEvent\n");
1621    if (![cocoaView handleEvent:event]) {
1622        [super sendEvent: event];
1623    }
1624}
1625@end
1626
1627static void create_initial_menus(void)
1628{
1629    // Add menus
1630    NSMenu      *menu;
1631    NSMenuItem  *menuItem;
1632
1633    [NSApp setMainMenu:[[NSMenu alloc] init]];
1634    [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1635
1636    // Application menu
1637    menu = [[NSMenu alloc] initWithTitle:@""];
1638    [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1639    [menu addItem:[NSMenuItem separatorItem]]; //Separator
1640    menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1641    [menuItem setSubmenu:[NSApp servicesMenu]];
1642    [menu addItem:[NSMenuItem separatorItem]];
1643    [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1644    menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1645    [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1646    [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1647    [menu addItem:[NSMenuItem separatorItem]]; //Separator
1648    [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1649    menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1650    [menuItem setSubmenu:menu];
1651    [[NSApp mainMenu] addItem:menuItem];
1652    [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1653
1654    // Machine menu
1655    menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1656    [menu setAutoenablesItems: NO];
1657    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1658    menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1659    [menu addItem: menuItem];
1660    [menuItem setEnabled: NO];
1661    [menu addItem: [NSMenuItem separatorItem]];
1662    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1663    [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1664    menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1665    [menuItem setSubmenu:menu];
1666    [[NSApp mainMenu] addItem:menuItem];
1667
1668    // View menu
1669    menu = [[NSMenu alloc] initWithTitle:@"View"];
1670    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1671    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1672    menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1673    [menuItem setSubmenu:menu];
1674    [[NSApp mainMenu] addItem:menuItem];
1675
1676    // Speed menu
1677    menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1678
1679    // Add the rest of the Speed menu items
1680    int p, percentage, throttle_pct;
1681    for (p = 10; p >= 0; p--)
1682    {
1683        percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1684
1685        menuItem = [[[NSMenuItem alloc]
1686                   initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1687
1688        if (percentage == 100) {
1689            [menuItem setState: NSControlStateValueOn];
1690        }
1691
1692        /* Calculate the throttle percentage */
1693        throttle_pct = -1 * percentage + 100;
1694
1695        [menuItem setTag: throttle_pct];
1696        [menu addItem: menuItem];
1697    }
1698    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1699    [menuItem setSubmenu:menu];
1700    [[NSApp mainMenu] addItem:menuItem];
1701
1702    // Window menu
1703    menu = [[NSMenu alloc] initWithTitle:@"Window"];
1704    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1705    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1706    [menuItem setSubmenu:menu];
1707    [[NSApp mainMenu] addItem:menuItem];
1708    [NSApp setWindowsMenu:menu];
1709
1710    // Help menu
1711    menu = [[NSMenu alloc] initWithTitle:@"Help"];
1712    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1713    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1714    [menuItem setSubmenu:menu];
1715    [[NSApp mainMenu] addItem:menuItem];
1716}
1717
1718/* Returns a name for a given console */
1719static NSString * getConsoleName(QemuConsole * console)
1720{
1721    g_autofree char *label = qemu_console_get_label(console);
1722
1723    return [NSString stringWithUTF8String:label];
1724}
1725
1726/* Add an entry to the View menu for each console */
1727static void add_console_menu_entries(void)
1728{
1729    NSMenu *menu;
1730    NSMenuItem *menuItem;
1731    int index = 0;
1732
1733    menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1734
1735    [menu addItem:[NSMenuItem separatorItem]];
1736
1737    while (qemu_console_lookup_by_index(index) != NULL) {
1738        menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1739                                               action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1740        [menuItem setTag: index];
1741        [menu addItem: menuItem];
1742        index++;
1743    }
1744}
1745
1746/* Make menu items for all removable devices.
1747 * Each device is given an 'Eject' and 'Change' menu item.
1748 */
1749static void addRemovableDevicesMenuItems(void)
1750{
1751    NSMenu *menu;
1752    NSMenuItem *menuItem;
1753    BlockInfoList *currentDevice, *pointerToFree;
1754    NSString *deviceName;
1755
1756    currentDevice = qmp_query_block(NULL);
1757    pointerToFree = currentDevice;
1758
1759    menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1760
1761    // Add a separator between related groups of menu items
1762    [menu addItem:[NSMenuItem separatorItem]];
1763
1764    // Set the attributes to the "Removable Media" menu item
1765    NSString *titleString = @"Removable Media";
1766    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1767    NSColor *newColor = [NSColor blackColor];
1768    NSFontManager *fontManager = [NSFontManager sharedFontManager];
1769    NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1770                                          traits:NSBoldFontMask|NSItalicFontMask
1771                                          weight:0
1772                                            size:14];
1773    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1774    [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1775    [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1776
1777    // Add the "Removable Media" menu item
1778    menuItem = [NSMenuItem new];
1779    [menuItem setAttributedTitle: attString];
1780    [menuItem setEnabled: NO];
1781    [menu addItem: menuItem];
1782
1783    /* Loop through all the block devices in the emulator */
1784    while (currentDevice) {
1785        deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1786
1787        if(currentDevice->value->removable) {
1788            menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1789                                                  action: @selector(changeDeviceMedia:)
1790                                           keyEquivalent: @""];
1791            [menu addItem: menuItem];
1792            [menuItem setRepresentedObject: deviceName];
1793            [menuItem autorelease];
1794
1795            menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1796                                                  action: @selector(ejectDeviceMedia:)
1797                                           keyEquivalent: @""];
1798            [menu addItem: menuItem];
1799            [menuItem setRepresentedObject: deviceName];
1800            [menuItem autorelease];
1801        }
1802        currentDevice = currentDevice->next;
1803    }
1804    qapi_free_BlockInfoList(pointerToFree);
1805}
1806
1807@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1808@end
1809
1810@implementation QemuCocoaPasteboardTypeOwner
1811
1812- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1813{
1814    if (type != NSPasteboardTypeString) {
1815        return;
1816    }
1817
1818    with_iothread_lock(^{
1819        QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1820        qemu_event_reset(&cbevent);
1821        qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1822
1823        while (info == cbinfo &&
1824               info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1825               info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1826            qemu_mutex_unlock_iothread();
1827            qemu_event_wait(&cbevent);
1828            qemu_mutex_lock_iothread();
1829        }
1830
1831        if (info == cbinfo) {
1832            NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1833                                           length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1834            [sender setData:data forType:NSPasteboardTypeString];
1835            [data release];
1836        }
1837
1838        qemu_clipboard_info_unref(info);
1839    });
1840}
1841
1842@end
1843
1844static QemuCocoaPasteboardTypeOwner *cbowner;
1845
1846static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1847static void cocoa_clipboard_request(QemuClipboardInfo *info,
1848                                    QemuClipboardType type);
1849
1850static QemuClipboardPeer cbpeer = {
1851    .name = "cocoa",
1852    .notifier = { .notify = cocoa_clipboard_notify },
1853    .request = cocoa_clipboard_request
1854};
1855
1856static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1857{
1858    if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1859        return;
1860    }
1861
1862    if (info != cbinfo) {
1863        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1864        qemu_clipboard_info_unref(cbinfo);
1865        cbinfo = qemu_clipboard_info_ref(info);
1866        cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1867        [pool release];
1868    }
1869
1870    qemu_event_set(&cbevent);
1871}
1872
1873static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1874{
1875    QemuClipboardNotify *notify = data;
1876
1877    switch (notify->type) {
1878    case QEMU_CLIPBOARD_UPDATE_INFO:
1879        cocoa_clipboard_update_info(notify->info);
1880        return;
1881    case QEMU_CLIPBOARD_RESET_SERIAL:
1882        /* ignore */
1883        return;
1884    }
1885}
1886
1887static void cocoa_clipboard_request(QemuClipboardInfo *info,
1888                                    QemuClipboardType type)
1889{
1890    NSData *text;
1891
1892    switch (type) {
1893    case QEMU_CLIPBOARD_TYPE_TEXT:
1894        text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1895        if (text) {
1896            qemu_clipboard_set_data(&cbpeer, info, type,
1897                                    [text length], [text bytes], true);
1898            [text release];
1899        }
1900        break;
1901    default:
1902        break;
1903    }
1904}
1905
1906/*
1907 * The startup process for the OSX/Cocoa UI is complicated, because
1908 * OSX insists that the UI runs on the initial main thread, and so we
1909 * need to start a second thread which runs the vl.c qemu_main():
1910 *
1911 * Initial thread:                    2nd thread:
1912 * in main():
1913 *  create qemu-main thread
1914 *  wait on display_init semaphore
1915 *                                    call qemu_main()
1916 *                                    ...
1917 *                                    in cocoa_display_init():
1918 *                                     post the display_init semaphore
1919 *                                     wait on app_started semaphore
1920 *  create application, menus, etc
1921 *  enter OSX run loop
1922 * in applicationDidFinishLaunching:
1923 *  post app_started semaphore
1924 *                                     tell main thread to fullscreen if needed
1925 *                                    [...]
1926 *                                    run qemu main-loop
1927 *
1928 * We do this in two stages so that we don't do the creation of the
1929 * GUI application menus and so on for command line options like --help
1930 * where we want to just print text to stdout and exit immediately.
1931 */
1932
1933static void *call_qemu_main(void *opaque)
1934{
1935    int status;
1936
1937    COCOA_DEBUG("Second thread: calling qemu_main()\n");
1938    status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1939    COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1940    [cbowner release];
1941    exit(status);
1942}
1943
1944int main (int argc, char **argv) {
1945    QemuThread thread;
1946
1947    COCOA_DEBUG("Entered main()\n");
1948    gArgc = argc;
1949    gArgv = argv;
1950
1951    qemu_sem_init(&display_init_sem, 0);
1952    qemu_sem_init(&app_started_sem, 0);
1953
1954    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1955                       NULL, QEMU_THREAD_DETACHED);
1956
1957    COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1958    qemu_sem_wait(&display_init_sem);
1959    COCOA_DEBUG("Main thread: initializing app\n");
1960
1961    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1962
1963    // Pull this console process up to being a fully-fledged graphical
1964    // app with a menubar and Dock icon
1965    ProcessSerialNumber psn = { 0, kCurrentProcess };
1966    TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1967
1968    [QemuApplication sharedApplication];
1969
1970    create_initial_menus();
1971
1972    /*
1973     * Create the menu entries which depend on QEMU state (for consoles
1974     * and removeable devices). These make calls back into QEMU functions,
1975     * which is OK because at this point we know that the second thread
1976     * holds the iothread lock and is synchronously waiting for us to
1977     * finish.
1978     */
1979    add_console_menu_entries();
1980    addRemovableDevicesMenuItems();
1981
1982    // Create an Application controller
1983    QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1984    [NSApp setDelegate:appController];
1985
1986    // Start the main event loop
1987    COCOA_DEBUG("Main thread: entering OSX run loop\n");
1988    [NSApp run];
1989    COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1990
1991    [appController release];
1992    [pool release];
1993
1994    return 0;
1995}
1996
1997
1998
1999#pragma mark qemu
2000static void cocoa_update(DisplayChangeListener *dcl,
2001                         int x, int y, int w, int h)
2002{
2003    COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
2004
2005    dispatch_async(dispatch_get_main_queue(), ^{
2006        NSRect rect;
2007        if ([cocoaView cdx] == 1.0) {
2008            rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
2009        } else {
2010            rect = NSMakeRect(
2011                x * [cocoaView cdx],
2012                ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
2013                w * [cocoaView cdx],
2014                h * [cocoaView cdy]);
2015        }
2016        [cocoaView setNeedsDisplayInRect:rect];
2017    });
2018}
2019
2020static void cocoa_switch(DisplayChangeListener *dcl,
2021                         DisplaySurface *surface)
2022{
2023    pixman_image_t *image = surface->image;
2024
2025    COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
2026
2027    // The DisplaySurface will be freed as soon as this callback returns.
2028    // We take a reference to the underlying pixman image here so it does
2029    // not disappear from under our feet; the switchSurface method will
2030    // deref the old image when it is done with it.
2031    pixman_image_ref(image);
2032
2033    dispatch_async(dispatch_get_main_queue(), ^{
2034        [cocoaView updateUIInfo];
2035        [cocoaView switchSurface:image];
2036    });
2037}
2038
2039static void cocoa_refresh(DisplayChangeListener *dcl)
2040{
2041    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2042
2043    COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2044    graphic_hw_update(NULL);
2045
2046    if (qemu_input_is_absolute()) {
2047        dispatch_async(dispatch_get_main_queue(), ^{
2048            if (![cocoaView isAbsoluteEnabled]) {
2049                if ([cocoaView isMouseGrabbed]) {
2050                    [cocoaView ungrabMouse];
2051                }
2052            }
2053            [cocoaView setAbsoluteEnabled:YES];
2054        });
2055    }
2056
2057    if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2058        qemu_clipboard_info_unref(cbinfo);
2059        cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2060        if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2061            cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2062        }
2063        qemu_clipboard_update(cbinfo);
2064        cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2065        qemu_event_set(&cbevent);
2066    }
2067
2068    [pool release];
2069}
2070
2071static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2072{
2073    COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2074
2075    /* Tell main thread to go ahead and create the app and enter the run loop */
2076    qemu_sem_post(&display_init_sem);
2077    qemu_sem_wait(&app_started_sem);
2078    COCOA_DEBUG("cocoa_display_init: app start completed\n");
2079
2080    QemuCocoaAppController *controller = (QemuCocoaAppController *)[[NSApplication sharedApplication] delegate];
2081    /* if fullscreen mode is to be used */
2082    if (opts->has_full_screen && opts->full_screen) {
2083        dispatch_async(dispatch_get_main_queue(), ^{
2084            [NSApp activateIgnoringOtherApps: YES];
2085            [controller toggleFullScreen: nil];
2086        });
2087    }
2088    if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2089        dispatch_async(dispatch_get_main_queue(), ^{
2090            [controller setFullGrab: nil];
2091        });
2092    }
2093
2094    if (opts->has_show_cursor && opts->show_cursor) {
2095        cursor_hide = 0;
2096    }
2097    if (opts->u.cocoa.has_swap_opt_cmd) {
2098        swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2099    }
2100
2101    if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2102        left_command_key_enabled = 0;
2103    }
2104
2105    // register vga output callbacks
2106    register_displaychangelistener(&dcl);
2107
2108    qemu_event_init(&cbevent, false);
2109    cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2110    qemu_clipboard_peer_register(&cbpeer);
2111}
2112
2113static QemuDisplay qemu_display_cocoa = {
2114    .type       = DISPLAY_TYPE_COCOA,
2115    .init       = cocoa_display_init,
2116};
2117
2118static void register_cocoa(void)
2119{
2120    qemu_display_register(&qemu_display_cocoa);
2121}
2122
2123type_init(register_cocoa);
2124