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([drive cStringUsingEncoding: NSASCIIStringEncoding],
1485 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([drive cStringUsingEncoding:
1520 NSASCIIStringEncoding],
1522 [file cStringUsingEncoding:
1523 NSASCIIStringEncoding],
1529 handleAnyDeviceErrors(err);
1533 /* Verifies if the user really wants to quit */
1536 NSAlert *alert = [NSAlert new];
1537 [alert autorelease];
1538 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1539 [alert addButtonWithTitle: @"Cancel"];
1540 [alert addButtonWithTitle: @"Quit"];
1541 if([alert runModal] == NSAlertSecondButtonReturn) {
1548 /* The action method for the About menu item */
1549 - (IBAction) do_about_menu_item: (id) sender
1551 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1552 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1553 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1554 g_free(icon_path_c);
1555 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1556 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1557 NSString *copyright = @QEMU_COPYRIGHT;
1558 NSDictionary *options;
1561 NSAboutPanelOptionApplicationIcon : icon,
1562 NSAboutPanelOptionApplicationVersion : version,
1563 @"Copyright" : copyright,
1568 NSAboutPanelOptionApplicationVersion : version,
1569 @"Copyright" : copyright,
1572 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1576 /* Used by the Speed menu items */
1577 - (void)adjustSpeed:(id)sender
1579 int throttle_pct; /* throttle percentage */
1582 menu = [sender menu];
1585 /* Unselect the currently selected item */
1586 for (NSMenuItem *item in [menu itemArray]) {
1587 if (item.state == NSControlStateValueOn) {
1588 [item setState: NSControlStateValueOff];
1594 // check the menu item
1595 [sender setState: NSControlStateValueOn];
1597 // get the throttle percentage
1598 throttle_pct = [sender tag];
1600 with_iothread_lock(^{
1601 cpu_throttle_set(throttle_pct);
1603 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1608 @interface QemuApplication : NSApplication
1611 @implementation QemuApplication
1612 - (void)sendEvent:(NSEvent *)event
1614 COCOA_DEBUG("QemuApplication: sendEvent\n");
1615 if (![cocoaView handleEvent:event]) {
1616 [super sendEvent: event];
1621 static void create_initial_menus(void)
1625 NSMenuItem *menuItem;
1627 [NSApp setMainMenu:[[NSMenu alloc] init]];
1628 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1631 menu = [[NSMenu alloc] initWithTitle:@""];
1632 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1633 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1634 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1635 [menuItem setSubmenu:[NSApp servicesMenu]];
1636 [menu addItem:[NSMenuItem separatorItem]];
1637 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1638 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1639 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1640 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1641 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1642 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1643 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1644 [menuItem setSubmenu:menu];
1645 [[NSApp mainMenu] addItem:menuItem];
1646 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1649 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1650 [menu setAutoenablesItems: NO];
1651 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1652 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1653 [menu addItem: menuItem];
1654 [menuItem setEnabled: NO];
1655 [menu addItem: [NSMenuItem separatorItem]];
1656 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1657 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1658 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1659 [menuItem setSubmenu:menu];
1660 [[NSApp mainMenu] addItem:menuItem];
1663 menu = [[NSMenu alloc] initWithTitle:@"View"];
1664 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1665 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1666 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1667 [menuItem setSubmenu:menu];
1668 [[NSApp mainMenu] addItem:menuItem];
1671 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1673 // Add the rest of the Speed menu items
1674 int p, percentage, throttle_pct;
1675 for (p = 10; p >= 0; p--)
1677 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1679 menuItem = [[[NSMenuItem alloc]
1680 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1682 if (percentage == 100) {
1683 [menuItem setState: NSControlStateValueOn];
1686 /* Calculate the throttle percentage */
1687 throttle_pct = -1 * percentage + 100;
1689 [menuItem setTag: throttle_pct];
1690 [menu addItem: menuItem];
1692 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1693 [menuItem setSubmenu:menu];
1694 [[NSApp mainMenu] addItem:menuItem];
1697 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1698 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1699 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1700 [menuItem setSubmenu:menu];
1701 [[NSApp mainMenu] addItem:menuItem];
1702 [NSApp setWindowsMenu:menu];
1705 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1706 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1707 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1708 [menuItem setSubmenu:menu];
1709 [[NSApp mainMenu] addItem:menuItem];
1712 /* Returns a name for a given console */
1713 static NSString * getConsoleName(QemuConsole * console)
1715 g_autofree char *label = qemu_console_get_label(console);
1717 return [NSString stringWithUTF8String:label];
1720 /* Add an entry to the View menu for each console */
1721 static void add_console_menu_entries(void)
1724 NSMenuItem *menuItem;
1727 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1729 [menu addItem:[NSMenuItem separatorItem]];
1731 while (qemu_console_lookup_by_index(index) != NULL) {
1732 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1733 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1734 [menuItem setTag: index];
1735 [menu addItem: menuItem];
1740 /* Make menu items for all removable devices.
1741 * Each device is given an 'Eject' and 'Change' menu item.
1743 static void addRemovableDevicesMenuItems(void)
1746 NSMenuItem *menuItem;
1747 BlockInfoList *currentDevice, *pointerToFree;
1748 NSString *deviceName;
1750 currentDevice = qmp_query_block(NULL);
1751 pointerToFree = currentDevice;
1753 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1755 // Add a separator between related groups of menu items
1756 [menu addItem:[NSMenuItem separatorItem]];
1758 // Set the attributes to the "Removable Media" menu item
1759 NSString *titleString = @"Removable Media";
1760 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1761 NSColor *newColor = [NSColor blackColor];
1762 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1763 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1764 traits:NSBoldFontMask|NSItalicFontMask
1767 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1768 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1769 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1771 // Add the "Removable Media" menu item
1772 menuItem = [NSMenuItem new];
1773 [menuItem setAttributedTitle: attString];
1774 [menuItem setEnabled: NO];
1775 [menu addItem: menuItem];
1777 /* Loop through all the block devices in the emulator */
1778 while (currentDevice) {
1779 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1781 if(currentDevice->value->removable) {
1782 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1783 action: @selector(changeDeviceMedia:)
1784 keyEquivalent: @""];
1785 [menu addItem: menuItem];
1786 [menuItem setRepresentedObject: deviceName];
1787 [menuItem autorelease];
1789 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1790 action: @selector(ejectDeviceMedia:)
1791 keyEquivalent: @""];
1792 [menu addItem: menuItem];
1793 [menuItem setRepresentedObject: deviceName];
1794 [menuItem autorelease];
1796 currentDevice = currentDevice->next;
1798 qapi_free_BlockInfoList(pointerToFree);
1801 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1804 @implementation QemuCocoaPasteboardTypeOwner
1806 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1808 if (type != NSPasteboardTypeString) {
1812 with_iothread_lock(^{
1813 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1814 qemu_event_reset(&cbevent);
1815 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1817 while (info == cbinfo &&
1818 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1819 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1820 qemu_mutex_unlock_iothread();
1821 qemu_event_wait(&cbevent);
1822 qemu_mutex_lock_iothread();
1825 if (info == cbinfo) {
1826 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1827 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1828 [sender setData:data forType:NSPasteboardTypeString];
1832 qemu_clipboard_info_unref(info);
1838 static QemuCocoaPasteboardTypeOwner *cbowner;
1840 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1841 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1842 QemuClipboardType type);
1844 static QemuClipboardPeer cbpeer = {
1846 .notifier = { .notify = cocoa_clipboard_notify },
1847 .request = cocoa_clipboard_request
1850 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1852 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1856 if (info != cbinfo) {
1857 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1858 qemu_clipboard_info_unref(cbinfo);
1859 cbinfo = qemu_clipboard_info_ref(info);
1860 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1864 qemu_event_set(&cbevent);
1867 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1869 QemuClipboardNotify *notify = data;
1871 switch (notify->type) {
1872 case QEMU_CLIPBOARD_UPDATE_INFO:
1873 cocoa_clipboard_update_info(notify->info);
1875 case QEMU_CLIPBOARD_RESET_SERIAL:
1881 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1882 QemuClipboardType type)
1884 NSAutoreleasePool *pool;
1888 case QEMU_CLIPBOARD_TYPE_TEXT:
1889 pool = [[NSAutoreleasePool alloc] init];
1890 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1892 qemu_clipboard_set_data(&cbpeer, info, type,
1893 [text length], [text bytes], true);
1903 * The startup process for the OSX/Cocoa UI is complicated, because
1904 * OSX insists that the UI runs on the initial main thread, and so we
1905 * need to start a second thread which runs the qemu_default_main():
1907 * in cocoa_display_init():
1908 * assign cocoa_main to qemu_main
1909 * create application, menus, etc
1911 * create qemu-main thread
1912 * enter OSX run loop
1915 static void *call_qemu_main(void *opaque)
1919 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
1920 qemu_mutex_lock_iothread();
1921 status = qemu_default_main();
1922 qemu_mutex_unlock_iothread();
1923 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
1928 static int cocoa_main()
1932 COCOA_DEBUG("Entered %s()\n", __func__);
1934 qemu_mutex_unlock_iothread();
1935 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1936 NULL, QEMU_THREAD_DETACHED);
1938 // Start the main event loop
1939 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1941 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
1949 static void cocoa_update(DisplayChangeListener *dcl,
1950 int x, int y, int w, int h)
1952 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1954 dispatch_async(dispatch_get_main_queue(), ^{
1956 if ([cocoaView cdx] == 1.0) {
1957 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1960 x * [cocoaView cdx],
1961 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1962 w * [cocoaView cdx],
1963 h * [cocoaView cdy]);
1965 [cocoaView setNeedsDisplayInRect:rect];
1969 static void cocoa_switch(DisplayChangeListener *dcl,
1970 DisplaySurface *surface)
1972 pixman_image_t *image = surface->image;
1974 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1976 // The DisplaySurface will be freed as soon as this callback returns.
1977 // We take a reference to the underlying pixman image here so it does
1978 // not disappear from under our feet; the switchSurface method will
1979 // deref the old image when it is done with it.
1980 pixman_image_ref(image);
1982 dispatch_async(dispatch_get_main_queue(), ^{
1983 [cocoaView updateUIInfo];
1984 [cocoaView switchSurface:image];
1988 static void cocoa_refresh(DisplayChangeListener *dcl)
1990 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1992 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1993 graphic_hw_update(NULL);
1995 if (qemu_input_is_absolute()) {
1996 dispatch_async(dispatch_get_main_queue(), ^{
1997 if (![cocoaView isAbsoluteEnabled]) {
1998 if ([cocoaView isMouseGrabbed]) {
1999 [cocoaView ungrabMouse];
2002 [cocoaView setAbsoluteEnabled:YES];
2006 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2007 qemu_clipboard_info_unref(cbinfo);
2008 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2009 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2010 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2012 qemu_clipboard_update(cbinfo);
2013 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2014 qemu_event_set(&cbevent);
2020 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2022 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2024 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2026 qemu_main = cocoa_main;
2028 // Pull this console process up to being a fully-fledged graphical
2029 // app with a menubar and Dock icon
2030 ProcessSerialNumber psn = { 0, kCurrentProcess };
2031 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2033 [QemuApplication sharedApplication];
2035 create_initial_menus();
2038 * Create the menu entries which depend on QEMU state (for consoles
2039 * and removeable devices). These make calls back into QEMU functions,
2040 * which is OK because at this point we know that the second thread
2041 * holds the iothread lock and is synchronously waiting for us to
2044 add_console_menu_entries();
2045 addRemovableDevicesMenuItems();
2047 // Create an Application controller
2048 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2049 [NSApp setDelegate:controller];
2051 /* if fullscreen mode is to be used */
2052 if (opts->has_full_screen && opts->full_screen) {
2053 [NSApp activateIgnoringOtherApps: YES];
2054 [controller toggleFullScreen: nil];
2056 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2057 [controller setFullGrab: nil];
2060 if (opts->has_show_cursor && opts->show_cursor) {
2063 if (opts->u.cocoa.has_swap_opt_cmd) {
2064 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2067 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2068 left_command_key_enabled = 0;
2071 // register vga output callbacks
2072 register_displaychangelistener(&dcl);
2074 qemu_event_init(&cbevent, false);
2075 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2076 qemu_clipboard_peer_register(&cbpeer);
2081 static QemuDisplay qemu_display_cocoa = {
2082 .type = DISPLAY_TYPE_COCOA,
2083 .init = cocoa_display_init,
2086 static void register_cocoa(void)
2088 qemu_display_register(&qemu_display_cocoa);
2091 type_init(register_cocoa);