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 #import <QuartzCore/QuartzCore.h>
29 #include <crt_externs.h>
31 #include "qemu/help-texts.h"
32 #include "qemu-main.h"
33 #include "ui/clipboard.h"
34 #include "ui/console.h"
36 #include "ui/kbd-state.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/runstate.h"
39 #include "sysemu/runstate-action.h"
40 #include "sysemu/cpu-throttle.h"
41 #include "qapi/error.h"
42 #include "qapi/qapi-commands-block.h"
43 #include "qapi/qapi-commands-machine.h"
44 #include "qapi/qapi-commands-misc.h"
45 #include "sysemu/blockdev.h"
46 #include "qemu-version.h"
47 #include "qemu/cutils.h"
48 #include "qemu/main-loop.h"
49 #include "qemu/module.h"
50 #include "qemu/error-report.h"
51 #include <Carbon/Carbon.h>
52 #include "hw/core/cpu.h"
54 #ifndef MAC_OS_VERSION_14_0
55 #define MAC_OS_VERSION_14_0 140000
61 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
63 #define COCOA_DEBUG(...) ((void) 0)
66 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
68 #define UC_CTRL_KEY "\xe2\x8c\x83"
69 #define UC_ALT_KEY "\xe2\x8c\xa5"
76 static void cocoa_update(DisplayChangeListener *dcl,
77 int x, int y, int w, int h);
79 static void cocoa_switch(DisplayChangeListener *dcl,
80 DisplaySurface *surface);
82 static void cocoa_refresh(DisplayChangeListener *dcl);
83 static void cocoa_mouse_set(DisplayChangeListener *dcl, int x, int y, bool on);
84 static void cocoa_cursor_define(DisplayChangeListener *dcl, QEMUCursor *cursor);
86 static const DisplayChangeListenerOps dcl_ops = {
88 .dpy_gfx_update = cocoa_update,
89 .dpy_gfx_switch = cocoa_switch,
90 .dpy_refresh = cocoa_refresh,
91 .dpy_mouse_set = cocoa_mouse_set,
92 .dpy_cursor_define = cocoa_cursor_define,
94 static DisplayChangeListener dcl = {
97 static QKbdState *kbd;
98 static int cursor_hide = 1;
99 static int left_command_key_enabled = 1;
100 static bool swap_opt_cmd;
102 static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
103 static NSTextField *pauseLabel;
105 static bool allow_events;
107 static NSInteger cbchangecount = -1;
108 static QemuClipboardInfo *cbinfo;
109 static QemuEvent cbevent;
111 // Utility functions to run specified code block with the BQL held
112 typedef void (^CodeBlock)(void);
113 typedef bool (^BoolCodeBlock)(void);
115 static void with_bql(CodeBlock block)
117 bool locked = bql_locked();
127 static bool bool_with_bql(BoolCodeBlock block)
129 bool locked = bql_locked();
142 // Mac to QKeyCode conversion
143 static const int mac_to_qkeycode_map[] = {
144 [kVK_ANSI_A] = Q_KEY_CODE_A,
145 [kVK_ANSI_B] = Q_KEY_CODE_B,
146 [kVK_ANSI_C] = Q_KEY_CODE_C,
147 [kVK_ANSI_D] = Q_KEY_CODE_D,
148 [kVK_ANSI_E] = Q_KEY_CODE_E,
149 [kVK_ANSI_F] = Q_KEY_CODE_F,
150 [kVK_ANSI_G] = Q_KEY_CODE_G,
151 [kVK_ANSI_H] = Q_KEY_CODE_H,
152 [kVK_ANSI_I] = Q_KEY_CODE_I,
153 [kVK_ANSI_J] = Q_KEY_CODE_J,
154 [kVK_ANSI_K] = Q_KEY_CODE_K,
155 [kVK_ANSI_L] = Q_KEY_CODE_L,
156 [kVK_ANSI_M] = Q_KEY_CODE_M,
157 [kVK_ANSI_N] = Q_KEY_CODE_N,
158 [kVK_ANSI_O] = Q_KEY_CODE_O,
159 [kVK_ANSI_P] = Q_KEY_CODE_P,
160 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
161 [kVK_ANSI_R] = Q_KEY_CODE_R,
162 [kVK_ANSI_S] = Q_KEY_CODE_S,
163 [kVK_ANSI_T] = Q_KEY_CODE_T,
164 [kVK_ANSI_U] = Q_KEY_CODE_U,
165 [kVK_ANSI_V] = Q_KEY_CODE_V,
166 [kVK_ANSI_W] = Q_KEY_CODE_W,
167 [kVK_ANSI_X] = Q_KEY_CODE_X,
168 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
169 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
171 [kVK_ANSI_0] = Q_KEY_CODE_0,
172 [kVK_ANSI_1] = Q_KEY_CODE_1,
173 [kVK_ANSI_2] = Q_KEY_CODE_2,
174 [kVK_ANSI_3] = Q_KEY_CODE_3,
175 [kVK_ANSI_4] = Q_KEY_CODE_4,
176 [kVK_ANSI_5] = Q_KEY_CODE_5,
177 [kVK_ANSI_6] = Q_KEY_CODE_6,
178 [kVK_ANSI_7] = Q_KEY_CODE_7,
179 [kVK_ANSI_8] = Q_KEY_CODE_8,
180 [kVK_ANSI_9] = Q_KEY_CODE_9,
182 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
183 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
184 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
185 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
186 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
187 [kVK_Tab] = Q_KEY_CODE_TAB,
188 [kVK_Return] = Q_KEY_CODE_RET,
189 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
190 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
191 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
192 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
193 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
194 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
195 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
196 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
197 [kVK_Space] = Q_KEY_CODE_SPC,
199 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
200 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
201 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
202 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
203 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
204 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
205 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
206 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
207 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
208 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
209 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
210 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
211 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
212 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
213 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
214 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
215 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
216 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
218 [kVK_UpArrow] = Q_KEY_CODE_UP,
219 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
220 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
221 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
223 [kVK_Help] = Q_KEY_CODE_INSERT,
224 [kVK_Home] = Q_KEY_CODE_HOME,
225 [kVK_PageUp] = Q_KEY_CODE_PGUP,
226 [kVK_PageDown] = Q_KEY_CODE_PGDN,
227 [kVK_End] = Q_KEY_CODE_END,
228 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
230 [kVK_Escape] = Q_KEY_CODE_ESC,
232 /* The Power key can't be used directly because the operating system uses
233 * it. This key can be emulated by using it in place of another key such as
234 * F1. Don't forget to disable the real key binding.
236 /* [kVK_F1] = Q_KEY_CODE_POWER, */
238 [kVK_F1] = Q_KEY_CODE_F1,
239 [kVK_F2] = Q_KEY_CODE_F2,
240 [kVK_F3] = Q_KEY_CODE_F3,
241 [kVK_F4] = Q_KEY_CODE_F4,
242 [kVK_F5] = Q_KEY_CODE_F5,
243 [kVK_F6] = Q_KEY_CODE_F6,
244 [kVK_F7] = Q_KEY_CODE_F7,
245 [kVK_F8] = Q_KEY_CODE_F8,
246 [kVK_F9] = Q_KEY_CODE_F9,
247 [kVK_F10] = Q_KEY_CODE_F10,
248 [kVK_F11] = Q_KEY_CODE_F11,
249 [kVK_F12] = Q_KEY_CODE_F12,
250 [kVK_F13] = Q_KEY_CODE_PRINT,
251 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
252 [kVK_F15] = Q_KEY_CODE_PAUSE,
254 // JIS keyboards only
255 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
256 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
257 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
258 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
259 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
262 * The eject and volume keys can't be used here because they are handled at
263 * a lower level than what an Application can see.
267 static int cocoa_keycode_to_qemu(int keycode)
269 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
270 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
273 return mac_to_qkeycode_map[keycode];
276 /* Displays an alert dialog box with the specified message */
277 static void QEMU_Alert(NSString *message)
280 alert = [NSAlert new];
281 [alert setMessageText: message];
285 /* Handles any errors that happen with a device transaction */
286 static void handleAnyDeviceErrors(Error * err)
289 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
290 encoding: NSASCIIStringEncoding]);
296 ------------------------------------------------------
298 ------------------------------------------------------
300 @interface QemuCocoaView : NSView
303 pixman_image_t *pixman_image;
304 /* The state surrounding mouse grabbing is potentially confusing.
305 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
306 * pointing device an absolute-position one?"], but is only updated on
308 * isMouseGrabbed tracks whether GUI events are directed to the guest;
309 * it controls whether special keys like Cmd get sent to the guest,
310 * and whether we capture the mouse when in non-absolute mode.
313 BOOL isAbsoluteEnabled;
314 CFMachPortRef eventsTap;
315 CGColorSpaceRef colorspace;
316 CALayer *cursorLayer;
322 - (void) switchSurface:(pixman_image_t *)image;
324 - (void) ungrabMouse;
325 - (void) setFullGrab:(id)sender;
326 - (void) handleMonitorInput:(NSEvent *)event;
327 - (bool) handleEvent:(NSEvent *)event;
328 - (bool) handleEventLocked:(NSEvent *)event;
329 - (void) notifyMouseModeChange;
330 - (BOOL) isMouseGrabbed;
331 - (QEMUScreen) gscreen;
332 - (void) raiseAllKeys;
335 QemuCocoaView *cocoaView;
337 static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
339 QemuCocoaView *view = userInfo;
340 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
341 if ([view isMouseGrabbed] && [view handleEvent:event]) {
342 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
345 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
350 @implementation QemuCocoaView
351 - (id)initWithFrame:(NSRect)frameRect
353 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
355 self = [super initWithFrame:frameRect];
358 NSTrackingAreaOptions options = NSTrackingActiveInKeyWindow |
359 NSTrackingMouseEnteredAndExited |
360 NSTrackingMouseMoved |
361 NSTrackingInVisibleRect;
363 NSTrackingArea *trackingArea =
364 [[NSTrackingArea alloc] initWithRect:CGRectZero
369 [self addTrackingArea:trackingArea];
370 [trackingArea release];
371 screen.width = frameRect.size.width;
372 screen.height = frameRect.size.height;
373 colorspace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
374 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
375 [self setClipsToBounds:YES];
377 [self setWantsLayer:YES];
378 cursorLayer = [[CALayer alloc] init];
379 [cursorLayer setAnchorPoint:CGPointMake(0, 1)];
380 [cursorLayer setAutoresizingMask:kCALayerMaxXMargin |
382 [[self layer] addSublayer:cursorLayer];
390 COCOA_DEBUG("QemuCocoaView: dealloc\n");
393 pixman_image_unref(pixman_image);
397 CFRelease(eventsTap);
400 CGColorSpaceRelease(colorspace);
401 [cursorLayer release];
402 cursor_unref(cursor);
411 - (void) viewDidMoveToWindow
416 - (void) selectConsoleLocked:(unsigned int)index
418 QemuConsole *con = qemu_console_lookup_by_index(index);
423 unregister_displaychangelistener(&dcl);
424 qkbd_state_switch_console(kbd, con);
426 register_displaychangelistener(&dcl);
427 [self notifyMouseModeChange];
439 - (void) unhideCursor
447 - (void)setMouseX:(int)x y:(int)y on:(bool)on
456 position.y = screen.height - mouseY;
458 [CATransaction begin];
459 [CATransaction setDisableActions:YES];
460 [cursorLayer setPosition:position];
461 [cursorLayer setHidden:!mouseOn];
462 [CATransaction commit];
465 - (void)setCursor:(QEMUCursor *)given_cursor
467 CGDataProviderRef provider;
469 CGRect bounds = CGRectZero;
471 cursor_unref(cursor);
472 cursor = given_cursor;
480 bounds.size.width = cursor->width;
481 bounds.size.height = cursor->height;
483 provider = CGDataProviderCreateWithData(
486 cursor->width * cursor->height * 4,
490 image = CGImageCreate(
491 cursor->width, //width
492 cursor->height, //height
493 8, //bitsPerComponent
495 cursor->width * 4, //bytesPerRow
496 colorspace, //colorspace
497 kCGBitmapByteOrder32Little | kCGImageAlphaFirst, //bitmapInfo
501 kCGRenderingIntentDefault //intent
504 CGDataProviderRelease(provider);
505 [CATransaction begin];
506 [CATransaction setDisableActions:YES];
507 [cursorLayer setBounds:bounds];
508 [cursorLayer setContents:(id)image];
509 [CATransaction commit];
510 CGImageRelease(image);
513 - (void) drawRect:(NSRect) rect
515 COCOA_DEBUG("QemuCocoaView: drawRect\n");
517 // get CoreGraphic context
518 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
520 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
521 CGContextSetShouldAntialias (viewContextRef, NO);
523 // draw screen bitmap directly to Core Graphics context
525 // Draw request before any guest device has set up a framebuffer:
526 // just draw an opaque black rectangle
527 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
528 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
530 int w = pixman_image_get_width(pixman_image);
531 int h = pixman_image_get_height(pixman_image);
532 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
533 int stride = pixman_image_get_stride(pixman_image);
534 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
536 pixman_image_get_data(pixman_image),
540 CGImageRef imageRef = CGImageCreate(
543 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
544 bitsPerPixel, //bitsPerPixel
545 stride, //bytesPerRow
546 colorspace, //colorspace
547 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
548 dataProviderRef, //provider
551 kCGRenderingIntentDefault //intent
553 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
554 const NSRect *rectList;
557 CGImageRef clipImageRef;
560 [self getRectsBeingDrawn:&rectList count:&rectCount];
561 for (i = 0; i < rectCount; i++) {
562 clipRect = rectList[i];
563 clipRect.origin.y = (float)h - (clipRect.origin.y + clipRect.size.height);
564 clipImageRef = CGImageCreateWithImageInRect(
568 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
569 CGImageRelease (clipImageRef);
571 CGImageRelease (imageRef);
572 CGDataProviderRelease(dataProviderRef);
576 - (NSSize)fixAspectRatio:(NSSize)max
581 scaled.width = screen.width * max.height;
582 scaled.height = screen.height * max.width;
585 * Here screen is our guest's output size, and max is the size of the
586 * largest possible area of the screen we can display on.
587 * We want to scale up (screen.width x screen.height) by either:
588 * 1) max.height / screen.height
589 * 2) max.width / screen.width
590 * With the first scale factor the scale will result in an output height of
591 * max.height (i.e. we will fill the whole height of the available screen
592 * space and have black bars left and right) and with the second scale
593 * factor the scaling will result in an output width of max.width (i.e. we
594 * fill the whole width of the available screen space and have black bars
595 * top and bottom). We need to pick whichever keeps the whole of the guest
596 * output on the screen, which is to say the smaller of the two scale
598 * To avoid doing more division than strictly necessary, instead of directly
599 * comparing scale factors 1 and 2 we instead calculate and compare those
600 * two scale factors multiplied by (screen.height * screen.width).
602 if (scaled.width < scaled.height) {
603 fixed.width = scaled.width / screen.height;
604 fixed.height = max.height;
606 fixed.width = max.width;
607 fixed.height = scaled.height / screen.width;
613 - (NSSize) screenSafeAreaSize
615 NSSize size = [[[self window] screen] frame].size;
616 NSEdgeInsets insets = [[[self window] screen] safeAreaInsets];
617 size.width -= insets.left + insets.right;
618 size.height -= insets.top + insets.bottom;
622 - (void) resizeWindow
624 [[self window] setContentAspectRatio:NSMakeSize(screen.width, screen.height)];
626 if (!([[self window] styleMask] & NSWindowStyleMaskResizable)) {
627 [[self window] setContentSize:NSMakeSize(screen.width, screen.height)];
628 [[self window] center];
629 } else if ([[self window] styleMask] & NSWindowStyleMaskFullScreen) {
630 [[self window] setContentSize:[self fixAspectRatio:[self screenSafeAreaSize]]];
631 [[self window] center];
633 [[self window] setContentSize:[self fixAspectRatio:[self frame].size]];
637 - (void) updateBounds
639 [self setBoundsSize:NSMakeSize(screen.width, screen.height)];
642 - (void) updateUIInfoLocked
644 /* Must be called with the BQL, i.e. via updateUIInfo */
648 if (!qemu_console_is_graphic(dcl.con)) {
653 NSDictionary *description = [[[self window] screen] deviceDescription];
654 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
655 NSSize screenSize = [[[self window] screen] frame].size;
656 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
657 bool isFullscreen = ([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0;
658 CVDisplayLinkRef displayLink;
660 frameSize = isFullscreen ? [self screenSafeAreaSize] : [self frame].size;
662 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
663 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
664 CVDisplayLinkRelease(displayLink);
665 if (!(period.flags & kCVTimeIsIndefinite)) {
666 update_displaychangelistener(&dcl,
667 1000 * period.timeValue / period.timeScale);
668 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
672 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
673 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
675 frameSize = [self frame].size;
682 info.width = frameSize.width;
683 info.height = frameSize.height;
685 dpy_set_ui_info(dcl.con, &info, TRUE);
688 - (void) updateUIInfo
692 * Don't try to tell QEMU about UI information in the application
693 * startup phase -- we haven't yet registered dcl with the QEMU UI
695 * When cocoa_display_init() does register the dcl, the UI layer
696 * will call cocoa_switch(), which will call updateUIInfo, so
697 * we don't lose any information here.
703 [self updateUIInfoLocked];
707 - (void) switchSurface:(pixman_image_t *)image
709 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
711 int w = pixman_image_get_width(image);
712 int h = pixman_image_get_height(image);
714 if (w != screen.width || h != screen.height) {
715 // Resize before we trigger the redraw, or we'll redraw at the wrong size
716 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
723 // update screenBuffer
725 pixman_image_unref(pixman_image);
728 pixman_image = image;
731 - (void) setFullGrab:(id)sender
733 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
735 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
736 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
737 mask, handleTapEvent, self);
739 warn_report("Could not create event tap, system key combos will not be captured.\n");
742 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
745 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
747 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
751 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
752 if (!tapEventsSrc ) {
753 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
757 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
758 CFRelease(tapEventsSrc);
761 - (void) toggleKey: (int)keycode {
762 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
765 // Does the work of sending input to the monitor
766 - (void) handleMonitorInput:(NSEvent *)event
771 // if the control key is down
772 if ([event modifierFlags] & NSEventModifierFlagControl) {
776 /* translates Macintosh keycodes to QEMU's keysym */
778 static const int without_control_translation[] = {
779 [0 ... 0xff] = 0, // invalid key
781 [kVK_UpArrow] = QEMU_KEY_UP,
782 [kVK_DownArrow] = QEMU_KEY_DOWN,
783 [kVK_RightArrow] = QEMU_KEY_RIGHT,
784 [kVK_LeftArrow] = QEMU_KEY_LEFT,
785 [kVK_Home] = QEMU_KEY_HOME,
786 [kVK_End] = QEMU_KEY_END,
787 [kVK_PageUp] = QEMU_KEY_PAGEUP,
788 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
789 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
790 [kVK_Delete] = QEMU_KEY_BACKSPACE,
793 static const int with_control_translation[] = {
794 [0 ... 0xff] = 0, // invalid key
796 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
797 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
798 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
799 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
800 [kVK_Home] = QEMU_KEY_CTRL_HOME,
801 [kVK_End] = QEMU_KEY_CTRL_END,
802 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
803 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
806 if (control_key != 0) { /* If the control key is being used */
807 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
808 keysym = with_control_translation[[event keyCode]];
811 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
812 keysym = without_control_translation[[event keyCode]];
816 // if not a key that needs translating
818 NSString *ks = [event characters];
819 if ([ks length] > 0) {
820 keysym = [ks characterAtIndex:0];
825 QemuTextConsole *con = QEMU_TEXT_CONSOLE(dcl.con);
826 qemu_text_console_put_keysym(con, keysym);
830 - (bool) handleEvent:(NSEvent *)event
832 return bool_with_bql(^{
833 return [self handleEventLocked:event];
837 - (bool) handleEventLocked:(NSEvent *)event
839 /* Return true if we handled the event, false if it should be given to OSX */
840 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
843 NSUInteger modifiers = [event modifierFlags];
846 * Check -[NSEvent modifierFlags] here.
848 * There is a NSEventType for an event notifying the change of
849 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
850 * are performed for any events because a modifier state may change while
851 * the application is inactive (i.e. no events fire) and we don't want to
852 * wait for another modifier state change to detect such a change.
854 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
855 * are handled in similar manners.
857 * NSEventModifierFlagCapsLock
858 * ---------------------------
860 * If CapsLock state is changed, "up" and "down" events will be fired in
861 * sequence, effectively updates CapsLock state on the guest.
866 * If a flag is not set, fire "up" events for all keys which correspond to
867 * the flag. Note that "down" events are not fired here because the flags
868 * checked here do not tell what exact keys are down.
870 * If one of the keys corresponding to a flag is down, we rely on
871 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
872 * NSEventTypeFlagsChanged to know the exact key which is down, which has
873 * the following two downsides:
874 * - It does not work when the application is inactive as described above.
875 * - It malfactions *after* the modifier state is changed while the
876 * application is inactive. It is because -[NSEvent keyCode] does not tell
877 * if the key is up or down, and requires to infer the current state from
878 * the previous state. It is still possible to fix such a malfanction by
879 * completely leaving your hands from the keyboard, which hopefully makes
880 * this implementation usable enough.
882 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
883 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
884 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
885 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
888 if (!(modifiers & NSEventModifierFlagShift)) {
889 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
890 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
892 if (!(modifiers & NSEventModifierFlagControl)) {
893 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
894 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
896 if (!(modifiers & NSEventModifierFlagOption)) {
898 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
899 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
901 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
902 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
905 if (!(modifiers & NSEventModifierFlagCommand)) {
907 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
908 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
910 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
911 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
915 switch ([event type]) {
916 case NSEventTypeFlagsChanged:
917 switch ([event keyCode]) {
919 if (!!(modifiers & NSEventModifierFlagShift)) {
920 [self toggleKey:Q_KEY_CODE_SHIFT];
925 if (!!(modifiers & NSEventModifierFlagShift)) {
926 [self toggleKey:Q_KEY_CODE_SHIFT_R];
931 if (!!(modifiers & NSEventModifierFlagControl)) {
932 [self toggleKey:Q_KEY_CODE_CTRL];
936 case kVK_RightControl:
937 if (!!(modifiers & NSEventModifierFlagControl)) {
938 [self toggleKey:Q_KEY_CODE_CTRL_R];
943 if (!!(modifiers & NSEventModifierFlagOption)) {
945 [self toggleKey:Q_KEY_CODE_META_L];
947 [self toggleKey:Q_KEY_CODE_ALT];
952 case kVK_RightOption:
953 if (!!(modifiers & NSEventModifierFlagOption)) {
955 [self toggleKey:Q_KEY_CODE_META_R];
957 [self toggleKey:Q_KEY_CODE_ALT_R];
962 /* Don't pass command key changes to guest unless mouse is grabbed */
964 if (isMouseGrabbed &&
965 !!(modifiers & NSEventModifierFlagCommand) &&
966 left_command_key_enabled) {
968 [self toggleKey:Q_KEY_CODE_ALT];
970 [self toggleKey:Q_KEY_CODE_META_L];
975 case kVK_RightCommand:
976 if (isMouseGrabbed &&
977 !!(modifiers & NSEventModifierFlagCommand)) {
979 [self toggleKey:Q_KEY_CODE_ALT_R];
981 [self toggleKey:Q_KEY_CODE_META_R];
987 case NSEventTypeKeyDown:
988 keycode = cocoa_keycode_to_qemu([event keyCode]);
990 // forward command key combos to the host UI unless the mouse is grabbed
991 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
997 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
998 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
999 NSString *keychar = [event charactersIgnoringModifiers];
1000 if ([keychar length] == 1) {
1001 char key = [keychar characterAtIndex:0];
1004 // enable graphic console
1006 [self selectConsoleLocked:key - '0' - 1]; /* ascii math */
1009 // release the mouse grab
1017 if (qemu_console_is_graphic(dcl.con)) {
1018 qkbd_state_key_event(kbd, keycode, true);
1020 [self handleMonitorInput: event];
1023 case NSEventTypeKeyUp:
1024 keycode = cocoa_keycode_to_qemu([event keyCode]);
1026 // don't pass the guest a spurious key-up if we treated this
1027 // command-key combo as a host UI action
1028 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
1032 if (qemu_console_is_graphic(dcl.con)) {
1033 qkbd_state_key_event(kbd, keycode, false);
1036 case NSEventTypeScrollWheel:
1038 * Send wheel events to the guest regardless of window focus.
1039 * This is in-line with standard Mac OS X UI behaviour.
1042 /* Determine if this is a scroll up or scroll down event */
1043 if ([event deltaY] != 0) {
1044 button = ([event deltaY] > 0) ?
1045 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1046 } else if ([event deltaX] != 0) {
1047 button = ([event deltaX] > 0) ?
1048 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1051 * We shouldn't have got a scroll event when deltaY and delta Y
1052 * are zero, hence no harm in dropping the event
1057 qemu_input_queue_btn(dcl.con, button, true);
1058 qemu_input_event_sync();
1059 qemu_input_queue_btn(dcl.con, button, false);
1060 qemu_input_event_sync();
1068 - (void) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
1070 if (!isMouseGrabbed) {
1075 qemu_input_queue_btn(dcl.con, button, down);
1078 [self handleMouseEvent:event];
1081 - (void) handleMouseEvent:(NSEvent *)event
1083 if (!isMouseGrabbed) {
1088 if (isAbsoluteEnabled) {
1089 CGFloat d = (CGFloat)screen.height / [self frame].size.height;
1090 NSPoint p = [event locationInWindow];
1092 /* Note that the origin for Cocoa mouse coords is bottom left, not top left. */
1093 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x * d, 0, screen.width);
1094 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y * d, 0, screen.height);
1096 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, [event deltaX]);
1097 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, [event deltaY]);
1100 qemu_input_event_sync();
1104 - (void) mouseExited:(NSEvent *)event
1106 if (isAbsoluteEnabled && isMouseGrabbed) {
1111 - (void) mouseEntered:(NSEvent *)event
1113 if (isAbsoluteEnabled && !isMouseGrabbed) {
1118 - (void) mouseMoved:(NSEvent *)event
1120 [self handleMouseEvent:event];
1123 - (void) mouseDown:(NSEvent *)event
1125 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
1128 - (void) rightMouseDown:(NSEvent *)event
1130 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
1133 - (void) otherMouseDown:(NSEvent *)event
1135 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
1138 - (void) mouseDragged:(NSEvent *)event
1140 [self handleMouseEvent:event];
1143 - (void) rightMouseDragged:(NSEvent *)event
1145 [self handleMouseEvent:event];
1148 - (void) otherMouseDragged:(NSEvent *)event
1150 [self handleMouseEvent:event];
1153 - (void) mouseUp:(NSEvent *)event
1155 if (!isMouseGrabbed) {
1159 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
1162 - (void) rightMouseUp:(NSEvent *)event
1164 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
1167 - (void) otherMouseUp:(NSEvent *)event
1169 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
1174 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1177 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]];
1179 [[self window] setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
1181 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1182 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1185 - (void) ungrabMouse
1187 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1190 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1192 [[self window] setTitle:@"QEMU"];
1193 [self unhideCursor];
1194 CGAssociateMouseAndMouseCursorPosition(TRUE);
1195 isMouseGrabbed = FALSE;
1196 [self raiseAllButtons];
1199 - (void) notifyMouseModeChange {
1200 bool tIsAbsoluteEnabled = bool_with_bql(^{
1201 return qemu_input_is_absolute(dcl.con);
1204 if (tIsAbsoluteEnabled == isAbsoluteEnabled) {
1208 isAbsoluteEnabled = tIsAbsoluteEnabled;
1210 if (isMouseGrabbed) {
1211 if (isAbsoluteEnabled) {
1214 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1218 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1219 - (QEMUScreen) gscreen {return screen;}
1222 * Makes the target think all down keys are being released.
1223 * This prevents a stuck key problem, since we will not see
1224 * key up events for those keys after we have lost focus.
1226 - (void) raiseAllKeys
1229 qkbd_state_lift_all_keys(kbd);
1233 - (void) raiseAllButtons
1236 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_LEFT, false);
1237 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_RIGHT, false);
1238 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_MIDDLE, false);
1246 ------------------------------------------------------
1247 QemuCocoaAppController
1248 ------------------------------------------------------
1250 @interface QemuCocoaAppController : NSObject
1251 <NSWindowDelegate, NSApplicationDelegate>
1254 - (void)doToggleFullScreen:(id)sender;
1255 - (void)showQEMUDoc:(id)sender;
1256 - (void)zoomToFit:(id) sender;
1257 - (void)displayConsole:(id)sender;
1258 - (void)pauseQEMU:(id)sender;
1259 - (void)resumeQEMU:(id)sender;
1260 - (void)displayPause;
1261 - (void)removePause;
1262 - (void)restartQEMU:(id)sender;
1263 - (void)powerDownQEMU:(id)sender;
1264 - (void)ejectDeviceMedia:(id)sender;
1265 - (void)changeDeviceMedia:(id)sender;
1267 - (void)openDocumentation:(NSString *)filename;
1268 - (IBAction) do_about_menu_item: (id) sender;
1269 - (void)adjustSpeed:(id)sender;
1272 @implementation QemuCocoaAppController
1277 COCOA_DEBUG("QemuCocoaAppController: init\n");
1279 self = [super init];
1282 // create a view and add it to the window
1283 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1285 error_report("(cocoa) can't create a view");
1290 window = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1291 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1292 backing:NSBackingStoreBuffered defer:NO];
1294 error_report("(cocoa) can't create window");
1297 [window setAcceptsMouseMovedEvents:YES];
1298 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
1299 [window setTitle:qemu_name ? [NSString stringWithFormat:@"QEMU %s", qemu_name] : @"QEMU"];
1300 [window setContentView:cocoaView];
1301 [window makeKeyAndOrderFront:self];
1303 [window setDelegate: self];
1305 /* Used for displaying pause on the screen */
1306 pauseLabel = [NSTextField new];
1307 [pauseLabel setBezeled:YES];
1308 [pauseLabel setDrawsBackground:YES];
1309 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1310 [pauseLabel setEditable:NO];
1311 [pauseLabel setSelectable:NO];
1312 [pauseLabel setStringValue: @"Paused"];
1313 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1314 [pauseLabel setTextColor: [NSColor blackColor]];
1315 [pauseLabel sizeToFit];
1322 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1325 [cocoaView release];
1329 - (void)applicationDidFinishLaunching: (NSNotification *) note
1331 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1332 allow_events = true;
1335 - (void)applicationWillTerminate:(NSNotification *)aNotification
1337 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1340 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1341 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1345 * Sleep here, because returning will cause OSX to kill us
1346 * immediately; the QEMU main loop will handle the shutdown
1347 * request and terminate the process.
1349 [NSThread sleepForTimeInterval:INFINITY];
1352 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1357 - (NSApplicationTerminateReply)applicationShouldTerminate:
1358 (NSApplication *)sender
1360 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1361 return [self verifyQuit];
1364 - (void)windowDidChangeScreen:(NSNotification *)notification
1366 [cocoaView updateUIInfo];
1369 - (void)windowDidEnterFullScreen:(NSNotification *)notification
1371 [cocoaView grabMouse];
1374 - (void)windowDidExitFullScreen:(NSNotification *)notification
1376 [cocoaView resizeWindow];
1377 [cocoaView ungrabMouse];
1380 - (void)windowDidResize:(NSNotification *)notification
1382 [cocoaView updateBounds];
1383 [cocoaView updateUIInfo];
1386 /* Called when the user clicks on a window's close button */
1387 - (BOOL)windowShouldClose:(id)sender
1389 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1390 [NSApp terminate: sender];
1391 /* If the user allows the application to quit then the call to
1392 * NSApp terminate will never return. If we get here then the user
1393 * cancelled the quit, so we should return NO to not permit the
1394 * closing of this window.
1399 - (NSApplicationPresentationOptions) window:(NSWindow *)window
1400 willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions;
1403 return (proposedOptions & ~(NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)) |
1404 NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
1408 * Called when QEMU goes into the background. Note that
1409 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1410 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1411 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1413 - (void) windowDidResignKey: (NSNotification *)aNotification
1415 COCOA_DEBUG("%s\n", __func__);
1416 [cocoaView ungrabMouse];
1417 [cocoaView raiseAllKeys];
1420 /* We abstract the method called by the Enter Fullscreen menu item
1421 * because Mac OS 10.7 and higher disables it. This is because of the
1422 * menu item's old selector's name toggleFullScreen:
1424 - (void) doToggleFullScreen:(id)sender
1426 [[cocoaView window] toggleFullScreen:sender];
1429 - (void) setFullGrab:(id)sender
1431 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1433 [cocoaView setFullGrab:sender];
1436 /* Tries to find then open the specified filename */
1437 - (void) openDocumentation: (NSString *) filename
1439 /* Where to look for local files */
1440 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1441 NSString *full_file_path;
1442 NSURL *full_file_url;
1444 /* iterate thru the possible paths until the file is found */
1446 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1447 full_file_path = [[NSBundle mainBundle] executablePath];
1448 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1449 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1450 path_array[index], filename];
1451 full_file_url = [NSURL fileURLWithPath: full_file_path
1452 isDirectory: false];
1453 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1458 /* If none of the paths opened a file */
1460 QEMU_Alert(@"Failed to open file");
1463 - (void)showQEMUDoc:(id)sender
1465 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1467 [self openDocumentation: @"index.html"];
1470 /* Stretches video to fit host monitor size */
1471 - (void)zoomToFit:(id) sender
1473 NSWindowStyleMask styleMask = [[cocoaView window] styleMask] ^ NSWindowStyleMaskResizable;
1475 [[cocoaView window] setStyleMask:styleMask];
1476 [sender setState:styleMask & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
1477 [cocoaView resizeWindow];
1480 - (void)toggleZoomInterpolation:(id) sender
1482 if (zoom_interpolation == kCGInterpolationNone) {
1483 zoom_interpolation = kCGInterpolationLow;
1484 [sender setState: NSControlStateValueOn];
1486 zoom_interpolation = kCGInterpolationNone;
1487 [sender setState: NSControlStateValueOff];
1491 /* Displays the console on the screen */
1492 - (void)displayConsole:(id)sender
1495 [cocoaView selectConsoleLocked:[sender tag]];
1499 /* Pause the guest */
1500 - (void)pauseQEMU:(id)sender
1505 [sender setEnabled: NO];
1506 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1507 [self displayPause];
1510 /* Resume running the guest operating system */
1511 - (void)resumeQEMU:(id) sender
1516 [sender setEnabled: NO];
1517 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1521 /* Displays the word pause on the screen */
1522 - (void)displayPause
1524 /* Coordinates have to be calculated each time because the window can change its size */
1525 int xCoord, yCoord, width, height;
1526 xCoord = ([cocoaView frame].size.width - [pauseLabel frame].size.width)/2;
1527 yCoord = [cocoaView frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1528 width = [pauseLabel frame].size.width;
1529 height = [pauseLabel frame].size.height;
1530 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1531 [cocoaView addSubview: pauseLabel];
1534 /* Removes the word pause from the screen */
1537 [pauseLabel removeFromSuperview];
1541 - (void)restartQEMU:(id)sender
1544 qmp_system_reset(NULL);
1548 /* Powers down QEMU */
1549 - (void)powerDownQEMU:(id)sender
1552 qmp_system_powerdown(NULL);
1556 /* Ejects the media.
1557 * Uses sender's tag to figure out the device to eject.
1559 - (void)ejectDeviceMedia:(id)sender
1562 drive = [sender representedObject];
1565 QEMU_Alert(@"Failed to find drive to eject!");
1569 __block Error *err = NULL;
1571 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1572 NULL, false, false, &err);
1574 handleAnyDeviceErrors(err);
1577 /* Displays a dialog box asking the user to select an image file to load.
1578 * Uses sender's represented object value to figure out which drive to use.
1580 - (void)changeDeviceMedia:(id)sender
1582 /* Find the drive name */
1584 drive = [sender representedObject];
1587 QEMU_Alert(@"Could not find drive!");
1591 /* Display the file open dialog */
1592 NSOpenPanel * openPanel;
1593 openPanel = [NSOpenPanel openPanel];
1594 [openPanel setCanChooseFiles: YES];
1595 [openPanel setAllowsMultipleSelection: NO];
1596 if([openPanel runModal] == NSModalResponseOK) {
1597 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1600 QEMU_Alert(@"Failed to convert URL to file path!");
1604 __block Error *err = NULL;
1606 qmp_blockdev_change_medium([drive cStringUsingEncoding:
1607 NSASCIIStringEncoding],
1609 [file cStringUsingEncoding:
1610 NSASCIIStringEncoding],
1616 handleAnyDeviceErrors(err);
1620 /* Verifies if the user really wants to quit */
1623 NSAlert *alert = [NSAlert new];
1624 [alert autorelease];
1625 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1626 [alert addButtonWithTitle: @"Cancel"];
1627 [alert addButtonWithTitle: @"Quit"];
1628 if([alert runModal] == NSAlertSecondButtonReturn) {
1635 /* The action method for the About menu item */
1636 - (IBAction) do_about_menu_item: (id) sender
1638 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1639 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1640 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1641 g_free(icon_path_c);
1642 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1643 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1644 NSString *copyright = @QEMU_COPYRIGHT;
1645 NSDictionary *options;
1648 NSAboutPanelOptionApplicationIcon : icon,
1649 NSAboutPanelOptionApplicationVersion : version,
1650 @"Copyright" : copyright,
1655 NSAboutPanelOptionApplicationVersion : version,
1656 @"Copyright" : copyright,
1659 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1663 /* Used by the Speed menu items */
1664 - (void)adjustSpeed:(id)sender
1666 int throttle_pct; /* throttle percentage */
1669 menu = [sender menu];
1672 /* Unselect the currently selected item */
1673 for (NSMenuItem *item in [menu itemArray]) {
1674 if (item.state == NSControlStateValueOn) {
1675 [item setState: NSControlStateValueOff];
1681 // check the menu item
1682 [sender setState: NSControlStateValueOn];
1684 // get the throttle percentage
1685 throttle_pct = [sender tag];
1688 cpu_throttle_set(throttle_pct);
1690 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1695 @interface QemuApplication : NSApplication
1698 @implementation QemuApplication
1699 - (void)sendEvent:(NSEvent *)event
1701 COCOA_DEBUG("QemuApplication: sendEvent\n");
1702 if (![cocoaView handleEvent:event]) {
1703 [super sendEvent: event];
1708 static void create_initial_menus(void)
1712 NSMenuItem *menuItem;
1714 [NSApp setMainMenu:[[NSMenu alloc] init]];
1715 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1718 menu = [[NSMenu alloc] initWithTitle:@""];
1719 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1720 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1721 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1722 [menuItem setSubmenu:[NSApp servicesMenu]];
1723 [menu addItem:[NSMenuItem separatorItem]];
1724 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1725 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1726 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1727 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1728 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1729 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1730 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1731 [menuItem setSubmenu:menu];
1732 [[NSApp mainMenu] addItem:menuItem];
1733 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1736 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1737 [menu setAutoenablesItems: NO];
1738 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1739 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1740 [menu addItem: menuItem];
1741 [menuItem setEnabled: NO];
1742 [menu addItem: [NSMenuItem separatorItem]];
1743 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1744 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1745 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1746 [menuItem setSubmenu:menu];
1747 [[NSApp mainMenu] addItem:menuItem];
1750 menu = [[NSMenu alloc] initWithTitle:@"View"];
1751 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1752 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1753 [menuItem setState: [[cocoaView window] styleMask] & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
1754 [menu addItem: menuItem];
1755 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1756 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1757 [menu addItem: menuItem];
1758 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1759 [menuItem setSubmenu:menu];
1760 [[NSApp mainMenu] addItem:menuItem];
1763 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1765 // Add the rest of the Speed menu items
1766 int p, percentage, throttle_pct;
1767 for (p = 10; p >= 0; p--)
1769 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1771 menuItem = [[[NSMenuItem alloc]
1772 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1774 if (percentage == 100) {
1775 [menuItem setState: NSControlStateValueOn];
1778 /* Calculate the throttle percentage */
1779 throttle_pct = -1 * percentage + 100;
1781 [menuItem setTag: throttle_pct];
1782 [menu addItem: menuItem];
1784 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1785 [menuItem setSubmenu:menu];
1786 [[NSApp mainMenu] addItem:menuItem];
1789 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1790 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1791 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1792 [menuItem setSubmenu:menu];
1793 [[NSApp mainMenu] addItem:menuItem];
1794 [NSApp setWindowsMenu:menu];
1797 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1798 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1799 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1800 [menuItem setSubmenu:menu];
1801 [[NSApp mainMenu] addItem:menuItem];
1804 /* Returns a name for a given console */
1805 static NSString * getConsoleName(QemuConsole * console)
1807 g_autofree char *label = qemu_console_get_label(console);
1809 return [NSString stringWithUTF8String:label];
1812 /* Add an entry to the View menu for each console */
1813 static void add_console_menu_entries(void)
1816 NSMenuItem *menuItem;
1819 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1821 [menu addItem:[NSMenuItem separatorItem]];
1823 while (qemu_console_lookup_by_index(index) != NULL) {
1824 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1825 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1826 [menuItem setTag: index];
1827 [menu addItem: menuItem];
1832 /* Make menu items for all removable devices.
1833 * Each device is given an 'Eject' and 'Change' menu item.
1835 static void addRemovableDevicesMenuItems(void)
1838 NSMenuItem *menuItem;
1839 BlockInfoList *currentDevice, *pointerToFree;
1840 NSString *deviceName;
1842 currentDevice = qmp_query_block(NULL);
1843 pointerToFree = currentDevice;
1845 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1847 // Add a separator between related groups of menu items
1848 [menu addItem:[NSMenuItem separatorItem]];
1850 // Set the attributes to the "Removable Media" menu item
1851 NSString *titleString = @"Removable Media";
1852 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1853 NSColor *newColor = [NSColor blackColor];
1854 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1855 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1856 traits:NSBoldFontMask|NSItalicFontMask
1859 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1860 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1861 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1863 // Add the "Removable Media" menu item
1864 menuItem = [NSMenuItem new];
1865 [menuItem setAttributedTitle: attString];
1866 [menuItem setEnabled: NO];
1867 [menu addItem: menuItem];
1869 /* Loop through all the block devices in the emulator */
1870 while (currentDevice) {
1871 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1873 if(currentDevice->value->removable) {
1874 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1875 action: @selector(changeDeviceMedia:)
1876 keyEquivalent: @""];
1877 [menu addItem: menuItem];
1878 [menuItem setRepresentedObject: deviceName];
1879 [menuItem autorelease];
1881 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1882 action: @selector(ejectDeviceMedia:)
1883 keyEquivalent: @""];
1884 [menu addItem: menuItem];
1885 [menuItem setRepresentedObject: deviceName];
1886 [menuItem autorelease];
1888 currentDevice = currentDevice->next;
1890 qapi_free_BlockInfoList(pointerToFree);
1893 static void cocoa_mouse_mode_change_notify(Notifier *notifier, void *data)
1895 dispatch_async(dispatch_get_main_queue(), ^{
1896 [cocoaView notifyMouseModeChange];
1900 static Notifier mouse_mode_change_notifier = {
1901 .notify = cocoa_mouse_mode_change_notify
1904 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1907 @implementation QemuCocoaPasteboardTypeOwner
1909 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1911 if (type != NSPasteboardTypeString) {
1916 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1917 qemu_event_reset(&cbevent);
1918 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1920 while (info == cbinfo &&
1921 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1922 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1924 qemu_event_wait(&cbevent);
1928 if (info == cbinfo) {
1929 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1930 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1931 [sender setData:data forType:NSPasteboardTypeString];
1935 qemu_clipboard_info_unref(info);
1941 static QemuCocoaPasteboardTypeOwner *cbowner;
1943 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1944 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1945 QemuClipboardType type);
1947 static QemuClipboardPeer cbpeer = {
1949 .notifier = { .notify = cocoa_clipboard_notify },
1950 .request = cocoa_clipboard_request
1953 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1955 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1959 if (info != cbinfo) {
1960 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1961 qemu_clipboard_info_unref(cbinfo);
1962 cbinfo = qemu_clipboard_info_ref(info);
1963 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1967 qemu_event_set(&cbevent);
1970 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1972 QemuClipboardNotify *notify = data;
1974 switch (notify->type) {
1975 case QEMU_CLIPBOARD_UPDATE_INFO:
1976 cocoa_clipboard_update_info(notify->info);
1978 case QEMU_CLIPBOARD_RESET_SERIAL:
1984 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1985 QemuClipboardType type)
1987 NSAutoreleasePool *pool;
1991 case QEMU_CLIPBOARD_TYPE_TEXT:
1992 pool = [[NSAutoreleasePool alloc] init];
1993 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1995 qemu_clipboard_set_data(&cbpeer, info, type,
1996 [text length], [text bytes], true);
2006 * The startup process for the OSX/Cocoa UI is complicated, because
2007 * OSX insists that the UI runs on the initial main thread, and so we
2008 * need to start a second thread which runs the qemu_default_main():
2010 * in cocoa_display_init():
2011 * assign cocoa_main to qemu_main
2012 * create application, menus, etc
2014 * create qemu-main thread
2015 * enter OSX run loop
2018 static void *call_qemu_main(void *opaque)
2022 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
2024 status = qemu_default_main();
2026 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
2031 static int cocoa_main(void)
2035 COCOA_DEBUG("Entered %s()\n", __func__);
2038 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
2039 NULL, QEMU_THREAD_DETACHED);
2041 // Start the main event loop
2042 COCOA_DEBUG("Main thread: entering OSX run loop\n");
2044 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
2052 static void cocoa_update(DisplayChangeListener *dcl,
2053 int x, int y, int w, int h)
2055 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
2057 dispatch_async(dispatch_get_main_queue(), ^{
2058 NSRect rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
2059 [cocoaView setNeedsDisplayInRect:rect];
2063 static void cocoa_switch(DisplayChangeListener *dcl,
2064 DisplaySurface *surface)
2066 pixman_image_t *image = surface->image;
2068 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
2070 // The DisplaySurface will be freed as soon as this callback returns.
2071 // We take a reference to the underlying pixman image here so it does
2072 // not disappear from under our feet; the switchSurface method will
2073 // deref the old image when it is done with it.
2074 pixman_image_ref(image);
2076 dispatch_async(dispatch_get_main_queue(), ^{
2077 [cocoaView switchSurface:image];
2081 static void cocoa_refresh(DisplayChangeListener *dcl)
2083 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2085 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2086 graphic_hw_update(dcl->con);
2088 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2089 qemu_clipboard_info_unref(cbinfo);
2090 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2091 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2092 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2094 qemu_clipboard_update(cbinfo);
2095 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2096 qemu_event_set(&cbevent);
2102 static void cocoa_mouse_set(DisplayChangeListener *dcl, int x, int y, bool on)
2104 dispatch_async(dispatch_get_main_queue(), ^{
2105 [cocoaView setMouseX:x y:y on:on];
2109 static void cocoa_cursor_define(DisplayChangeListener *dcl, QEMUCursor *cursor)
2111 dispatch_async(dispatch_get_main_queue(), ^{
2113 [cocoaView setCursor:qemu_console_get_cursor(dcl->con)];
2117 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2119 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2121 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2123 qemu_main = cocoa_main;
2125 // Pull this console process up to being a fully-fledged graphical
2126 // app with a menubar and Dock icon
2127 ProcessSerialNumber psn = { 0, kCurrentProcess };
2128 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2130 [QemuApplication sharedApplication];
2132 // Create an Application controller
2133 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2134 [NSApp setDelegate:controller];
2136 /* if fullscreen mode is to be used */
2137 if (opts->has_full_screen && opts->full_screen) {
2138 [[cocoaView window] toggleFullScreen: nil];
2140 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2141 [controller setFullGrab: nil];
2144 if (opts->has_show_cursor && opts->show_cursor) {
2147 if (opts->u.cocoa.has_swap_opt_cmd) {
2148 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2151 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2152 left_command_key_enabled = 0;
2155 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2156 [cocoaView window].styleMask |= NSWindowStyleMaskResizable;
2159 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2160 zoom_interpolation = kCGInterpolationLow;
2163 create_initial_menus();
2165 * Create the menu entries which depend on QEMU state (for consoles
2166 * and removable devices). These make calls back into QEMU functions,
2167 * which is OK because at this point we know that the second thread
2168 * holds the BQL and is synchronously waiting for us to
2171 add_console_menu_entries();
2172 addRemovableDevicesMenuItems();
2174 dcl.con = qemu_console_lookup_default();
2175 kbd = qkbd_state_init(dcl.con);
2177 // register vga output callbacks
2178 register_displaychangelistener(&dcl);
2179 qemu_add_mouse_mode_change_notifier(&mouse_mode_change_notifier);
2180 [cocoaView notifyMouseModeChange];
2181 [cocoaView updateUIInfo];
2183 qemu_event_init(&cbevent, false);
2184 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2185 qemu_clipboard_peer_register(&cbpeer);
2190 static QemuDisplay qemu_display_cocoa = {
2191 .type = DISPLAY_TYPE_COCOA,
2192 .init = cocoa_display_init,
2195 static void register_cocoa(void)
2197 qemu_display_register(&qemu_display_cocoa);
2200 type_init(register_cocoa);