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-common.h"
31 #include "ui/clipboard.h"
32 #include "ui/console.h"
34 #include "ui/kbd-state.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/runstate.h"
37 #include "sysemu/cpu-throttle.h"
38 #include "qapi/error.h"
39 #include "qapi/qapi-commands-block.h"
40 #include "qapi/qapi-commands-machine.h"
41 #include "qapi/qapi-commands-misc.h"
42 #include "sysemu/blockdev.h"
43 #include "qemu-version.h"
44 #include "qemu/cutils.h"
45 #include "qemu/main-loop.h"
46 #include "qemu/module.h"
47 #include <Carbon/Carbon.h>
48 #include "hw/core/cpu.h"
50 #ifndef MAC_OS_X_VERSION_10_13
51 #define MAC_OS_X_VERSION_10_13 101300
54 /* 10.14 deprecates NSOnState and NSOffState in favor of
55 * NSControlStateValueOn/Off, which were introduced in 10.13.
56 * Define for older versions
58 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
59 #define NSControlStateValueOn NSOnState
60 #define NSControlStateValueOff NSOffState
66 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
68 #define COCOA_DEBUG(...) ((void) 0)
71 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
78 static void cocoa_update(DisplayChangeListener *dcl,
79 int x, int y, int w, int h);
81 static void cocoa_switch(DisplayChangeListener *dcl,
82 DisplaySurface *surface);
84 static void cocoa_refresh(DisplayChangeListener *dcl);
86 static NSWindow *normalWindow;
87 static const DisplayChangeListenerOps dcl_ops = {
89 .dpy_gfx_update = cocoa_update,
90 .dpy_gfx_switch = cocoa_switch,
91 .dpy_refresh = cocoa_refresh,
93 static DisplayChangeListener dcl = {
96 static int last_buttons;
97 static int cursor_hide = 1;
98 static int left_command_key_enabled = 1;
99 static bool swap_opt_cmd;
103 static bool stretch_video;
104 static NSTextField *pauseLabel;
106 static QemuSemaphore display_init_sem;
107 static QemuSemaphore app_started_sem;
108 static bool allow_events;
110 static NSInteger cbchangecount = -1;
111 static QemuClipboardInfo *cbinfo;
112 static QemuEvent cbevent;
114 // Utility functions to run specified code block with iothread lock held
115 typedef void (^CodeBlock)(void);
116 typedef bool (^BoolCodeBlock)(void);
118 static void with_iothread_lock(CodeBlock block)
120 bool locked = qemu_mutex_iothread_locked();
122 qemu_mutex_lock_iothread();
126 qemu_mutex_unlock_iothread();
130 static bool bool_with_iothread_lock(BoolCodeBlock block)
132 bool locked = qemu_mutex_iothread_locked();
136 qemu_mutex_lock_iothread();
140 qemu_mutex_unlock_iothread();
145 // Mac to QKeyCode conversion
146 static const int mac_to_qkeycode_map[] = {
147 [kVK_ANSI_A] = Q_KEY_CODE_A,
148 [kVK_ANSI_B] = Q_KEY_CODE_B,
149 [kVK_ANSI_C] = Q_KEY_CODE_C,
150 [kVK_ANSI_D] = Q_KEY_CODE_D,
151 [kVK_ANSI_E] = Q_KEY_CODE_E,
152 [kVK_ANSI_F] = Q_KEY_CODE_F,
153 [kVK_ANSI_G] = Q_KEY_CODE_G,
154 [kVK_ANSI_H] = Q_KEY_CODE_H,
155 [kVK_ANSI_I] = Q_KEY_CODE_I,
156 [kVK_ANSI_J] = Q_KEY_CODE_J,
157 [kVK_ANSI_K] = Q_KEY_CODE_K,
158 [kVK_ANSI_L] = Q_KEY_CODE_L,
159 [kVK_ANSI_M] = Q_KEY_CODE_M,
160 [kVK_ANSI_N] = Q_KEY_CODE_N,
161 [kVK_ANSI_O] = Q_KEY_CODE_O,
162 [kVK_ANSI_P] = Q_KEY_CODE_P,
163 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
164 [kVK_ANSI_R] = Q_KEY_CODE_R,
165 [kVK_ANSI_S] = Q_KEY_CODE_S,
166 [kVK_ANSI_T] = Q_KEY_CODE_T,
167 [kVK_ANSI_U] = Q_KEY_CODE_U,
168 [kVK_ANSI_V] = Q_KEY_CODE_V,
169 [kVK_ANSI_W] = Q_KEY_CODE_W,
170 [kVK_ANSI_X] = Q_KEY_CODE_X,
171 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
172 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
174 [kVK_ANSI_0] = Q_KEY_CODE_0,
175 [kVK_ANSI_1] = Q_KEY_CODE_1,
176 [kVK_ANSI_2] = Q_KEY_CODE_2,
177 [kVK_ANSI_3] = Q_KEY_CODE_3,
178 [kVK_ANSI_4] = Q_KEY_CODE_4,
179 [kVK_ANSI_5] = Q_KEY_CODE_5,
180 [kVK_ANSI_6] = Q_KEY_CODE_6,
181 [kVK_ANSI_7] = Q_KEY_CODE_7,
182 [kVK_ANSI_8] = Q_KEY_CODE_8,
183 [kVK_ANSI_9] = Q_KEY_CODE_9,
185 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
186 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
187 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
188 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
189 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
190 [kVK_Tab] = Q_KEY_CODE_TAB,
191 [kVK_Return] = Q_KEY_CODE_RET,
192 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
193 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
194 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
195 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
196 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
197 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
198 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
199 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
200 [kVK_Space] = Q_KEY_CODE_SPC,
202 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
203 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
204 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
205 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
206 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
207 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
208 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
209 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
210 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
211 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
212 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
213 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
214 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
215 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
216 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
217 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
218 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
219 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
221 [kVK_UpArrow] = Q_KEY_CODE_UP,
222 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
223 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
224 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
226 [kVK_Help] = Q_KEY_CODE_INSERT,
227 [kVK_Home] = Q_KEY_CODE_HOME,
228 [kVK_PageUp] = Q_KEY_CODE_PGUP,
229 [kVK_PageDown] = Q_KEY_CODE_PGDN,
230 [kVK_End] = Q_KEY_CODE_END,
231 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
233 [kVK_Escape] = Q_KEY_CODE_ESC,
235 /* The Power key can't be used directly because the operating system uses
236 * it. This key can be emulated by using it in place of another key such as
237 * F1. Don't forget to disable the real key binding.
239 /* [kVK_F1] = Q_KEY_CODE_POWER, */
241 [kVK_F1] = Q_KEY_CODE_F1,
242 [kVK_F2] = Q_KEY_CODE_F2,
243 [kVK_F3] = Q_KEY_CODE_F3,
244 [kVK_F4] = Q_KEY_CODE_F4,
245 [kVK_F5] = Q_KEY_CODE_F5,
246 [kVK_F6] = Q_KEY_CODE_F6,
247 [kVK_F7] = Q_KEY_CODE_F7,
248 [kVK_F8] = Q_KEY_CODE_F8,
249 [kVK_F9] = Q_KEY_CODE_F9,
250 [kVK_F10] = Q_KEY_CODE_F10,
251 [kVK_F11] = Q_KEY_CODE_F11,
252 [kVK_F12] = Q_KEY_CODE_F12,
253 [kVK_F13] = Q_KEY_CODE_PRINT,
254 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
255 [kVK_F15] = Q_KEY_CODE_PAUSE,
257 // JIS keyboards only
258 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
259 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
260 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
261 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
262 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
265 * The eject and volume keys can't be used here because they are handled at
266 * a lower level than what an Application can see.
270 static int cocoa_keycode_to_qemu(int keycode)
272 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
273 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
276 return mac_to_qkeycode_map[keycode];
279 /* Displays an alert dialog box with the specified message */
280 static void QEMU_Alert(NSString *message)
283 alert = [NSAlert new];
284 [alert setMessageText: message];
288 /* Handles any errors that happen with a device transaction */
289 static void handleAnyDeviceErrors(Error * err)
292 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
293 encoding: NSASCIIStringEncoding]);
299 ------------------------------------------------------
301 ------------------------------------------------------
303 @interface QemuCocoaView : NSView
306 NSWindow *fullScreenWindow;
307 float cx,cy,cw,ch,cdx,cdy;
308 pixman_image_t *pixman_image;
312 BOOL isAbsoluteEnabled;
313 CFMachPortRef eventsTap;
315 - (void) switchSurface:(pixman_image_t *)image;
317 - (void) ungrabMouse;
318 - (void) toggleFullScreen:(id)sender;
319 - (void) setFullGrab:(id)sender;
320 - (void) handleMonitorInput:(NSEvent *)event;
321 - (bool) handleEvent:(NSEvent *)event;
322 - (bool) handleEventLocked:(NSEvent *)event;
323 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
324 /* The state surrounding mouse grabbing is potentially confusing.
325 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
326 * pointing device an absolute-position one?"], but is only updated on
328 * isMouseGrabbed tracks whether GUI events are directed to the guest;
329 * it controls whether special keys like Cmd get sent to the guest,
330 * and whether we capture the mouse when in non-absolute mode.
332 - (BOOL) isMouseGrabbed;
333 - (BOOL) isAbsoluteEnabled;
336 - (QEMUScreen) gscreen;
337 - (void) raiseAllKeys;
340 QemuCocoaView *cocoaView;
342 static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
344 QemuCocoaView *cocoaView = userInfo;
345 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
346 if ([cocoaView isMouseGrabbed] && [cocoaView handleEvent:event]) {
347 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
350 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
355 @implementation QemuCocoaView
356 - (id)initWithFrame:(NSRect)frameRect
358 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
360 self = [super initWithFrame:frameRect];
363 screen.width = frameRect.size.width;
364 screen.height = frameRect.size.height;
365 kbd = qkbd_state_init(dcl.con);
373 COCOA_DEBUG("QemuCocoaView: dealloc\n");
376 pixman_image_unref(pixman_image);
379 qkbd_state_free(kbd);
382 CFRelease(eventsTap);
393 - (BOOL) screenContainsPoint:(NSPoint) p
395 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
398 /* Get location of event and convert to virtual screen coordinate */
399 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
401 NSWindow *eventWindow = [ev window];
402 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
403 CGRect r = CGRectZero;
404 r.origin = [ev locationInWindow];
407 return [[self window] convertRectFromScreen:r].origin;
409 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
410 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
417 } else if ([[self window] isEqual:eventWindow]) {
421 CGPoint loc = [self convertPoint:r.origin fromView:nil];
429 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
441 - (void) unhideCursor
449 - (void) drawRect:(NSRect) rect
451 COCOA_DEBUG("QemuCocoaView: drawRect\n");
453 // get CoreGraphic context
454 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
456 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
457 CGContextSetShouldAntialias (viewContextRef, NO);
459 // draw screen bitmap directly to Core Graphics context
461 // Draw request before any guest device has set up a framebuffer:
462 // just draw an opaque black rectangle
463 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
464 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
466 int w = pixman_image_get_width(pixman_image);
467 int h = pixman_image_get_height(pixman_image);
468 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
469 int stride = pixman_image_get_stride(pixman_image);
470 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
472 pixman_image_get_data(pixman_image),
476 CGImageRef imageRef = CGImageCreate(
479 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
480 bitsPerPixel, //bitsPerPixel
481 stride, //bytesPerRow
482 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
483 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
484 dataProviderRef, //provider
487 kCGRenderingIntentDefault //intent
489 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
490 const NSRect *rectList;
493 CGImageRef clipImageRef;
496 [self getRectsBeingDrawn:&rectList count:&rectCount];
497 for (i = 0; i < rectCount; i++) {
498 clipRect.origin.x = rectList[i].origin.x / cdx;
499 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
500 clipRect.size.width = rectList[i].size.width / cdx;
501 clipRect.size.height = rectList[i].size.height / cdy;
502 clipImageRef = CGImageCreateWithImageInRect(
506 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
507 CGImageRelease (clipImageRef);
509 CGImageRelease (imageRef);
510 CGDataProviderRelease(dataProviderRef);
514 - (void) setContentDimensions
516 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
519 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
520 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
522 /* stretches video, but keeps same aspect ratio */
523 if (stretch_video == true) {
524 /* use smallest stretch value - prevents clipping on sides */
525 if (MIN(cdx, cdy) == cdx) {
530 } else { /* No stretching */
533 cw = screen.width * cdx;
534 ch = screen.height * cdy;
535 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
536 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
547 - (void) updateUIInfoLocked
549 /* Must be called with the iothread lock, i.e. via updateUIInfo */
553 if (!qemu_console_is_graphic(dcl.con)) {
558 NSDictionary *description = [[[self window] screen] deviceDescription];
559 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
560 NSSize screenSize = [[[self window] screen] frame].size;
561 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
563 frameSize = isFullscreen ? screenSize : [self frame].size;
564 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
565 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
567 frameSize = [self frame].size;
574 info.width = frameSize.width;
575 info.height = frameSize.height;
577 dpy_set_ui_info(dcl.con, &info, TRUE);
580 - (void) updateUIInfo
584 * Don't try to tell QEMU about UI information in the application
585 * startup phase -- we haven't yet registered dcl with the QEMU UI
586 * layer, and also trying to take the iothread lock would deadlock.
587 * When cocoa_display_init() does register the dcl, the UI layer
588 * will call cocoa_switch(), which will call updateUIInfo, so
589 * we don't lose any information here.
594 with_iothread_lock(^{
595 [self updateUIInfoLocked];
599 - (void)viewDidMoveToWindow
604 - (void) switchSurface:(pixman_image_t *)image
606 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
608 int w = pixman_image_get_width(image);
609 int h = pixman_image_get_height(image);
610 /* cdx == 0 means this is our very first surface, in which case we need
611 * to recalculate the content dimensions even if it happens to be the size
612 * of the initial empty window.
614 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
616 int oldh = screen.height;
618 // Resize before we trigger the redraw, or we'll redraw at the wrong size
619 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
622 [self setContentDimensions];
623 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
626 // update screenBuffer
628 pixman_image_unref(pixman_image);
631 pixman_image = image;
635 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
636 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
639 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
640 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
644 [normalWindow center];
648 - (void) toggleFullScreen:(id)sender
650 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
652 if (isFullscreen) { // switch from fullscreen to desktop
653 isFullscreen = FALSE;
655 [self setContentDimensions];
656 [fullScreenWindow close];
657 [normalWindow setContentView: self];
658 [normalWindow makeKeyAndOrderFront: self];
659 [NSMenu setMenuBarVisible:YES];
660 } else { // switch from desktop to fullscreen
662 [normalWindow orderOut: nil]; /* Hide the window */
664 [self setContentDimensions];
665 [NSMenu setMenuBarVisible:NO];
666 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
667 styleMask:NSWindowStyleMaskBorderless
668 backing:NSBackingStoreBuffered
670 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
671 [fullScreenWindow setHasShadow:NO];
672 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
673 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
674 [[fullScreenWindow contentView] addSubview: self];
675 [fullScreenWindow makeKeyAndOrderFront:self];
679 - (void) setFullGrab:(id)sender
681 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
683 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
684 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
685 mask, handleTapEvent, self);
687 warn_report("Could not create event tap, system key combos will not be captured.\n");
690 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
693 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
695 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
699 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
700 if (!tapEventsSrc ) {
701 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
705 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
706 CFRelease(tapEventsSrc);
709 - (void) toggleKey: (int)keycode {
710 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
713 // Does the work of sending input to the monitor
714 - (void) handleMonitorInput:(NSEvent *)event
719 // if the control key is down
720 if ([event modifierFlags] & NSEventModifierFlagControl) {
724 /* translates Macintosh keycodes to QEMU's keysym */
726 static const int without_control_translation[] = {
727 [0 ... 0xff] = 0, // invalid key
729 [kVK_UpArrow] = QEMU_KEY_UP,
730 [kVK_DownArrow] = QEMU_KEY_DOWN,
731 [kVK_RightArrow] = QEMU_KEY_RIGHT,
732 [kVK_LeftArrow] = QEMU_KEY_LEFT,
733 [kVK_Home] = QEMU_KEY_HOME,
734 [kVK_End] = QEMU_KEY_END,
735 [kVK_PageUp] = QEMU_KEY_PAGEUP,
736 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
737 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
738 [kVK_Delete] = QEMU_KEY_BACKSPACE,
741 static const int with_control_translation[] = {
742 [0 ... 0xff] = 0, // invalid key
744 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
745 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
746 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
747 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
748 [kVK_Home] = QEMU_KEY_CTRL_HOME,
749 [kVK_End] = QEMU_KEY_CTRL_END,
750 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
751 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
754 if (control_key != 0) { /* If the control key is being used */
755 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
756 keysym = with_control_translation[[event keyCode]];
759 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
760 keysym = without_control_translation[[event keyCode]];
764 // if not a key that needs translating
766 NSString *ks = [event characters];
767 if ([ks length] > 0) {
768 keysym = [ks characterAtIndex:0];
773 kbd_put_keysym(keysym);
777 - (bool) handleEvent:(NSEvent *)event
781 * Just let OSX have all events that arrive before
782 * applicationDidFinishLaunching.
783 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
784 * will not drop until after the app_started_sem is posted. (In theory
785 * there should not be any such events, but OSX Catalina now emits some.)
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 static bool switched_to_fullscreen = false;
802 // Location of event in virtual screen coordinates
803 NSPoint p = [self screenLocationOfEvent:event];
804 NSUInteger modifiers = [event modifierFlags];
807 * Check -[NSEvent modifierFlags] here.
809 * There is a NSEventType for an event notifying the change of
810 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
811 * are performed for any events because a modifier state may change while
812 * the application is inactive (i.e. no events fire) and we don't want to
813 * wait for another modifier state change to detect such a change.
815 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
816 * are handled in similar manners.
818 * NSEventModifierFlagCapsLock
819 * ---------------------------
821 * If CapsLock state is changed, "up" and "down" events will be fired in
822 * sequence, effectively updates CapsLock state on the guest.
827 * If a flag is not set, fire "up" events for all keys which correspond to
828 * the flag. Note that "down" events are not fired here because the flags
829 * checked here do not tell what exact keys are down.
831 * If one of the keys corresponding to a flag is down, we rely on
832 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
833 * NSEventTypeFlagsChanged to know the exact key which is down, which has
834 * the following two downsides:
835 * - It does not work when the application is inactive as described above.
836 * - It malfactions *after* the modifier state is changed while the
837 * application is inactive. It is because -[NSEvent keyCode] does not tell
838 * if the key is up or down, and requires to infer the current state from
839 * the previous state. It is still possible to fix such a malfanction by
840 * completely leaving your hands from the keyboard, which hopefully makes
841 * this implementation usable enough.
843 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
844 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
845 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
846 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
849 if (!(modifiers & NSEventModifierFlagShift)) {
850 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
851 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
853 if (!(modifiers & NSEventModifierFlagControl)) {
854 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
855 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
857 if (!(modifiers & NSEventModifierFlagOption)) {
859 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
860 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
862 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
863 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
866 if (!(modifiers & NSEventModifierFlagCommand)) {
868 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
869 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
871 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
872 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
876 switch ([event type]) {
877 case NSEventTypeFlagsChanged:
878 switch ([event keyCode]) {
880 if (!!(modifiers & NSEventModifierFlagShift)) {
881 [self toggleKey:Q_KEY_CODE_SHIFT];
886 if (!!(modifiers & NSEventModifierFlagShift)) {
887 [self toggleKey:Q_KEY_CODE_SHIFT_R];
892 if (!!(modifiers & NSEventModifierFlagControl)) {
893 [self toggleKey:Q_KEY_CODE_CTRL];
897 case kVK_RightControl:
898 if (!!(modifiers & NSEventModifierFlagControl)) {
899 [self toggleKey:Q_KEY_CODE_CTRL_R];
904 if (!!(modifiers & NSEventModifierFlagOption)) {
906 [self toggleKey:Q_KEY_CODE_META_L];
908 [self toggleKey:Q_KEY_CODE_ALT];
913 case kVK_RightOption:
914 if (!!(modifiers & NSEventModifierFlagOption)) {
916 [self toggleKey:Q_KEY_CODE_META_R];
918 [self toggleKey:Q_KEY_CODE_ALT_R];
923 /* Don't pass command key changes to guest unless mouse is grabbed */
925 if (isMouseGrabbed &&
926 !!(modifiers & NSEventModifierFlagCommand)) {
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)) {
953 * Prevent the command key from being stuck down in the guest
954 * when using Command-F to switch to full screen mode.
956 if (keycode == Q_KEY_CODE_F) {
957 switched_to_fullscreen = true;
964 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
965 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
966 NSString *keychar = [event charactersIgnoringModifiers];
967 if ([keychar length] == 1) {
968 char key = [keychar characterAtIndex:0];
971 // enable graphic console
973 console_select(key - '0' - 1); /* ascii math */
976 // release the mouse grab
984 if (qemu_console_is_graphic(NULL)) {
985 qkbd_state_key_event(kbd, keycode, true);
987 [self handleMonitorInput: event];
990 case NSEventTypeKeyUp:
991 keycode = cocoa_keycode_to_qemu([event keyCode]);
993 // don't pass the guest a spurious key-up if we treated this
994 // command-key combo as a host UI action
995 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
999 if (qemu_console_is_graphic(NULL)) {
1000 qkbd_state_key_event(kbd, keycode, false);
1003 case NSEventTypeMouseMoved:
1004 if (isAbsoluteEnabled) {
1005 // Cursor re-entered into a window might generate events bound to screen coordinates
1006 // and `nil` window property, and in full screen mode, current window might not be
1007 // key window, where event location alone should suffice.
1008 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
1009 if (isMouseGrabbed) {
1013 if (!isMouseGrabbed) {
1020 case NSEventTypeLeftMouseDown:
1021 buttons |= MOUSE_EVENT_LBUTTON;
1024 case NSEventTypeRightMouseDown:
1025 buttons |= MOUSE_EVENT_RBUTTON;
1028 case NSEventTypeOtherMouseDown:
1029 buttons |= MOUSE_EVENT_MBUTTON;
1032 case NSEventTypeLeftMouseDragged:
1033 buttons |= MOUSE_EVENT_LBUTTON;
1036 case NSEventTypeRightMouseDragged:
1037 buttons |= MOUSE_EVENT_RBUTTON;
1040 case NSEventTypeOtherMouseDragged:
1041 buttons |= MOUSE_EVENT_MBUTTON;
1044 case NSEventTypeLeftMouseUp:
1046 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
1048 * In fullscreen mode, the window of cocoaView may not be the
1049 * key window, therefore the position relative to the virtual
1050 * screen alone will be sufficient.
1052 if(isFullscreen || [[self window] isKeyWindow]) {
1057 case NSEventTypeRightMouseUp:
1060 case NSEventTypeOtherMouseUp:
1063 case NSEventTypeScrollWheel:
1065 * Send wheel events to the guest regardless of window focus.
1066 * This is in-line with standard Mac OS X UI behaviour.
1070 * We shouldn't have got a scroll event when deltaY and delta Y
1071 * are zero, hence no harm in dropping the event
1073 if ([event deltaY] != 0 || [event deltaX] != 0) {
1074 /* Determine if this is a scroll up or scroll down event */
1075 if ([event deltaY] != 0) {
1076 buttons = ([event deltaY] > 0) ?
1077 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1078 } else if ([event deltaX] != 0) {
1079 buttons = ([event deltaX] > 0) ?
1080 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1083 qemu_input_queue_btn(dcl.con, buttons, true);
1084 qemu_input_event_sync();
1085 qemu_input_queue_btn(dcl.con, buttons, false);
1086 qemu_input_event_sync();
1090 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
1091 * movement code from executing.
1093 mouse_event = false;
1100 /* Don't send button events to the guest unless we've got a
1101 * mouse grab or window focus. If we have neither then this event
1102 * is the user clicking on the background window to activate and
1103 * bring us to the front, which will be done by the sendEvent
1104 * call below. We definitely don't want to pass that click through
1107 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1108 (last_buttons != buttons)) {
1109 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1110 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1111 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1112 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
1114 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1115 last_buttons = buttons;
1117 if (isMouseGrabbed) {
1118 if (isAbsoluteEnabled) {
1119 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1120 * The check on screenContainsPoint is to avoid sending out of range values for
1121 * clicks in the titlebar.
1123 if ([self screenContainsPoint:p]) {
1124 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1125 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1128 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1129 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1134 qemu_input_event_sync();
1141 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1143 if (!isFullscreen) {
1145 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1147 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1150 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1151 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1154 - (void) ungrabMouse
1156 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1158 if (!isFullscreen) {
1160 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1162 [normalWindow setTitle:@"QEMU"];
1164 [self unhideCursor];
1165 CGAssociateMouseAndMouseCursorPosition(TRUE);
1166 isMouseGrabbed = FALSE;
1169 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1170 isAbsoluteEnabled = tIsAbsoluteEnabled;
1171 if (isMouseGrabbed) {
1172 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1175 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1176 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1177 - (float) cdx {return cdx;}
1178 - (float) cdy {return cdy;}
1179 - (QEMUScreen) gscreen {return screen;}
1182 * Makes the target think all down keys are being released.
1183 * This prevents a stuck key problem, since we will not see
1184 * key up events for those keys after we have lost focus.
1186 - (void) raiseAllKeys
1188 with_iothread_lock(^{
1189 qkbd_state_lift_all_keys(kbd);
1197 ------------------------------------------------------
1198 QemuCocoaAppController
1199 ------------------------------------------------------
1201 @interface QemuCocoaAppController : NSObject
1202 <NSWindowDelegate, NSApplicationDelegate>
1205 - (void)doToggleFullScreen:(id)sender;
1206 - (void)toggleFullScreen:(id)sender;
1207 - (void)showQEMUDoc:(id)sender;
1208 - (void)zoomToFit:(id) sender;
1209 - (void)displayConsole:(id)sender;
1210 - (void)pauseQEMU:(id)sender;
1211 - (void)resumeQEMU:(id)sender;
1212 - (void)displayPause;
1213 - (void)removePause;
1214 - (void)restartQEMU:(id)sender;
1215 - (void)powerDownQEMU:(id)sender;
1216 - (void)ejectDeviceMedia:(id)sender;
1217 - (void)changeDeviceMedia:(id)sender;
1219 - (void)openDocumentation:(NSString *)filename;
1220 - (IBAction) do_about_menu_item: (id) sender;
1221 - (void)adjustSpeed:(id)sender;
1224 @implementation QemuCocoaAppController
1227 COCOA_DEBUG("QemuCocoaAppController: init\n");
1229 self = [super init];
1232 // create a view and add it to the window
1233 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1235 error_report("(cocoa) can't create a view");
1240 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1241 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1242 backing:NSBackingStoreBuffered defer:NO];
1244 error_report("(cocoa) can't create window");
1247 [normalWindow setAcceptsMouseMovedEvents:YES];
1248 [normalWindow setTitle:@"QEMU"];
1249 [normalWindow setContentView:cocoaView];
1250 [normalWindow makeKeyAndOrderFront:self];
1251 [normalWindow center];
1252 [normalWindow setDelegate: self];
1253 stretch_video = false;
1255 /* Used for displaying pause on the screen */
1256 pauseLabel = [NSTextField new];
1257 [pauseLabel setBezeled:YES];
1258 [pauseLabel setDrawsBackground:YES];
1259 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1260 [pauseLabel setEditable:NO];
1261 [pauseLabel setSelectable:NO];
1262 [pauseLabel setStringValue: @"Paused"];
1263 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1264 [pauseLabel setTextColor: [NSColor blackColor]];
1265 [pauseLabel sizeToFit];
1272 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1275 [cocoaView release];
1279 - (void)applicationDidFinishLaunching: (NSNotification *) note
1281 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1282 allow_events = true;
1283 /* Tell cocoa_display_init to proceed */
1284 qemu_sem_post(&app_started_sem);
1287 - (void)applicationWillTerminate:(NSNotification *)aNotification
1289 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1291 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1294 * Sleep here, because returning will cause OSX to kill us
1295 * immediately; the QEMU main loop will handle the shutdown
1296 * request and terminate the process.
1298 [NSThread sleepForTimeInterval:INFINITY];
1301 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1306 - (NSApplicationTerminateReply)applicationShouldTerminate:
1307 (NSApplication *)sender
1309 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1310 return [self verifyQuit];
1313 - (void)windowDidChangeScreen:(NSNotification *)notification
1315 [cocoaView updateUIInfo];
1318 - (void)windowDidResize:(NSNotification *)notification
1320 [cocoaView updateUIInfo];
1323 /* Called when the user clicks on a window's close button */
1324 - (BOOL)windowShouldClose:(id)sender
1326 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1327 [NSApp terminate: sender];
1328 /* If the user allows the application to quit then the call to
1329 * NSApp terminate will never return. If we get here then the user
1330 * cancelled the quit, so we should return NO to not permit the
1331 * closing of this window.
1336 /* Called when QEMU goes into the background */
1337 - (void) applicationWillResignActive: (NSNotification *)aNotification
1339 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1340 [cocoaView ungrabMouse];
1341 [cocoaView raiseAllKeys];
1344 /* We abstract the method called by the Enter Fullscreen menu item
1345 * because Mac OS 10.7 and higher disables it. This is because of the
1346 * menu item's old selector's name toggleFullScreen:
1348 - (void) doToggleFullScreen:(id)sender
1350 [self toggleFullScreen:(id)sender];
1353 - (void)toggleFullScreen:(id)sender
1355 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1357 [cocoaView toggleFullScreen:sender];
1360 - (void) setFullGrab:(id)sender
1362 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1364 [cocoaView setFullGrab:sender];
1367 /* Tries to find then open the specified filename */
1368 - (void) openDocumentation: (NSString *) filename
1370 /* Where to look for local files */
1371 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1372 NSString *full_file_path;
1373 NSURL *full_file_url;
1375 /* iterate thru the possible paths until the file is found */
1377 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1378 full_file_path = [[NSBundle mainBundle] executablePath];
1379 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1380 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1381 path_array[index], filename];
1382 full_file_url = [NSURL fileURLWithPath: full_file_path
1383 isDirectory: false];
1384 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1389 /* If none of the paths opened a file */
1391 QEMU_Alert(@"Failed to open file");
1394 - (void)showQEMUDoc:(id)sender
1396 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1398 [self openDocumentation: @"index.html"];
1401 /* Stretches video to fit host monitor size */
1402 - (void)zoomToFit:(id) sender
1404 stretch_video = !stretch_video;
1405 if (stretch_video == true) {
1406 [sender setState: NSControlStateValueOn];
1408 [sender setState: NSControlStateValueOff];
1412 /* Displays the console on the screen */
1413 - (void)displayConsole:(id)sender
1415 console_select([sender tag]);
1418 /* Pause the guest */
1419 - (void)pauseQEMU:(id)sender
1421 with_iothread_lock(^{
1424 [sender setEnabled: NO];
1425 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1426 [self displayPause];
1429 /* Resume running the guest operating system */
1430 - (void)resumeQEMU:(id) sender
1432 with_iothread_lock(^{
1435 [sender setEnabled: NO];
1436 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1440 /* Displays the word pause on the screen */
1441 - (void)displayPause
1443 /* Coordinates have to be calculated each time because the window can change its size */
1444 int xCoord, yCoord, width, height;
1445 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1446 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1447 width = [pauseLabel frame].size.width;
1448 height = [pauseLabel frame].size.height;
1449 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1450 [cocoaView addSubview: pauseLabel];
1453 /* Removes the word pause from the screen */
1456 [pauseLabel removeFromSuperview];
1460 - (void)restartQEMU:(id)sender
1462 with_iothread_lock(^{
1463 qmp_system_reset(NULL);
1467 /* Powers down QEMU */
1468 - (void)powerDownQEMU:(id)sender
1470 with_iothread_lock(^{
1471 qmp_system_powerdown(NULL);
1475 /* Ejects the media.
1476 * Uses sender's tag to figure out the device to eject.
1478 - (void)ejectDeviceMedia:(id)sender
1481 drive = [sender representedObject];
1484 QEMU_Alert(@"Failed to find drive to eject!");
1488 __block Error *err = NULL;
1489 with_iothread_lock(^{
1490 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1491 false, NULL, false, false, &err);
1493 handleAnyDeviceErrors(err);
1496 /* Displays a dialog box asking the user to select an image file to load.
1497 * Uses sender's represented object value to figure out which drive to use.
1499 - (void)changeDeviceMedia:(id)sender
1501 /* Find the drive name */
1503 drive = [sender representedObject];
1506 QEMU_Alert(@"Could not find drive!");
1510 /* Display the file open dialog */
1511 NSOpenPanel * openPanel;
1512 openPanel = [NSOpenPanel openPanel];
1513 [openPanel setCanChooseFiles: YES];
1514 [openPanel setAllowsMultipleSelection: NO];
1515 if([openPanel runModal] == NSModalResponseOK) {
1516 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1519 QEMU_Alert(@"Failed to convert URL to file path!");
1523 __block Error *err = NULL;
1524 with_iothread_lock(^{
1525 qmp_blockdev_change_medium(true,
1526 [drive cStringUsingEncoding:
1527 NSASCIIStringEncoding],
1529 [file cStringUsingEncoding:
1530 NSASCIIStringEncoding],
1535 handleAnyDeviceErrors(err);
1539 /* Verifies if the user really wants to quit */
1542 NSAlert *alert = [NSAlert new];
1543 [alert autorelease];
1544 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1545 [alert addButtonWithTitle: @"Cancel"];
1546 [alert addButtonWithTitle: @"Quit"];
1547 if([alert runModal] == NSAlertSecondButtonReturn) {
1554 /* The action method for the About menu item */
1555 - (IBAction) do_about_menu_item: (id) sender
1557 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1558 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1559 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1560 g_free(icon_path_c);
1561 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1562 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1563 NSString *copyright = @QEMU_COPYRIGHT;
1564 NSDictionary *options;
1567 NSAboutPanelOptionApplicationIcon : icon,
1568 NSAboutPanelOptionApplicationVersion : version,
1569 @"Copyright" : copyright,
1574 NSAboutPanelOptionApplicationVersion : version,
1575 @"Copyright" : copyright,
1578 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1582 /* Used by the Speed menu items */
1583 - (void)adjustSpeed:(id)sender
1585 int throttle_pct; /* throttle percentage */
1588 menu = [sender menu];
1591 /* Unselect the currently selected item */
1592 for (NSMenuItem *item in [menu itemArray]) {
1593 if (item.state == NSControlStateValueOn) {
1594 [item setState: NSControlStateValueOff];
1600 // check the menu item
1601 [sender setState: NSControlStateValueOn];
1603 // get the throttle percentage
1604 throttle_pct = [sender tag];
1606 with_iothread_lock(^{
1607 cpu_throttle_set(throttle_pct);
1609 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1614 @interface QemuApplication : NSApplication
1617 @implementation QemuApplication
1618 - (void)sendEvent:(NSEvent *)event
1620 COCOA_DEBUG("QemuApplication: sendEvent\n");
1621 if (![cocoaView handleEvent:event]) {
1622 [super sendEvent: event];
1627 static void create_initial_menus(void)
1631 NSMenuItem *menuItem;
1633 [NSApp setMainMenu:[[NSMenu alloc] init]];
1634 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1637 menu = [[NSMenu alloc] initWithTitle:@""];
1638 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1639 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1640 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1641 [menuItem setSubmenu:[NSApp servicesMenu]];
1642 [menu addItem:[NSMenuItem separatorItem]];
1643 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1644 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1645 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1646 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1647 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1648 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1649 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1650 [menuItem setSubmenu:menu];
1651 [[NSApp mainMenu] addItem:menuItem];
1652 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1655 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1656 [menu setAutoenablesItems: NO];
1657 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1658 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1659 [menu addItem: menuItem];
1660 [menuItem setEnabled: NO];
1661 [menu addItem: [NSMenuItem separatorItem]];
1662 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1663 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1664 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1665 [menuItem setSubmenu:menu];
1666 [[NSApp mainMenu] addItem:menuItem];
1669 menu = [[NSMenu alloc] initWithTitle:@"View"];
1670 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1671 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1672 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1673 [menuItem setSubmenu:menu];
1674 [[NSApp mainMenu] addItem:menuItem];
1677 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1679 // Add the rest of the Speed menu items
1680 int p, percentage, throttle_pct;
1681 for (p = 10; p >= 0; p--)
1683 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1685 menuItem = [[[NSMenuItem alloc]
1686 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1688 if (percentage == 100) {
1689 [menuItem setState: NSControlStateValueOn];
1692 /* Calculate the throttle percentage */
1693 throttle_pct = -1 * percentage + 100;
1695 [menuItem setTag: throttle_pct];
1696 [menu addItem: menuItem];
1698 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1699 [menuItem setSubmenu:menu];
1700 [[NSApp mainMenu] addItem:menuItem];
1703 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1704 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1705 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1706 [menuItem setSubmenu:menu];
1707 [[NSApp mainMenu] addItem:menuItem];
1708 [NSApp setWindowsMenu:menu];
1711 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1712 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1713 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1714 [menuItem setSubmenu:menu];
1715 [[NSApp mainMenu] addItem:menuItem];
1718 /* Returns a name for a given console */
1719 static NSString * getConsoleName(QemuConsole * console)
1721 g_autofree char *label = qemu_console_get_label(console);
1723 return [NSString stringWithUTF8String:label];
1726 /* Add an entry to the View menu for each console */
1727 static void add_console_menu_entries(void)
1730 NSMenuItem *menuItem;
1733 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1735 [menu addItem:[NSMenuItem separatorItem]];
1737 while (qemu_console_lookup_by_index(index) != NULL) {
1738 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1739 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1740 [menuItem setTag: index];
1741 [menu addItem: menuItem];
1746 /* Make menu items for all removable devices.
1747 * Each device is given an 'Eject' and 'Change' menu item.
1749 static void addRemovableDevicesMenuItems(void)
1752 NSMenuItem *menuItem;
1753 BlockInfoList *currentDevice, *pointerToFree;
1754 NSString *deviceName;
1756 currentDevice = qmp_query_block(NULL);
1757 pointerToFree = currentDevice;
1759 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1761 // Add a separator between related groups of menu items
1762 [menu addItem:[NSMenuItem separatorItem]];
1764 // Set the attributes to the "Removable Media" menu item
1765 NSString *titleString = @"Removable Media";
1766 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1767 NSColor *newColor = [NSColor blackColor];
1768 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1769 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1770 traits:NSBoldFontMask|NSItalicFontMask
1773 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1774 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1775 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1777 // Add the "Removable Media" menu item
1778 menuItem = [NSMenuItem new];
1779 [menuItem setAttributedTitle: attString];
1780 [menuItem setEnabled: NO];
1781 [menu addItem: menuItem];
1783 /* Loop through all the block devices in the emulator */
1784 while (currentDevice) {
1785 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1787 if(currentDevice->value->removable) {
1788 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1789 action: @selector(changeDeviceMedia:)
1790 keyEquivalent: @""];
1791 [menu addItem: menuItem];
1792 [menuItem setRepresentedObject: deviceName];
1793 [menuItem autorelease];
1795 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1796 action: @selector(ejectDeviceMedia:)
1797 keyEquivalent: @""];
1798 [menu addItem: menuItem];
1799 [menuItem setRepresentedObject: deviceName];
1800 [menuItem autorelease];
1802 currentDevice = currentDevice->next;
1804 qapi_free_BlockInfoList(pointerToFree);
1807 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1810 @implementation QemuCocoaPasteboardTypeOwner
1812 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1814 if (type != NSPasteboardTypeString) {
1818 with_iothread_lock(^{
1819 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1820 qemu_event_reset(&cbevent);
1821 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1823 while (info == cbinfo &&
1824 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1825 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1826 qemu_mutex_unlock_iothread();
1827 qemu_event_wait(&cbevent);
1828 qemu_mutex_lock_iothread();
1831 if (info == cbinfo) {
1832 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1833 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1834 [sender setData:data forType:NSPasteboardTypeString];
1838 qemu_clipboard_info_unref(info);
1844 static QemuCocoaPasteboardTypeOwner *cbowner;
1846 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1847 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1848 QemuClipboardType type);
1850 static QemuClipboardPeer cbpeer = {
1852 .notifier = { .notify = cocoa_clipboard_notify },
1853 .request = cocoa_clipboard_request
1856 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1858 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1862 if (info != cbinfo) {
1863 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1864 qemu_clipboard_info_unref(cbinfo);
1865 cbinfo = qemu_clipboard_info_ref(info);
1866 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1870 qemu_event_set(&cbevent);
1873 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1875 QemuClipboardNotify *notify = data;
1877 switch (notify->type) {
1878 case QEMU_CLIPBOARD_UPDATE_INFO:
1879 cocoa_clipboard_update_info(notify->info);
1881 case QEMU_CLIPBOARD_RESET_SERIAL:
1887 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1888 QemuClipboardType type)
1893 case QEMU_CLIPBOARD_TYPE_TEXT:
1894 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1896 qemu_clipboard_set_data(&cbpeer, info, type,
1897 [text length], [text bytes], true);
1907 * The startup process for the OSX/Cocoa UI is complicated, because
1908 * OSX insists that the UI runs on the initial main thread, and so we
1909 * need to start a second thread which runs the vl.c qemu_main():
1911 * Initial thread: 2nd thread:
1913 * create qemu-main thread
1914 * wait on display_init semaphore
1917 * in cocoa_display_init():
1918 * post the display_init semaphore
1919 * wait on app_started semaphore
1920 * create application, menus, etc
1921 * enter OSX run loop
1922 * in applicationDidFinishLaunching:
1923 * post app_started semaphore
1924 * tell main thread to fullscreen if needed
1926 * run qemu main-loop
1928 * We do this in two stages so that we don't do the creation of the
1929 * GUI application menus and so on for command line options like --help
1930 * where we want to just print text to stdout and exit immediately.
1933 static void *call_qemu_main(void *opaque)
1937 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1938 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1939 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1944 int main (int argc, char **argv) {
1947 COCOA_DEBUG("Entered main()\n");
1951 qemu_sem_init(&display_init_sem, 0);
1952 qemu_sem_init(&app_started_sem, 0);
1954 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1955 NULL, QEMU_THREAD_DETACHED);
1957 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1958 qemu_sem_wait(&display_init_sem);
1959 COCOA_DEBUG("Main thread: initializing app\n");
1961 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1963 // Pull this console process up to being a fully-fledged graphical
1964 // app with a menubar and Dock icon
1965 ProcessSerialNumber psn = { 0, kCurrentProcess };
1966 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1968 [QemuApplication sharedApplication];
1970 create_initial_menus();
1973 * Create the menu entries which depend on QEMU state (for consoles
1974 * and removeable devices). These make calls back into QEMU functions,
1975 * which is OK because at this point we know that the second thread
1976 * holds the iothread lock and is synchronously waiting for us to
1979 add_console_menu_entries();
1980 addRemovableDevicesMenuItems();
1982 // Create an Application controller
1983 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1984 [NSApp setDelegate:appController];
1986 // Start the main event loop
1987 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1989 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1991 [appController release];
2000 static void cocoa_update(DisplayChangeListener *dcl,
2001 int x, int y, int w, int h)
2003 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
2005 dispatch_async(dispatch_get_main_queue(), ^{
2007 if ([cocoaView cdx] == 1.0) {
2008 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
2011 x * [cocoaView cdx],
2012 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
2013 w * [cocoaView cdx],
2014 h * [cocoaView cdy]);
2016 [cocoaView setNeedsDisplayInRect:rect];
2020 static void cocoa_switch(DisplayChangeListener *dcl,
2021 DisplaySurface *surface)
2023 pixman_image_t *image = surface->image;
2025 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
2027 // The DisplaySurface will be freed as soon as this callback returns.
2028 // We take a reference to the underlying pixman image here so it does
2029 // not disappear from under our feet; the switchSurface method will
2030 // deref the old image when it is done with it.
2031 pixman_image_ref(image);
2033 dispatch_async(dispatch_get_main_queue(), ^{
2034 [cocoaView updateUIInfo];
2035 [cocoaView switchSurface:image];
2039 static void cocoa_refresh(DisplayChangeListener *dcl)
2041 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2043 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2044 graphic_hw_update(NULL);
2046 if (qemu_input_is_absolute()) {
2047 dispatch_async(dispatch_get_main_queue(), ^{
2048 if (![cocoaView isAbsoluteEnabled]) {
2049 if ([cocoaView isMouseGrabbed]) {
2050 [cocoaView ungrabMouse];
2053 [cocoaView setAbsoluteEnabled:YES];
2057 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2058 qemu_clipboard_info_unref(cbinfo);
2059 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2060 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2061 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2063 qemu_clipboard_update(cbinfo);
2064 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2065 qemu_event_set(&cbevent);
2071 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2073 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2075 /* Tell main thread to go ahead and create the app and enter the run loop */
2076 qemu_sem_post(&display_init_sem);
2077 qemu_sem_wait(&app_started_sem);
2078 COCOA_DEBUG("cocoa_display_init: app start completed\n");
2080 QemuCocoaAppController *controller = (QemuCocoaAppController *)[[NSApplication sharedApplication] delegate];
2081 /* if fullscreen mode is to be used */
2082 if (opts->has_full_screen && opts->full_screen) {
2083 dispatch_async(dispatch_get_main_queue(), ^{
2084 [NSApp activateIgnoringOtherApps: YES];
2085 [controller toggleFullScreen: nil];
2088 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2089 dispatch_async(dispatch_get_main_queue(), ^{
2090 [controller setFullGrab: nil];
2094 if (opts->has_show_cursor && opts->show_cursor) {
2097 if (opts->u.cocoa.has_swap_opt_cmd) {
2098 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2101 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2102 left_command_key_enabled = 0;
2105 // register vga output callbacks
2106 register_displaychangelistener(&dcl);
2108 qemu_event_init(&cbevent, false);
2109 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2110 qemu_clipboard_peer_register(&cbpeer);
2113 static QemuDisplay qemu_display_cocoa = {
2114 .type = DISPLAY_TYPE_COCOA,
2115 .init = cocoa_display_init,
2118 static void register_cocoa(void)
2120 qemu_display_register(&qemu_display_cocoa);
2123 type_init(register_cocoa);