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