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