1/* 2 * QEMU Cocoa CG display driver 3 * 4 * Copyright (c) 2008 Mike Kronenberg 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining a copy 7 * of this software and associated documentation files (the "Software"), to deal 8 * in the Software without restriction, including without limitation the rights 9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 * copies of the Software, and to permit persons to whom the Software is 11 * furnished to do so, subject to the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be included in 14 * all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 * THE SOFTWARE. 23 */ 24 25#include "qemu/osdep.h" 26 27#import <Cocoa/Cocoa.h> 28#include <crt_externs.h> 29 30#include "qemu/help-texts.h" 31#include "qemu-main.h" 32#include "ui/clipboard.h" 33#include "ui/console.h" 34#include "ui/input.h" 35#include "ui/kbd-state.h" 36#include "sysemu/sysemu.h" 37#include "sysemu/runstate.h" 38#include "sysemu/runstate-action.h" 39#include "sysemu/cpu-throttle.h" 40#include "qapi/error.h" 41#include "qapi/qapi-commands-block.h" 42#include "qapi/qapi-commands-machine.h" 43#include "qapi/qapi-commands-misc.h" 44#include "sysemu/blockdev.h" 45#include "qemu-version.h" 46#include "qemu/cutils.h" 47#include "qemu/main-loop.h" 48#include "qemu/module.h" 49#include "qemu/error-report.h" 50#include <Carbon/Carbon.h> 51#include "hw/core/cpu.h" 52 53#ifndef MAC_OS_X_VERSION_10_13 54#define MAC_OS_X_VERSION_10_13 101300 55#endif 56 57/* 10.14 deprecates NSOnState and NSOffState in favor of 58 * NSControlStateValueOn/Off, which were introduced in 10.13. 59 * Define for older versions 60 */ 61#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13 62#define NSControlStateValueOn NSOnState 63#define NSControlStateValueOff NSOffState 64#endif 65 66//#define DEBUG 67 68#ifdef DEBUG 69#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); } 70#else 71#define COCOA_DEBUG(...) ((void) 0) 72#endif 73 74#define cgrect(nsrect) (*(CGRect *)&(nsrect)) 75 76#define UC_CTRL_KEY "\xe2\x8c\x83" 77#define UC_ALT_KEY "\xe2\x8c\xa5" 78 79typedef struct { 80 int width; 81 int height; 82} QEMUScreen; 83 84static void cocoa_update(DisplayChangeListener *dcl, 85 int x, int y, int w, int h); 86 87static void cocoa_switch(DisplayChangeListener *dcl, 88 DisplaySurface *surface); 89 90static void cocoa_refresh(DisplayChangeListener *dcl); 91 92static NSWindow *normalWindow; 93static const DisplayChangeListenerOps dcl_ops = { 94 .dpy_name = "cocoa", 95 .dpy_gfx_update = cocoa_update, 96 .dpy_gfx_switch = cocoa_switch, 97 .dpy_refresh = cocoa_refresh, 98}; 99static DisplayChangeListener dcl = { 100 .ops = &dcl_ops, 101}; 102static int last_buttons; 103static int cursor_hide = 1; 104static int left_command_key_enabled = 1; 105static bool swap_opt_cmd; 106 107static bool stretch_video; 108static NSTextField *pauseLabel; 109 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 *view = userInfo; 347 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent]; 348 if ([view isMouseGrabbed] && [view 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 CVDisplayLinkRef displayLink; 565 566 frameSize = isFullscreen ? screenSize : [self frame].size; 567 568 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) { 569 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink); 570 CVDisplayLinkRelease(displayLink); 571 if (!(period.flags & kCVTimeIsIndefinite)) { 572 update_displaychangelistener(&dcl, 573 1000 * period.timeValue / period.timeScale); 574 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue; 575 } 576 } 577 578 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width; 579 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height; 580 } else { 581 frameSize = [self frame].size; 582 info.width_mm = 0; 583 info.height_mm = 0; 584 } 585 586 info.xoff = 0; 587 info.yoff = 0; 588 info.width = frameSize.width; 589 info.height = frameSize.height; 590 591 dpy_set_ui_info(dcl.con, &info, TRUE); 592} 593 594- (void) updateUIInfo 595{ 596 if (!allow_events) { 597 /* 598 * Don't try to tell QEMU about UI information in the application 599 * startup phase -- we haven't yet registered dcl with the QEMU UI 600 * layer. 601 * When cocoa_display_init() does register the dcl, the UI layer 602 * will call cocoa_switch(), which will call updateUIInfo, so 603 * we don't lose any information here. 604 */ 605 return; 606 } 607 608 with_iothread_lock(^{ 609 [self updateUIInfoLocked]; 610 }); 611} 612 613- (void)viewDidMoveToWindow 614{ 615 [self updateUIInfo]; 616} 617 618- (void) switchSurface:(pixman_image_t *)image 619{ 620 COCOA_DEBUG("QemuCocoaView: switchSurface\n"); 621 622 int w = pixman_image_get_width(image); 623 int h = pixman_image_get_height(image); 624 /* cdx == 0 means this is our very first surface, in which case we need 625 * to recalculate the content dimensions even if it happens to be the size 626 * of the initial empty window. 627 */ 628 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0); 629 630 int oldh = screen.height; 631 if (isResize) { 632 // Resize before we trigger the redraw, or we'll redraw at the wrong size 633 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h); 634 screen.width = w; 635 screen.height = h; 636 [self setContentDimensions]; 637 [self setFrame:NSMakeRect(cx, cy, cw, ch)]; 638 } 639 640 // update screenBuffer 641 if (pixman_image) { 642 pixman_image_unref(pixman_image); 643 } 644 645 pixman_image = image; 646 647 // update windows 648 if (isFullscreen) { 649 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]]; 650 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO]; 651 } else { 652 if (qemu_name) 653 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]]; 654 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO]; 655 } 656 657 if (isResize) { 658 [normalWindow center]; 659 } 660} 661 662- (void) toggleFullScreen:(id)sender 663{ 664 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n"); 665 666 if (isFullscreen) { // switch from fullscreen to desktop 667 isFullscreen = FALSE; 668 [self ungrabMouse]; 669 [self setContentDimensions]; 670 [fullScreenWindow close]; 671 [normalWindow setContentView: self]; 672 [normalWindow makeKeyAndOrderFront: self]; 673 [NSMenu setMenuBarVisible:YES]; 674 } else { // switch from desktop to fullscreen 675 isFullscreen = TRUE; 676 [normalWindow orderOut: nil]; /* Hide the window */ 677 [self grabMouse]; 678 [self setContentDimensions]; 679 [NSMenu setMenuBarVisible:NO]; 680 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame] 681 styleMask:NSWindowStyleMaskBorderless 682 backing:NSBackingStoreBuffered 683 defer:NO]; 684 [fullScreenWindow setAcceptsMouseMovedEvents: YES]; 685 [fullScreenWindow setHasShadow:NO]; 686 [fullScreenWindow setBackgroundColor: [NSColor blackColor]]; 687 [self setFrame:NSMakeRect(cx, cy, cw, ch)]; 688 [[fullScreenWindow contentView] addSubview: self]; 689 [fullScreenWindow makeKeyAndOrderFront:self]; 690 } 691} 692 693- (void) setFullGrab:(id)sender 694{ 695 COCOA_DEBUG("QemuCocoaView: setFullGrab\n"); 696 697 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged); 698 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, 699 mask, handleTapEvent, self); 700 if (!eventsTap) { 701 warn_report("Could not create event tap, system key combos will not be captured.\n"); 702 return; 703 } else { 704 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n"); 705 } 706 707 CFRunLoopRef runLoop = CFRunLoopGetCurrent(); 708 if (!runLoop) { 709 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n"); 710 return; 711 } 712 713 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0); 714 if (!tapEventsSrc ) { 715 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n"); 716 return; 717 } 718 719 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode); 720 CFRelease(tapEventsSrc); 721} 722 723- (void) toggleKey: (int)keycode { 724 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode)); 725} 726 727// Does the work of sending input to the monitor 728- (void) handleMonitorInput:(NSEvent *)event 729{ 730 int keysym = 0; 731 int control_key = 0; 732 733 // if the control key is down 734 if ([event modifierFlags] & NSEventModifierFlagControl) { 735 control_key = 1; 736 } 737 738 /* translates Macintosh keycodes to QEMU's keysym */ 739 740 static const int without_control_translation[] = { 741 [0 ... 0xff] = 0, // invalid key 742 743 [kVK_UpArrow] = QEMU_KEY_UP, 744 [kVK_DownArrow] = QEMU_KEY_DOWN, 745 [kVK_RightArrow] = QEMU_KEY_RIGHT, 746 [kVK_LeftArrow] = QEMU_KEY_LEFT, 747 [kVK_Home] = QEMU_KEY_HOME, 748 [kVK_End] = QEMU_KEY_END, 749 [kVK_PageUp] = QEMU_KEY_PAGEUP, 750 [kVK_PageDown] = QEMU_KEY_PAGEDOWN, 751 [kVK_ForwardDelete] = QEMU_KEY_DELETE, 752 [kVK_Delete] = QEMU_KEY_BACKSPACE, 753 }; 754 755 static const int with_control_translation[] = { 756 [0 ... 0xff] = 0, // invalid key 757 758 [kVK_UpArrow] = QEMU_KEY_CTRL_UP, 759 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN, 760 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT, 761 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT, 762 [kVK_Home] = QEMU_KEY_CTRL_HOME, 763 [kVK_End] = QEMU_KEY_CTRL_END, 764 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP, 765 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN, 766 }; 767 768 if (control_key != 0) { /* If the control key is being used */ 769 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) { 770 keysym = with_control_translation[[event keyCode]]; 771 } 772 } else { 773 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) { 774 keysym = without_control_translation[[event keyCode]]; 775 } 776 } 777 778 // if not a key that needs translating 779 if (keysym == 0) { 780 NSString *ks = [event characters]; 781 if ([ks length] > 0) { 782 keysym = [ks characterAtIndex:0]; 783 } 784 } 785 786 if (keysym) { 787 qemu_text_console_put_keysym(NULL, keysym); 788 } 789} 790 791- (bool) handleEvent:(NSEvent *)event 792{ 793 return bool_with_iothread_lock(^{ 794 return [self handleEventLocked:event]; 795 }); 796} 797 798- (bool) handleEventLocked:(NSEvent *)event 799{ 800 /* Return true if we handled the event, false if it should be given to OSX */ 801 COCOA_DEBUG("QemuCocoaView: handleEvent\n"); 802 int buttons = 0; 803 int keycode = 0; 804 bool mouse_event = false; 805 // Location of event in virtual screen coordinates 806 NSPoint p = [self screenLocationOfEvent:event]; 807 NSUInteger modifiers = [event modifierFlags]; 808 809 /* 810 * Check -[NSEvent modifierFlags] here. 811 * 812 * There is a NSEventType for an event notifying the change of 813 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations 814 * are performed for any events because a modifier state may change while 815 * the application is inactive (i.e. no events fire) and we don't want to 816 * wait for another modifier state change to detect such a change. 817 * 818 * NSEventModifierFlagCapsLock requires a special treatment. The other flags 819 * are handled in similar manners. 820 * 821 * NSEventModifierFlagCapsLock 822 * --------------------------- 823 * 824 * If CapsLock state is changed, "up" and "down" events will be fired in 825 * sequence, effectively updates CapsLock state on the guest. 826 * 827 * The other flags 828 * --------------- 829 * 830 * If a flag is not set, fire "up" events for all keys which correspond to 831 * the flag. Note that "down" events are not fired here because the flags 832 * checked here do not tell what exact keys are down. 833 * 834 * If one of the keys corresponding to a flag is down, we rely on 835 * -[NSEvent keyCode] of an event whose -[NSEvent type] is 836 * NSEventTypeFlagsChanged to know the exact key which is down, which has 837 * the following two downsides: 838 * - It does not work when the application is inactive as described above. 839 * - It malfactions *after* the modifier state is changed while the 840 * application is inactive. It is because -[NSEvent keyCode] does not tell 841 * if the key is up or down, and requires to infer the current state from 842 * the previous state. It is still possible to fix such a malfanction by 843 * completely leaving your hands from the keyboard, which hopefully makes 844 * this implementation usable enough. 845 */ 846 if (!!(modifiers & NSEventModifierFlagCapsLock) != 847 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) { 848 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true); 849 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false); 850 } 851 852 if (!(modifiers & NSEventModifierFlagShift)) { 853 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false); 854 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false); 855 } 856 if (!(modifiers & NSEventModifierFlagControl)) { 857 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false); 858 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false); 859 } 860 if (!(modifiers & NSEventModifierFlagOption)) { 861 if (swap_opt_cmd) { 862 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false); 863 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false); 864 } else { 865 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false); 866 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false); 867 } 868 } 869 if (!(modifiers & NSEventModifierFlagCommand)) { 870 if (swap_opt_cmd) { 871 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false); 872 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false); 873 } else { 874 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false); 875 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false); 876 } 877 } 878 879 switch ([event type]) { 880 case NSEventTypeFlagsChanged: 881 switch ([event keyCode]) { 882 case kVK_Shift: 883 if (!!(modifiers & NSEventModifierFlagShift)) { 884 [self toggleKey:Q_KEY_CODE_SHIFT]; 885 } 886 break; 887 888 case kVK_RightShift: 889 if (!!(modifiers & NSEventModifierFlagShift)) { 890 [self toggleKey:Q_KEY_CODE_SHIFT_R]; 891 } 892 break; 893 894 case kVK_Control: 895 if (!!(modifiers & NSEventModifierFlagControl)) { 896 [self toggleKey:Q_KEY_CODE_CTRL]; 897 } 898 break; 899 900 case kVK_RightControl: 901 if (!!(modifiers & NSEventModifierFlagControl)) { 902 [self toggleKey:Q_KEY_CODE_CTRL_R]; 903 } 904 break; 905 906 case kVK_Option: 907 if (!!(modifiers & NSEventModifierFlagOption)) { 908 if (swap_opt_cmd) { 909 [self toggleKey:Q_KEY_CODE_META_L]; 910 } else { 911 [self toggleKey:Q_KEY_CODE_ALT]; 912 } 913 } 914 break; 915 916 case kVK_RightOption: 917 if (!!(modifiers & NSEventModifierFlagOption)) { 918 if (swap_opt_cmd) { 919 [self toggleKey:Q_KEY_CODE_META_R]; 920 } else { 921 [self toggleKey:Q_KEY_CODE_ALT_R]; 922 } 923 } 924 break; 925 926 /* Don't pass command key changes to guest unless mouse is grabbed */ 927 case kVK_Command: 928 if (isMouseGrabbed && 929 !!(modifiers & NSEventModifierFlagCommand) && 930 left_command_key_enabled) { 931 if (swap_opt_cmd) { 932 [self toggleKey:Q_KEY_CODE_ALT]; 933 } else { 934 [self toggleKey:Q_KEY_CODE_META_L]; 935 } 936 } 937 break; 938 939 case kVK_RightCommand: 940 if (isMouseGrabbed && 941 !!(modifiers & NSEventModifierFlagCommand)) { 942 if (swap_opt_cmd) { 943 [self toggleKey:Q_KEY_CODE_ALT_R]; 944 } else { 945 [self toggleKey:Q_KEY_CODE_META_R]; 946 } 947 } 948 break; 949 } 950 break; 951 case NSEventTypeKeyDown: 952 keycode = cocoa_keycode_to_qemu([event keyCode]); 953 954 // forward command key combos to the host UI unless the mouse is grabbed 955 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) { 956 return false; 957 } 958 959 // default 960 961 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU) 962 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) { 963 NSString *keychar = [event charactersIgnoringModifiers]; 964 if ([keychar length] == 1) { 965 char key = [keychar characterAtIndex:0]; 966 switch (key) { 967 968 // enable graphic console 969 case '1' ... '9': 970 console_select(key - '0' - 1); /* ascii math */ 971 return true; 972 973 // release the mouse grab 974 case 'g': 975 [self ungrabMouse]; 976 return true; 977 } 978 } 979 } 980 981 if (qemu_console_is_graphic(NULL)) { 982 qkbd_state_key_event(kbd, keycode, true); 983 } else { 984 [self handleMonitorInput: event]; 985 } 986 break; 987 case NSEventTypeKeyUp: 988 keycode = cocoa_keycode_to_qemu([event keyCode]); 989 990 // don't pass the guest a spurious key-up if we treated this 991 // command-key combo as a host UI action 992 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) { 993 return true; 994 } 995 996 if (qemu_console_is_graphic(NULL)) { 997 qkbd_state_key_event(kbd, keycode, false); 998 } 999 break; 1000 case NSEventTypeMouseMoved: 1001 if (isAbsoluteEnabled) { 1002 // Cursor re-entered into a window might generate events bound to screen coordinates 1003 // and `nil` window property, and in full screen mode, current window might not be 1004 // key window, where event location alone should suffice. 1005 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) { 1006 if (isMouseGrabbed) { 1007 [self ungrabMouse]; 1008 } 1009 } else { 1010 if (!isMouseGrabbed) { 1011 [self grabMouse]; 1012 } 1013 } 1014 } 1015 mouse_event = true; 1016 break; 1017 case NSEventTypeLeftMouseDown: 1018 buttons |= MOUSE_EVENT_LBUTTON; 1019 mouse_event = true; 1020 break; 1021 case NSEventTypeRightMouseDown: 1022 buttons |= MOUSE_EVENT_RBUTTON; 1023 mouse_event = true; 1024 break; 1025 case NSEventTypeOtherMouseDown: 1026 buttons |= MOUSE_EVENT_MBUTTON; 1027 mouse_event = true; 1028 break; 1029 case NSEventTypeLeftMouseDragged: 1030 buttons |= MOUSE_EVENT_LBUTTON; 1031 mouse_event = true; 1032 break; 1033 case NSEventTypeRightMouseDragged: 1034 buttons |= MOUSE_EVENT_RBUTTON; 1035 mouse_event = true; 1036 break; 1037 case NSEventTypeOtherMouseDragged: 1038 buttons |= MOUSE_EVENT_MBUTTON; 1039 mouse_event = true; 1040 break; 1041 case NSEventTypeLeftMouseUp: 1042 mouse_event = true; 1043 if (!isMouseGrabbed && [self screenContainsPoint:p]) { 1044 /* 1045 * In fullscreen mode, the window of cocoaView may not be the 1046 * key window, therefore the position relative to the virtual 1047 * screen alone will be sufficient. 1048 */ 1049 if(isFullscreen || [[self window] isKeyWindow]) { 1050 [self grabMouse]; 1051 } 1052 } 1053 break; 1054 case NSEventTypeRightMouseUp: 1055 mouse_event = true; 1056 break; 1057 case NSEventTypeOtherMouseUp: 1058 mouse_event = true; 1059 break; 1060 case NSEventTypeScrollWheel: 1061 /* 1062 * Send wheel events to the guest regardless of window focus. 1063 * This is in-line with standard Mac OS X UI behaviour. 1064 */ 1065 1066 /* 1067 * We shouldn't have got a scroll event when deltaY and delta Y 1068 * are zero, hence no harm in dropping the event 1069 */ 1070 if ([event deltaY] != 0 || [event deltaX] != 0) { 1071 /* Determine if this is a scroll up or scroll down event */ 1072 if ([event deltaY] != 0) { 1073 buttons = ([event deltaY] > 0) ? 1074 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN; 1075 } else if ([event deltaX] != 0) { 1076 buttons = ([event deltaX] > 0) ? 1077 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT; 1078 } 1079 1080 qemu_input_queue_btn(dcl.con, buttons, true); 1081 qemu_input_event_sync(); 1082 qemu_input_queue_btn(dcl.con, buttons, false); 1083 qemu_input_event_sync(); 1084 } 1085 1086 /* 1087 * Since deltaX/deltaY also report scroll wheel events we prevent mouse 1088 * movement code from executing. 1089 */ 1090 mouse_event = false; 1091 break; 1092 default: 1093 return false; 1094 } 1095 1096 if (mouse_event) { 1097 /* Don't send button events to the guest unless we've got a 1098 * mouse grab or window focus. If we have neither then this event 1099 * is the user clicking on the background window to activate and 1100 * bring us to the front, which will be done by the sendEvent 1101 * call below. We definitely don't want to pass that click through 1102 * to the guest. 1103 */ 1104 if ((isMouseGrabbed || [[self window] isKeyWindow]) && 1105 (last_buttons != buttons)) { 1106 static uint32_t bmap[INPUT_BUTTON__MAX] = { 1107 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON, 1108 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON, 1109 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON 1110 }; 1111 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons); 1112 last_buttons = buttons; 1113 } 1114 if (isMouseGrabbed) { 1115 if (isAbsoluteEnabled) { 1116 /* Note that the origin for Cocoa mouse coords is bottom left, not top left. 1117 * The check on screenContainsPoint is to avoid sending out of range values for 1118 * clicks in the titlebar. 1119 */ 1120 if ([self screenContainsPoint:p]) { 1121 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width); 1122 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height); 1123 } 1124 } else { 1125 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]); 1126 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]); 1127 } 1128 } else { 1129 return false; 1130 } 1131 qemu_input_event_sync(); 1132 } 1133 return true; 1134} 1135 1136- (void) grabMouse 1137{ 1138 COCOA_DEBUG("QemuCocoaView: grabMouse\n"); 1139 1140 if (!isFullscreen) { 1141 if (qemu_name) 1142 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]]; 1143 else 1144 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"]; 1145 } 1146 [self hideCursor]; 1147 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled); 1148 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:] 1149} 1150 1151- (void) ungrabMouse 1152{ 1153 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n"); 1154 1155 if (!isFullscreen) { 1156 if (qemu_name) 1157 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]]; 1158 else 1159 [normalWindow setTitle:@"QEMU"]; 1160 } 1161 [self unhideCursor]; 1162 CGAssociateMouseAndMouseCursorPosition(TRUE); 1163 isMouseGrabbed = FALSE; 1164} 1165 1166- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled { 1167 isAbsoluteEnabled = tIsAbsoluteEnabled; 1168 if (isMouseGrabbed) { 1169 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled); 1170 } 1171} 1172- (BOOL) isMouseGrabbed {return isMouseGrabbed;} 1173- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;} 1174- (float) cdx {return cdx;} 1175- (float) cdy {return cdy;} 1176- (QEMUScreen) gscreen {return screen;} 1177 1178/* 1179 * Makes the target think all down keys are being released. 1180 * This prevents a stuck key problem, since we will not see 1181 * key up events for those keys after we have lost focus. 1182 */ 1183- (void) raiseAllKeys 1184{ 1185 with_iothread_lock(^{ 1186 qkbd_state_lift_all_keys(kbd); 1187 }); 1188} 1189@end 1190 1191 1192 1193/* 1194 ------------------------------------------------------ 1195 QemuCocoaAppController 1196 ------------------------------------------------------ 1197*/ 1198@interface QemuCocoaAppController : NSObject 1199 <NSWindowDelegate, NSApplicationDelegate> 1200{ 1201} 1202- (void)doToggleFullScreen:(id)sender; 1203- (void)toggleFullScreen:(id)sender; 1204- (void)showQEMUDoc:(id)sender; 1205- (void)zoomToFit:(id) sender; 1206- (void)displayConsole:(id)sender; 1207- (void)pauseQEMU:(id)sender; 1208- (void)resumeQEMU:(id)sender; 1209- (void)displayPause; 1210- (void)removePause; 1211- (void)restartQEMU:(id)sender; 1212- (void)powerDownQEMU:(id)sender; 1213- (void)ejectDeviceMedia:(id)sender; 1214- (void)changeDeviceMedia:(id)sender; 1215- (BOOL)verifyQuit; 1216- (void)openDocumentation:(NSString *)filename; 1217- (IBAction) do_about_menu_item: (id) sender; 1218- (void)adjustSpeed:(id)sender; 1219@end 1220 1221@implementation QemuCocoaAppController 1222- (id) init 1223{ 1224 COCOA_DEBUG("QemuCocoaAppController: init\n"); 1225 1226 self = [super init]; 1227 if (self) { 1228 1229 // create a view and add it to the window 1230 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)]; 1231 if(!cocoaView) { 1232 error_report("(cocoa) can't create a view"); 1233 exit(1); 1234 } 1235 1236 // create a window 1237 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame] 1238 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable 1239 backing:NSBackingStoreBuffered defer:NO]; 1240 if(!normalWindow) { 1241 error_report("(cocoa) can't create window"); 1242 exit(1); 1243 } 1244 [normalWindow setAcceptsMouseMovedEvents:YES]; 1245 [normalWindow setTitle:@"QEMU"]; 1246 [normalWindow setContentView:cocoaView]; 1247 [normalWindow makeKeyAndOrderFront:self]; 1248 [normalWindow center]; 1249 [normalWindow setDelegate: self]; 1250 stretch_video = false; 1251 1252 /* Used for displaying pause on the screen */ 1253 pauseLabel = [NSTextField new]; 1254 [pauseLabel setBezeled:YES]; 1255 [pauseLabel setDrawsBackground:YES]; 1256 [pauseLabel setBackgroundColor: [NSColor whiteColor]]; 1257 [pauseLabel setEditable:NO]; 1258 [pauseLabel setSelectable:NO]; 1259 [pauseLabel setStringValue: @"Paused"]; 1260 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]]; 1261 [pauseLabel setTextColor: [NSColor blackColor]]; 1262 [pauseLabel sizeToFit]; 1263 } 1264 return self; 1265} 1266 1267- (void) dealloc 1268{ 1269 COCOA_DEBUG("QemuCocoaAppController: dealloc\n"); 1270 1271 if (cocoaView) 1272 [cocoaView release]; 1273 [super dealloc]; 1274} 1275 1276- (void)applicationDidFinishLaunching: (NSNotification *) note 1277{ 1278 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n"); 1279 allow_events = true; 1280} 1281 1282- (void)applicationWillTerminate:(NSNotification *)aNotification 1283{ 1284 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n"); 1285 1286 with_iothread_lock(^{ 1287 shutdown_action = SHUTDOWN_ACTION_POWEROFF; 1288 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI); 1289 }); 1290 1291 /* 1292 * Sleep here, because returning will cause OSX to kill us 1293 * immediately; the QEMU main loop will handle the shutdown 1294 * request and terminate the process. 1295 */ 1296 [NSThread sleepForTimeInterval:INFINITY]; 1297} 1298 1299- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication 1300{ 1301 return YES; 1302} 1303 1304- (NSApplicationTerminateReply)applicationShouldTerminate: 1305 (NSApplication *)sender 1306{ 1307 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n"); 1308 return [self verifyQuit]; 1309} 1310 1311- (void)windowDidChangeScreen:(NSNotification *)notification 1312{ 1313 [cocoaView updateUIInfo]; 1314} 1315 1316- (void)windowDidResize:(NSNotification *)notification 1317{ 1318 [cocoaView updateUIInfo]; 1319} 1320 1321/* Called when the user clicks on a window's close button */ 1322- (BOOL)windowShouldClose:(id)sender 1323{ 1324 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n"); 1325 [NSApp terminate: sender]; 1326 /* If the user allows the application to quit then the call to 1327 * NSApp terminate will never return. If we get here then the user 1328 * cancelled the quit, so we should return NO to not permit the 1329 * closing of this window. 1330 */ 1331 return NO; 1332} 1333 1334/* 1335 * Called when QEMU goes into the background. Note that 1336 * [-NSWindowDelegate windowDidResignKey:] is used here instead of 1337 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot 1338 * detect that the window loses focus when the deck is clicked on macOS 13.2.1. 1339 */ 1340- (void) windowDidResignKey: (NSNotification *)aNotification 1341{ 1342 COCOA_DEBUG("%s\n", __func__); 1343 [cocoaView ungrabMouse]; 1344 [cocoaView raiseAllKeys]; 1345} 1346 1347/* We abstract the method called by the Enter Fullscreen menu item 1348 * because Mac OS 10.7 and higher disables it. This is because of the 1349 * menu item's old selector's name toggleFullScreen: 1350 */ 1351- (void) doToggleFullScreen:(id)sender 1352{ 1353 [self toggleFullScreen:(id)sender]; 1354} 1355 1356- (void)toggleFullScreen:(id)sender 1357{ 1358 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n"); 1359 1360 [cocoaView toggleFullScreen:sender]; 1361} 1362 1363- (void) setFullGrab:(id)sender 1364{ 1365 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n"); 1366 1367 [cocoaView setFullGrab:sender]; 1368} 1369 1370/* Tries to find then open the specified filename */ 1371- (void) openDocumentation: (NSString *) filename 1372{ 1373 /* Where to look for local files */ 1374 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"}; 1375 NSString *full_file_path; 1376 NSURL *full_file_url; 1377 1378 /* iterate thru the possible paths until the file is found */ 1379 int index; 1380 for (index = 0; index < ARRAY_SIZE(path_array); index++) { 1381 full_file_path = [[NSBundle mainBundle] executablePath]; 1382 full_file_path = [full_file_path stringByDeletingLastPathComponent]; 1383 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path, 1384 path_array[index], filename]; 1385 full_file_url = [NSURL fileURLWithPath: full_file_path 1386 isDirectory: false]; 1387 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) { 1388 return; 1389 } 1390 } 1391 1392 /* If none of the paths opened a file */ 1393 NSBeep(); 1394 QEMU_Alert(@"Failed to open file"); 1395} 1396 1397- (void)showQEMUDoc:(id)sender 1398{ 1399 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n"); 1400 1401 [self openDocumentation: @"index.html"]; 1402} 1403 1404/* Stretches video to fit host monitor size */ 1405- (void)zoomToFit:(id) sender 1406{ 1407 stretch_video = !stretch_video; 1408 if (stretch_video == true) { 1409 [sender setState: NSControlStateValueOn]; 1410 } else { 1411 [sender setState: NSControlStateValueOff]; 1412 } 1413} 1414 1415/* Displays the console on the screen */ 1416- (void)displayConsole:(id)sender 1417{ 1418 console_select([sender tag]); 1419} 1420 1421/* Pause the guest */ 1422- (void)pauseQEMU:(id)sender 1423{ 1424 with_iothread_lock(^{ 1425 qmp_stop(NULL); 1426 }); 1427 [sender setEnabled: NO]; 1428 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES]; 1429 [self displayPause]; 1430} 1431 1432/* Resume running the guest operating system */ 1433- (void)resumeQEMU:(id) sender 1434{ 1435 with_iothread_lock(^{ 1436 qmp_cont(NULL); 1437 }); 1438 [sender setEnabled: NO]; 1439 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES]; 1440 [self removePause]; 1441} 1442 1443/* Displays the word pause on the screen */ 1444- (void)displayPause 1445{ 1446 /* Coordinates have to be calculated each time because the window can change its size */ 1447 int xCoord, yCoord, width, height; 1448 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2; 1449 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5); 1450 width = [pauseLabel frame].size.width; 1451 height = [pauseLabel frame].size.height; 1452 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)]; 1453 [cocoaView addSubview: pauseLabel]; 1454} 1455 1456/* Removes the word pause from the screen */ 1457- (void)removePause 1458{ 1459 [pauseLabel removeFromSuperview]; 1460} 1461 1462/* Restarts QEMU */ 1463- (void)restartQEMU:(id)sender 1464{ 1465 with_iothread_lock(^{ 1466 qmp_system_reset(NULL); 1467 }); 1468} 1469 1470/* Powers down QEMU */ 1471- (void)powerDownQEMU:(id)sender 1472{ 1473 with_iothread_lock(^{ 1474 qmp_system_powerdown(NULL); 1475 }); 1476} 1477 1478/* Ejects the media. 1479 * Uses sender's tag to figure out the device to eject. 1480 */ 1481- (void)ejectDeviceMedia:(id)sender 1482{ 1483 NSString * drive; 1484 drive = [sender representedObject]; 1485 if(drive == nil) { 1486 NSBeep(); 1487 QEMU_Alert(@"Failed to find drive to eject!"); 1488 return; 1489 } 1490 1491 __block Error *err = NULL; 1492 with_iothread_lock(^{ 1493 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding], 1494 NULL, false, false, &err); 1495 }); 1496 handleAnyDeviceErrors(err); 1497} 1498 1499/* Displays a dialog box asking the user to select an image file to load. 1500 * Uses sender's represented object value to figure out which drive to use. 1501 */ 1502- (void)changeDeviceMedia:(id)sender 1503{ 1504 /* Find the drive name */ 1505 NSString * drive; 1506 drive = [sender representedObject]; 1507 if(drive == nil) { 1508 NSBeep(); 1509 QEMU_Alert(@"Could not find drive!"); 1510 return; 1511 } 1512 1513 /* Display the file open dialog */ 1514 NSOpenPanel * openPanel; 1515 openPanel = [NSOpenPanel openPanel]; 1516 [openPanel setCanChooseFiles: YES]; 1517 [openPanel setAllowsMultipleSelection: NO]; 1518 if([openPanel runModal] == NSModalResponseOK) { 1519 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path]; 1520 if(file == nil) { 1521 NSBeep(); 1522 QEMU_Alert(@"Failed to convert URL to file path!"); 1523 return; 1524 } 1525 1526 __block Error *err = NULL; 1527 with_iothread_lock(^{ 1528 qmp_blockdev_change_medium([drive cStringUsingEncoding: 1529 NSASCIIStringEncoding], 1530 NULL, 1531 [file cStringUsingEncoding: 1532 NSASCIIStringEncoding], 1533 "raw", 1534 true, false, 1535 false, 0, 1536 &err); 1537 }); 1538 handleAnyDeviceErrors(err); 1539 } 1540} 1541 1542/* Verifies if the user really wants to quit */ 1543- (BOOL)verifyQuit 1544{ 1545 NSAlert *alert = [NSAlert new]; 1546 [alert autorelease]; 1547 [alert setMessageText: @"Are you sure you want to quit QEMU?"]; 1548 [alert addButtonWithTitle: @"Cancel"]; 1549 [alert addButtonWithTitle: @"Quit"]; 1550 if([alert runModal] == NSAlertSecondButtonReturn) { 1551 return YES; 1552 } else { 1553 return NO; 1554 } 1555} 1556 1557/* The action method for the About menu item */ 1558- (IBAction) do_about_menu_item: (id) sender 1559{ 1560 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 1561 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png"); 1562 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c]; 1563 g_free(icon_path_c); 1564 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path]; 1565 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION; 1566 NSString *copyright = @QEMU_COPYRIGHT; 1567 NSDictionary *options; 1568 if (icon) { 1569 options = @{ 1570 NSAboutPanelOptionApplicationIcon : icon, 1571 NSAboutPanelOptionApplicationVersion : version, 1572 @"Copyright" : copyright, 1573 }; 1574 [icon release]; 1575 } else { 1576 options = @{ 1577 NSAboutPanelOptionApplicationVersion : version, 1578 @"Copyright" : copyright, 1579 }; 1580 } 1581 [NSApp orderFrontStandardAboutPanelWithOptions:options]; 1582 [pool release]; 1583} 1584 1585/* Used by the Speed menu items */ 1586- (void)adjustSpeed:(id)sender 1587{ 1588 int throttle_pct; /* throttle percentage */ 1589 NSMenu *menu; 1590 1591 menu = [sender menu]; 1592 if (menu != nil) 1593 { 1594 /* Unselect the currently selected item */ 1595 for (NSMenuItem *item in [menu itemArray]) { 1596 if (item.state == NSControlStateValueOn) { 1597 [item setState: NSControlStateValueOff]; 1598 break; 1599 } 1600 } 1601 } 1602 1603 // check the menu item 1604 [sender setState: NSControlStateValueOn]; 1605 1606 // get the throttle percentage 1607 throttle_pct = [sender tag]; 1608 1609 with_iothread_lock(^{ 1610 cpu_throttle_set(throttle_pct); 1611 }); 1612 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%'); 1613} 1614 1615@end 1616 1617@interface QemuApplication : NSApplication 1618@end 1619 1620@implementation QemuApplication 1621- (void)sendEvent:(NSEvent *)event 1622{ 1623 COCOA_DEBUG("QemuApplication: sendEvent\n"); 1624 if (![cocoaView handleEvent:event]) { 1625 [super sendEvent: event]; 1626 } 1627} 1628@end 1629 1630static void create_initial_menus(void) 1631{ 1632 // Add menus 1633 NSMenu *menu; 1634 NSMenuItem *menuItem; 1635 1636 [NSApp setMainMenu:[[NSMenu alloc] init]]; 1637 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]]; 1638 1639 // Application menu 1640 menu = [[NSMenu alloc] initWithTitle:@""]; 1641 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU 1642 [menu addItem:[NSMenuItem separatorItem]]; //Separator 1643 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""]; 1644 [menuItem setSubmenu:[NSApp servicesMenu]]; 1645 [menu addItem:[NSMenuItem separatorItem]]; 1646 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU 1647 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others 1648 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)]; 1649 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All 1650 [menu addItem:[NSMenuItem separatorItem]]; //Separator 1651 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"]; 1652 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""]; 1653 [menuItem setSubmenu:menu]; 1654 [[NSApp mainMenu] addItem:menuItem]; 1655 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+) 1656 1657 // Machine menu 1658 menu = [[NSMenu alloc] initWithTitle: @"Machine"]; 1659 [menu setAutoenablesItems: NO]; 1660 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]]; 1661 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease]; 1662 [menu addItem: menuItem]; 1663 [menuItem setEnabled: NO]; 1664 [menu addItem: [NSMenuItem separatorItem]]; 1665 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]]; 1666 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]]; 1667 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease]; 1668 [menuItem setSubmenu:menu]; 1669 [[NSApp mainMenu] addItem:menuItem]; 1670 1671 // View menu 1672 menu = [[NSMenu alloc] initWithTitle:@"View"]; 1673 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen 1674 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]]; 1675 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease]; 1676 [menuItem setSubmenu:menu]; 1677 [[NSApp mainMenu] addItem:menuItem]; 1678 1679 // Speed menu 1680 menu = [[NSMenu alloc] initWithTitle:@"Speed"]; 1681 1682 // Add the rest of the Speed menu items 1683 int p, percentage, throttle_pct; 1684 for (p = 10; p >= 0; p--) 1685 { 1686 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item 1687 1688 menuItem = [[[NSMenuItem alloc] 1689 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease]; 1690 1691 if (percentage == 100) { 1692 [menuItem setState: NSControlStateValueOn]; 1693 } 1694 1695 /* Calculate the throttle percentage */ 1696 throttle_pct = -1 * percentage + 100; 1697 1698 [menuItem setTag: throttle_pct]; 1699 [menu addItem: menuItem]; 1700 } 1701 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease]; 1702 [menuItem setSubmenu:menu]; 1703 [[NSApp mainMenu] addItem:menuItem]; 1704 1705 // Window menu 1706 menu = [[NSMenu alloc] initWithTitle:@"Window"]; 1707 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize 1708 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease]; 1709 [menuItem setSubmenu:menu]; 1710 [[NSApp mainMenu] addItem:menuItem]; 1711 [NSApp setWindowsMenu:menu]; 1712 1713 // Help menu 1714 menu = [[NSMenu alloc] initWithTitle:@"Help"]; 1715 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help 1716 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease]; 1717 [menuItem setSubmenu:menu]; 1718 [[NSApp mainMenu] addItem:menuItem]; 1719} 1720 1721/* Returns a name for a given console */ 1722static NSString * getConsoleName(QemuConsole * console) 1723{ 1724 g_autofree char *label = qemu_console_get_label(console); 1725 1726 return [NSString stringWithUTF8String:label]; 1727} 1728 1729/* Add an entry to the View menu for each console */ 1730static void add_console_menu_entries(void) 1731{ 1732 NSMenu *menu; 1733 NSMenuItem *menuItem; 1734 int index = 0; 1735 1736 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu]; 1737 1738 [menu addItem:[NSMenuItem separatorItem]]; 1739 1740 while (qemu_console_lookup_by_index(index) != NULL) { 1741 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index)) 1742 action: @selector(displayConsole:) keyEquivalent: @""] autorelease]; 1743 [menuItem setTag: index]; 1744 [menu addItem: menuItem]; 1745 index++; 1746 } 1747} 1748 1749/* Make menu items for all removable devices. 1750 * Each device is given an 'Eject' and 'Change' menu item. 1751 */ 1752static void addRemovableDevicesMenuItems(void) 1753{ 1754 NSMenu *menu; 1755 NSMenuItem *menuItem; 1756 BlockInfoList *currentDevice, *pointerToFree; 1757 NSString *deviceName; 1758 1759 currentDevice = qmp_query_block(NULL); 1760 pointerToFree = currentDevice; 1761 1762 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu]; 1763 1764 // Add a separator between related groups of menu items 1765 [menu addItem:[NSMenuItem separatorItem]]; 1766 1767 // Set the attributes to the "Removable Media" menu item 1768 NSString *titleString = @"Removable Media"; 1769 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString]; 1770 NSColor *newColor = [NSColor blackColor]; 1771 NSFontManager *fontManager = [NSFontManager sharedFontManager]; 1772 NSFont *font = [fontManager fontWithFamily:@"Helvetica" 1773 traits:NSBoldFontMask|NSItalicFontMask 1774 weight:0 1775 size:14]; 1776 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])]; 1777 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])]; 1778 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])]; 1779 1780 // Add the "Removable Media" menu item 1781 menuItem = [NSMenuItem new]; 1782 [menuItem setAttributedTitle: attString]; 1783 [menuItem setEnabled: NO]; 1784 [menu addItem: menuItem]; 1785 1786 /* Loop through all the block devices in the emulator */ 1787 while (currentDevice) { 1788 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain]; 1789 1790 if(currentDevice->value->removable) { 1791 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device] 1792 action: @selector(changeDeviceMedia:) 1793 keyEquivalent: @""]; 1794 [menu addItem: menuItem]; 1795 [menuItem setRepresentedObject: deviceName]; 1796 [menuItem autorelease]; 1797 1798 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device] 1799 action: @selector(ejectDeviceMedia:) 1800 keyEquivalent: @""]; 1801 [menu addItem: menuItem]; 1802 [menuItem setRepresentedObject: deviceName]; 1803 [menuItem autorelease]; 1804 } 1805 currentDevice = currentDevice->next; 1806 } 1807 qapi_free_BlockInfoList(pointerToFree); 1808} 1809 1810@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner> 1811@end 1812 1813@implementation QemuCocoaPasteboardTypeOwner 1814 1815- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type 1816{ 1817 if (type != NSPasteboardTypeString) { 1818 return; 1819 } 1820 1821 with_iothread_lock(^{ 1822 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo); 1823 qemu_event_reset(&cbevent); 1824 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT); 1825 1826 while (info == cbinfo && 1827 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available && 1828 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) { 1829 qemu_mutex_unlock_iothread(); 1830 qemu_event_wait(&cbevent); 1831 qemu_mutex_lock_iothread(); 1832 } 1833 1834 if (info == cbinfo) { 1835 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data 1836 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size]; 1837 [sender setData:data forType:NSPasteboardTypeString]; 1838 [data release]; 1839 } 1840 1841 qemu_clipboard_info_unref(info); 1842 }); 1843} 1844 1845@end 1846 1847static QemuCocoaPasteboardTypeOwner *cbowner; 1848 1849static void cocoa_clipboard_notify(Notifier *notifier, void *data); 1850static void cocoa_clipboard_request(QemuClipboardInfo *info, 1851 QemuClipboardType type); 1852 1853static QemuClipboardPeer cbpeer = { 1854 .name = "cocoa", 1855 .notifier = { .notify = cocoa_clipboard_notify }, 1856 .request = cocoa_clipboard_request 1857}; 1858 1859static void cocoa_clipboard_update_info(QemuClipboardInfo *info) 1860{ 1861 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) { 1862 return; 1863 } 1864 1865 if (info != cbinfo) { 1866 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 1867 qemu_clipboard_info_unref(cbinfo); 1868 cbinfo = qemu_clipboard_info_ref(info); 1869 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner]; 1870 [pool release]; 1871 } 1872 1873 qemu_event_set(&cbevent); 1874} 1875 1876static void cocoa_clipboard_notify(Notifier *notifier, void *data) 1877{ 1878 QemuClipboardNotify *notify = data; 1879 1880 switch (notify->type) { 1881 case QEMU_CLIPBOARD_UPDATE_INFO: 1882 cocoa_clipboard_update_info(notify->info); 1883 return; 1884 case QEMU_CLIPBOARD_RESET_SERIAL: 1885 /* ignore */ 1886 return; 1887 } 1888} 1889 1890static void cocoa_clipboard_request(QemuClipboardInfo *info, 1891 QemuClipboardType type) 1892{ 1893 NSAutoreleasePool *pool; 1894 NSData *text; 1895 1896 switch (type) { 1897 case QEMU_CLIPBOARD_TYPE_TEXT: 1898 pool = [[NSAutoreleasePool alloc] init]; 1899 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString]; 1900 if (text) { 1901 qemu_clipboard_set_data(&cbpeer, info, type, 1902 [text length], [text bytes], true); 1903 } 1904 [pool release]; 1905 break; 1906 default: 1907 break; 1908 } 1909} 1910 1911/* 1912 * The startup process for the OSX/Cocoa UI is complicated, because 1913 * OSX insists that the UI runs on the initial main thread, and so we 1914 * need to start a second thread which runs the qemu_default_main(): 1915 * in main(): 1916 * in cocoa_display_init(): 1917 * assign cocoa_main to qemu_main 1918 * create application, menus, etc 1919 * in cocoa_main(): 1920 * create qemu-main thread 1921 * enter OSX run loop 1922 */ 1923 1924static void *call_qemu_main(void *opaque) 1925{ 1926 int status; 1927 1928 COCOA_DEBUG("Second thread: calling qemu_default_main()\n"); 1929 qemu_mutex_lock_iothread(); 1930 status = qemu_default_main(); 1931 qemu_mutex_unlock_iothread(); 1932 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n"); 1933 [cbowner release]; 1934 exit(status); 1935} 1936 1937static int cocoa_main(void) 1938{ 1939 QemuThread thread; 1940 1941 COCOA_DEBUG("Entered %s()\n", __func__); 1942 1943 qemu_mutex_unlock_iothread(); 1944 qemu_thread_create(&thread, "qemu_main", call_qemu_main, 1945 NULL, QEMU_THREAD_DETACHED); 1946 1947 // Start the main event loop 1948 COCOA_DEBUG("Main thread: entering OSX run loop\n"); 1949 [NSApp run]; 1950 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n"); 1951 1952 abort(); 1953} 1954 1955 1956 1957#pragma mark qemu 1958static void cocoa_update(DisplayChangeListener *dcl, 1959 int x, int y, int w, int h) 1960{ 1961 COCOA_DEBUG("qemu_cocoa: cocoa_update\n"); 1962 1963 dispatch_async(dispatch_get_main_queue(), ^{ 1964 NSRect rect; 1965 if ([cocoaView cdx] == 1.0) { 1966 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h); 1967 } else { 1968 rect = NSMakeRect( 1969 x * [cocoaView cdx], 1970 ([cocoaView gscreen].height - y - h) * [cocoaView cdy], 1971 w * [cocoaView cdx], 1972 h * [cocoaView cdy]); 1973 } 1974 [cocoaView setNeedsDisplayInRect:rect]; 1975 }); 1976} 1977 1978static void cocoa_switch(DisplayChangeListener *dcl, 1979 DisplaySurface *surface) 1980{ 1981 pixman_image_t *image = surface->image; 1982 1983 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n"); 1984 1985 // The DisplaySurface will be freed as soon as this callback returns. 1986 // We take a reference to the underlying pixman image here so it does 1987 // not disappear from under our feet; the switchSurface method will 1988 // deref the old image when it is done with it. 1989 pixman_image_ref(image); 1990 1991 dispatch_async(dispatch_get_main_queue(), ^{ 1992 [cocoaView updateUIInfo]; 1993 [cocoaView switchSurface:image]; 1994 }); 1995} 1996 1997static void cocoa_refresh(DisplayChangeListener *dcl) 1998{ 1999 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 2000 2001 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n"); 2002 graphic_hw_update(NULL); 2003 2004 if (qemu_input_is_absolute(dcl->con)) { 2005 dispatch_async(dispatch_get_main_queue(), ^{ 2006 if (![cocoaView isAbsoluteEnabled]) { 2007 if ([cocoaView isMouseGrabbed]) { 2008 [cocoaView ungrabMouse]; 2009 } 2010 } 2011 [cocoaView setAbsoluteEnabled:YES]; 2012 }); 2013 } 2014 2015 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) { 2016 qemu_clipboard_info_unref(cbinfo); 2017 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD); 2018 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) { 2019 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true; 2020 } 2021 qemu_clipboard_update(cbinfo); 2022 cbchangecount = [[NSPasteboard generalPasteboard] changeCount]; 2023 qemu_event_set(&cbevent); 2024 } 2025 2026 [pool release]; 2027} 2028 2029static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts) 2030{ 2031 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 2032 2033 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n"); 2034 2035 qemu_main = cocoa_main; 2036 2037 // Pull this console process up to being a fully-fledged graphical 2038 // app with a menubar and Dock icon 2039 ProcessSerialNumber psn = { 0, kCurrentProcess }; 2040 TransformProcessType(&psn, kProcessTransformToForegroundApplication); 2041 2042 [QemuApplication sharedApplication]; 2043 2044 create_initial_menus(); 2045 2046 /* 2047 * Create the menu entries which depend on QEMU state (for consoles 2048 * and removable devices). These make calls back into QEMU functions, 2049 * which is OK because at this point we know that the second thread 2050 * holds the iothread lock and is synchronously waiting for us to 2051 * finish. 2052 */ 2053 add_console_menu_entries(); 2054 addRemovableDevicesMenuItems(); 2055 2056 // Create an Application controller 2057 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init]; 2058 [NSApp setDelegate:controller]; 2059 2060 /* if fullscreen mode is to be used */ 2061 if (opts->has_full_screen && opts->full_screen) { 2062 [NSApp activateIgnoringOtherApps: YES]; 2063 [controller toggleFullScreen: nil]; 2064 } 2065 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) { 2066 [controller setFullGrab: nil]; 2067 } 2068 2069 if (opts->has_show_cursor && opts->show_cursor) { 2070 cursor_hide = 0; 2071 } 2072 if (opts->u.cocoa.has_swap_opt_cmd) { 2073 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd; 2074 } 2075 2076 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) { 2077 left_command_key_enabled = 0; 2078 } 2079 2080 // register vga output callbacks 2081 register_displaychangelistener(&dcl); 2082 2083 qemu_event_init(&cbevent, false); 2084 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init]; 2085 qemu_clipboard_peer_register(&cbpeer); 2086 2087 [pool release]; 2088} 2089 2090static QemuDisplay qemu_display_cocoa = { 2091 .type = DISPLAY_TYPE_COCOA, 2092 .init = cocoa_display_init, 2093}; 2094 2095static void register_cocoa(void) 2096{ 2097 qemu_display_register(&qemu_display_cocoa); 2098} 2099 2100type_init(register_cocoa); 2101