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