2 * QEMU Cocoa CG display driver
4 * Copyright (c) 2008 Mike Kronenberg
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 #include "qemu/osdep.h"
27 #import <Cocoa/Cocoa.h>
28 #include <crt_externs.h>
30 #include "qemu/help-texts.h"
31 #include "qemu-main.h"
32 #include "ui/clipboard.h"
33 #include "ui/console.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"
53 #ifndef MAC_OS_X_VERSION_10_13
54 #define MAC_OS_X_VERSION_10_13 101300
57 #ifndef MAC_OS_VERSION_14_0
58 #define MAC_OS_VERSION_14_0 140000
61 /* 10.14 deprecates NSOnState and NSOffState in favor of
62 * NSControlStateValueOn/Off, which were introduced in 10.13.
63 * Define for older versions
65 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
66 #define NSControlStateValueOn NSOnState
67 #define NSControlStateValueOff NSOffState
73 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
75 #define COCOA_DEBUG(...) ((void) 0)
78 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
80 #define UC_CTRL_KEY "\xe2\x8c\x83"
81 #define UC_ALT_KEY "\xe2\x8c\xa5"
88 static void cocoa_update(DisplayChangeListener *dcl,
89 int x, int y, int w, int h);
91 static void cocoa_switch(DisplayChangeListener *dcl,
92 DisplaySurface *surface);
94 static void cocoa_refresh(DisplayChangeListener *dcl);
96 static const DisplayChangeListenerOps dcl_ops = {
98 .dpy_gfx_update = cocoa_update,
99 .dpy_gfx_switch = cocoa_switch,
100 .dpy_refresh = cocoa_refresh,
102 static DisplayChangeListener dcl = {
105 static QKbdState *kbd;
106 static int cursor_hide = 1;
107 static int left_command_key_enabled = 1;
108 static bool swap_opt_cmd;
110 static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
111 static NSTextField *pauseLabel;
113 static bool allow_events;
115 static NSInteger cbchangecount = -1;
116 static QemuClipboardInfo *cbinfo;
117 static QemuEvent cbevent;
119 // Utility functions to run specified code block with the BQL held
120 typedef void (^CodeBlock)(void);
121 typedef bool (^BoolCodeBlock)(void);
123 static void with_bql(CodeBlock block)
125 bool locked = bql_locked();
135 static bool bool_with_bql(BoolCodeBlock block)
137 bool locked = bql_locked();
150 // Mac to QKeyCode conversion
151 static const int mac_to_qkeycode_map[] = {
152 [kVK_ANSI_A] = Q_KEY_CODE_A,
153 [kVK_ANSI_B] = Q_KEY_CODE_B,
154 [kVK_ANSI_C] = Q_KEY_CODE_C,
155 [kVK_ANSI_D] = Q_KEY_CODE_D,
156 [kVK_ANSI_E] = Q_KEY_CODE_E,
157 [kVK_ANSI_F] = Q_KEY_CODE_F,
158 [kVK_ANSI_G] = Q_KEY_CODE_G,
159 [kVK_ANSI_H] = Q_KEY_CODE_H,
160 [kVK_ANSI_I] = Q_KEY_CODE_I,
161 [kVK_ANSI_J] = Q_KEY_CODE_J,
162 [kVK_ANSI_K] = Q_KEY_CODE_K,
163 [kVK_ANSI_L] = Q_KEY_CODE_L,
164 [kVK_ANSI_M] = Q_KEY_CODE_M,
165 [kVK_ANSI_N] = Q_KEY_CODE_N,
166 [kVK_ANSI_O] = Q_KEY_CODE_O,
167 [kVK_ANSI_P] = Q_KEY_CODE_P,
168 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
169 [kVK_ANSI_R] = Q_KEY_CODE_R,
170 [kVK_ANSI_S] = Q_KEY_CODE_S,
171 [kVK_ANSI_T] = Q_KEY_CODE_T,
172 [kVK_ANSI_U] = Q_KEY_CODE_U,
173 [kVK_ANSI_V] = Q_KEY_CODE_V,
174 [kVK_ANSI_W] = Q_KEY_CODE_W,
175 [kVK_ANSI_X] = Q_KEY_CODE_X,
176 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
177 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
179 [kVK_ANSI_0] = Q_KEY_CODE_0,
180 [kVK_ANSI_1] = Q_KEY_CODE_1,
181 [kVK_ANSI_2] = Q_KEY_CODE_2,
182 [kVK_ANSI_3] = Q_KEY_CODE_3,
183 [kVK_ANSI_4] = Q_KEY_CODE_4,
184 [kVK_ANSI_5] = Q_KEY_CODE_5,
185 [kVK_ANSI_6] = Q_KEY_CODE_6,
186 [kVK_ANSI_7] = Q_KEY_CODE_7,
187 [kVK_ANSI_8] = Q_KEY_CODE_8,
188 [kVK_ANSI_9] = Q_KEY_CODE_9,
190 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
191 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
192 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
193 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
194 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
195 [kVK_Tab] = Q_KEY_CODE_TAB,
196 [kVK_Return] = Q_KEY_CODE_RET,
197 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
198 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
199 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
200 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
201 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
202 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
203 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
204 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
205 [kVK_Space] = Q_KEY_CODE_SPC,
207 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
208 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
209 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
210 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
211 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
212 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
213 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
214 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
215 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
216 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
217 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
218 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
219 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
220 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
221 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
222 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
223 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
224 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
226 [kVK_UpArrow] = Q_KEY_CODE_UP,
227 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
228 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
229 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
231 [kVK_Help] = Q_KEY_CODE_INSERT,
232 [kVK_Home] = Q_KEY_CODE_HOME,
233 [kVK_PageUp] = Q_KEY_CODE_PGUP,
234 [kVK_PageDown] = Q_KEY_CODE_PGDN,
235 [kVK_End] = Q_KEY_CODE_END,
236 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
238 [kVK_Escape] = Q_KEY_CODE_ESC,
240 /* The Power key can't be used directly because the operating system uses
241 * it. This key can be emulated by using it in place of another key such as
242 * F1. Don't forget to disable the real key binding.
244 /* [kVK_F1] = Q_KEY_CODE_POWER, */
246 [kVK_F1] = Q_KEY_CODE_F1,
247 [kVK_F2] = Q_KEY_CODE_F2,
248 [kVK_F3] = Q_KEY_CODE_F3,
249 [kVK_F4] = Q_KEY_CODE_F4,
250 [kVK_F5] = Q_KEY_CODE_F5,
251 [kVK_F6] = Q_KEY_CODE_F6,
252 [kVK_F7] = Q_KEY_CODE_F7,
253 [kVK_F8] = Q_KEY_CODE_F8,
254 [kVK_F9] = Q_KEY_CODE_F9,
255 [kVK_F10] = Q_KEY_CODE_F10,
256 [kVK_F11] = Q_KEY_CODE_F11,
257 [kVK_F12] = Q_KEY_CODE_F12,
258 [kVK_F13] = Q_KEY_CODE_PRINT,
259 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
260 [kVK_F15] = Q_KEY_CODE_PAUSE,
262 // JIS keyboards only
263 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
264 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
265 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
266 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
267 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
270 * The eject and volume keys can't be used here because they are handled at
271 * a lower level than what an Application can see.
275 static int cocoa_keycode_to_qemu(int keycode)
277 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
278 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
281 return mac_to_qkeycode_map[keycode];
284 /* Displays an alert dialog box with the specified message */
285 static void QEMU_Alert(NSString *message)
288 alert = [NSAlert new];
289 [alert setMessageText: message];
293 /* Handles any errors that happen with a device transaction */
294 static void handleAnyDeviceErrors(Error * err)
297 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
298 encoding: NSASCIIStringEncoding]);
304 ------------------------------------------------------
306 ------------------------------------------------------
308 @interface QemuCocoaView : NSView
311 pixman_image_t *pixman_image;
313 BOOL isAbsoluteEnabled;
314 CFMachPortRef eventsTap;
316 - (void) switchSurface:(pixman_image_t *)image;
318 - (void) ungrabMouse;
319 - (void) setFullGrab:(id)sender;
320 - (void) handleMonitorInput:(NSEvent *)event;
321 - (bool) handleEvent:(NSEvent *)event;
322 - (bool) handleEventLocked:(NSEvent *)event;
323 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
324 /* The state surrounding mouse grabbing is potentially confusing.
325 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
326 * pointing device an absolute-position one?"], but is only updated on
328 * isMouseGrabbed tracks whether GUI events are directed to the guest;
329 * it controls whether special keys like Cmd get sent to the guest,
330 * and whether we capture the mouse when in non-absolute mode.
332 - (BOOL) isMouseGrabbed;
333 - (BOOL) isAbsoluteEnabled;
334 - (QEMUScreen) gscreen;
335 - (void) raiseAllKeys;
338 QemuCocoaView *cocoaView;
340 static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
342 QemuCocoaView *view = userInfo;
343 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
344 if ([view isMouseGrabbed] && [view handleEvent:event]) {
345 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
348 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
353 @implementation QemuCocoaView
354 - (id)initWithFrame:(NSRect)frameRect
356 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
358 self = [super initWithFrame:frameRect];
361 NSTrackingAreaOptions options = NSTrackingActiveInKeyWindow |
362 NSTrackingMouseEnteredAndExited |
363 NSTrackingMouseMoved |
364 NSTrackingInVisibleRect;
366 NSTrackingArea *trackingArea =
367 [[NSTrackingArea alloc] initWithRect:CGRectZero
372 [self addTrackingArea:trackingArea];
373 [trackingArea release];
374 screen.width = frameRect.size.width;
375 screen.height = frameRect.size.height;
376 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
377 [self setClipsToBounds:YES];
386 COCOA_DEBUG("QemuCocoaView: dealloc\n");
389 pixman_image_unref(pixman_image);
393 CFRelease(eventsTap);
404 - (void) viewDidMoveToWindow
409 - (void) selectConsoleLocked:(unsigned int)index
411 QemuConsole *con = qemu_console_lookup_by_index(index);
416 unregister_displaychangelistener(&dcl);
417 qkbd_state_switch_console(kbd, con);
419 register_displaychangelistener(&dcl);
431 - (void) unhideCursor
439 - (void) drawRect:(NSRect) rect
441 COCOA_DEBUG("QemuCocoaView: drawRect\n");
443 // get CoreGraphic context
444 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
446 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
447 CGContextSetShouldAntialias (viewContextRef, NO);
449 // draw screen bitmap directly to Core Graphics context
451 // Draw request before any guest device has set up a framebuffer:
452 // just draw an opaque black rectangle
453 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
454 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
456 int w = pixman_image_get_width(pixman_image);
457 int h = pixman_image_get_height(pixman_image);
458 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
459 int stride = pixman_image_get_stride(pixman_image);
460 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
462 pixman_image_get_data(pixman_image),
466 CGImageRef imageRef = CGImageCreate(
469 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
470 bitsPerPixel, //bitsPerPixel
471 stride, //bytesPerRow
472 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
473 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
474 dataProviderRef, //provider
477 kCGRenderingIntentDefault //intent
479 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
480 const NSRect *rectList;
483 CGImageRef clipImageRef;
486 [self getRectsBeingDrawn:&rectList count:&rectCount];
487 for (i = 0; i < rectCount; i++) {
488 clipRect = rectList[i];
489 clipRect.origin.y = (float)h - (clipRect.origin.y + clipRect.size.height);
490 clipImageRef = CGImageCreateWithImageInRect(
494 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
495 CGImageRelease (clipImageRef);
497 CGImageRelease (imageRef);
498 CGDataProviderRelease(dataProviderRef);
502 - (NSSize)fixAspectRatio:(NSSize)max
507 scaled.width = screen.width * max.height;
508 scaled.height = screen.height * max.width;
511 * Here screen is our guest's output size, and max is the size of the
512 * largest possible area of the screen we can display on.
513 * We want to scale up (screen.width x screen.height) by either:
514 * 1) max.height / screen.height
515 * 2) max.width / screen.width
516 * With the first scale factor the scale will result in an output height of
517 * max.height (i.e. we will fill the whole height of the available screen
518 * space and have black bars left and right) and with the second scale
519 * factor the scaling will result in an output width of max.width (i.e. we
520 * fill the whole width of the available screen space and have black bars
521 * top and bottom). We need to pick whichever keeps the whole of the guest
522 * output on the screen, which is to say the smaller of the two scale
524 * To avoid doing more division than strictly necessary, instead of directly
525 * comparing scale factors 1 and 2 we instead calculate and compare those
526 * two scale factors multiplied by (screen.height * screen.width).
528 if (scaled.width < scaled.height) {
529 fixed.width = scaled.width / screen.height;
530 fixed.height = max.height;
532 fixed.width = max.width;
533 fixed.height = scaled.height / screen.width;
539 - (NSSize) screenSafeAreaSize
541 NSSize size = [[[self window] screen] frame].size;
542 NSEdgeInsets insets = [[[self window] screen] safeAreaInsets];
543 size.width -= insets.left + insets.right;
544 size.height -= insets.top + insets.bottom;
548 - (void) resizeWindow
550 [[self window] setContentAspectRatio:NSMakeSize(screen.width, screen.height)];
552 if (!([[self window] styleMask] & NSWindowStyleMaskResizable)) {
553 [[self window] setContentSize:NSMakeSize(screen.width, screen.height)];
554 [[self window] center];
555 } else if ([[self window] styleMask] & NSWindowStyleMaskFullScreen) {
556 [[self window] setContentSize:[self fixAspectRatio:[self screenSafeAreaSize]]];
557 [[self window] center];
559 [[self window] setContentSize:[self fixAspectRatio:[self frame].size]];
563 - (void) updateBounds
565 [self setBoundsSize:NSMakeSize(screen.width, screen.height)];
568 - (void) updateUIInfoLocked
570 /* Must be called with the BQL, i.e. via updateUIInfo */
574 if (!qemu_console_is_graphic(dcl.con)) {
579 NSDictionary *description = [[[self window] screen] deviceDescription];
580 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
581 NSSize screenSize = [[[self window] screen] frame].size;
582 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
583 bool isFullscreen = ([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0;
584 CVDisplayLinkRef displayLink;
586 frameSize = isFullscreen ? [self screenSafeAreaSize] : [self frame].size;
588 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
589 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
590 CVDisplayLinkRelease(displayLink);
591 if (!(period.flags & kCVTimeIsIndefinite)) {
592 update_displaychangelistener(&dcl,
593 1000 * period.timeValue / period.timeScale);
594 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
598 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
599 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
601 frameSize = [self frame].size;
608 info.width = frameSize.width;
609 info.height = frameSize.height;
611 dpy_set_ui_info(dcl.con, &info, TRUE);
614 - (void) updateUIInfo
618 * Don't try to tell QEMU about UI information in the application
619 * startup phase -- we haven't yet registered dcl with the QEMU UI
621 * When cocoa_display_init() does register the dcl, the UI layer
622 * will call cocoa_switch(), which will call updateUIInfo, so
623 * we don't lose any information here.
629 [self updateUIInfoLocked];
633 - (void) switchSurface:(pixman_image_t *)image
635 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
637 int w = pixman_image_get_width(image);
638 int h = pixman_image_get_height(image);
640 if (w != screen.width || h != screen.height) {
641 // Resize before we trigger the redraw, or we'll redraw at the wrong size
642 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
649 // update screenBuffer
651 pixman_image_unref(pixman_image);
654 pixman_image = image;
657 - (void) setFullGrab:(id)sender
659 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
661 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
662 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
663 mask, handleTapEvent, self);
665 warn_report("Could not create event tap, system key combos will not be captured.\n");
668 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
671 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
673 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
677 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
678 if (!tapEventsSrc ) {
679 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
683 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
684 CFRelease(tapEventsSrc);
687 - (void) toggleKey: (int)keycode {
688 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
691 // Does the work of sending input to the monitor
692 - (void) handleMonitorInput:(NSEvent *)event
697 // if the control key is down
698 if ([event modifierFlags] & NSEventModifierFlagControl) {
702 /* translates Macintosh keycodes to QEMU's keysym */
704 static const int without_control_translation[] = {
705 [0 ... 0xff] = 0, // invalid key
707 [kVK_UpArrow] = QEMU_KEY_UP,
708 [kVK_DownArrow] = QEMU_KEY_DOWN,
709 [kVK_RightArrow] = QEMU_KEY_RIGHT,
710 [kVK_LeftArrow] = QEMU_KEY_LEFT,
711 [kVK_Home] = QEMU_KEY_HOME,
712 [kVK_End] = QEMU_KEY_END,
713 [kVK_PageUp] = QEMU_KEY_PAGEUP,
714 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
715 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
716 [kVK_Delete] = QEMU_KEY_BACKSPACE,
719 static const int with_control_translation[] = {
720 [0 ... 0xff] = 0, // invalid key
722 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
723 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
724 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
725 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
726 [kVK_Home] = QEMU_KEY_CTRL_HOME,
727 [kVK_End] = QEMU_KEY_CTRL_END,
728 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
729 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
732 if (control_key != 0) { /* If the control key is being used */
733 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
734 keysym = with_control_translation[[event keyCode]];
737 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
738 keysym = without_control_translation[[event keyCode]];
742 // if not a key that needs translating
744 NSString *ks = [event characters];
745 if ([ks length] > 0) {
746 keysym = [ks characterAtIndex:0];
751 QemuTextConsole *con = QEMU_TEXT_CONSOLE(dcl.con);
752 qemu_text_console_put_keysym(con, keysym);
756 - (bool) handleEvent:(NSEvent *)event
758 return bool_with_bql(^{
759 return [self handleEventLocked:event];
763 - (bool) handleEventLocked:(NSEvent *)event
765 /* Return true if we handled the event, false if it should be given to OSX */
766 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
769 NSUInteger modifiers = [event modifierFlags];
772 * Check -[NSEvent modifierFlags] here.
774 * There is a NSEventType for an event notifying the change of
775 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
776 * are performed for any events because a modifier state may change while
777 * the application is inactive (i.e. no events fire) and we don't want to
778 * wait for another modifier state change to detect such a change.
780 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
781 * are handled in similar manners.
783 * NSEventModifierFlagCapsLock
784 * ---------------------------
786 * If CapsLock state is changed, "up" and "down" events will be fired in
787 * sequence, effectively updates CapsLock state on the guest.
792 * If a flag is not set, fire "up" events for all keys which correspond to
793 * the flag. Note that "down" events are not fired here because the flags
794 * checked here do not tell what exact keys are down.
796 * If one of the keys corresponding to a flag is down, we rely on
797 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
798 * NSEventTypeFlagsChanged to know the exact key which is down, which has
799 * the following two downsides:
800 * - It does not work when the application is inactive as described above.
801 * - It malfactions *after* the modifier state is changed while the
802 * application is inactive. It is because -[NSEvent keyCode] does not tell
803 * if the key is up or down, and requires to infer the current state from
804 * the previous state. It is still possible to fix such a malfanction by
805 * completely leaving your hands from the keyboard, which hopefully makes
806 * this implementation usable enough.
808 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
809 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
810 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
811 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
814 if (!(modifiers & NSEventModifierFlagShift)) {
815 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
816 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
818 if (!(modifiers & NSEventModifierFlagControl)) {
819 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
820 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
822 if (!(modifiers & NSEventModifierFlagOption)) {
824 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
825 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
827 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
828 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
831 if (!(modifiers & NSEventModifierFlagCommand)) {
833 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
834 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
836 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
837 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
841 switch ([event type]) {
842 case NSEventTypeFlagsChanged:
843 switch ([event keyCode]) {
845 if (!!(modifiers & NSEventModifierFlagShift)) {
846 [self toggleKey:Q_KEY_CODE_SHIFT];
851 if (!!(modifiers & NSEventModifierFlagShift)) {
852 [self toggleKey:Q_KEY_CODE_SHIFT_R];
857 if (!!(modifiers & NSEventModifierFlagControl)) {
858 [self toggleKey:Q_KEY_CODE_CTRL];
862 case kVK_RightControl:
863 if (!!(modifiers & NSEventModifierFlagControl)) {
864 [self toggleKey:Q_KEY_CODE_CTRL_R];
869 if (!!(modifiers & NSEventModifierFlagOption)) {
871 [self toggleKey:Q_KEY_CODE_META_L];
873 [self toggleKey:Q_KEY_CODE_ALT];
878 case kVK_RightOption:
879 if (!!(modifiers & NSEventModifierFlagOption)) {
881 [self toggleKey:Q_KEY_CODE_META_R];
883 [self toggleKey:Q_KEY_CODE_ALT_R];
888 /* Don't pass command key changes to guest unless mouse is grabbed */
890 if (isMouseGrabbed &&
891 !!(modifiers & NSEventModifierFlagCommand) &&
892 left_command_key_enabled) {
894 [self toggleKey:Q_KEY_CODE_ALT];
896 [self toggleKey:Q_KEY_CODE_META_L];
901 case kVK_RightCommand:
902 if (isMouseGrabbed &&
903 !!(modifiers & NSEventModifierFlagCommand)) {
905 [self toggleKey:Q_KEY_CODE_ALT_R];
907 [self toggleKey:Q_KEY_CODE_META_R];
913 case NSEventTypeKeyDown:
914 keycode = cocoa_keycode_to_qemu([event keyCode]);
916 // forward command key combos to the host UI unless the mouse is grabbed
917 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
923 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
924 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
925 NSString *keychar = [event charactersIgnoringModifiers];
926 if ([keychar length] == 1) {
927 char key = [keychar characterAtIndex:0];
930 // enable graphic console
932 [self selectConsoleLocked:key - '0' - 1]; /* ascii math */
935 // release the mouse grab
943 if (qemu_console_is_graphic(dcl.con)) {
944 qkbd_state_key_event(kbd, keycode, true);
946 [self handleMonitorInput: event];
949 case NSEventTypeKeyUp:
950 keycode = cocoa_keycode_to_qemu([event keyCode]);
952 // don't pass the guest a spurious key-up if we treated this
953 // command-key combo as a host UI action
954 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
958 if (qemu_console_is_graphic(dcl.con)) {
959 qkbd_state_key_event(kbd, keycode, false);
962 case NSEventTypeScrollWheel:
964 * Send wheel events to the guest regardless of window focus.
965 * This is in-line with standard Mac OS X UI behaviour.
968 /* Determine if this is a scroll up or scroll down event */
969 if ([event deltaY] != 0) {
970 button = ([event deltaY] > 0) ?
971 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
972 } else if ([event deltaX] != 0) {
973 button = ([event deltaX] > 0) ?
974 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
977 * We shouldn't have got a scroll event when deltaY and delta Y
978 * are zero, hence no harm in dropping the event
983 qemu_input_queue_btn(dcl.con, button, true);
984 qemu_input_event_sync();
985 qemu_input_queue_btn(dcl.con, button, false);
986 qemu_input_event_sync();
994 - (void) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
996 if (!isMouseGrabbed) {
1001 qemu_input_queue_btn(dcl.con, button, down);
1004 [self handleMouseEvent:event];
1007 - (void) handleMouseEvent:(NSEvent *)event
1009 if (!isMouseGrabbed) {
1014 if (isAbsoluteEnabled) {
1015 CGFloat d = (CGFloat)screen.height / [self frame].size.height;
1016 NSPoint p = [event locationInWindow];
1018 /* Note that the origin for Cocoa mouse coords is bottom left, not top left. */
1019 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x * d, 0, screen.width);
1020 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y * d, 0, screen.height);
1022 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, [event deltaX]);
1023 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, [event deltaY]);
1026 qemu_input_event_sync();
1030 - (void) mouseExited:(NSEvent *)event
1032 if (isAbsoluteEnabled && isMouseGrabbed) {
1037 - (void) mouseEntered:(NSEvent *)event
1039 if (isAbsoluteEnabled && !isMouseGrabbed) {
1044 - (void) mouseMoved:(NSEvent *)event
1046 [self handleMouseEvent:event];
1049 - (void) mouseDown:(NSEvent *)event
1051 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
1054 - (void) rightMouseDown:(NSEvent *)event
1056 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
1059 - (void) otherMouseDown:(NSEvent *)event
1061 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
1064 - (void) mouseDragged:(NSEvent *)event
1066 [self handleMouseEvent:event];
1069 - (void) rightMouseDragged:(NSEvent *)event
1071 [self handleMouseEvent:event];
1074 - (void) otherMouseDragged:(NSEvent *)event
1076 [self handleMouseEvent:event];
1079 - (void) mouseUp:(NSEvent *)event
1081 if (!isMouseGrabbed) {
1085 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
1088 - (void) rightMouseUp:(NSEvent *)event
1090 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
1093 - (void) otherMouseUp:(NSEvent *)event
1095 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
1100 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1103 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]];
1105 [[self window] setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
1107 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1108 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1111 - (void) ungrabMouse
1113 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1116 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1118 [[self window] setTitle:@"QEMU"];
1119 [self unhideCursor];
1120 CGAssociateMouseAndMouseCursorPosition(TRUE);
1121 isMouseGrabbed = FALSE;
1122 [self raiseAllButtons];
1125 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1126 isAbsoluteEnabled = tIsAbsoluteEnabled;
1127 if (isMouseGrabbed) {
1128 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1131 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1132 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1133 - (QEMUScreen) gscreen {return screen;}
1136 * Makes the target think all down keys are being released.
1137 * This prevents a stuck key problem, since we will not see
1138 * key up events for those keys after we have lost focus.
1140 - (void) raiseAllKeys
1143 qkbd_state_lift_all_keys(kbd);
1147 - (void) raiseAllButtons
1150 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_LEFT, false);
1151 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_RIGHT, false);
1152 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_MIDDLE, false);
1160 ------------------------------------------------------
1161 QemuCocoaAppController
1162 ------------------------------------------------------
1164 @interface QemuCocoaAppController : NSObject
1165 <NSWindowDelegate, NSApplicationDelegate>
1168 - (void)doToggleFullScreen:(id)sender;
1169 - (void)showQEMUDoc:(id)sender;
1170 - (void)zoomToFit:(id) sender;
1171 - (void)displayConsole:(id)sender;
1172 - (void)pauseQEMU:(id)sender;
1173 - (void)resumeQEMU:(id)sender;
1174 - (void)displayPause;
1175 - (void)removePause;
1176 - (void)restartQEMU:(id)sender;
1177 - (void)powerDownQEMU:(id)sender;
1178 - (void)ejectDeviceMedia:(id)sender;
1179 - (void)changeDeviceMedia:(id)sender;
1181 - (void)openDocumentation:(NSString *)filename;
1182 - (IBAction) do_about_menu_item: (id) sender;
1183 - (void)adjustSpeed:(id)sender;
1186 @implementation QemuCocoaAppController
1191 COCOA_DEBUG("QemuCocoaAppController: init\n");
1193 self = [super init];
1196 // create a view and add it to the window
1197 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1199 error_report("(cocoa) can't create a view");
1204 window = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1205 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1206 backing:NSBackingStoreBuffered defer:NO];
1208 error_report("(cocoa) can't create window");
1211 [window setAcceptsMouseMovedEvents:YES];
1212 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
1213 [window setTitle:qemu_name ? [NSString stringWithFormat:@"QEMU %s", qemu_name] : @"QEMU"];
1214 [window setContentView:cocoaView];
1215 [window makeKeyAndOrderFront:self];
1217 [window setDelegate: self];
1219 /* Used for displaying pause on the screen */
1220 pauseLabel = [NSTextField new];
1221 [pauseLabel setBezeled:YES];
1222 [pauseLabel setDrawsBackground:YES];
1223 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1224 [pauseLabel setEditable:NO];
1225 [pauseLabel setSelectable:NO];
1226 [pauseLabel setStringValue: @"Paused"];
1227 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1228 [pauseLabel setTextColor: [NSColor blackColor]];
1229 [pauseLabel sizeToFit];
1236 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1239 [cocoaView release];
1243 - (void)applicationDidFinishLaunching: (NSNotification *) note
1245 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1246 allow_events = true;
1249 - (void)applicationWillTerminate:(NSNotification *)aNotification
1251 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1254 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1255 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1259 * Sleep here, because returning will cause OSX to kill us
1260 * immediately; the QEMU main loop will handle the shutdown
1261 * request and terminate the process.
1263 [NSThread sleepForTimeInterval:INFINITY];
1266 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1271 - (NSApplicationTerminateReply)applicationShouldTerminate:
1272 (NSApplication *)sender
1274 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1275 return [self verifyQuit];
1278 - (void)windowDidChangeScreen:(NSNotification *)notification
1280 [cocoaView updateUIInfo];
1283 - (void)windowDidEnterFullScreen:(NSNotification *)notification
1285 [cocoaView grabMouse];
1288 - (void)windowDidExitFullScreen:(NSNotification *)notification
1290 [cocoaView resizeWindow];
1291 [cocoaView ungrabMouse];
1294 - (void)windowDidResize:(NSNotification *)notification
1296 [cocoaView updateBounds];
1297 [cocoaView updateUIInfo];
1300 /* Called when the user clicks on a window's close button */
1301 - (BOOL)windowShouldClose:(id)sender
1303 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1304 [NSApp terminate: sender];
1305 /* If the user allows the application to quit then the call to
1306 * NSApp terminate will never return. If we get here then the user
1307 * cancelled the quit, so we should return NO to not permit the
1308 * closing of this window.
1313 - (NSApplicationPresentationOptions) window:(NSWindow *)window
1314 willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions;
1317 return (proposedOptions & ~(NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)) |
1318 NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
1322 * Called when QEMU goes into the background. Note that
1323 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1324 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1325 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1327 - (void) windowDidResignKey: (NSNotification *)aNotification
1329 COCOA_DEBUG("%s\n", __func__);
1330 [cocoaView ungrabMouse];
1331 [cocoaView raiseAllKeys];
1334 /* We abstract the method called by the Enter Fullscreen menu item
1335 * because Mac OS 10.7 and higher disables it. This is because of the
1336 * menu item's old selector's name toggleFullScreen:
1338 - (void) doToggleFullScreen:(id)sender
1340 [[cocoaView window] toggleFullScreen:sender];
1343 - (void) setFullGrab:(id)sender
1345 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1347 [cocoaView setFullGrab:sender];
1350 /* Tries to find then open the specified filename */
1351 - (void) openDocumentation: (NSString *) filename
1353 /* Where to look for local files */
1354 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1355 NSString *full_file_path;
1356 NSURL *full_file_url;
1358 /* iterate thru the possible paths until the file is found */
1360 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1361 full_file_path = [[NSBundle mainBundle] executablePath];
1362 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1363 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1364 path_array[index], filename];
1365 full_file_url = [NSURL fileURLWithPath: full_file_path
1366 isDirectory: false];
1367 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1372 /* If none of the paths opened a file */
1374 QEMU_Alert(@"Failed to open file");
1377 - (void)showQEMUDoc:(id)sender
1379 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1381 [self openDocumentation: @"index.html"];
1384 /* Stretches video to fit host monitor size */
1385 - (void)zoomToFit:(id) sender
1387 NSWindowStyleMask styleMask = [[cocoaView window] styleMask] ^ NSWindowStyleMaskResizable;
1389 [[cocoaView window] setStyleMask:styleMask];
1390 [sender setState:styleMask & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
1391 [cocoaView resizeWindow];
1394 - (void)toggleZoomInterpolation:(id) sender
1396 if (zoom_interpolation == kCGInterpolationNone) {
1397 zoom_interpolation = kCGInterpolationLow;
1398 [sender setState: NSControlStateValueOn];
1400 zoom_interpolation = kCGInterpolationNone;
1401 [sender setState: NSControlStateValueOff];
1405 /* Displays the console on the screen */
1406 - (void)displayConsole:(id)sender
1409 [cocoaView selectConsoleLocked:[sender tag]];
1413 /* Pause the guest */
1414 - (void)pauseQEMU:(id)sender
1419 [sender setEnabled: NO];
1420 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1421 [self displayPause];
1424 /* Resume running the guest operating system */
1425 - (void)resumeQEMU:(id) sender
1430 [sender setEnabled: NO];
1431 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1435 /* Displays the word pause on the screen */
1436 - (void)displayPause
1438 /* Coordinates have to be calculated each time because the window can change its size */
1439 int xCoord, yCoord, width, height;
1440 xCoord = ([cocoaView frame].size.width - [pauseLabel frame].size.width)/2;
1441 yCoord = [cocoaView frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1442 width = [pauseLabel frame].size.width;
1443 height = [pauseLabel frame].size.height;
1444 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1445 [cocoaView addSubview: pauseLabel];
1448 /* Removes the word pause from the screen */
1451 [pauseLabel removeFromSuperview];
1455 - (void)restartQEMU:(id)sender
1458 qmp_system_reset(NULL);
1462 /* Powers down QEMU */
1463 - (void)powerDownQEMU:(id)sender
1466 qmp_system_powerdown(NULL);
1470 /* Ejects the media.
1471 * Uses sender's tag to figure out the device to eject.
1473 - (void)ejectDeviceMedia:(id)sender
1476 drive = [sender representedObject];
1479 QEMU_Alert(@"Failed to find drive to eject!");
1483 __block Error *err = NULL;
1485 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1486 NULL, false, false, &err);
1488 handleAnyDeviceErrors(err);
1491 /* Displays a dialog box asking the user to select an image file to load.
1492 * Uses sender's represented object value to figure out which drive to use.
1494 - (void)changeDeviceMedia:(id)sender
1496 /* Find the drive name */
1498 drive = [sender representedObject];
1501 QEMU_Alert(@"Could not find drive!");
1505 /* Display the file open dialog */
1506 NSOpenPanel * openPanel;
1507 openPanel = [NSOpenPanel openPanel];
1508 [openPanel setCanChooseFiles: YES];
1509 [openPanel setAllowsMultipleSelection: NO];
1510 if([openPanel runModal] == NSModalResponseOK) {
1511 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1514 QEMU_Alert(@"Failed to convert URL to file path!");
1518 __block Error *err = NULL;
1520 qmp_blockdev_change_medium([drive cStringUsingEncoding:
1521 NSASCIIStringEncoding],
1523 [file cStringUsingEncoding:
1524 NSASCIIStringEncoding],
1530 handleAnyDeviceErrors(err);
1534 /* Verifies if the user really wants to quit */
1537 NSAlert *alert = [NSAlert new];
1538 [alert autorelease];
1539 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1540 [alert addButtonWithTitle: @"Cancel"];
1541 [alert addButtonWithTitle: @"Quit"];
1542 if([alert runModal] == NSAlertSecondButtonReturn) {
1549 /* The action method for the About menu item */
1550 - (IBAction) do_about_menu_item: (id) sender
1552 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1553 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1554 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1555 g_free(icon_path_c);
1556 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1557 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1558 NSString *copyright = @QEMU_COPYRIGHT;
1559 NSDictionary *options;
1562 NSAboutPanelOptionApplicationIcon : icon,
1563 NSAboutPanelOptionApplicationVersion : version,
1564 @"Copyright" : copyright,
1569 NSAboutPanelOptionApplicationVersion : version,
1570 @"Copyright" : copyright,
1573 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1577 /* Used by the Speed menu items */
1578 - (void)adjustSpeed:(id)sender
1580 int throttle_pct; /* throttle percentage */
1583 menu = [sender menu];
1586 /* Unselect the currently selected item */
1587 for (NSMenuItem *item in [menu itemArray]) {
1588 if (item.state == NSControlStateValueOn) {
1589 [item setState: NSControlStateValueOff];
1595 // check the menu item
1596 [sender setState: NSControlStateValueOn];
1598 // get the throttle percentage
1599 throttle_pct = [sender tag];
1602 cpu_throttle_set(throttle_pct);
1604 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1609 @interface QemuApplication : NSApplication
1612 @implementation QemuApplication
1613 - (void)sendEvent:(NSEvent *)event
1615 COCOA_DEBUG("QemuApplication: sendEvent\n");
1616 if (![cocoaView handleEvent:event]) {
1617 [super sendEvent: event];
1622 static void create_initial_menus(void)
1626 NSMenuItem *menuItem;
1628 [NSApp setMainMenu:[[NSMenu alloc] init]];
1629 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1632 menu = [[NSMenu alloc] initWithTitle:@""];
1633 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1634 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1635 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1636 [menuItem setSubmenu:[NSApp servicesMenu]];
1637 [menu addItem:[NSMenuItem separatorItem]];
1638 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1639 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1640 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1641 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1642 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1643 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1644 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1645 [menuItem setSubmenu:menu];
1646 [[NSApp mainMenu] addItem:menuItem];
1647 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1650 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1651 [menu setAutoenablesItems: NO];
1652 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1653 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1654 [menu addItem: menuItem];
1655 [menuItem setEnabled: NO];
1656 [menu addItem: [NSMenuItem separatorItem]];
1657 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1658 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1659 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1660 [menuItem setSubmenu:menu];
1661 [[NSApp mainMenu] addItem:menuItem];
1664 menu = [[NSMenu alloc] initWithTitle:@"View"];
1665 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1666 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1667 [menuItem setState: [[cocoaView window] styleMask] & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
1668 [menu addItem: menuItem];
1669 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1670 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1671 [menu addItem: menuItem];
1672 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1673 [menuItem setSubmenu:menu];
1674 [[NSApp mainMenu] addItem:menuItem];
1677 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1679 // Add the rest of the Speed menu items
1680 int p, percentage, throttle_pct;
1681 for (p = 10; p >= 0; p--)
1683 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1685 menuItem = [[[NSMenuItem alloc]
1686 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1688 if (percentage == 100) {
1689 [menuItem setState: NSControlStateValueOn];
1692 /* Calculate the throttle percentage */
1693 throttle_pct = -1 * percentage + 100;
1695 [menuItem setTag: throttle_pct];
1696 [menu addItem: menuItem];
1698 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1699 [menuItem setSubmenu:menu];
1700 [[NSApp mainMenu] addItem:menuItem];
1703 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1704 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1705 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1706 [menuItem setSubmenu:menu];
1707 [[NSApp mainMenu] addItem:menuItem];
1708 [NSApp setWindowsMenu:menu];
1711 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1712 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1713 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1714 [menuItem setSubmenu:menu];
1715 [[NSApp mainMenu] addItem:menuItem];
1718 /* Returns a name for a given console */
1719 static NSString * getConsoleName(QemuConsole * console)
1721 g_autofree char *label = qemu_console_get_label(console);
1723 return [NSString stringWithUTF8String:label];
1726 /* Add an entry to the View menu for each console */
1727 static void add_console_menu_entries(void)
1730 NSMenuItem *menuItem;
1733 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1735 [menu addItem:[NSMenuItem separatorItem]];
1737 while (qemu_console_lookup_by_index(index) != NULL) {
1738 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1739 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1740 [menuItem setTag: index];
1741 [menu addItem: menuItem];
1746 /* Make menu items for all removable devices.
1747 * Each device is given an 'Eject' and 'Change' menu item.
1749 static void addRemovableDevicesMenuItems(void)
1752 NSMenuItem *menuItem;
1753 BlockInfoList *currentDevice, *pointerToFree;
1754 NSString *deviceName;
1756 currentDevice = qmp_query_block(NULL);
1757 pointerToFree = currentDevice;
1759 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1761 // Add a separator between related groups of menu items
1762 [menu addItem:[NSMenuItem separatorItem]];
1764 // Set the attributes to the "Removable Media" menu item
1765 NSString *titleString = @"Removable Media";
1766 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1767 NSColor *newColor = [NSColor blackColor];
1768 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1769 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1770 traits:NSBoldFontMask|NSItalicFontMask
1773 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1774 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1775 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1777 // Add the "Removable Media" menu item
1778 menuItem = [NSMenuItem new];
1779 [menuItem setAttributedTitle: attString];
1780 [menuItem setEnabled: NO];
1781 [menu addItem: menuItem];
1783 /* Loop through all the block devices in the emulator */
1784 while (currentDevice) {
1785 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1787 if(currentDevice->value->removable) {
1788 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1789 action: @selector(changeDeviceMedia:)
1790 keyEquivalent: @""];
1791 [menu addItem: menuItem];
1792 [menuItem setRepresentedObject: deviceName];
1793 [menuItem autorelease];
1795 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1796 action: @selector(ejectDeviceMedia:)
1797 keyEquivalent: @""];
1798 [menu addItem: menuItem];
1799 [menuItem setRepresentedObject: deviceName];
1800 [menuItem autorelease];
1802 currentDevice = currentDevice->next;
1804 qapi_free_BlockInfoList(pointerToFree);
1807 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1810 @implementation QemuCocoaPasteboardTypeOwner
1812 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1814 if (type != NSPasteboardTypeString) {
1819 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1820 qemu_event_reset(&cbevent);
1821 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1823 while (info == cbinfo &&
1824 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1825 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1827 qemu_event_wait(&cbevent);
1831 if (info == cbinfo) {
1832 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1833 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1834 [sender setData:data forType:NSPasteboardTypeString];
1838 qemu_clipboard_info_unref(info);
1844 static QemuCocoaPasteboardTypeOwner *cbowner;
1846 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1847 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1848 QemuClipboardType type);
1850 static QemuClipboardPeer cbpeer = {
1852 .notifier = { .notify = cocoa_clipboard_notify },
1853 .request = cocoa_clipboard_request
1856 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1858 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1862 if (info != cbinfo) {
1863 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1864 qemu_clipboard_info_unref(cbinfo);
1865 cbinfo = qemu_clipboard_info_ref(info);
1866 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1870 qemu_event_set(&cbevent);
1873 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1875 QemuClipboardNotify *notify = data;
1877 switch (notify->type) {
1878 case QEMU_CLIPBOARD_UPDATE_INFO:
1879 cocoa_clipboard_update_info(notify->info);
1881 case QEMU_CLIPBOARD_RESET_SERIAL:
1887 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1888 QemuClipboardType type)
1890 NSAutoreleasePool *pool;
1894 case QEMU_CLIPBOARD_TYPE_TEXT:
1895 pool = [[NSAutoreleasePool alloc] init];
1896 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1898 qemu_clipboard_set_data(&cbpeer, info, type,
1899 [text length], [text bytes], true);
1909 * The startup process for the OSX/Cocoa UI is complicated, because
1910 * OSX insists that the UI runs on the initial main thread, and so we
1911 * need to start a second thread which runs the qemu_default_main():
1913 * in cocoa_display_init():
1914 * assign cocoa_main to qemu_main
1915 * create application, menus, etc
1917 * create qemu-main thread
1918 * enter OSX run loop
1921 static void *call_qemu_main(void *opaque)
1925 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
1927 status = qemu_default_main();
1929 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
1934 static int cocoa_main(void)
1938 COCOA_DEBUG("Entered %s()\n", __func__);
1941 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1942 NULL, QEMU_THREAD_DETACHED);
1944 // Start the main event loop
1945 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1947 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
1955 static void cocoa_update(DisplayChangeListener *dcl,
1956 int x, int y, int w, int h)
1958 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1960 dispatch_async(dispatch_get_main_queue(), ^{
1961 NSRect rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1962 [cocoaView setNeedsDisplayInRect:rect];
1966 static void cocoa_switch(DisplayChangeListener *dcl,
1967 DisplaySurface *surface)
1969 pixman_image_t *image = surface->image;
1971 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1973 // The DisplaySurface will be freed as soon as this callback returns.
1974 // We take a reference to the underlying pixman image here so it does
1975 // not disappear from under our feet; the switchSurface method will
1976 // deref the old image when it is done with it.
1977 pixman_image_ref(image);
1979 dispatch_async(dispatch_get_main_queue(), ^{
1980 [cocoaView switchSurface:image];
1984 static void cocoa_refresh(DisplayChangeListener *dcl)
1986 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1988 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1989 graphic_hw_update(dcl->con);
1991 if (qemu_input_is_absolute(dcl->con)) {
1992 dispatch_async(dispatch_get_main_queue(), ^{
1993 if (![cocoaView isAbsoluteEnabled]) {
1994 if ([cocoaView isMouseGrabbed]) {
1995 [cocoaView ungrabMouse];
1998 [cocoaView setAbsoluteEnabled:YES];
2002 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2003 qemu_clipboard_info_unref(cbinfo);
2004 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2005 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2006 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2008 qemu_clipboard_update(cbinfo);
2009 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2010 qemu_event_set(&cbevent);
2016 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2018 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2020 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2022 qemu_main = cocoa_main;
2024 // Pull this console process up to being a fully-fledged graphical
2025 // app with a menubar and Dock icon
2026 ProcessSerialNumber psn = { 0, kCurrentProcess };
2027 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2029 [QemuApplication sharedApplication];
2031 // Create an Application controller
2032 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2033 [NSApp setDelegate:controller];
2035 /* if fullscreen mode is to be used */
2036 if (opts->has_full_screen && opts->full_screen) {
2037 [[cocoaView window] toggleFullScreen: nil];
2039 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2040 [controller setFullGrab: nil];
2043 if (opts->has_show_cursor && opts->show_cursor) {
2046 if (opts->u.cocoa.has_swap_opt_cmd) {
2047 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2050 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2051 left_command_key_enabled = 0;
2054 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2055 [cocoaView window].styleMask |= NSWindowStyleMaskResizable;
2058 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2059 zoom_interpolation = kCGInterpolationLow;
2062 create_initial_menus();
2064 * Create the menu entries which depend on QEMU state (for consoles
2065 * and removable devices). These make calls back into QEMU functions,
2066 * which is OK because at this point we know that the second thread
2067 * holds the BQL and is synchronously waiting for us to
2070 add_console_menu_entries();
2071 addRemovableDevicesMenuItems();
2073 dcl.con = qemu_console_lookup_default();
2074 kbd = qkbd_state_init(dcl.con);
2076 // register vga output callbacks
2077 register_displaychangelistener(&dcl);
2078 [cocoaView updateUIInfo];
2080 qemu_event_init(&cbevent, false);
2081 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2082 qemu_clipboard_peer_register(&cbpeer);
2087 static QemuDisplay qemu_display_cocoa = {
2088 .type = DISPLAY_TYPE_COCOA,
2089 .init = cocoa_display_init,
2092 static void register_cocoa(void)
2094 qemu_display_register(&qemu_display_cocoa);
2097 type_init(register_cocoa);