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