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