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