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