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 <Carbon/Carbon.h>
50 #include "hw/core/cpu.h"
52 #ifndef MAC_OS_X_VERSION_10_13
53 #define MAC_OS_X_VERSION_10_13 101300
56 /* 10.14 deprecates NSOnState and NSOffState in favor of
57 * NSControlStateValueOn/Off, which were introduced in 10.13.
58 * Define for older versions
60 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
61 #define NSControlStateValueOn NSOnState
62 #define NSControlStateValueOff NSOffState
68 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
70 #define COCOA_DEBUG(...) ((void) 0)
73 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
80 static void cocoa_update(DisplayChangeListener *dcl,
81 int x, int y, int w, int h);
83 static void cocoa_switch(DisplayChangeListener *dcl,
84 DisplaySurface *surface);
86 static void cocoa_refresh(DisplayChangeListener *dcl);
88 static NSWindow *normalWindow;
89 static const DisplayChangeListenerOps dcl_ops = {
91 .dpy_gfx_update = cocoa_update,
92 .dpy_gfx_switch = cocoa_switch,
93 .dpy_refresh = cocoa_refresh,
95 static DisplayChangeListener dcl = {
98 static int last_buttons;
99 static int cursor_hide = 1;
100 static int left_command_key_enabled = 1;
101 static bool swap_opt_cmd;
103 static bool stretch_video;
104 static NSTextField *pauseLabel;
106 static bool allow_events;
108 static NSInteger cbchangecount = -1;
109 static QemuClipboardInfo *cbinfo;
110 static QemuEvent cbevent;
112 // Utility functions to run specified code block with iothread lock held
113 typedef void (^CodeBlock)(void);
114 typedef bool (^BoolCodeBlock)(void);
116 static void with_iothread_lock(CodeBlock block)
118 bool locked = qemu_mutex_iothread_locked();
120 qemu_mutex_lock_iothread();
124 qemu_mutex_unlock_iothread();
128 static bool bool_with_iothread_lock(BoolCodeBlock block)
130 bool locked = qemu_mutex_iothread_locked();
134 qemu_mutex_lock_iothread();
138 qemu_mutex_unlock_iothread();
143 // Mac to QKeyCode conversion
144 static const int mac_to_qkeycode_map[] = {
145 [kVK_ANSI_A] = Q_KEY_CODE_A,
146 [kVK_ANSI_B] = Q_KEY_CODE_B,
147 [kVK_ANSI_C] = Q_KEY_CODE_C,
148 [kVK_ANSI_D] = Q_KEY_CODE_D,
149 [kVK_ANSI_E] = Q_KEY_CODE_E,
150 [kVK_ANSI_F] = Q_KEY_CODE_F,
151 [kVK_ANSI_G] = Q_KEY_CODE_G,
152 [kVK_ANSI_H] = Q_KEY_CODE_H,
153 [kVK_ANSI_I] = Q_KEY_CODE_I,
154 [kVK_ANSI_J] = Q_KEY_CODE_J,
155 [kVK_ANSI_K] = Q_KEY_CODE_K,
156 [kVK_ANSI_L] = Q_KEY_CODE_L,
157 [kVK_ANSI_M] = Q_KEY_CODE_M,
158 [kVK_ANSI_N] = Q_KEY_CODE_N,
159 [kVK_ANSI_O] = Q_KEY_CODE_O,
160 [kVK_ANSI_P] = Q_KEY_CODE_P,
161 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
162 [kVK_ANSI_R] = Q_KEY_CODE_R,
163 [kVK_ANSI_S] = Q_KEY_CODE_S,
164 [kVK_ANSI_T] = Q_KEY_CODE_T,
165 [kVK_ANSI_U] = Q_KEY_CODE_U,
166 [kVK_ANSI_V] = Q_KEY_CODE_V,
167 [kVK_ANSI_W] = Q_KEY_CODE_W,
168 [kVK_ANSI_X] = Q_KEY_CODE_X,
169 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
170 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
172 [kVK_ANSI_0] = Q_KEY_CODE_0,
173 [kVK_ANSI_1] = Q_KEY_CODE_1,
174 [kVK_ANSI_2] = Q_KEY_CODE_2,
175 [kVK_ANSI_3] = Q_KEY_CODE_3,
176 [kVK_ANSI_4] = Q_KEY_CODE_4,
177 [kVK_ANSI_5] = Q_KEY_CODE_5,
178 [kVK_ANSI_6] = Q_KEY_CODE_6,
179 [kVK_ANSI_7] = Q_KEY_CODE_7,
180 [kVK_ANSI_8] = Q_KEY_CODE_8,
181 [kVK_ANSI_9] = Q_KEY_CODE_9,
183 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
184 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
185 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
186 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
187 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
188 [kVK_Tab] = Q_KEY_CODE_TAB,
189 [kVK_Return] = Q_KEY_CODE_RET,
190 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
191 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
192 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
193 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
194 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
195 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
196 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
197 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
198 [kVK_Space] = Q_KEY_CODE_SPC,
200 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
201 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
202 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
203 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
204 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
205 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
206 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
207 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
208 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
209 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
210 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
211 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
212 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
213 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
214 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
215 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
216 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
217 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
219 [kVK_UpArrow] = Q_KEY_CODE_UP,
220 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
221 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
222 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
224 [kVK_Help] = Q_KEY_CODE_INSERT,
225 [kVK_Home] = Q_KEY_CODE_HOME,
226 [kVK_PageUp] = Q_KEY_CODE_PGUP,
227 [kVK_PageDown] = Q_KEY_CODE_PGDN,
228 [kVK_End] = Q_KEY_CODE_END,
229 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
231 [kVK_Escape] = Q_KEY_CODE_ESC,
233 /* The Power key can't be used directly because the operating system uses
234 * it. This key can be emulated by using it in place of another key such as
235 * F1. Don't forget to disable the real key binding.
237 /* [kVK_F1] = Q_KEY_CODE_POWER, */
239 [kVK_F1] = Q_KEY_CODE_F1,
240 [kVK_F2] = Q_KEY_CODE_F2,
241 [kVK_F3] = Q_KEY_CODE_F3,
242 [kVK_F4] = Q_KEY_CODE_F4,
243 [kVK_F5] = Q_KEY_CODE_F5,
244 [kVK_F6] = Q_KEY_CODE_F6,
245 [kVK_F7] = Q_KEY_CODE_F7,
246 [kVK_F8] = Q_KEY_CODE_F8,
247 [kVK_F9] = Q_KEY_CODE_F9,
248 [kVK_F10] = Q_KEY_CODE_F10,
249 [kVK_F11] = Q_KEY_CODE_F11,
250 [kVK_F12] = Q_KEY_CODE_F12,
251 [kVK_F13] = Q_KEY_CODE_PRINT,
252 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
253 [kVK_F15] = Q_KEY_CODE_PAUSE,
255 // JIS keyboards only
256 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
257 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
258 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
259 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
260 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
263 * The eject and volume keys can't be used here because they are handled at
264 * a lower level than what an Application can see.
268 static int cocoa_keycode_to_qemu(int keycode)
270 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
271 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
274 return mac_to_qkeycode_map[keycode];
277 /* Displays an alert dialog box with the specified message */
278 static void QEMU_Alert(NSString *message)
281 alert = [NSAlert new];
282 [alert setMessageText: message];
286 /* Handles any errors that happen with a device transaction */
287 static void handleAnyDeviceErrors(Error * err)
290 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
291 encoding: NSASCIIStringEncoding]);
297 ------------------------------------------------------
299 ------------------------------------------------------
301 @interface QemuCocoaView : NSView
304 NSWindow *fullScreenWindow;
305 float cx,cy,cw,ch,cdx,cdy;
306 pixman_image_t *pixman_image;
310 BOOL isAbsoluteEnabled;
311 CFMachPortRef eventsTap;
313 - (void) switchSurface:(pixman_image_t *)image;
315 - (void) ungrabMouse;
316 - (void) toggleFullScreen:(id)sender;
317 - (void) setFullGrab:(id)sender;
318 - (void) handleMonitorInput:(NSEvent *)event;
319 - (bool) handleEvent:(NSEvent *)event;
320 - (bool) handleEventLocked:(NSEvent *)event;
321 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
322 /* The state surrounding mouse grabbing is potentially confusing.
323 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
324 * pointing device an absolute-position one?"], but is only updated on
326 * isMouseGrabbed tracks whether GUI events are directed to the guest;
327 * it controls whether special keys like Cmd get sent to the guest,
328 * and whether we capture the mouse when in non-absolute mode.
330 - (BOOL) isMouseGrabbed;
331 - (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 *cocoaView = userInfo;
343 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
344 if ([cocoaView isMouseGrabbed] && [cocoaView 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 screen.width = frameRect.size.width;
362 screen.height = frameRect.size.height;
363 kbd = qkbd_state_init(dcl.con);
371 COCOA_DEBUG("QemuCocoaView: dealloc\n");
374 pixman_image_unref(pixman_image);
377 qkbd_state_free(kbd);
380 CFRelease(eventsTap);
391 - (BOOL) screenContainsPoint:(NSPoint) p
393 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
396 /* Get location of event and convert to virtual screen coordinate */
397 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
399 NSWindow *eventWindow = [ev window];
400 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
401 CGRect r = CGRectZero;
402 r.origin = [ev locationInWindow];
405 return [[self window] convertRectFromScreen:r].origin;
407 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
408 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
415 } else if ([[self window] isEqual:eventWindow]) {
419 CGPoint loc = [self convertPoint:r.origin fromView:nil];
427 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
439 - (void) unhideCursor
447 - (void) drawRect:(NSRect) rect
449 COCOA_DEBUG("QemuCocoaView: drawRect\n");
451 // get CoreGraphic context
452 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
454 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
455 CGContextSetShouldAntialias (viewContextRef, NO);
457 // draw screen bitmap directly to Core Graphics context
459 // Draw request before any guest device has set up a framebuffer:
460 // just draw an opaque black rectangle
461 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
462 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
464 int w = pixman_image_get_width(pixman_image);
465 int h = pixman_image_get_height(pixman_image);
466 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
467 int stride = pixman_image_get_stride(pixman_image);
468 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
470 pixman_image_get_data(pixman_image),
474 CGImageRef imageRef = CGImageCreate(
477 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
478 bitsPerPixel, //bitsPerPixel
479 stride, //bytesPerRow
480 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
481 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
482 dataProviderRef, //provider
485 kCGRenderingIntentDefault //intent
487 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
488 const NSRect *rectList;
491 CGImageRef clipImageRef;
494 [self getRectsBeingDrawn:&rectList count:&rectCount];
495 for (i = 0; i < rectCount; i++) {
496 clipRect.origin.x = rectList[i].origin.x / cdx;
497 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
498 clipRect.size.width = rectList[i].size.width / cdx;
499 clipRect.size.height = rectList[i].size.height / cdy;
500 clipImageRef = CGImageCreateWithImageInRect(
504 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
505 CGImageRelease (clipImageRef);
507 CGImageRelease (imageRef);
508 CGDataProviderRelease(dataProviderRef);
512 - (void) setContentDimensions
514 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
517 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
518 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
520 /* stretches video, but keeps same aspect ratio */
521 if (stretch_video == true) {
522 /* use smallest stretch value - prevents clipping on sides */
523 if (MIN(cdx, cdy) == cdx) {
528 } else { /* No stretching */
531 cw = screen.width * cdx;
532 ch = screen.height * cdy;
533 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
534 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
545 - (void) updateUIInfoLocked
547 /* Must be called with the iothread lock, i.e. via updateUIInfo */
551 if (!qemu_console_is_graphic(dcl.con)) {
556 NSDictionary *description = [[[self window] screen] deviceDescription];
557 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
558 NSSize screenSize = [[[self window] screen] frame].size;
559 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
560 CVDisplayLinkRef displayLink;
562 frameSize = isFullscreen ? screenSize : [self frame].size;
564 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
565 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
566 CVDisplayLinkRelease(displayLink);
567 if (!(period.flags & kCVTimeIsIndefinite)) {
568 update_displaychangelistener(&dcl,
569 1000 * period.timeValue / period.timeScale);
570 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
574 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
575 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
577 frameSize = [self frame].size;
584 info.width = frameSize.width;
585 info.height = frameSize.height;
587 dpy_set_ui_info(dcl.con, &info, TRUE);
590 - (void) updateUIInfo
594 * Don't try to tell QEMU about UI information in the application
595 * startup phase -- we haven't yet registered dcl with the QEMU UI
597 * When cocoa_display_init() does register the dcl, the UI layer
598 * will call cocoa_switch(), which will call updateUIInfo, so
599 * we don't lose any information here.
604 with_iothread_lock(^{
605 [self updateUIInfoLocked];
609 - (void)viewDidMoveToWindow
614 - (void) switchSurface:(pixman_image_t *)image
616 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
618 int w = pixman_image_get_width(image);
619 int h = pixman_image_get_height(image);
620 /* cdx == 0 means this is our very first surface, in which case we need
621 * to recalculate the content dimensions even if it happens to be the size
622 * of the initial empty window.
624 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
626 int oldh = screen.height;
628 // Resize before we trigger the redraw, or we'll redraw at the wrong size
629 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
632 [self setContentDimensions];
633 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
636 // update screenBuffer
638 pixman_image_unref(pixman_image);
641 pixman_image = image;
645 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
646 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
649 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
650 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
654 [normalWindow center];
658 - (void) toggleFullScreen:(id)sender
660 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
662 if (isFullscreen) { // switch from fullscreen to desktop
663 isFullscreen = FALSE;
665 [self setContentDimensions];
666 [fullScreenWindow close];
667 [normalWindow setContentView: self];
668 [normalWindow makeKeyAndOrderFront: self];
669 [NSMenu setMenuBarVisible:YES];
670 } else { // switch from desktop to fullscreen
672 [normalWindow orderOut: nil]; /* Hide the window */
674 [self setContentDimensions];
675 [NSMenu setMenuBarVisible:NO];
676 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
677 styleMask:NSWindowStyleMaskBorderless
678 backing:NSBackingStoreBuffered
680 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
681 [fullScreenWindow setHasShadow:NO];
682 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
683 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
684 [[fullScreenWindow contentView] addSubview: self];
685 [fullScreenWindow makeKeyAndOrderFront:self];
689 - (void) setFullGrab:(id)sender
691 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
693 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
694 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
695 mask, handleTapEvent, self);
697 warn_report("Could not create event tap, system key combos will not be captured.\n");
700 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
703 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
705 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
709 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
710 if (!tapEventsSrc ) {
711 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
715 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
716 CFRelease(tapEventsSrc);
719 - (void) toggleKey: (int)keycode {
720 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
723 // Does the work of sending input to the monitor
724 - (void) handleMonitorInput:(NSEvent *)event
729 // if the control key is down
730 if ([event modifierFlags] & NSEventModifierFlagControl) {
734 /* translates Macintosh keycodes to QEMU's keysym */
736 static const int without_control_translation[] = {
737 [0 ... 0xff] = 0, // invalid key
739 [kVK_UpArrow] = QEMU_KEY_UP,
740 [kVK_DownArrow] = QEMU_KEY_DOWN,
741 [kVK_RightArrow] = QEMU_KEY_RIGHT,
742 [kVK_LeftArrow] = QEMU_KEY_LEFT,
743 [kVK_Home] = QEMU_KEY_HOME,
744 [kVK_End] = QEMU_KEY_END,
745 [kVK_PageUp] = QEMU_KEY_PAGEUP,
746 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
747 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
748 [kVK_Delete] = QEMU_KEY_BACKSPACE,
751 static const int with_control_translation[] = {
752 [0 ... 0xff] = 0, // invalid key
754 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
755 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
756 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
757 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
758 [kVK_Home] = QEMU_KEY_CTRL_HOME,
759 [kVK_End] = QEMU_KEY_CTRL_END,
760 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
761 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
764 if (control_key != 0) { /* If the control key is being used */
765 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
766 keysym = with_control_translation[[event keyCode]];
769 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
770 keysym = without_control_translation[[event keyCode]];
774 // if not a key that needs translating
776 NSString *ks = [event characters];
777 if ([ks length] > 0) {
778 keysym = [ks characterAtIndex:0];
783 kbd_put_keysym(keysym);
787 - (bool) handleEvent:(NSEvent *)event
789 return bool_with_iothread_lock(^{
790 return [self handleEventLocked:event];
794 - (bool) handleEventLocked:(NSEvent *)event
796 /* Return true if we handled the event, false if it should be given to OSX */
797 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
800 bool mouse_event = false;
801 // Location of event in virtual screen coordinates
802 NSPoint p = [self screenLocationOfEvent:event];
803 NSUInteger modifiers = [event modifierFlags];
806 * Check -[NSEvent modifierFlags] here.
808 * There is a NSEventType for an event notifying the change of
809 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
810 * are performed for any events because a modifier state may change while
811 * the application is inactive (i.e. no events fire) and we don't want to
812 * wait for another modifier state change to detect such a change.
814 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
815 * are handled in similar manners.
817 * NSEventModifierFlagCapsLock
818 * ---------------------------
820 * If CapsLock state is changed, "up" and "down" events will be fired in
821 * sequence, effectively updates CapsLock state on the guest.
826 * If a flag is not set, fire "up" events for all keys which correspond to
827 * the flag. Note that "down" events are not fired here because the flags
828 * checked here do not tell what exact keys are down.
830 * If one of the keys corresponding to a flag is down, we rely on
831 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
832 * NSEventTypeFlagsChanged to know the exact key which is down, which has
833 * the following two downsides:
834 * - It does not work when the application is inactive as described above.
835 * - It malfactions *after* the modifier state is changed while the
836 * application is inactive. It is because -[NSEvent keyCode] does not tell
837 * if the key is up or down, and requires to infer the current state from
838 * the previous state. It is still possible to fix such a malfanction by
839 * completely leaving your hands from the keyboard, which hopefully makes
840 * this implementation usable enough.
842 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
843 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
844 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
845 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
848 if (!(modifiers & NSEventModifierFlagShift)) {
849 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
850 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
852 if (!(modifiers & NSEventModifierFlagControl)) {
853 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
854 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
856 if (!(modifiers & NSEventModifierFlagOption)) {
858 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
859 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
861 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
862 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
865 if (!(modifiers & NSEventModifierFlagCommand)) {
867 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
868 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
870 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
871 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
875 switch ([event type]) {
876 case NSEventTypeFlagsChanged:
877 switch ([event keyCode]) {
879 if (!!(modifiers & NSEventModifierFlagShift)) {
880 [self toggleKey:Q_KEY_CODE_SHIFT];
885 if (!!(modifiers & NSEventModifierFlagShift)) {
886 [self toggleKey:Q_KEY_CODE_SHIFT_R];
891 if (!!(modifiers & NSEventModifierFlagControl)) {
892 [self toggleKey:Q_KEY_CODE_CTRL];
896 case kVK_RightControl:
897 if (!!(modifiers & NSEventModifierFlagControl)) {
898 [self toggleKey:Q_KEY_CODE_CTRL_R];
903 if (!!(modifiers & NSEventModifierFlagOption)) {
905 [self toggleKey:Q_KEY_CODE_META_L];
907 [self toggleKey:Q_KEY_CODE_ALT];
912 case kVK_RightOption:
913 if (!!(modifiers & NSEventModifierFlagOption)) {
915 [self toggleKey:Q_KEY_CODE_META_R];
917 [self toggleKey:Q_KEY_CODE_ALT_R];
922 /* Don't pass command key changes to guest unless mouse is grabbed */
924 if (isMouseGrabbed &&
925 !!(modifiers & NSEventModifierFlagCommand) &&
926 left_command_key_enabled) {
928 [self toggleKey:Q_KEY_CODE_ALT];
930 [self toggleKey:Q_KEY_CODE_META_L];
935 case kVK_RightCommand:
936 if (isMouseGrabbed &&
937 !!(modifiers & NSEventModifierFlagCommand)) {
939 [self toggleKey:Q_KEY_CODE_ALT_R];
941 [self toggleKey:Q_KEY_CODE_META_R];
947 case NSEventTypeKeyDown:
948 keycode = cocoa_keycode_to_qemu([event keyCode]);
950 // forward command key combos to the host UI unless the mouse is grabbed
951 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
957 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
958 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
959 NSString *keychar = [event charactersIgnoringModifiers];
960 if ([keychar length] == 1) {
961 char key = [keychar characterAtIndex:0];
964 // enable graphic console
966 console_select(key - '0' - 1); /* ascii math */
969 // release the mouse grab
977 if (qemu_console_is_graphic(NULL)) {
978 qkbd_state_key_event(kbd, keycode, true);
980 [self handleMonitorInput: event];
983 case NSEventTypeKeyUp:
984 keycode = cocoa_keycode_to_qemu([event keyCode]);
986 // don't pass the guest a spurious key-up if we treated this
987 // command-key combo as a host UI action
988 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
992 if (qemu_console_is_graphic(NULL)) {
993 qkbd_state_key_event(kbd, keycode, false);
996 case NSEventTypeMouseMoved:
997 if (isAbsoluteEnabled) {
998 // Cursor re-entered into a window might generate events bound to screen coordinates
999 // and `nil` window property, and in full screen mode, current window might not be
1000 // key window, where event location alone should suffice.
1001 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
1002 if (isMouseGrabbed) {
1006 if (!isMouseGrabbed) {
1013 case NSEventTypeLeftMouseDown:
1014 buttons |= MOUSE_EVENT_LBUTTON;
1017 case NSEventTypeRightMouseDown:
1018 buttons |= MOUSE_EVENT_RBUTTON;
1021 case NSEventTypeOtherMouseDown:
1022 buttons |= MOUSE_EVENT_MBUTTON;
1025 case NSEventTypeLeftMouseDragged:
1026 buttons |= MOUSE_EVENT_LBUTTON;
1029 case NSEventTypeRightMouseDragged:
1030 buttons |= MOUSE_EVENT_RBUTTON;
1033 case NSEventTypeOtherMouseDragged:
1034 buttons |= MOUSE_EVENT_MBUTTON;
1037 case NSEventTypeLeftMouseUp:
1039 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
1041 * In fullscreen mode, the window of cocoaView may not be the
1042 * key window, therefore the position relative to the virtual
1043 * screen alone will be sufficient.
1045 if(isFullscreen || [[self window] isKeyWindow]) {
1050 case NSEventTypeRightMouseUp:
1053 case NSEventTypeOtherMouseUp:
1056 case NSEventTypeScrollWheel:
1058 * Send wheel events to the guest regardless of window focus.
1059 * This is in-line with standard Mac OS X UI behaviour.
1063 * We shouldn't have got a scroll event when deltaY and delta Y
1064 * are zero, hence no harm in dropping the event
1066 if ([event deltaY] != 0 || [event deltaX] != 0) {
1067 /* Determine if this is a scroll up or scroll down event */
1068 if ([event deltaY] != 0) {
1069 buttons = ([event deltaY] > 0) ?
1070 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1071 } else if ([event deltaX] != 0) {
1072 buttons = ([event deltaX] > 0) ?
1073 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1076 qemu_input_queue_btn(dcl.con, buttons, true);
1077 qemu_input_event_sync();
1078 qemu_input_queue_btn(dcl.con, buttons, false);
1079 qemu_input_event_sync();
1083 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
1084 * movement code from executing.
1086 mouse_event = false;
1093 /* Don't send button events to the guest unless we've got a
1094 * mouse grab or window focus. If we have neither then this event
1095 * is the user clicking on the background window to activate and
1096 * bring us to the front, which will be done by the sendEvent
1097 * call below. We definitely don't want to pass that click through
1100 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1101 (last_buttons != buttons)) {
1102 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1103 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1104 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1105 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
1107 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1108 last_buttons = buttons;
1110 if (isMouseGrabbed) {
1111 if (isAbsoluteEnabled) {
1112 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1113 * The check on screenContainsPoint is to avoid sending out of range values for
1114 * clicks in the titlebar.
1116 if ([self screenContainsPoint:p]) {
1117 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1118 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1121 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1122 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1127 qemu_input_event_sync();
1134 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1136 if (!isFullscreen) {
1138 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1140 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1143 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1144 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1147 - (void) ungrabMouse
1149 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1151 if (!isFullscreen) {
1153 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1155 [normalWindow setTitle:@"QEMU"];
1157 [self unhideCursor];
1158 CGAssociateMouseAndMouseCursorPosition(TRUE);
1159 isMouseGrabbed = FALSE;
1162 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1163 isAbsoluteEnabled = tIsAbsoluteEnabled;
1164 if (isMouseGrabbed) {
1165 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1168 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1169 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1170 - (float) cdx {return cdx;}
1171 - (float) cdy {return cdy;}
1172 - (QEMUScreen) gscreen {return screen;}
1175 * Makes the target think all down keys are being released.
1176 * This prevents a stuck key problem, since we will not see
1177 * key up events for those keys after we have lost focus.
1179 - (void) raiseAllKeys
1181 with_iothread_lock(^{
1182 qkbd_state_lift_all_keys(kbd);
1190 ------------------------------------------------------
1191 QemuCocoaAppController
1192 ------------------------------------------------------
1194 @interface QemuCocoaAppController : NSObject
1195 <NSWindowDelegate, NSApplicationDelegate>
1198 - (void)doToggleFullScreen:(id)sender;
1199 - (void)toggleFullScreen:(id)sender;
1200 - (void)showQEMUDoc:(id)sender;
1201 - (void)zoomToFit:(id) sender;
1202 - (void)displayConsole:(id)sender;
1203 - (void)pauseQEMU:(id)sender;
1204 - (void)resumeQEMU:(id)sender;
1205 - (void)displayPause;
1206 - (void)removePause;
1207 - (void)restartQEMU:(id)sender;
1208 - (void)powerDownQEMU:(id)sender;
1209 - (void)ejectDeviceMedia:(id)sender;
1210 - (void)changeDeviceMedia:(id)sender;
1212 - (void)openDocumentation:(NSString *)filename;
1213 - (IBAction) do_about_menu_item: (id) sender;
1214 - (void)adjustSpeed:(id)sender;
1217 @implementation QemuCocoaAppController
1220 COCOA_DEBUG("QemuCocoaAppController: init\n");
1222 self = [super init];
1225 // create a view and add it to the window
1226 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1228 error_report("(cocoa) can't create a view");
1233 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1234 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1235 backing:NSBackingStoreBuffered defer:NO];
1237 error_report("(cocoa) can't create window");
1240 [normalWindow setAcceptsMouseMovedEvents:YES];
1241 [normalWindow setTitle:@"QEMU"];
1242 [normalWindow setContentView:cocoaView];
1243 [normalWindow makeKeyAndOrderFront:self];
1244 [normalWindow center];
1245 [normalWindow setDelegate: self];
1246 stretch_video = false;
1248 /* Used for displaying pause on the screen */
1249 pauseLabel = [NSTextField new];
1250 [pauseLabel setBezeled:YES];
1251 [pauseLabel setDrawsBackground:YES];
1252 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1253 [pauseLabel setEditable:NO];
1254 [pauseLabel setSelectable:NO];
1255 [pauseLabel setStringValue: @"Paused"];
1256 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1257 [pauseLabel setTextColor: [NSColor blackColor]];
1258 [pauseLabel sizeToFit];
1265 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1268 [cocoaView release];
1272 - (void)applicationDidFinishLaunching: (NSNotification *) note
1274 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1275 allow_events = true;
1278 - (void)applicationWillTerminate:(NSNotification *)aNotification
1280 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1282 with_iothread_lock(^{
1283 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1284 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1288 * Sleep here, because returning will cause OSX to kill us
1289 * immediately; the QEMU main loop will handle the shutdown
1290 * request and terminate the process.
1292 [NSThread sleepForTimeInterval:INFINITY];
1295 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1300 - (NSApplicationTerminateReply)applicationShouldTerminate:
1301 (NSApplication *)sender
1303 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1304 return [self verifyQuit];
1307 - (void)windowDidChangeScreen:(NSNotification *)notification
1309 [cocoaView updateUIInfo];
1312 - (void)windowDidResize:(NSNotification *)notification
1314 [cocoaView updateUIInfo];
1317 /* Called when the user clicks on a window's close button */
1318 - (BOOL)windowShouldClose:(id)sender
1320 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1321 [NSApp terminate: sender];
1322 /* If the user allows the application to quit then the call to
1323 * NSApp terminate will never return. If we get here then the user
1324 * cancelled the quit, so we should return NO to not permit the
1325 * closing of this window.
1330 /* Called when QEMU goes into the background */
1331 - (void) applicationWillResignActive: (NSNotification *)aNotification
1333 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1334 [cocoaView ungrabMouse];
1335 [cocoaView raiseAllKeys];
1338 /* We abstract the method called by the Enter Fullscreen menu item
1339 * because Mac OS 10.7 and higher disables it. This is because of the
1340 * menu item's old selector's name toggleFullScreen:
1342 - (void) doToggleFullScreen:(id)sender
1344 [self toggleFullScreen:(id)sender];
1347 - (void)toggleFullScreen:(id)sender
1349 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1351 [cocoaView toggleFullScreen:sender];
1354 - (void) setFullGrab:(id)sender
1356 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1358 [cocoaView setFullGrab:sender];
1361 /* Tries to find then open the specified filename */
1362 - (void) openDocumentation: (NSString *) filename
1364 /* Where to look for local files */
1365 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1366 NSString *full_file_path;
1367 NSURL *full_file_url;
1369 /* iterate thru the possible paths until the file is found */
1371 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1372 full_file_path = [[NSBundle mainBundle] executablePath];
1373 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1374 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1375 path_array[index], filename];
1376 full_file_url = [NSURL fileURLWithPath: full_file_path
1377 isDirectory: false];
1378 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1383 /* If none of the paths opened a file */
1385 QEMU_Alert(@"Failed to open file");
1388 - (void)showQEMUDoc:(id)sender
1390 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1392 [self openDocumentation: @"index.html"];
1395 /* Stretches video to fit host monitor size */
1396 - (void)zoomToFit:(id) sender
1398 stretch_video = !stretch_video;
1399 if (stretch_video == true) {
1400 [sender setState: NSControlStateValueOn];
1402 [sender setState: NSControlStateValueOff];
1406 /* Displays the console on the screen */
1407 - (void)displayConsole:(id)sender
1409 console_select([sender tag]);
1412 /* Pause the guest */
1413 - (void)pauseQEMU:(id)sender
1415 with_iothread_lock(^{
1418 [sender setEnabled: NO];
1419 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1420 [self displayPause];
1423 /* Resume running the guest operating system */
1424 - (void)resumeQEMU:(id) sender
1426 with_iothread_lock(^{
1429 [sender setEnabled: NO];
1430 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1434 /* Displays the word pause on the screen */
1435 - (void)displayPause
1437 /* Coordinates have to be calculated each time because the window can change its size */
1438 int xCoord, yCoord, width, height;
1439 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1440 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1441 width = [pauseLabel frame].size.width;
1442 height = [pauseLabel frame].size.height;
1443 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1444 [cocoaView addSubview: pauseLabel];
1447 /* Removes the word pause from the screen */
1450 [pauseLabel removeFromSuperview];
1454 - (void)restartQEMU:(id)sender
1456 with_iothread_lock(^{
1457 qmp_system_reset(NULL);
1461 /* Powers down QEMU */
1462 - (void)powerDownQEMU:(id)sender
1464 with_iothread_lock(^{
1465 qmp_system_powerdown(NULL);
1469 /* Ejects the media.
1470 * Uses sender's tag to figure out the device to eject.
1472 - (void)ejectDeviceMedia:(id)sender
1475 drive = [sender representedObject];
1478 QEMU_Alert(@"Failed to find drive to eject!");
1482 __block Error *err = NULL;
1483 with_iothread_lock(^{
1484 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1485 false, NULL, false, false, &err);
1487 handleAnyDeviceErrors(err);
1490 /* Displays a dialog box asking the user to select an image file to load.
1491 * Uses sender's represented object value to figure out which drive to use.
1493 - (void)changeDeviceMedia:(id)sender
1495 /* Find the drive name */
1497 drive = [sender representedObject];
1500 QEMU_Alert(@"Could not find drive!");
1504 /* Display the file open dialog */
1505 NSOpenPanel * openPanel;
1506 openPanel = [NSOpenPanel openPanel];
1507 [openPanel setCanChooseFiles: YES];
1508 [openPanel setAllowsMultipleSelection: NO];
1509 if([openPanel runModal] == NSModalResponseOK) {
1510 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1513 QEMU_Alert(@"Failed to convert URL to file path!");
1517 __block Error *err = NULL;
1518 with_iothread_lock(^{
1519 qmp_blockdev_change_medium(true,
1520 [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];
1601 with_iothread_lock(^{
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 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1667 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1668 [menuItem setSubmenu:menu];
1669 [[NSApp mainMenu] addItem:menuItem];
1672 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1674 // Add the rest of the Speed menu items
1675 int p, percentage, throttle_pct;
1676 for (p = 10; p >= 0; p--)
1678 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1680 menuItem = [[[NSMenuItem alloc]
1681 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1683 if (percentage == 100) {
1684 [menuItem setState: NSControlStateValueOn];
1687 /* Calculate the throttle percentage */
1688 throttle_pct = -1 * percentage + 100;
1690 [menuItem setTag: throttle_pct];
1691 [menu addItem: menuItem];
1693 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1694 [menuItem setSubmenu:menu];
1695 [[NSApp mainMenu] addItem:menuItem];
1698 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1699 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1700 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1701 [menuItem setSubmenu:menu];
1702 [[NSApp mainMenu] addItem:menuItem];
1703 [NSApp setWindowsMenu:menu];
1706 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1707 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1708 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1709 [menuItem setSubmenu:menu];
1710 [[NSApp mainMenu] addItem:menuItem];
1713 /* Returns a name for a given console */
1714 static NSString * getConsoleName(QemuConsole * console)
1716 g_autofree char *label = qemu_console_get_label(console);
1718 return [NSString stringWithUTF8String:label];
1721 /* Add an entry to the View menu for each console */
1722 static void add_console_menu_entries(void)
1725 NSMenuItem *menuItem;
1728 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1730 [menu addItem:[NSMenuItem separatorItem]];
1732 while (qemu_console_lookup_by_index(index) != NULL) {
1733 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1734 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1735 [menuItem setTag: index];
1736 [menu addItem: menuItem];
1741 /* Make menu items for all removable devices.
1742 * Each device is given an 'Eject' and 'Change' menu item.
1744 static void addRemovableDevicesMenuItems(void)
1747 NSMenuItem *menuItem;
1748 BlockInfoList *currentDevice, *pointerToFree;
1749 NSString *deviceName;
1751 currentDevice = qmp_query_block(NULL);
1752 pointerToFree = currentDevice;
1754 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1756 // Add a separator between related groups of menu items
1757 [menu addItem:[NSMenuItem separatorItem]];
1759 // Set the attributes to the "Removable Media" menu item
1760 NSString *titleString = @"Removable Media";
1761 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1762 NSColor *newColor = [NSColor blackColor];
1763 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1764 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1765 traits:NSBoldFontMask|NSItalicFontMask
1768 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1769 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1770 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1772 // Add the "Removable Media" menu item
1773 menuItem = [NSMenuItem new];
1774 [menuItem setAttributedTitle: attString];
1775 [menuItem setEnabled: NO];
1776 [menu addItem: menuItem];
1778 /* Loop through all the block devices in the emulator */
1779 while (currentDevice) {
1780 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1782 if(currentDevice->value->removable) {
1783 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1784 action: @selector(changeDeviceMedia:)
1785 keyEquivalent: @""];
1786 [menu addItem: menuItem];
1787 [menuItem setRepresentedObject: deviceName];
1788 [menuItem autorelease];
1790 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1791 action: @selector(ejectDeviceMedia:)
1792 keyEquivalent: @""];
1793 [menu addItem: menuItem];
1794 [menuItem setRepresentedObject: deviceName];
1795 [menuItem autorelease];
1797 currentDevice = currentDevice->next;
1799 qapi_free_BlockInfoList(pointerToFree);
1802 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1805 @implementation QemuCocoaPasteboardTypeOwner
1807 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1809 if (type != NSPasteboardTypeString) {
1813 with_iothread_lock(^{
1814 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1815 qemu_event_reset(&cbevent);
1816 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1818 while (info == cbinfo &&
1819 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1820 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1821 qemu_mutex_unlock_iothread();
1822 qemu_event_wait(&cbevent);
1823 qemu_mutex_lock_iothread();
1826 if (info == cbinfo) {
1827 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1828 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1829 [sender setData:data forType:NSPasteboardTypeString];
1833 qemu_clipboard_info_unref(info);
1839 static QemuCocoaPasteboardTypeOwner *cbowner;
1841 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1842 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1843 QemuClipboardType type);
1845 static QemuClipboardPeer cbpeer = {
1847 .notifier = { .notify = cocoa_clipboard_notify },
1848 .request = cocoa_clipboard_request
1851 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1853 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1857 if (info != cbinfo) {
1858 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1859 qemu_clipboard_info_unref(cbinfo);
1860 cbinfo = qemu_clipboard_info_ref(info);
1861 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1865 qemu_event_set(&cbevent);
1868 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1870 QemuClipboardNotify *notify = data;
1872 switch (notify->type) {
1873 case QEMU_CLIPBOARD_UPDATE_INFO:
1874 cocoa_clipboard_update_info(notify->info);
1876 case QEMU_CLIPBOARD_RESET_SERIAL:
1882 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1883 QemuClipboardType type)
1885 NSAutoreleasePool *pool;
1889 case QEMU_CLIPBOARD_TYPE_TEXT:
1890 pool = [[NSAutoreleasePool alloc] init];
1891 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1893 qemu_clipboard_set_data(&cbpeer, info, type,
1894 [text length], [text bytes], true);
1904 * The startup process for the OSX/Cocoa UI is complicated, because
1905 * OSX insists that the UI runs on the initial main thread, and so we
1906 * need to start a second thread which runs the qemu_default_main():
1908 * in cocoa_display_init():
1909 * assign cocoa_main to qemu_main
1910 * create application, menus, etc
1912 * create qemu-main thread
1913 * enter OSX run loop
1916 static void *call_qemu_main(void *opaque)
1920 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
1921 qemu_mutex_lock_iothread();
1922 status = qemu_default_main();
1923 qemu_mutex_unlock_iothread();
1924 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
1929 static int cocoa_main()
1933 COCOA_DEBUG("Entered %s()\n", __func__);
1935 qemu_mutex_unlock_iothread();
1936 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1937 NULL, QEMU_THREAD_DETACHED);
1939 // Start the main event loop
1940 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1942 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
1950 static void cocoa_update(DisplayChangeListener *dcl,
1951 int x, int y, int w, int h)
1953 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1955 dispatch_async(dispatch_get_main_queue(), ^{
1957 if ([cocoaView cdx] == 1.0) {
1958 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1961 x * [cocoaView cdx],
1962 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1963 w * [cocoaView cdx],
1964 h * [cocoaView cdy]);
1966 [cocoaView setNeedsDisplayInRect:rect];
1970 static void cocoa_switch(DisplayChangeListener *dcl,
1971 DisplaySurface *surface)
1973 pixman_image_t *image = surface->image;
1975 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1977 // The DisplaySurface will be freed as soon as this callback returns.
1978 // We take a reference to the underlying pixman image here so it does
1979 // not disappear from under our feet; the switchSurface method will
1980 // deref the old image when it is done with it.
1981 pixman_image_ref(image);
1983 dispatch_async(dispatch_get_main_queue(), ^{
1984 [cocoaView updateUIInfo];
1985 [cocoaView switchSurface:image];
1989 static void cocoa_refresh(DisplayChangeListener *dcl)
1991 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1993 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1994 graphic_hw_update(NULL);
1996 if (qemu_input_is_absolute()) {
1997 dispatch_async(dispatch_get_main_queue(), ^{
1998 if (![cocoaView isAbsoluteEnabled]) {
1999 if ([cocoaView isMouseGrabbed]) {
2000 [cocoaView ungrabMouse];
2003 [cocoaView setAbsoluteEnabled:YES];
2007 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2008 qemu_clipboard_info_unref(cbinfo);
2009 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2010 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2011 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2013 qemu_clipboard_update(cbinfo);
2014 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2015 qemu_event_set(&cbevent);
2021 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2023 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2025 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2027 qemu_main = cocoa_main;
2029 // Pull this console process up to being a fully-fledged graphical
2030 // app with a menubar and Dock icon
2031 ProcessSerialNumber psn = { 0, kCurrentProcess };
2032 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2034 [QemuApplication sharedApplication];
2036 create_initial_menus();
2039 * Create the menu entries which depend on QEMU state (for consoles
2040 * and removeable devices). These make calls back into QEMU functions,
2041 * which is OK because at this point we know that the second thread
2042 * holds the iothread lock and is synchronously waiting for us to
2045 add_console_menu_entries();
2046 addRemovableDevicesMenuItems();
2048 // Create an Application controller
2049 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2050 [NSApp setDelegate:controller];
2052 /* if fullscreen mode is to be used */
2053 if (opts->has_full_screen && opts->full_screen) {
2054 [NSApp activateIgnoringOtherApps: YES];
2055 [controller toggleFullScreen: nil];
2057 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2058 [controller setFullGrab: nil];
2061 if (opts->has_show_cursor && opts->show_cursor) {
2064 if (opts->u.cocoa.has_swap_opt_cmd) {
2065 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2068 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2069 left_command_key_enabled = 0;
2072 // register vga output callbacks
2073 register_displaychangelistener(&dcl);
2075 qemu_event_init(&cbevent, false);
2076 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2077 qemu_clipboard_peer_register(&cbpeer);
2082 static QemuDisplay qemu_display_cocoa = {
2083 .type = DISPLAY_TYPE_COCOA,
2084 .init = cocoa_display_init,
2087 static void register_cocoa(void)
2089 qemu_display_register(&qemu_display_cocoa);
2092 type_init(register_cocoa);