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